content stringlengths 5 1.05M |
|---|
#! /usr/bin/env lua
require 'example'
require 'hooks'
local EVENT = require 'event'
local function main()
local trigger = EVENT.trigger
local npc = Creature("leo", 40, 40, 100);
trigger(EventType.kCreatureBorn, npc);
local player = Player("jax", 40, 70, 100, 10, 20);
trigger(EventType.kPlayerLogin, player);
while npc:GetHP() > 0 do
player:Attack(npc);
player:SpellHit(npc);
trigger(EventType.kCreatureHurt, npc);
end
trigger(EventType.kPlayerKill, player, npc);
trigger(EventType.kPlayerLogout, player);
end
local ok, STP = pcall(require, 'StackTracePlus')
local traceback = ok and STP.stacktrace or debug.traceback
xpcall(main, function(...) print('\n' .. traceback(...)) end)
|
local Prefs = {};
ThemePrefs.InitAll(Prefs)
function InitUserPrefs()
local Prefs = {
UserPrefScoringMode = 'DDR Extreme',
UserPrefSoundPack = 'default',
UserPrefProtimingP1 = false,
UserPrefProtimingP2 = false,
UserPrefAllowW1 = 'CoursesOnly',
}
for k, v in pairs(Prefs) do
-- kind of xxx
local GetPref = type(v) == "boolean" and GetUserPrefB or GetUserPref
if GetPref(k) == nil then
SetUserPref(k, v)
end
end
end
|
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ==========
PlaceObj('StoryBit', {
ActivationEffects = {
PlaceObj('KillColonist', nil),
},
Category = "Tick_FounderStageDone",
Effects = {},
Enabled = true,
Image = "UI/Messages/Events/10_protest.tga",
Prerequisites = {
PlaceObj('PickFromLabel', {
'Label', "Colonist",
'Conditions', {
PlaceObj('HasTrait', {
'Trait', "Renegade",
}),
PlaceObj('HasTrait', {
'Trait', "Senior",
'Negate', true,
}),
},
}),
PlaceObj('CheckObjectCount', {
'Label', "SecurityStation",
'Filters', {},
'Condition', ">=",
'Amount', 1,
}),
},
ScriptDone = true,
Text = T(837464417554, --[[StoryBit Oppression Text]] "A young renegade, <DisplayName>, has been killed by our security forces in a tragic sequence of events. \n\nThe colony is shocked and many Colonists are coming forward with accusations of Security Officers using excessive force when confronting mere acts of vandalism.\n\nThe community, both Renegade and non-Renegade citizens, demand justice in the form of retaliatory actions against the Officers involved."),
TextReadyForValidation = true,
TextsDone = true,
Title = T(685295205241, --[[StoryBit Oppression Title]] "Renegades: Justice"),
VoicedText = T(960167046928, --[[voice:narrator]] "A tragedy has mired the colony today."),
group = "Renegades",
id = "Oppression",
qa_info = PlaceObj('PresetQAInfo', {
data = {
{
action = "Modified",
time = 1551084963,
user = "Radomir",
},
},
}),
PlaceObj('StoryBitReply', {
'Text', T(121445056181, --[[StoryBit Oppression Text]] "This kind of behavior doesn't suit their station. Punish the Officers."),
'OutcomeText', "custom",
'CustomOutcomeText', T(447741238430, --[[StoryBit Oppression CustomOutcomeText]] " all workers in Security Stations lose Morale"),
}),
PlaceObj('StoryBitParamSols', {
'Name', "sols",
'Value', 7200000,
}),
PlaceObj('StoryBitParamNumber', {
'Name', "morale_penalty",
'Value', -35,
}),
PlaceObj('StoryBitOutcome', {
'Prerequisites', {},
'Effects', {
PlaceObj('ForEachExecuteEffects', {
'Label', "SecurityStation",
'Filters', {},
'Effects', {
PlaceObj('ForEachWorker', {
'Filters', {},
'Effects', {
PlaceObj('ModifyObject', {
'Prop', "base_morale",
'Amount', "<morale_penalty>",
'Sols', "<sols>",
}),
},
}),
},
}),
},
}),
PlaceObj('StoryBitReply', {
'Text', T(714078729397, --[[StoryBit Oppression Text]] "The Officers were doing their jobs. No punishment is necessary. "),
'OutcomeText', "custom",
'CustomOutcomeText', T(451541096754, --[[StoryBit Oppression CustomOutcomeText]] "some Colonists will become Renegades"),
}),
PlaceObj('StoryBitOutcome', {
'Prerequisites', {},
'VoicedText', T(12238, --[[voice:narrator]] "Your answer was met with fury from the colonists."),
'Text', T(807192936015, --[[StoryBit Oppression Text]] "Violent protests and unflattering slurs could be heard for several more hours.\n\nWhile we do not have precise numbers, its safe to say that our renegade population has increased."),
'Effects', {
PlaceObj('ForEachExecuteEffects', {
'Label', "Colonist",
'Filters', {
PlaceObj('HasTrait', {
'Trait', "Renegade",
'Negate', true,
}),
},
'RandomCount', 10,
'Effects', {
PlaceObj('AddTrait', {
'Trait', "Renegade",
}),
},
}),
},
}),
PlaceObj('StoryBitReply', {
'Text', T(573455130085, --[[StoryBit Oppression Text]] "Close all Security Stations for <sols(sols)> Sols for retraining. This must never happen again."),
}),
PlaceObj('StoryBitOutcome', {
'Prerequisites', {},
'Effects', {
PlaceObj('ForEachExecuteEffects', {
'Label', "SecurityStation",
'Filters', {},
'Effects', {
PlaceObj('SetBuildingEnabledState', {
'Duration', "<sols>",
}),
},
}),
},
}),
})
|
function model.setSphereSize(h,diameter)
local r,mmin=sim.getObjectFloatParameter(h,sim.objfloatparam_objbbox_min_x)
local r,mmax=sim.getObjectFloatParameter(h,sim.objfloatparam_objbbox_max_x)
local sx=mmax-mmin
local r,mmin=sim.getObjectFloatParameter(h,sim.objfloatparam_objbbox_min_y)
local r,mmax=sim.getObjectFloatParameter(h,sim.objfloatparam_objbbox_max_y)
local sy=mmax-mmin
local r,mmin=sim.getObjectFloatParameter(h,sim.objfloatparam_objbbox_min_z)
local r,mmax=sim.getObjectFloatParameter(h,sim.objfloatparam_objbbox_max_z)
local sz=mmax-mmin
sim.scaleObject(h,diameter/sx,diameter/sy,diameter/sz)
end
function model.setSphereMassAndInertia(h,diameter,mass,inertiaFact)
local inertiaFact=1
local transf=sim.getObjectMatrix(h,-1)
local I=2*mass*inertiaFact*(diameter*0.5)*(diameter*0.5)/5
local inertia={I,0,0,0,I,0,0,0,I}
sim.setShapeMassAndInertia(h,mass,inertia,{0,0,0},transf)
end
function model.setColor(red,green,blue,spec)
sim.setShapeColor(model.handle,nil,sim.colorcomponent_ambient_diffuse,{red,green,blue})
for i=1,3,1 do
sim.setShapeColor(model.specHandles.auxSpheres[i],nil,sim.colorcomponent_ambient_diffuse,{red,green,blue})
end
end
function model.getColor()
local r,rgb=sim.getShapeColor(model.handle,nil,sim.colorcomponent_ambient_diffuse)
return rgb[1],rgb[2],rgb[3]
end
function model.updateModel()
local c=model.readInfo()
local d=c.partSpecific['diameter']
local count=c.partSpecific['count']
local offset=c.partSpecific['offset']*d
local mass=c.partSpecific['mass']
model.setSphereSize(model.handle,d)
model.setSphereMassAndInertia(model.handle,d,mass/count,2)
for i=1,3,1 do
model.setSphereSize(model.specHandles.auxSpheres[i],d)
model.setSphereMassAndInertia(model.specHandles.auxSpheres[i],d,mass/count,2)
sim.setObjectPosition(model.specHandles.auxSpheres[i],model.handle,{0,0,0})
end
if count>=2 then
sim.setObjectPosition(model.specHandles.auxSpheres[1],model.handle,{offset,0,0})
end
if count>=3 then
sim.setObjectPosition(model.specHandles.auxSpheres[2],model.handle,{offset*0.5,0.866*offset,0})
end
if count==4 then
sim.setObjectPosition(model.specHandles.auxSpheres[3],model.handle,{offset*0.5,0.288*offset,0.81*offset})
end
end
function sysCall_cleanup_specific()
local c=model.readInfo()
local fs=sim.getObjectsInTree(model.handle,sim.object_forcesensor_type,1+2)
for i=1,#fs,1 do
sim.removeObject(fs[i])
end
if c.partSpecific['count']<4 then
sim.removeObject(model.specHandles.auxSpheres[3])
end
if c.partSpecific['count']<3 then
sim.removeObject(model.specHandles.auxSpheres[2])
end
if c.partSpecific['count']<2 then
sim.removeObject(model.specHandles.auxSpheres[1])
else
local dummy=sim.createDummy(0.01)
sim.setObjectOrientation(dummy,model.handle,{0,0,0})
local oss=sim.getObjectsInTree(model.handle,sim.object_shape_type,1)
oss[#oss+1]=model.handle
local r=sim.groupShapes(oss)
sim.reorientShapeBoundingBox(r,dummy)
sim.removeObject(dummy)
end
end
|
--[[
TheNexusAvenger
Text button that disables auto button colors when disabled.
--]]
local CLASS_NAME = "NexusTextButton"
local NexusPluginFramework = require(script.Parent.Parent.Parent:WaitForChild("NexusPluginFrameworkProject")):GetContext(script)
local NexusGuiButton = NexusPluginFramework:GetResource("UI.Input.Abstract.NexusGuiButton")
local NexusTextBox = NexusGuiButton:Extend()
NexusTextBox:SetClassName(CLASS_NAME)
NexusPluginFramework:SetContextResource(NexusTextBox)
--[[
Creates a Nexus Text Box object.
--]]
function NexusTextBox:__new()
self:InitializeSuper("TextButton")
self.Name = CLASS_NAME
--Set the defaults.
self.BackgroundColor3 = "Button"
self.BorderColor3 = "ButtonBorder"
self.TextColor3 = "ButtonText"
self.Font = "SourceSans"
self.TextSize = 14
end
return NexusTextBox |
--
-- from src/grBMP.c
--
-- void putbytes(FILE *, int, unsigned long) to NBWriter
-- void gr_dot(int, int, long) to BMP; :dot
-- void gr_clear(long) to BMP; :clear
-- void gr_BMP(char *) to BMP; :write
--
-- from src/circle.c
--
-- void gr_circle(int, int, int, long) to BMP; :circle
--
-- from src/ellipse.c
--
-- void gr_ellipse(int, int, int, int, long) to BMP; :ellipse
--
-- from src/line.c
--
-- void gr_line(int, int, int, int, long) to BMP; :line
--
-- from src/window.c
--
-- void gr_window(double, double, double, double, int) to BMP; :setWindow
-- void gr_wdot(double, double, long) to BMP; :wdot
-- void gr_wline(double, double, double, double, long) to BMP; :wline
--
local H = require '_helper'
local readOnlyTable = H.readOnlyTable
local unpack = table.unpack
local abs = math.abs
local floor = math.floor
local function NBWriter(n)
local fmt, t = ("B"):rep(n), {}
return function (fh, x)
for i=1,n do t[i], x = x & 255, x >> 8 end
fh:write(fmt:pack(unpack(t)))
end
end
local write2B = NBWriter(2)
local write4B = NBWriter(4)
local function BMP(X, Y)
local T = {
data = {},
--
xfac = 1,
yfac = 1,
xconst = 0,
yconst = 0
}
function header(fh)
fh:write("BM")
write4B(fh, X * Y * 4 + 54)
write4B(fh, 0)
write4B(fh, 54)
write4B(fh, 40)
write4B(fh, X)
write4B(fh, Y)
write2B(fh, 1)
write2B(fh, 32)
write4B(fh, 0)
write4B(fh, X * Y * 4)
write4B(fh, 3780)
write4B(fh, 3780)
write4B(fh, 0)
write4B(fh, 0)
end
function body(fh)
for y=1,Y do
for x=1,X do
-- assert(T.data[y][x] ~= nil, ("data[%d][%d] is nil"):format(y, x))
write4B(fh, T.data[y][x])
end
end
end
function inRange(x, y)
return x >= 1 and x <= X and y >= 1 and y <= Y
end
function T:dot(x, y, color)
if inRange(x, y) then
if T.data[y] == nil then T.data[y] = {} end
T.data[y][x] = color
end
end
function T:rect(lX, rX, lY, rY, color)
for x=lX,rX do
for y=lY,rY do
T:dot(x, y, color)
end
end
end
function T:clear(color)
T:rect(1, X, 1, Y, color)
end
function T:circle(cX, cY, r, color)
local x, y = r, 0
while x >= y do
T:dot(cX + x, cY + y, color)
T:dot(cX + x, cY - y, color)
T:dot(cX - x, cY + y, color)
T:dot(cX - x, cY - y, color)
T:dot(cX + y, cY + x, color)
T:dot(cX + y, cY - x, color)
T:dot(cX - y, cY + x, color)
T:dot(cX - y, cY - x, color)
r, y = r - ((y << 1) + 1), y + 1
if r <= 0 then
x = x - 1
r = r + (x << 1)
end
end
end
function T:ellipse(cX, cY, rX, rY, color)
local step = (function ()
function _step(a, b, c, d)
T:dot(cX + a, cY + b, color)
T:dot(cX + a, cY - b, color)
T:dot(cX - a, cY + b, color)
T:dot(cX - a, cY - b, color)
T:dot(cX + c, cY + d, color)
T:dot(cX + c, cY - d, color)
T:dot(cX - c, cY + d, color)
T:dot(cX - c, cY - d, color)
end
return rX > rY and function (x, y)
_step(x, y * rY // rX, y, x * rY // rX)
end or function (x, y)
_step(x * rX // rY, y, y * rX // rY, x)
end
end)()
local x = rX > rY and rX or rY
local r, y = x, 0
while x >= y do
step(x, y)
r, y = r - ((y << 1) + 1), y + 1
if r <= 0 then
x = x - 1
r = r + (x << 1)
end
end
end
function T:line(x1, y1, x2, y2, color)
function loop(a1, a2, b1, b2, dA, dB, dotter)
local step
if a1 > a2 then
step = b1 > b2 and 1 or -1
a1, a2, b1 = a2, a1, b2
else
step = b1 < b2 and 1 or -1
end
dotter(a1, b1)
local t = dA >> 1
for a=a1+1,a2 do
t = t - dB
if t < 0 then
t, b1 = t + dA, b1 + step
end
dotter(a, b1)
end
end
local dX, dY = abs(x2 - x1), abs(y2 - y1)
if dX > dY then
loop(x1, x2, y1, y2, dX, dY, function (a,b) T:dot(a,b,color) end)
else
loop(y1, y2, x1, x2, dY, dX, function (a,b) T:dot(b,a,color) end)
end
end
function adjustX(x) return floor(T.xfac * x + T.xconst) end
function adjustY(y) return floor(T.yfac * y + T.yconst) end
function T:setWindow(left, right, top, bottom, isSquareWindow)
isSquareWindow = isSquareWindow ~= nil and isSquareWindow or false
T.xfac, T.yfac = X / (right - left), Y / (top - bottom)
if isSquareWindow then
if abs(T.xfac) > abs(T.yfac) then
T.xfac = T.xfac * abs(T.yfac / T.xfac)
else
T.yfac = T.yfac * abs(T.xfac / T.yfac)
end
end
T.xconst, T.yconst = 0.5 - T.xfac * left, 0.5 - T.yfac * bottom
end
function T:wDot(x, y, color)
T:dot(adjustX(x), adjustY(y), color)
end
function T:wLine(x1, y1, x2, y2, color)
T:line(adjustX(x1), adjustY(y1), adjustX(x2), adjustY(y2), color)
end
function T:write(fh)
header(fh)
body(fh)
end
return T
end
local PRESETCOLORS = readOnlyTable({
BLACK = 0x000000,
WHITE = 0xffffff,
RED = 0xff0000,
GREEN = 0x00ff00,
BLUE = 0x0000ff
})
return {
BMP = BMP,
PRESETCOLORS = PRESETCOLORS
}
|
-- tools/init.lua
local path = microexpansion.get_module_path("tools")
-- Load In Xtremo Tools
dofile(path.."/xtremo.lua")
|
-- return directly when the required module cannot be loaded
local ok, gitsigns = pcall(require, "gitsigns")
if not ok then
return
end
-- configurations
-- --------------------------------------
gitsigns.setup({
signs = {
add = {hl = "GitSignsAdd" , text = "+"},
change = {hl = "GitSignsChange", text = "~"},
delete = {hl = "GitSignsDelete", text = "-"},
topdelete = {hl = "GitSignsDelete", text = "‾"},
changedelete = {hl = "GitSignsChange", text = "~_"},
},
})
|
local utils = require("csharpls_extended.utils")
--local lsp_util = require 'vim.lsp.util'
--local pickers = require("telescope.pickers")
--local finders = require("telescope.finders")
--local conf = require("telescope.config").values
local M = {}
M.defolderize = function(str)
-- private static string Folderize(string path) => string.Join("/", path.Split('.'));
return string.gsub(str, "[/\\]", ".")
end
M.matcher = "metadata[/\\]projects[/\\](.*)[/\\]assemblies[/\\](.*)[/\\]symbols[/\\](.*).cs"
--M.matcher_meta_uri = "(metadata%$[/\\].*)"
-- it return a nil?
M.parse_meta_uri = function(uri)
--print(uri)
--local found, _, project, assembly, symbol = string.find(uri, M.matcher)
local found, _, project, assembly, symbol = string.find(uri, M.matcher)
--print(found)
if found ~= nil then
return found, M.defolderize(project), M.defolderize(assembly), M.defolderize(symbol)
end
return nil
end
-- get client
M.get_csharpls_client = function()
local clients = vim.lsp.buf_get_clients(0)
for _, client in pairs(clients) do
if client.name == "csharp_ls" then
return client
end
end
return nil
end
M.buf_from_metadata = function(result, client_id)
local normalized = string.gsub(result.source, "\r\n", "\n")
local source_lines = utils.split(normalized, "\n")
-- normalize backwards slash to forwards slash
local normalized_source_name = string.gsub(result.assemblyName, "\\", "/")
local file_name = "/" .. normalized_source_name
-- this will be /$metadata$/...
local bufnr = utils.get_or_create_buf(file_name)
-- TODO: check if bufnr == 0 -> error
vim.api.nvim_buf_set_option(bufnr, "modifiable", true)
vim.api.nvim_buf_set_option(bufnr, "readonly", false)
vim.api.nvim_buf_set_lines(bufnr, 0, -1, true, source_lines)
vim.api.nvim_buf_set_option(bufnr, "modifiable", false)
vim.api.nvim_buf_set_option(bufnr, "readonly", true)
vim.api.nvim_buf_set_option(bufnr, "filetype", "cs")
vim.api.nvim_buf_set_option(bufnr, "modified", false)
-- attach lsp client ??
vim.lsp.buf_attach_client(bufnr, client_id)
-- vim.api.nvim_win_set_buf(0, bufnr)
-- set_cursor is (1, 0) indexed, where LSP range is 0 indexed, so add 1 to line number
-- vim.api.nvim_win_set_cursor(0, { range.start.line+1, range.start.character })
--
return bufnr, file_name
end
-- Gets metadata for all locations with $metadata$
-- Returns: boolean whether any requests were made
M.get_metadata = function(locations)
local client = M.get_csharpls_client()
if not client then
-- TODO: Error?
return false
end
local fetched = {}
for _, loc in pairs(locations) do
-- url, get the message from csharp_ls
local uri = utils.urldecode(loc.uri)
--print(uri)
--if has get messages
local is_meta, _, _, _ = M.parse_meta_uri(uri)
--print(is_meta,project,assembly,symbol)
if is_meta then
--print(uri)
local params = {
timeout = 5000,
textDocument = {
uri = uri,
},
}
--print("ssss")
-- request_sync?
-- if async, need to trigger when all are finished
local result, err = client.request_sync("csharp/metadata", params, 10000)
--print(result.result.source)
if not err then
local bufnr, name = M.buf_from_metadata(result.result, client.id)
-- change location name to the one returned from metadata
-- alternative is to open buffer under location uri
-- not sure which one is better
loc.uri = "file://" .. name
fetched[loc.uri] = {
bufnr = bufnr,
range = loc.range,
}
end
end
end
return fetched
end
M.textdocument_definition_to_locations = function(result)
if not vim.tbl_islist(result) then
return { result }
end
return result
end
M.handle_locations = function(locations)
local fetched = M.get_metadata(locations)
if not vim.tbl_isempty(fetched) then
if #locations > 1 then
utils.set_qflist_locations(locations)
vim.api.nvim_command("copen")
return true
else
-- utils.jump_to_location(locations[1], fetched[locations[1].uri].bufnr)
vim.lsp.util.jump_to_location(locations[1])
return true
end
else
return false
end
end
M.handler = function(err, result, ctx, config)
local locations = M.textdocument_definition_to_locations(result)
local handled = M.handle_locations(locations)
if not handled then
return vim.lsp.handlers["textDocument/definition"](err, result, ctx, config)
end
end
M.lsp_definitions = function()
local client = M.get_csharpls_client()
if client then
local params = vim.lsp.util.make_position_params()
local handler = function(err, result, ctx, config)
ctx.params = params
M.handler(err, result, ctx, config)
end
client.request("textDocument/definition", params, handler)
end
end
return M
|
-- Inofficial Nimiq Extension for MoneyMoney
-- Fetches Nimiq quantity for addresses via blockexplorer API
-- Fetches Nimiq price in EUR via coingecko API
-- Returns cryptoassets as securities
--
-- Username: Nimiq Adresses comma separated
-- MIT License
-- Copyright (c) 2018 Pascal Berrang
-- 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.
WebBanking{
version = 1.2,
description = "Include your Nimiq as cryptoportfolio in MoneyMoney by providing Nimiq addresses as username (comma separated) and a random password",
services = { "Nimiq" }
}
local nimiqAddresses
local nativeCurrency = "EUR"
function SupportsBank (protocol, bankCode)
return protocol == ProtocolWebBanking and bankCode == "Nimiq"
end
function InitializeSession (protocol, bankCode, username, username2, password, username3)
nimiqAddresses = username:gsub("%s+", "")
end
function ListAccounts (knownAccounts)
local account = {
name = "Nimiq",
accountNumber = "Main",
currency = nativeCurrency,
portfolio = true,
type = "AccountTypePortfolio"
}
return {account}
end
function RefreshAccount (account, since)
local s = {}
price = queryExchangeRate()
for address in string.gmatch(nimiqAddresses, '([^,]+)') do
nimiqQuantity = queryBalance(address)
s[#s+1] = {
name = address:gsub("....", "%1 "):upper(),
currency = nil,
market = "CoinGecko",
quantity = nimiqQuantity,
price = price["eur"],
prettyPrint = false
}
end
return {securities = s}
end
function EndSession ()
end
-- Query Functions
function queryExchangeRate()
local response = Connection():request("GET", "https://api.coingecko.com/api/v3/simple/price?ids=nimiq-2&vs_currencies=eur")
local json = JSON(response)
return json:dictionary()["nimiq-2"]
end
function queryBalance(nimiqAddress)
local url = string.format("https://api.nimiq.watch/account/%s", nimiqAddress)
local response = Connection():request("GET", url)
local json = JSON(response)
return convertNatoshiToNimiq(json:dictionary()["balance"])
end
-- Helper Functions
function convertNatoshiToNimiq(natoshi)
return natoshi / 100000
end
-- SIGNATURE: MCwCFErJW+IENzIYjJi8Psf7JU+UTO9GAhRmJoJetKXL6Lr9g7RH2hnRHF+mZg==
|
workspace "SurvivalVoxelGame"
location "build"
configurations {
"Debug",
"Release"
}
startproject "SurvivalVoxel"
flags {
"MultiProcessorCompile"
}
filter "configurations:Debug"
defines {
"DEBUG",
"DEBUG_SHADER"
}
symbols "On"
filter "configurations:Release"
defines {
"RELEASE"
}
optimize "Speed"
flags {
"LinkTimeOptimization"
}
project "SurvivalVoxel"
kind "ConsoleApp"
language "C++"
cppdialect "C++17"
architecture "x86_64"
targetdir "build/bin/%{cfg.buildcfg}"
objdir "build/obj/%{cfg.buildcfg}"
defines {
"AL_LIBTYPE_STATIC"
}
includedirs {
"src/",
"dependencies/glad/include/",
"dependencies/glfw/include/",
"dependencies/glm/",
"dependencies/imgui/",
"dependencies/imgui/examples",
"dependencies/soil2/src/SOIL2",
"dependencies/PerlinNoise/",
"dependencies/bullet3/src",
"dependencies/assimp/include",
"dependencies/assimp/config/",
"dependencies/GLSL-Shader-Includes/",
"dependencies/jsoncpp/include",
"dependencies/spdlog/include",
"dependencies/openal-soft/include",
"dependencies/gainput/lib/include"
}
files {
"src/**.cpp",
"src/**.hpp",
"src/**.h",
}
links {
"GLFW",
"GLM",
"GLAD",
"ImGui",
"Soil2",
"Bullet3",
"assimp",
"Jsoncpp",
"SpdLog",
"OpenAl",
"Gainput"
}
filter "system:linux"
links {
"dl",
"pthread"
}
defines {
"_X11"
}
filter "system:windows"
defines {
"_WINDOWS"
}
group "Dependencies"
include "dependencies/glfw.lua"
include "dependencies/glad.lua"
include "dependencies/glm.lua"
include "dependencies/imgui.lua"
include "dependencies/soil2.lua"
include "dependencies/bullet3.lua"
include "dependencies/assimp.lua"
include "dependencies/jsoncpp.lua"
include "dependencies/spdlog.lua"
include "dependencies/openal.lua"
include "dependencies/gainput.lua"
|
-- Physics example.
-- This sample demonstrates:
-- - Creating both static and moving physics objects to a scene
-- - Displaying physics debug geometry
-- - Using the Skybox component for setting up an unmoving sky
-- - Saving a scene to a file and loading it to restore a previous state
require "LuaScripts/Utilities/Sample"
function Start()
-- Execute the common startup for samples
SampleStart()
-- Create the scene content
CreateScene()
-- Create the UI content
CreateInstructions()
-- Setup the viewport for displaying the scene
SetupViewport()
-- Set the mouse mode to use in the sample
SampleInitMouseMode(MM_RELATIVE)
-- Hook up to the frame update and render post-update events
SubscribeToEvents()
end
function CreateScene()
scene_ = Scene()
-- Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
-- Create a physics simulation world with default parameters, which will update at 60fps. Like the Octree must
-- exist before creating drawable components, the PhysicsWorld must exist before creating physics components.
-- Finally, create a DebugRenderer component so that we can draw physics debug geometry
scene_:CreateComponent("Octree")
scene_:CreateComponent("PhysicsWorld")
scene_:CreateComponent("DebugRenderer")
-- Create a Zone component for ambient lighting & fog control
local zoneNode = scene_:CreateChild("Zone")
local zone = zoneNode:CreateComponent("Zone")
zone.boundingBox = BoundingBox(-1000.0, 1000.0)
zone.ambientColor = Color(0.15, 0.15, 0.15)
zone.fogColor = Color(1.0, 1.0, 1.0)
zone.fogStart = 300.0
zone.fogEnd = 500.0
-- Create a directional light to the world. Enable cascaded shadows on it
local lightNode = scene_:CreateChild("DirectionalLight")
lightNode.direction = Vector3(0.6, -1.0, 0.8)
local light = lightNode:CreateComponent("Light")
light.lightType = LIGHT_DIRECTIONAL
light.castShadows = true
light.shadowBias = BiasParameters(0.00025, 0.5)
-- Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8)
-- Create skybox. The Skybox component is used like StaticModel, but it will be always located at the camera, giving the
-- illusion of the box planes being far away. Use just the ordinary Box model and a suitable material, whose shader will
-- generate the necessary 3D texture coordinates for cube mapping
local skyNode = scene_:CreateChild("Sky")
skyNode:SetScale(500.0) -- The scale actually does not matter
local skybox = skyNode:CreateComponent("Skybox")
skybox.model = cache:GetResource("Model", "Models/Box.mdl")
skybox.material = cache:GetResource("Material", "Materials/Skybox.xml")
-- Create a floor object, 1000 x 1000 world units. Adjust position so that the ground is at zero Y
local floorNode = scene_:CreateChild("Floor")
floorNode.position = Vector3(0.0, -0.5, 0.0)
floorNode.scale = Vector3(1000.0, 1.0, 1000.0)
local floorObject = floorNode:CreateComponent("StaticModel")
floorObject.model = cache:GetResource("Model", "Models/Box.mdl")
floorObject.material = cache:GetResource("Material", "Materials/StoneTiled.xml")
-- Make the floor physical by adding RigidBody and CollisionShape components. The RigidBody's default
-- parameters make the object static (zero mass.) Note that a CollisionShape by itself will not participate
-- in the physics simulation
local body = floorNode:CreateComponent("RigidBody")
local shape = floorNode:CreateComponent("CollisionShape")
-- Set a box shape of size 1 x 1 x 1 for collision. The shape will be scaled with the scene node scale, so the
-- rendering and physics representation sizes should match (the box model is also 1 x 1 x 1.)
shape:SetBox(Vector3(1.0, 1.0, 1.0))
-- Create a pyramid of movable physics objects
for y = 0, 7 do
for x = -y, y do
local boxNode = scene_:CreateChild("Box")
boxNode.position = Vector3(x, -y + 8.0, 0.0)
local boxObject = boxNode:CreateComponent("StaticModel")
boxObject.model = cache:GetResource("Model", "Models/Box.mdl")
boxObject.material = cache:GetResource("Material", "Materials/StoneEnvMapSmall.xml")
boxObject.castShadows = true
-- Create RigidBody and CollisionShape components like above. Give the RigidBody mass to make it movable
-- and also adjust friction. The actual mass is not important only the mass ratios between colliding
-- objects are significant
local body = boxNode:CreateComponent("RigidBody")
body.mass = 1.0
body.friction = 0.75
local shape = boxNode:CreateComponent("CollisionShape")
shape:SetBox(Vector3(1.0, 1.0, 1.0))
end
end
-- Create the camera. Set far clip to match the fog. Note: now we actually create the camera node outside
-- the scene, because we want it to be unaffected by scene load / save
cameraNode = Node()
local camera = cameraNode:CreateComponent("Camera")
camera.farClip = 500.0
-- Set an initial position for the camera scene node above the floor
cameraNode.position = Vector3(0.0, 5.0, -20.0)
end
function CreateInstructions()
-- Construct new Text object, set string to display and font to use
local instructionText = ui.root:CreateChild("Text")
instructionText:SetText("Use WASD keys and mouse to move\n"..
"LMB to spawn physics objects\n"..
"F5 to save scene, F7 to load\n"..
"Space to toggle physics debug geometry")
instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
-- The text has multiple rows. Center them in relation to each other
instructionText.textAlignment = HA_CENTER
-- Position the text relative to the screen center
instructionText.horizontalAlignment = HA_CENTER
instructionText.verticalAlignment = VA_CENTER
instructionText:SetPosition(0, ui.root.height / 4)
end
function SetupViewport()
-- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera"))
renderer:SetViewport(0, viewport)
end
function SubscribeToEvents()
-- Subscribe HandleUpdate() function for processing update events
SubscribeToEvent("Update", "HandleUpdate")
-- Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
-- debug geometry
SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate")
end
function MoveCamera(timeStep)
-- Do not move if the UI has a focused element (the console)
if ui.focusElement ~= nil then
return
end
-- Movement speed as world units per second
local MOVE_SPEED = 20.0
-- Mouse sensitivity as degrees per pixel
local MOUSE_SENSITIVITY = 0.1
-- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
local mouseMove = input.mouseMove
yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x
pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y
pitch = Clamp(pitch, -90.0, 90.0)
-- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
cameraNode.rotation = Quaternion(pitch, yaw, 0.0)
-- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
if input:GetKeyDown(KEY_W) then
cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_S) then
cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_A) then
cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_D) then
cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
end
-- "Shoot" a physics object with left mousebutton
if input:GetMouseButtonPress(MOUSEB_LEFT) then
SpawnObject()
end
-- Check for loading/saving the scene. Save the scene to the file Data/Scenes/Physics.xml relative to the executable
-- directory
if input:GetKeyPress(KEY_F5) then
scene_:SaveXML(fileSystem:GetProgramDir().."Data/Scenes/Physics.xml")
end
if input:GetKeyPress(KEY_F7) then
scene_:LoadXML(fileSystem:GetProgramDir().."Data/Scenes/Physics.xml")
end
-- Toggle debug geometry with space
if input:GetKeyPress(KEY_SPACE) then
drawDebug = not drawDebug
end
end
function SpawnObject()
-- Create a smaller box at camera position
local boxNode = scene_:CreateChild("SmallBox")
boxNode.position = cameraNode.position
boxNode.rotation = cameraNode.rotation
boxNode:SetScale(0.25)
local boxObject = boxNode:CreateComponent("StaticModel")
boxObject.model = cache:GetResource("Model", "Models/Box.mdl")
boxObject.material = cache:GetResource("Material", "Materials/StoneEnvMapSmall.xml")
boxObject.castShadows = true
-- Create physics components, use a smaller mass also
local body = boxNode:CreateComponent("RigidBody")
body.mass = 0.25
body.friction = 0.75
local shape = boxNode:CreateComponent("CollisionShape")
shape:SetBox(Vector3(1.0, 1.0, 1.0))
local OBJECT_VELOCITY = 10.0
-- Set initial velocity for the RigidBody based on camera forward vector. Add also a slight up component
-- to overcome gravity better
body.linearVelocity = cameraNode.rotation * Vector3(0.0, 0.25, 1.0) * OBJECT_VELOCITY
end
function HandleUpdate(eventType, eventData)
-- Take the frame time step, which is stored as a float
local timeStep = eventData["TimeStep"]:GetFloat()
-- Move the camera, scale movement with time step
MoveCamera(timeStep)
end
function HandlePostRenderUpdate(eventType, eventData)
-- If draw debug mode is enabled, draw physics debug geometry. Use depth test to make the result easier to interpret
-- Note the convenience accessor to the physics world component
if drawDebug then
scene_:GetComponent("PhysicsWorld"):DrawDebugGeometry(true)
end
end
-- Create XML patch instructions for screen joystick layout specific to this sample app
function GetScreenJoystickPatchString()
return
"<patch>" ..
" <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" ..
" <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Spawn</replace>" ..
" <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" ..
" <element type=\"Text\">" ..
" <attribute name=\"Name\" value=\"MouseButtonBinding\" />" ..
" <attribute name=\"Text\" value=\"LEFT\" />" ..
" </element>" ..
" </add>" ..
" <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" ..
" <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Debug</replace>" ..
" <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" ..
" <element type=\"Text\">" ..
" <attribute name=\"Name\" value=\"KeyBinding\" />" ..
" <attribute name=\"Text\" value=\"SPACE\" />" ..
" </element>" ..
" </add>" ..
"</patch>"
end
|
testfiledir = "testfiles-dvips"
-- resultdir = builddir .. "/result/dvips"
checkengines = {"latexdvips"}
stdengine = "latexdvips"
-- ps2pdfopt = " -sDocumentUUID=DocumentUUID -sInstanceUUID=InstanceUUID -dCompressStreams=false -dCompressPages=false -dNOSAFER "
ps2pdfopt = " -dNOSAFER "
|
angleScale = 0.5
max_fov = 360
max_vfov = 360
onload = "f_fov 180"
function lens_inverse(x,y)
local r = sqrt(x*x+y*y)
local theta = atan(r)/angleScale
local s = sin(theta)
return x/r*s, y/r*s, cos(theta)
end
function lens_forward(x,y,z)
local theta = acos(z)
local r = tan(theta*angleScale)
local c = r/sqrt(x*x+y*y)
return x*c, y*c
end
|
return {
{
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "damageRatioBullet",
number = 0.15
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "damageRatioBullet",
number = 0.166
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "damageRatioBullet",
number = 0.182
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "damageRatioBullet",
number = 0.198
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "damageRatioBullet",
number = 0.214
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "damageRatioBullet",
number = 0.23
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "damageRatioBullet",
number = 0.246
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "damageRatioBullet",
number = 0.264
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "damageRatioBullet",
number = 0.282
}
}
}
},
{
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "damageRatioBullet",
number = 0.3
}
}
}
},
time = 20,
name = "室内系女仆",
init_effect = "jinengchufared",
color = "yellow",
picture = "",
desc = "",
stack = 1,
id = 105052,
icon = 105050,
last_effect = "",
blink = {
1,
0,
0,
0.3,
0.3
},
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach",
"onRemove"
},
arg_list = {
attr = "damageRatioBullet",
number = 0.15
}
}
}
}
|
--
-- a simple mainMenu
--
local mainMenu = {}
local Slab = require 'lib.slab'
local movieState = require("state.movie")
local nyiState = require("state.nyi")
function mainMenu:init()
print("mainMenu:init()")
love.graphics.setBackgroundColor(0, 0, 0)
Slab.SetINIStatePath(nil)
Slab.Initialize()
self.imgMonster = love.graphics.newImage("assets/monster.png")
end
function mainMenu:enter() print("mainMenu:enter()") end
function mainMenu:update(dt)
Slab.Update(dt)
Slab.BeginWindow("mainMenu", {
Title = "Movie Monsters",
X = love.graphics.getWidth() / 2 - 275,
Y = love.graphics.getHeight() / 2 - 150,
W = 550,
H = 300,
AllowMove = false,
AutoSizeWindow = false,
ShowMinimize = false
})
Slab.BeginLayout("mainMenu-layout", {
AlignX = "center",
AlignY = "center",
AlignRowY = "center",
ExpandW = false,
Columns = 2
})
do
Slab.SetLayoutColumn(1)
Slab.Image("monster", {Image = self.imgMonster})
Slab.SetLayoutColumn(2)
do
local params = {W = 150, H = 50}
if Slab.Button("Enter Movie", params) then
GameState.push(movieState)
end
if Slab.Button("Ticket Booth", params) then
GameState.push(nyiState)
end
if Slab.Button("Box Office", params) then
GameState.push(nyiState)
end
if Slab.Button("Manager's Office", params) then
GameState.push(nyiState)
end
if Slab.Button("Quit", params) then love.event.quit() end
end
end
Slab.EndLayout()
Slab.EndWindow()
end
function mainMenu:draw() Slab.Draw() end
function mainMenu:keypressed(key) if key == "escape" then love.event.quit() end end
function mainMenu:quit() print("mainMenu:quit()") end
return mainMenu
|
-- "Nametag" [nametag]
-- Copyright (c) 2015 BlockMen <blockmen2015@gmail.com>
--
-- init.lua
--
-- This software is provided 'as-is', without any express or implied warranty. In no
-- event will the authors be held liable for any damages arising from the use of
-- this software.
--
-- Permission is granted to anyone to use this software for any purpose, including
-- commercial applications, and to alter it and redistribute it freely, subject to the
-- following restrictions:
--
-- 1. The origin of this software must not be misrepresented; you must not
-- claim that you wrote the original software. If you use this software in a
-- product, an acknowledgment in the product documentation is required.
-- 2. Altered source versions must be plainly marked as such, and must not
-- be misrepresented as being the original software.
-- 3. This notice may not be removed or altered from any source distribution.
--
local current_obj = {}
local current_stack = {}
local function set_nametag(self, clicker)
if self and self.object and clicker then
if self.object:is_player() then
core.chat_send_player(clicker:get_player_name(), "You can't rename players, sorry.")
return false
end
local item = clicker:get_wielded_item()
if item then
local name = item:get_name()
if name == "nametag:tag" then
local player_name = clicker:get_player_name()
current_obj[player_name] = self
current_stack[player_name] = item
--show formspec
local formspec = "size[8,8]" .. default.gui_bg ..
"field[0.5,1;7.5,0;name;Name:;]" ..
"button_exit[2.5,7.5;3,1;save_name;Save name]"
core.show_formspec(player_name, "nametag_name_obj", formspec)
return true
end
end
else
if clicker then
core.chat_send_player(clicker:get_player_name(), "You can't name this object, sorry.")
end
end
end
local function getentities()
for a,b in pairs(core.registered_entities) do
local org = table.copy(b)
b.on_activate = function(self, staticdata, dtime_s)
local new_stats
if staticdata then
new_stats = core.deserialize(staticdata)
end
if new_stats and new_stats.flag then
if new_stats.nametag then
self.nametag = new_stats.nametag
end
end
if self.object and self.nametag and self.nametag ~= "" then
self.object:set_properties({nametag = self.nametag, nametag_color = "#FFFF00"})
end
if org.on_activate then
return org.on_activate(self, (new_stats and new_stats.org) or "", dtime_s)
end
end
b.on_rightclick = function(self, clicker)
local retval = set_nametag(self, clicker)
if retval then
return
end
if org.on_rightclick then
org.on_rightclick(self, clicker)
end
end
b.get_staticdata = function(self)
local retval
local tab = {}
if org.get_staticdata then
retval = org.get_staticdata(self)
end
if retval then
tab.org = retval
else
tab.org = {}
end
-- insert own data
tab.nametag = self.nametag
tab.flag = "yes"
return core.serialize(tab)
end
end
end
core.register_craftitem("nametag:tag", {
description = "Nametag",
inventory_image = "nametag_tag.png",
liquids_pointable = false
})
core.register_craft({
type = "shapeless",
output = "nametag:tag",
recipe = {"default:paper", "default:coal_lump"},
})
core.register_on_player_receive_fields(function(player, form_name, fields)
if form_name ~= "nametag_name_obj" or not fields.save_name or fields.name == "" then
return
end
local name = player:get_player_name()
local obj = current_obj[name]
if obj and obj.object then
obj.object:set_properties({nametag = fields.name, nametag_color = "#FFFF00"})
obj.nametag = fields.name
current_obj[name] = nil
if not core.setting_getbool("creative_mode") then
local itemstack = current_stack[name]
itemstack:take_item()
player:set_wielded_item(itemstack)
end
current_stack[name] = nil
end
end)
core.after(0.1, getentities)
|
local collision_mask_util_extended = require("__Constructron-Continued__.data.collision-mask-util-extended")
local pathing_collision_mask = {
"water-tile",
"colliding-with-tiles-only",
"not-colliding-with-itself"
}
if mods["space-exploration"] then
local spaceship_collision_layer = collision_mask_util_extended.get_named_collision_mask("moving-tile")
table.insert(pathing_collision_mask, spaceship_collision_layer)
if not settings.startup["enable_rocket_powered_constructron"].value then
local empty_space_collision_layer = collision_mask_util_extended.get_named_collision_mask("empty-space-tile")
table.insert(pathing_collision_mask, empty_space_collision_layer)
end
end
local template_entity = {
type = "simple-entity",
icon = "__core__/graphics/empty.png",
icon_size = 1,
icon_mipmaps = 0,
flags = {"placeable-neutral", "not-on-map"},
order = "z",
max_health = 1,
render_layer = "object",
collision_mask = pathing_collision_mask,
pictures = {
{
filename = "__core__/graphics/empty.png",
width = 1,
height = 1
}
}
}
local template_item = {
type = "item",
flags = {
"hidden"
},
name = "constructron_pathing_dummy",
icon = "__core__/graphics/empty.png",
icon_size = 1,
order = "z",
stack_size = 1
}
for _, size in pairs({12, 8, 6, 4, 2, 1}) do
local proxy_entity = table.deepcopy(template_entity)
proxy_entity.collision_box = {{-size / 2, -size / 2}, {size / 2, size / 2}}
proxy_entity.selection_box = {{-size / 2, -size / 2}, {size / 2, size / 2}}
proxy_entity.name = "constructron_pathing_proxy_" .. size
local proxy_item = table.deepcopy(template_item)
proxy_item.name = "constructron_pathing_proxy_" .. size
proxy_item.place_result = "constructron_pathing_proxy_" .. size
data:extend({proxy_entity, proxy_item})
end
|
local http = require "http"
local shortport = require "shortport"
local stdnse = require "stdnse"
local string = require "string"
local openssl = require "openssl"
local ls = require "ls"
description = [[
Shows the content of an "index" Web page.
TODO:
- add support for more page formats
]]
author = "Pierre Lalet"
license = "Same as Nmap--See http://nmap.org/book/man-legal.html"
categories = {"default", "discovery", "safe"}
---
-- @usage
-- nmap -n -p 80 --script http-ls test-debit.free.fr
--
-- @args http-ls.checksum compute a checksum for each listed file
-- (default: false)
-- @args http-ls.url base URL path to use (default: /)
--
-- @output
-- PORT STATE SERVICE
-- 80/tcp open http
-- | http-ls:
-- | Volume /
-- | maxfiles limit reached (10)
-- | SIZE TIME FILENAME
-- | 524288 02-Oct-2013 18:26 512.rnd
-- | 1048576 02-Oct-2013 18:26 1024.rnd
-- | 2097152 02-Oct-2013 18:26 2048.rnd
-- | 4194304 02-Oct-2013 18:26 4096.rnd
-- | 8388608 02-Oct-2013 18:26 8192.rnd
-- | 16777216 02-Oct-2013 18:26 16384.rnd
-- | 33554432 02-Oct-2013 18:26 32768.rnd
-- | 67108864 02-Oct-2013 18:26 65536.rnd
-- | 1073741824 03-Oct-2013 16:46 1048576.rnd
-- | 188 03-Oct-2013 17:15 README.html
-- |_
--
-- @xmloutput
-- <table key="volumes">
-- <table>
-- <elem key="volume">/</elem>
-- <table key="files">
-- <table>
-- <elem key="size">524288</elem>
-- <elem key="time">02-Oct-2013 18:26</elem>
-- <elem key="filename">512.rnd</elem>
-- </table>
-- <table>
-- <elem key="size">1048576</elem>
-- <elem key="time">02-Oct-2013 18:26</elem>
-- <elem key="filename">1024.rnd</elem>
-- </table>
-- <table>
-- <elem key="size">2097152</elem>
-- <elem key="time">02-Oct-2013 18:26</elem>
-- <elem key="filename">2048.rnd</elem>
-- </table>
-- <table>
-- <elem key="size">4194304</elem>
-- <elem key="time">02-Oct-2013 18:26</elem>
-- <elem key="filename">4096.rnd</elem>
-- </table>
-- <table>
-- <elem key="size">8388608</elem>
-- <elem key="time">02-Oct-2013 18:26</elem>
-- <elem key="filename">8192.rnd</elem>
-- </table>
-- <table>
-- <elem key="size">16777216</elem>
-- <elem key="time">02-Oct-2013 18:26</elem>
-- <elem key="filename">16384.rnd</elem>
-- </table>
-- <table>
-- <elem key="size">33554432</elem>
-- <elem key="time">02-Oct-2013 18:26</elem>
-- <elem key="filename">32768.rnd</elem>
-- </table>
-- <table>
-- <elem key="size">67108864</elem>
-- <elem key="time">02-Oct-2013 18:26</elem>
-- <elem key="filename">65536.rnd</elem>
-- </table>
-- <table>
-- <elem key="size">1073741824</elem>
-- <elem key="time">03-Oct-2013 16:46</elem>
-- <elem key="filename">1048576.rnd</elem>
-- </table>
-- <table>
-- <elem key="size">188</elem>
-- <elem key="time">03-Oct-2013 17:15</elem>
-- <elem key="filename">README.html</elem>
-- </table>
-- </table>
-- <table key="info">
-- <elem>maxfiles limit reached (10)</elem>
-- </table>
-- </table>
-- </table>
-- <table key="total">
-- <elem key="files">10</elem>
-- <elem key="bytes">1207435452</elem>
-- </table>
portrule = shortport.http
local function isdir(fname, size)
-- we consider a file is (probably) a directory if its name
-- terminates with a '/' or if the string representing its size is
-- either empty or a single dash ('-').
if string.sub(fname, -1, -1) == '/' then
return true
end
if size == '' or size == '-' then
return true
end
return false
end
local function list_files(host, port, url, output, maxdepth, basedir)
basedir = basedir or ""
local resp = http.get(host, port, url)
if resp.location or not resp.body then
return true
end
if not string.match(resp.body, "<[Tt][Ii][Tt][Ll][Ee][^>]*> *[Ii][Nn][Dd][Ee][Xx] +[Oo][Ff]") then
return true
end
local patterns = {
'<[Aa] [Hh][Rr][Ee][Ff]="([^"]+)">[^<]+</[Aa]></[Tt][Dd]><[Tt][Dd][^>]*> *([0-9]+-[A-Za-z0-9]+-[0-9]+ [0-9]+:[0-9]+) *</[Tt][Dd]><[Tt][Dd][^>]*> *([^<]+)</[Tt][Dd]>',
'<[Aa] [Hh][Rr][Ee][Ff]="([^"]+)">[^<]+</[Aa]> *([0-9]+-[A-Za-z0-9]+-[0-9]+ [0-9]+:[0-9]+) *([^ \r\n]+)',
}
for _, pattern in ipairs(patterns) do
for fname, date, size in string.gmatch(resp.body, pattern) do
local continue = true
local directory = isdir(fname, size)
if ls.config('checksum') and not directory then
local checksum = ""
local resp = http.get(host, port, url .. fname)
if not resp.location and resp.body then
checksum = stdnse.tohex(openssl.sha1(resp.body))
end
continue = ls.add_file(output, {size, date, basedir .. fname, checksum})
else
continue = ls.add_file(output, {size, date, basedir .. fname})
end
if not continue then
return false
end
if directory then
if string.sub(fname, -1, -1) ~= "/" then fname = fname .. '/' end
continue = true
if maxdepth > 0 then
continue = list_files(host, port, url .. fname, output, maxdepth - 1,
basedir .. fname)
elseif maxdepth < 0 then
continue = list_files(host, port, url .. fname, output, -1,
basedir .. fname)
end
if not continue then
return false
end
end
end
end
return true
end
action = function(host, port)
local url = stdnse.get_script_args(SCRIPT_NAME .. '.url') or "/"
local output = ls.new_listing()
ls.new_vol(output, url, false)
local continue = list_files(host, port, url, output, ls.config('maxdepth'))
if not continue then
ls.report_info(
output,
string.format("maxfiles limit reached (%d)", ls.config('maxfiles')))
end
ls.end_vol(output)
return ls.end_listing(output)
end
|
-----------------------------------------
-- ID: 5067
-- Scroll of Water Threnody
-- Teaches the song Water Threnody
-----------------------------------------
function onItemCheck(target)
return target:canLearnSpell(459)
end
function onItemUse(target)
target:addSpell(459)
end |
--Avatar frames which also includes current additive %score, mods, and the song stepsttype/difficulty.
local t = Def.ActorFrame{
Name="Avatars";
};
local bareBone = isBareBone()
local profileP1
local profileP2
local profileNameP1 = "No Profile"
local profileNameP2 = "No Profile"
local AvatarXP1 = 0
local AvatarYP1 = SCREEN_HEIGHT-50
local AvatarXP2 = SCREEN_WIDTH-50
local AvatarYP2 = SCREEN_HEIGHT-50
local avatarPosition = {
PlayerNumber_P1 = {
X = 0,
Y = SCREEN_HEIGHT-50
},
PlayerNumber_P2 = {
X = SCREEN_WIDTH-50,
Y = SCREEN_HEIGHT-50
}
}
local function avatarFrame(pn)
local t = Def.ActorFrame{
InitCommand = function(self)
self:xy(avatarPosition[pn].X,avatarPosition[pn].Y)
end;
}
local profile = GetPlayerOrMachineProfile(pn)
t[#t+1] = Def.Quad {
InitCommand = function(self)
if pn == PLAYER_1 then
self:zoomto(200,50):faderight(0.7)
self:halign(0):valign(0)
else
self:x(50):zoomto(200,50):fadeleft(0.7)
self:halign(1):valign(0)
end
self:queuecommand('Set')
end;
SetCommand=function(self)
local steps = GAMESTATE:GetCurrentSteps(pn);
local diff = steps:GetDifficulty()
self:diffuse(getDifficultyColor(diff))
self:diffusealpha(0.7)
end;
CurrentSongChangedMessageCommand = function(self) self:queuecommand('Set') end;
}
t[#t+1] = Def.Sprite {
InitCommand = function(self)
self:halign(0):valign(0):zoomto(50,50)
end,
Texture=LoadModule("Options.GetProfileData.lua")(pn)["Image"]
};
t[#t+1] = LoadFont("Common Normal") .. {
InitCommand= function(self)
local name = profile:GetDisplayName()
if pn == PLAYER_1 then
self:xy(53,7):zoom(0.6):shadowlength(1):halign(0):maxwidth(180/0.6)
else
self:xy(-3,7):zoom(0.6):shadowlength(1):halign(1):maxwidth(180/0.6)
end
self:settext(name.." 0.00%")
end;
SetCommand=function(self)
local temp1 = getCurScoreST(pn,0)
local temp2 = getMaxScoreST(pn,0)
temp2 = math.max(temp2,1)
self:settextf("%s %.2f%%",profile:GetDisplayName(),math.floor((temp1/temp2)*10000)/100)
end;
JudgmentMessageCommand = function(self) self:queuecommand('Set') end;
};
t[#t+1] = LoadFont("Common Normal") .. {
InitCommand = function(self)
if pn == PLAYER_1 then
self:xy(53,20):zoom(0.4):halign(0):maxwidth(180/0.4)
self:shadowlength(1)
else
self:xy(-3,20):zoom(0.4):halign(1):maxwidth(180/0.4)
self:shadowlength(1)
end
end;
BeginCommand = function(self) self:queuecommand('Set') end;
SetCommand=function(self)
local steps = GAMESTATE:GetCurrentSteps(pn);
local diff = getDifficulty(steps:GetDifficulty())
local meter = steps:GetMeter()
local stype = ToEnumShortString(steps:GetStepsType()):gsub("%_"," ")
self:settext(stype.." "..diff.." "..meter)
end;
CurrentSongChangedMessageCommand = function(self) self:queuecommand('Set') end;
};
t[#t+1] = LoadFont("Common Normal") .. {
InitCommand = function(self)
if pn == PLAYER_1 then
self:xy(53,32):zoom(0.4):halign(0):maxwidth(180/0.4)
self:shadowlength(1)
else
self:xy(-3,32):zoom(0.4):halign(1):maxwidth(180/0.4)
self:shadowlength(1)
end
end;
BeginCommand = function(self) self:queuecommand('Set') end;
SetCommand=function(self)
self:settext(GAMESTATE:GetPlayerState(pn):GetPlayerOptionsString('ModsLevel_Current'))
end;
};
return t
end
local function bareBoneFrame(pn)
local profile = GetPlayerOrMachineProfile(pn)
local name = profile:GetDisplayName()
local t = Def.ActorFrame{
InitCommand = function(self)
self:xy(avatarPosition[pn].X,avatarPosition[pn].Y)
end;
}
t[#t+1] = LoadFont("Common Normal") .. {
InitCommand = function(self)
if pn == PLAYER_1 then
self:xy(3,7):halign(0)
else
self:xy(-3,7):halign(1)
end
self:zoom(0.6):maxwidth(180/0.4)
end;
BeginCommand = function(self) self:queuecommand('Set') end;
SetCommand=function(self)
local temp1 = getCurScoreST(pn,0)
local temp2 = getMaxScoreST(pn,0)
temp2 = math.max(temp2,1)
self:settextf("%s %.2f%%",name,math.floor((temp1/temp2)*10000)/100)
end;
JudgmentMessageCommand = function(self) self:queuecommand('Set') end;
};
t[#t+1] = LoadFont("Common Normal") .. {
InitCommand = function(self)
if pn == PLAYER_1 then
self:xy(3,20):halign(0)
else
self:xy(-3,20):halign(1)
end
self:zoom(0.4):maxwidth(180/0.4)
end;
BeginCommand = function(self) self:queuecommand('Set') end;
SetCommand=function(self)
local steps = GAMESTATE:GetCurrentSteps(pn);
local diff = getDifficulty(steps:GetDifficulty())
local meter = steps:GetMeter()
local stype = ToEnumShortString(steps:GetStepsType()):gsub("%_"," ")
self:settext(stype.." "..diff.." "..meter)
end;
CurrentSongChangedMessageCommand = function(self) self:queuecommand('Set') end;
};
t[#t+1] = LoadFont("Common Normal") .. {
InitCommand = function(self)
if pn == PLAYER_1 then
self:xy(3,32):halign(0)
else
self:xy(-3,32):halign(1)
end
self:zoom(0.4):maxwidth(180/0.4)
end;
BeginCommand = function(self) self:queuecommand('Set') end;
SetCommand=function(self)
self:settext(GAMESTATE:GetPlayerState(pn):GetPlayerOptionsString('ModsLevel_Current'))
end;
};
return t
end
for _,pn in pairs(GAMESTATE:GetEnabledPlayers()) do
if bareBone then
t[#t+1] = bareBoneFrame(pn)
else
t[#t+1] = avatarFrame(pn)
end
end
return t; |
local BaseService = require "kong.cli.services.base_service"
local logger = require "kong.cli.utils.logger"
local IO = require "kong.tools.io"
local Dnsmasq = BaseService:extend()
local SERVICE_NAME = "dnsmasq"
function Dnsmasq:new(configuration)
self._configuration = configuration
Dnsmasq.super.new(self, SERVICE_NAME, self._configuration.nginx_working_dir)
end
function Dnsmasq:prepare()
return Dnsmasq.super.prepare(self, self._configuration.nginx_working_dir)
end
function Dnsmasq:start()
if self._configuration.dns_resolver.dnsmasq then
if self:is_running() then
return nil, SERVICE_NAME.." is already running"
end
local cmd, err = Dnsmasq.super._get_cmd(self)
if err then
return nil, err
end
-- dnsmasq always listens on the local 127.0.0.1 address
local res, code = IO.os_execute(cmd.." -p "..self._configuration.dns_resolver.port.." --pid-file="..self._pid_file_path.." -N -o --listen-address=127.0.0.1")
if code == 0 then
while not self:is_running() do
-- Wait for PID file to be created
end
setmetatable(self._configuration.dns_resolver, require "kong.tools.printable")
logger:info(string.format([[dnsmasq............%s]], tostring(self._configuration.dns_resolver)))
return true
else
return nil, res
end
end
return true
end
function Dnsmasq:stop()
if self._configuration.dns_resolver.dnsmasq then
Dnsmasq.super.stop(self, true) -- Killing dnsmasq just with "kill PID" apparently doesn't terminate it
end
end
return Dnsmasq |
--接受nginx变量
local var = ngx.var
ngx.say("ngx.var.a : ", var.a, "<br/>")
ngx.say("ngx.var.b : ", var.b, "<br/>")
ngx.say("ngx.var[2] : ", var[2], "<br/>")
ngx.var.b = 2;
ngx.say("<br/>")
--请求头
local headers = ngx.req.get_headers()
ngx.say("headers begin", "<br/>")
ngx.say("Host : ", headers["Host"], "<br/>")
ngx.say("user-agent : ", headers["user-agent"], "<br/>")
ngx.say("user-agent : ", headers.user_agent, "<br/>")
ngx.say("user-agent : ", ngx.req.get_headers("user-agent"), "<br/>")
for k,v in pairs(headers) do
if type(v) == "table" then
ngx.say(k, " : ", table.concat(v, ","), "<br/>")
else
ngx.say(k, " : ", v, "<br/>")
end
end
ngx.say("headers end", "<br/>")
ngx.say("<br/>")
--get请求uri参数
ngx.say("uri args begin", "<br/>")
local uri_args = ngx.req.get_uri_args()
for k, v in pairs(uri_args) do
if type(v) == "table" then
ngx.say(k, " : ", table.concat(v, ", "), "<br/>")
else
ngx.say(k, ": ", v, "<br/>")
end
end
ngx.say("uri args end", "<br/>")
ngx.say("<br/>")
--post请求参数
ngx.req.read_body()
ngx.say("post args begin", "<br/>")
local post_args = ngx.req.get_post_args()
for k, v in pairs(post_args) do
if type(v) == "table" then
ngx.say(k, " : ", table.concat(v, ", "), "<br/>")
else
ngx.say(k, ": ", v, "<br/>")
end
end
ngx.say("post args end", "<br/>")
ngx.say("<br/>")
--请求的http协议版本
ngx.say("ngx.req.http_version : ", ngx.req.http_version(), "<br/>")
--请求方法
ngx.say("ngx.req.get_method : ", ngx.req.get_method(), "<br/>")
--原始的请求头内容
ngx.say("ngx.req.raw_header : ", ngx.req.raw_header(), "<br/>")
--请求的body内容体
ngx.say("ngx.req.get_body_data() : ", ngx.req.get_body_data(), "<br/>")
ngx.say("<br/>")
--[[
执行结果:
root@tinywan:/opt/openresty/nginx/conf# curl http://127.0.0.1/lua_request/123/890
ngx.var.a : 123<br/>
ngx.var.b : 127.0.0.1<br/>
ngx.var[2] : 890<br/>
<br/>
headers begin<br/>
Host : 127.0.0.1<br/>
user-agent : curl/7.47.0<br/>
user-agent : curl/7.47.0<br/>
host : 127.0.0.1<br/>
accept : */*<br/>
user-agent : curl/7.47.0<br/>
headers end<br/>
<br/>
uri args begin<br/>
uri args end<br/>
<br/>
post args begin<br/>
post args end<br/>
<br/>
ngx.req.http_version : 1.1<br/>
ngx.req.get_method : GET<br/>
ngx.req.raw_header : GET /lua_request/123/890 HTTP/1.1
Host: 127.0.0.1
User-Agent: curl/7.47.0
Accept: */*
<br/>
ngx.req.get_body_data() : nil<br/>
<br/>
ngx.var.b 2
--]] |
if SERVER then
AddCSLuaFile("shared.lua")
end
if CLIENT then
SWEP.Slot = 0
SWEP.SlotPos = 1
SWEP.DrawAmmo = false
SWEP.PrintName = "Position Utility"
SWEP.DrawCrosshair = true
end
SWEP.PrintName = "Position Utility"
SWEP.AdminSpawnable = true
SWEP.Spawnable = true
SWEP.Author = "Azzen"
SWEP.Instructions = ""
SWEP.ViewModel = "models/weapons/v_grenade.mdl"
SWEP.WorldModel = "models/weapons/w_grenade.mdl"
SWEP.Primary.Delay = 1
SWEP.Primary.ClipSize = -1
SWEP.Primary.DefaultClip = 0
SWEP.Primary.Automatic = false
SWEP.Primary.Ammo = ""
SWEP.Secondary.Delay = 1
SWEP.Secondary.ClipSize = -1
SWEP.Secondary.DefaultClip = 0
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = ""
function SWEP:Initialize()
self:SetWeaponHoldType("normal")
end
function SWEP:PrimaryAttack()
if CLIENT and IsFirstTimePredicted() then
SetClipboardText(self.Owner:GetPos():VecToString())
ClientsideNotify("Copied Vector to clipboard.")
end
end
function SWEP:SecondaryAttack()
if CLIENT and IsFirstTimePredicted() then
SetClipboardText(self.Owner:GetAngles():AngToString())
ClientsideNotify("Copied Angles to clipboard.")
end
end
function SWEP:DrawHUD()
draw.RoundedBox(5, ScrW() * .5 - 380 / 2, ScrH() * .84, 380, 58, Color(12, 12, 12, 175))
local ac_viewangles = self.Owner:GetAngles():AngToString()
local ac_pos = self.Owner:GetPos():VecToString()
draw.DrawText("Actual Position: " .. ac_pos .. "\nActual Angles: " .. ac_viewangles, "VBFONT_HUDNORMAL", ScrW() * .5 - 380 / 2 + 5, ScrH() * .85, Color(255, 255, 255, 255))
end
function SWEP:Think()
end
function SWEP:Deploy()
return true
end
function SWEP:Holster()
return true
end
function SWEP:OnRemove()
end
function SWEP:OnRestore()
end
function SWEP:Precache()
end
function SWEP:OwnerChanged()
end |
------------
--- HTTP NG module
-- Implements HTTP client.
-- @module http_ng
--- HTTP Client
-- @type HTTP
local type = type
local unpack = unpack
local assert = assert
local tostring = tostring
local setmetatable = setmetatable
local getmetatable = getmetatable
local rawset = rawset
local upper = string.upper
local rawget = rawget
local pack = table.pack
local next = next
local pairs = pairs
local concat = table.concat
local resty_backend = require 'resty.http_ng.backend.resty'
local json = require 'cjson'
local request = require 'resty.http_ng.request'
local resty_url = require 'resty.url'
local DEFAULT_PATH = ''
local http = { request = request }
local function merge(...)
local all = pack(...)
if #all == 1 then return all[next(all)] end
local res
for i = 1, all.n do
local t = all[i]
if type(t) == 'table' then
res = res or setmetatable({}, getmetatable(t))
for k,v in pairs(t) do
res[k] = merge(res[k], v)
end
elseif type(t) ~= 'nil' then
res = t
end
end
return res
end
local function get_request_params(method, client, url, options)
local opts = {}
local scheme, user, pass, host, port, path = unpack(assert(resty_url.split(url)))
if port then host = concat({host, port}, ':') end
opts.headers = {}
opts.headers.host = host
if user or pass then
opts.headers.authorization = "Basic " .. ngx.encode_base64(concat({ user or '', pass or '' }, ':'))
end
return {
url = concat({ scheme, '://', host, path or DEFAULT_PATH }, ''),
method = method,
options = merge(opts, rawget(client, 'options'), options),
client = client,
serializer = client.serializer or http.serializers.default
}
end
http.method = function(method, client)
assert(method)
assert(client)
return function(url, options)
if type(url) == 'table' and not options then
options = url
url = unpack(url)
end
assert(url, 'url as first parameter is required')
local req_params = get_request_params(method, client, url, options)
local req = http.request.new(req_params)
return client.backend:send(req)
end
end
http.method_with_body = function(method, client)
assert(method)
assert(client)
return function(url, body, options)
if type(url) == 'table' and not body and not options then
options = url
url, body = unpack(url)
end
assert(url, 'url as first parameter is required')
assert(body, 'body as second parameter is required')
local req_params = get_request_params(method, client, url, options)
req_params.body = body
local req = http.request.new(req_params)
return client.backend:send(req)
end
end
--- Make GET request.
-- @param[type=string] url
-- @param[type=options] options
-- @return[type=response] a response
-- @function http.get
http.GET = http.method
--- Make HEAD request.
-- @param[type=string] url
-- @param[type=options] options
-- @return[type=response] a response
-- @function http.head
http.HEAD = http.method
--- Make DELETE request.
-- @param[type=string] url
-- @param[type=options] options
-- @return[type=response] a response
-- @function http.delete
http.DELETE = http.method
--- Make OPTIONS request.
-- @param[type=string] url
-- @param[type=options] options
-- @return[type=response] a response
-- @function http.options
http.OPTIONS = http.method
--- Make PUT request.
-- The **body** is serialized by @{HTTP.urlencoded} unless you used different serializer.
-- @param[type=string] url
-- @param[type=string|table] body
-- @param[type=options] options
-- @return[type=response] a response
-- @function http.put
http.PUT = http.method_with_body
--- Make POST request.
-- The **body** is serialized by @{HTTP.urlencoded} unless you used different serializer.
-- @param[type=string] url
-- @param[type=string|table] body
-- @param[type=options] options
-- @return[type=response] a response
-- @function http.post
http.POST = http.method_with_body
--- Make PATCH request.
-- The **body** is serialized by @{HTTP.urlencoded} unless you used different serializer.
-- @param[type=string] url
-- @param[type=string|table] body
-- @param[type=options] options
-- @return[type=response] a response
-- @function http.patch
http.PATCH = http.method_with_body
http.TRACE = http.method_with_body
http.serializers = {}
--- Urlencoded serializer
-- Serializes your data to `application/x-www-form-urlencoded` format
-- and sets correct Content-Type header.
-- @http HTTP.urlencoded
-- @usage http.urlencoded.post(url, { example = 'table' })
http.serializers.urlencoded = function(req)
req.body = ngx.encode_args(req.body)
req.headers.content_type = req.headers.content_type or 'application/x-www-form-urlencoded'
http.serializers.string(req)
end
http.serializers.string = function(req)
req.body = tostring(req.body)
req.headers['Content-Length'] = #req.body
end
--- JSON serializer
-- Converts the body to JSON unless it is already a string
-- and sets correct Content-Type `application/json`.
-- @http HTTP.json
-- @usage http.json.post(url, { example = 'table' })
-- @see http.post
http.serializers.json = function(req)
if type(req.body) ~= 'string' then
req.body = json.encode(req.body)
end
req.headers.content_type = req.headers.content_type or 'application/json'
http.serializers.string(req)
end
http.serializers.default = function(req)
if req.body then
if type(req.body) ~= 'string' then
http.serializers.urlencoded(req)
else
http.serializers.string(req)
end
end
end
local function add_http_method(client, method)
local m = upper(method)
local cached = rawget(client, m)
if cached then
return cached
end
local generator = http[m]
if generator then
local func = generator(m, client)
rawset(client, m, func)
return func
end
end
local function chain_serializer(client, format)
local serializer = http.serializers[format]
if serializer then
return http.new{ backend = client.backend, serializer = serializer }
end
end
local function generate_client_method(client, method_or_format)
return add_http_method(client, method_or_format) or chain_serializer(client, method_or_format)
end
function http.new(client)
client = client or { }
client.backend = client.backend or resty_backend
return setmetatable(client, { __index = generate_client_method })
end
return http
|
local M = {}
local name = require("game.db.keyNameCfg")
local build_level = require("game.config.build_level")
local function getSqrtV(base,max,cv,v,vb)
if cv > max then return v+vb end
local tw = max-base
local w = cv-base
local ev = w/tw
local er = math.sqrt(ev)
return math.floor(er * v + vb)
end
function M.buildTblSetHero(buildTbl,heroTbl)
local blCfg = build_level[buildTbl.buildId][buildTbl.level]
local attrEnum = blCfg.hero_add_max[1]
local dbHeroTbl = require("game.db.dbHeroTbl")
local heroAttr = dbHeroTbl.getHeroBaseAttr(heroTbl,attrEnum)
local attrMax = blCfg.hero_add_max[2]
local mulMax = blCfg.hero_add_max[3]
local v = getSqrtV(0,attrMax,heroAttr,mulMax,0)
buildTbl.heroAttrMul = math.floor(v)
buildTbl.heroId = heroTbl.heroId
end
function M.buildTblLeftHero(buildTbl)
buildTbl.heroId = 0
buildTbl.heroAttrMul = 0
end
local function getKey(pid,cityId)
return "p"..pid.."_"..name.build.."_"..cityId
end
function M.newBuildTbl(cityId,buildId)
return { buildId = buildId,
cityId=cityId,
heroId = 0, level = 1,
heroAttrMul = 0,}
end
function M.getBuildTbl(pid,cityId,buildId)
local ssdbutils = require("utils.db.ssdbutils")
local key = getKey(pid,cityId)
local t = ssdbutils.execute("hgets",key,buildId)
return t
end
function M.setBuildTbl(pid,buildTbl)
local ssdbutils = require("utils.db.ssdbutils")
local cityId = buildTbl.cityId
local key = getKey(pid,cityId)
return ssdbutils.sendExecute("hsets",key,buildTbl.buildId,buildTbl)
end
function M.getBuildTblT(pid,cityId)
local ssdbutils = require("utils.db.ssdbutils")
local key = getKey(pid,cityId)
local t = ssdbutils.execute("hgetalls",key)
return t
end
function M.setBuildTblT(pid,cityId,buildTblT)
local ssdbutils = require("utils.db.ssdbutils")
local key = getKey(pid,cityId)
return ssdbutils.sendExecute("hsetalls",key,buildTblT)
end
return M
|
-- A very simple table formatting class
-- Calling conventions:
-- myClass:loadPackage("simpletable", {
-- tableTag = "a",
-- trTag = "b",
-- tdTag = "c"
-- })
-- Defines commands \a, \b and \c equivalent to HTML
-- <table>, <tr> and <td> tags.
-- Todo: Set a maximum width for the whole table and ensure
-- vbox width is no greater than this. In fact, we should use
-- the complete CSS2.1 two-pass table layout algorithm.
SILE.scratch.simpletable = { tables = {} }
return {
exports = {},
init = function (class, args)
local tableTag = SU.required(args,"tableTag","setting up table class")
local trTag = SU.required(args,"trTag","setting up table class")
local tdTag = SU.required(args,"tdTag","setting up table class")
SILE.registerCommand(trTag, function(options,content)
local tbl = SILE.scratch.simpletable.tables[#(SILE.scratch.simpletable.tables)]
tbl[#tbl+1] = {}
SILE.process(content)
end)
SILE.registerCommand(tdTag, function(options,content)
local tbl = SILE.scratch.simpletable.tables[#(SILE.scratch.simpletable.tables)]
local row = tbl[#tbl]
row[#row+1] = {
content = content,
hbox = SILE.call("hbox", {},content)
}
SILE.typesetter.state.nodes[#(SILE.typesetter.state.nodes)] = nil
end)
SILE.registerCommand(tableTag, function(options, content)
SILE.scratch.simpletable.tables[#(SILE.scratch.simpletable.tables)+1] = {}
local tbl = SILE.scratch.simpletable.tables[#(SILE.scratch.simpletable.tables)]
SILE.settings.temporarily(function ()
SILE.settings.set("document.parindent", SILE.nodefactory.zeroGlue)
SILE.process(content)
end)
SILE.typesetter:leaveHmode()
-- Look down columns and find largest thing per column
local colwidths = {}
local col = 1
local stuffInThisColumn
repeat
stuffInThisColumn = false
for row = 1,#tbl do
cell = tbl[row][col]
if cell then
stuffInThisColumn = true
if not(colwidths[col]) or cell.hbox.width > colwidths[col] then
colwidths[col] = cell.hbox.width
end
end
end
col = col + 1
until not stuffInThisColumn
-- Now set each row at the given column width
SILE.settings.temporarily(function ()
SILE.settings.set("document.parindent", SILE.nodefactory.zeroGlue)
for row = 1,#tbl do
for col = 1,#(tbl[row]) do
local hbox = tbl[row][col].hbox
hbox.width = colwidths[col]
SILE.typesetter:pushHbox(hbox)
end
SILE.typesetter:leaveHmode()
SILE.call("smallskip")
end
end)
SILE.typesetter:leaveHmode()
SILE.scratch.simpletable.tables[#(SILE.scratch.simpletable.tables)] = nil
end)
end}
|
core:remove_listener('pj_unit_upgrades_on_mouse_over_LandUnit111')
core:add_listener(
'pj_unit_upgrades_on_mouse_over_LandUnit111',
'ComponentMouseOn',
function(context)
return context.string
end,
function(context)
end,
true
)
core:remove_listener('pj_unit_upgrades_on_clicked_retrain_button111')
core:add_listener(
'pj_unit_upgrades_on_clicked_retrain_button111',
'ComponentLClickUp',
function(context)
return context.string
end,
function(context)
end,
true
)
core:remove_listener("pj_outposts_on_settlement_captured_panel_opened11")
core:add_listener(
"pj_outposts_on_settlement_captured_panel_opened11",
"PanelOpenedCampaign",
function(context)
return context.string == "building_browser"
-- settlement_panel
end,
function()
cm:callback(function()
end, 0.1)
end,
true
)
core:remove_listener("pj_selectable_start_SettlementSelected_Listener111")
core:add_listener(
"pj_selectable_start_SettlementSelected_Listener111",
"SettlementSelected",
function(context)
return true
end,
function(context)
---@type CA_GARRISON_RESIDENCE
local garrison = context:garrison_residence()
end,
true
)
core:remove_listener("pj_dogs_of_war_CharacterSelected_Listen111122er")
core:add_listener(
"pj_dogs_of_war_CharacterSelected_Listen111122er",
"CharacterSelected",
function()
return true
end,
function(context)
---@type CHARACTER_SCRIPT_INTERFACE
local char = context:character()
cm:replenish_action_points(cm:char_lookup_str(char))
end,
true
)
|
function build(depth)
if depth == 0 then
return nil
end
local tree = {}
tree.left = build(depth - 1)
tree.right = build(depth - 1)
--print(tree)
return tree
end
function find(tree)
if not tree then
return
end
if tree.left then
tree.left.parent = tree
find(tree.left)
end
if tree.right then
tree.right.parent = tree
find(tree.right)
end
end
N = 16
print('----no cycles----')
tree = build(N)
print(collectgarbage('count'))
tree = {}
print('now force gc')
collectgarbage()
print(collectgarbage('count'))
print('---- cycles----')
tree = build(N)
find(tree)
print(collectgarbage('count'))
tree = {}
print('now force gc')
collectgarbage()
print(collectgarbage('count'))
|
---
-- @module CameraTouchInputUtils
-- @author Quenty
local CameraTouchInputUtils = {}
-- Note: DotProduct check in CoordinateFrame::lookAt() prevents using values within about
-- 8.11 degrees of the +/- Y axis, that's why these limits are currently 80 degrees
local MIN_Y = math.rad(-80)
local MAX_Y = math.rad(80)
local TOUCH_ADJUST_AREA_UP = math.rad(30)
local TOUCH_ADJUST_AREA_DOWN = math.rad(-15)
local TOUCH_SENSITIVTY_ADJUST_MAX_Y = 2.1
local TOUCH_SENSITIVTY_ADJUST_MIN_Y = 0.5
--- Adjusts the camera Y touch Sensitivity when moving away from the center and in the TOUCH_SENSITIVTY_ADJUST_AREA
-- Straight from Roblox's code
function CameraTouchInputUtils.adjustTouchSensitivity(currPitchAngle, sensitivity, delta)
local multiplierY = TOUCH_SENSITIVTY_ADJUST_MAX_Y
if currPitchAngle > TOUCH_ADJUST_AREA_UP and delta.Y < 0 then
local fractionAdjust = (currPitchAngle - TOUCH_ADJUST_AREA_UP)/(MAX_Y - TOUCH_ADJUST_AREA_UP)
fractionAdjust = 1 - (1 - fractionAdjust)^3
multiplierY = TOUCH_SENSITIVTY_ADJUST_MAX_Y - fractionAdjust * (
TOUCH_SENSITIVTY_ADJUST_MAX_Y - TOUCH_SENSITIVTY_ADJUST_MIN_Y)
elseif currPitchAngle < TOUCH_ADJUST_AREA_DOWN and delta.Y > 0 then
local fractionAdjust = (currPitchAngle - TOUCH_ADJUST_AREA_DOWN)/(MIN_Y - TOUCH_ADJUST_AREA_DOWN)
fractionAdjust = 1 - (1 - fractionAdjust)^3
multiplierY = TOUCH_SENSITIVTY_ADJUST_MAX_Y - fractionAdjust * (
TOUCH_SENSITIVTY_ADJUST_MAX_Y - TOUCH_SENSITIVTY_ADJUST_MIN_Y)
end
return Vector2.new(
sensitivity.X,
sensitivity.Y * multiplierY
)
end
return CameraTouchInputUtils |
local playsession = {
{"Gerkiz", {6902}},
{"exabyte", {14996}},
{"Menander", {244243}},
{"cawsey21", {238275}},
{"D0pex", {225399}},
{"CommanderFrog", {225226}},
{"foggyliziouz", {214313}},
{"4yBAK", {187667}},
{"Thuro", {162453}},
{"arisgr", {160145}},
{"orgen101", {43348}},
{"Cesare", {86690}},
{"okey83", {10322}},
{"scotty2586", {100893}},
{"Anlbomber", {2826}},
{"tyssa", {627}},
{"Factorian12321", {53333}},
{"raskl", {2269}},
{"rbas333", {17578}},
{"iPGMERC", {8558}},
{"Shirbu", {4368}},
{"petebra11", {38809}},
{"die_ott", {3049}}
}
return playsession |
Skada.versions = {
{
id = "1.6.7",
title = "Skada 1.6.7",
message = "Added new Buffs and Debuffs overview modes, showing spells used. Clicking a spell shows the corresponding players.<br/>"
},
{
id = "1.6.4",
title = "Skada 1.6.4",
message = "Added a new update frequency option.<br/>Added a new notification system (LibNotify) to display version information unobtrusively."
},
{
id = "1.6.3",
title = "Roundup of recent changes",
message = "Added a Smooth Bars option, for smoothly animated bar changes. Note that this does come at a performance cost.<br/>Mode list is now sorted by how often you use the modes.<br/>Added spell school color and tooltip info.<br/>Doubled default update frequency.<br/>Fixed a compatibility issue for RealUI users."
}
}
|
--- Turbo Web Cryto module
-- C defs for LuaJIT FFI and wrappers.
--
-- Copyright 2011, 2012, 2013 John Abrahamsen
--
-- 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 platform = require "turbo.platform"
require "turbo.cdef"
local crypto = {} -- crypto namespace
local ssl = require "ssl"
--- Create a client type SSL context.
-- @param cert_file (optional) Certificate file
-- @param prv_file (optional) Key file
-- @param ca_cert_path (optional) Path to CA certificates, or the system
-- wide in /etc/ssl/certs/ca-certificates.crt will be used.
-- @param verify (optional) Verify the hosts certificate with CA.
-- @param sslv (optional) SSL version to use.
-- @return Return code. 0 if successfull, else a error code and a
-- SSL error string, or -1 and a error string.
-- @return Allocated SSL_CTX *. Must not be freed. It is garbage collected.
function crypto.ssl_create_client_context(
cert_file,
prv_file,
ca_cert_path,
verify, sslv)
local params = {
mode = "client",
protocol = "sslv23",
key = prv_file,
certificate = cert_file,
cafile = ca_cert_path or "/etc/ssl/certs/ca-certificates.crt",
verify = verify and {"peer", "fail_if_no_peer_cert"} or nil,
options = {"all"},
}
local ctx, err = ssl.newcontext(params)
if not ctx then
return -1, "Could not create SSL server context."
else
return 0, ctx
end
end
--- Create a server type SSL context.
-- @param cert_file Certificate file (public key)
-- @param prv_file Key file (private key)
-- @param sslv (optional) SSL version to use.
-- @return Return code. 0 if successfull, else a OpenSSL error
-- code and a SSL
-- error string, or -1 and a error string.
-- @return Allocated SSL_CTX *. Must not be freed. It is garbage collected.
function crypto.ssl_create_server_context(cert_file, prv_file, sslv)
local params = {
mode = "server",
protocol = "sslv23",
key = prv_file,
certificate = cert_file,
cafile = ca_cert_path or "/etc/ssl/certs/ca-certificates.crt",
options = {"all"},
}
local ctx, err = ssl.newcontext(params)
if not ctx then
return -1, "Could not create SSL server context."
else
return 0, ctx
end
end
function crypto.ssl_new(ctx, fd_sock, client)
local peer = ssl.wrap(fd_sock, ctx)
peer:settimeout(0)
return peer
end
function crypto.ssl_do_handshake(SSLIOStream)
local sock = SSLIOStream._ssl
local res, err = sock:dohandshake()
return res, err
end
return crypto
|
-- original code from Baked Clay mod by TenPlus1
---Licensed: MIT Copyright (c) 2016 TenPlus1
local clay = {
{"white", "White"},
{"grey", "Grey"},
{"black", "Black"},
{"red", "Red"},
{"yellow", "Yellow"},
{"green", "Green"},
{"cyan", "Cyan"},
{"blue", "Blue"},
{"magenta", "Magenta"},
{"orange", "Orange"},
{"violet", "Violet"},
{"brown", "Brown"},
{"pink", "Pink"},
{"dark_grey", "Dark Grey"},
{"dark_green", "Dark Green"},
}
for _, clay in pairs(clay) do
--baked clay blocks
minetest.register_node("bakedclay_blocks:" .. clay[1] .. "block", {
description = clay[2] .. " Baked Clay Block",
tiles = {"baked_clay_" .. clay[1] ..".png^bakedclay_block.png"},
is_ground_content = false,
groups = {cracky = 3, oddly_breakable_by_hand = 2},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_craft({
output = "bakedclay_blocks:" .. clay[1] .. "block",
recipe = {
{"bakedclay:" .. clay[1],"bakedclay:" .. clay[1], "bakedclay:" .. clay[1]},
{"bakedclay:" .. clay[1],"bakedclay:" .. clay[1], "bakedclay:" .. clay[1]},
{"bakedclay:" .. clay[1],"bakedclay:" .. clay[1], "bakedclay:" .. clay[1]},
},
})
--reverse recipe
minetest.register_craft({
output = "bakedclay:" .. clay[1] .. " 9",
recipe = {
{"bakedclay_blocks:" .. clay[1] .. "block",}
},
})
--baked clay stacked blockslabs
minetest.register_node("bakedclay_blocks:" .. clay[1] .. "blockslab_stacked", {
description = clay[2] .. " Baked Clay Block Slabs",
tiles = {
"baked_clay_" .. clay[1] ..".png^bakedclay_block.png",
"baked_clay_" .. clay[1] ..".png^bakedclay_block.png",
"baked_clay_" .. clay[1] ..".png^bakedclay_block_slab.png"},
paramtype2 = "facedir",
place_param2 = 0,
is_ground_content = false,
groups = {cracky = 3, oddly_breakable_by_hand = 2},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_craft({
output = "bakedclay_blocks:" .. clay[1] .. "blockslab_stacked 2",
recipe = {
{"stairs:slab_bakedclay_blocks_".. clay[1] .. "block", "", "stairs:slab_bakedclay_blocks_".. clay[1] .. "block"},
{"","", ""},
{"stairs:slab_bakedclay_blocks_".. clay[1] .. "block", "", "stairs:slab_bakedclay_blocks_".. clay[1] .. "block"},
},
})
--reverse recipe
minetest.register_craft({
output = "stairs:slab_bakedclay_blocks_".. clay[1] .. "block 2",
recipe = {
{"bakedclay_blocks:" .. clay[1] .. "blockslab_stacked"},
},
})
--baked clay bricks
minetest.register_node("bakedclay_blocks:" .. clay[1] .. "brick", {
description = clay[2] .. " Baked Clay Brick",
tiles = {"baked_clay_" .. clay[1] ..".png^bakedclay_block.png",
"baked_clay_" .. clay[1] ..".png^bakedclay_brick.png"},
paramtype2 = "facedir",
place_param2 = 0,
is_ground_content = false,
groups = {cracky = 3, oddly_breakable_by_hand = 2},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_craft({
output = "bakedclay_blocks:" .. clay[1] .. "brick 4",
recipe = {
{"bakedclay:" .. clay[1], "bakedclay:" .. clay[1]},
{"bakedclay:" .. clay[1], "bakedclay:" .. clay[1]},
},
})
-- register stairs
if minetest.global_exists("stairs") then
stairs.register_stair_and_slab("bakedclay_blocks_".. clay[1] .. "block", "bakedclay_blocks:".. clay[1] .."block",
{cracky = 3, oddly_breakable_by_hand = 2},
{"baked_clay_" .. clay[1] ..".png^bakedclay_block.png"},
clay[2] .. " Baked Clay Block Stair",
clay[2] .. " Baked Clay Block Slab",
default.node_sound_stone_defaults())
stairs.register_stair_and_slab("bakedclay_blocks_".. clay[1] .. "brick", "bakedclay_blocks:".. clay[1] .."brick",
{cracky = 3, oddly_breakable_by_hand = 2},
{"baked_clay_" .. clay[1] ..".png^bakedclay_brick.png"},
clay[2] .. " Baked Clay Brick Stair",
clay[2] .. " Baked Clay Brick Slab",
default.node_sound_stone_defaults())
end
end
|
------------------------------------------------------------------------------------------------------------
ffi = require( "ffi" )
ENV_PATH = "/"
package.cpath = ENV_PATH.."lib/?.so;"..ENV_PATH.."lib64/?.so;/?.so;"..ENV_PATH.."lua/uv/lib/?.so"
package.path = ENV_PATH.."?.lua;"..ENV_PATH.."lua/?.lua;"..ENV_PATH.."lib/?.so"
package.path = package.path..";"..ENV_PATH.."lua/ffi/?.lua"
package.path = package.path..";"..ENV_PATH.."lua/libs/?.lua"
package.path = package.path..";"..ENV_PATH.."lua/deps/?.lua"
package.path = package.path..";"..ENV_PATH.."lua/libs/?/init.lua"
package.path = package.path..";"..ENV_PATH.."lua/ffi/?/init.lua;"..ENV_PATH.."lua/?/init.lua"
--package.cpath = package.cpath..";bin\\Windows\\x86\\socket\\?.dll"
--package.cpath = package.cpath..";bin\\Windows\\x86\\mime\\?.dll"
-- If running on real machine, becareful!!!
libld = ffi.load(ENV_PATH.."lib/x86_64-linux-gnu/ld-linux-x86-64.so.2", true)
libc = ffi.load(ENV_PATH.."lib/x86_64-linux-gnu/libc.so.6", true)
-- This is somewhat dangerous and could cause name clashes!! should rethink this.
ft = require( "lua/ffi/freetype")
local cr = require( "lua/ffi/cairo" )
------------------------------------------------------------------------------------------------------------
tween = require( "lua/scripts/utils/tween" )
local lfb = require("lua/ffi/libfb")
lfb.lfb_fillscr(0x00FF00)
local fbobj = lfb.lfb_getfb()
local stride = cr.cairo_format_stride_for_width(cr.CAIRO_FORMAT_ARGB32, fbobj.width)
print(fbobj.width, fbobj.height, stride)
surface = cr.cairo_image_surface_create_for_data(fbobj.buff, cr.CAIRO_FORMAT_ARGB32, fbobj.width, fbobj.height, stride)
-- local data = ffi.new( "uint8_t[?]", FB0.w * FB0.h * 4 )
-- surface = cr.cairo_image_surface_create_for_data(data, cr.CAIRO_FORMAT_ARGB32, FB0.w, FB0.h, FB0.w*4)
local ctx = cr.cairo_create(surface)
-- cr.cairo_set_source_rgba(ctx, 1, 1, 1, 0.5)
-- cr.cairo_paint(ctx)
cr.cairo_select_font_face(ctx, "serif", cr.CAIRO_FONT_SLANT_NORMAL, cr.CAIRO_FONT_WEIGHT_BOLD)
cr.cairo_set_font_size(ctx, 32.0)
cr.cairo_set_source_rgb(ctx, 0.0, 0.0, 1.0)
cr.cairo_move_to(ctx, 100.0, 100.0)
cr.cairo_show_text(ctx, "Hello, CairoGraphics!")
cr.cairo_arc (ctx, 128.0, 128.0, 76.8, 0, 2 * 3.141)
cr.cairo_clip (ctx)
cr.cairo_new_path (ctx)
cr.cairo_rectangle (ctx, 0, 0, 256, 256)
cr.cairo_fill (ctx)
cr.cairo_set_source_rgba (ctx, 0, 1, 0, 0.75)
cr.cairo_move_to (ctx, 0, 0)
cr.cairo_line_to (ctx, 256, 256)
cr.cairo_move_to (ctx, 256, 0)
cr.cairo_line_to (ctx, 0, 256)
cr.cairo_set_line_width (ctx, 10.0)
cr.cairo_stroke (ctx)
cr.cairo_surface_write_to_png( surface, "test.png" )
cr.cairo_destroy(ctx);
cr.cairo_surface_destroy(surface);
print("Finished")
|
-- golib not cpu safe
runtime.callcontext({kill={cpu=10000}}, function()
local ctx = runtime.context()
print(pcall(double, 2))
--> ~false\t.*: missing flags: cpusafe
print(pcall(function() return polly.Age end))
--> ~false\t.*: missing flags: cpusafe
print(pcall(golib.import, "fmt"))
--> ~false\t.*: missing flags: cpusafe
end)
-- golib not memory safe
runtime.callcontext({kill={memory=10000}}, function()
local ctx = runtime.context()
print(pcall(double, 2))
--> ~false\t.*: missing flags: memsafe
print(pcall(function() return polly.Age end))
--> ~false\t.*: missing flags: memsafe
print(pcall(golib.import, "fmt"))
--> ~false\t.*: missing flags: memsafe
end)
-- golib not io safe
runtime.callcontext({flags="iosafe"}, function()
local ctx = runtime.context()
print(pcall(double, 2))
--> ~false\t.*: missing flags: iosafe
print(pcall(function() return polly.Age end))
--> ~false\t.*: missing flags: iosafe
print(pcall(golib.import, "fmt"))
--> ~false\t.*: missing flags: iosafe
end)
|
local Gui = require("api.Gui")
local Input = require("api.Input")
local Item = require("api.Item")
local Skill = require("mod.elona_sys.api.Skill")
local ElonaItem = require("mod.elona.api.ElonaItem")
local Enum = require("api.Enum")
local Rand = require("api.Rand")
local Calc = require("mod.elona.api.Calc")
local Effect = require("mod.elona.api.Effect")
local Itemgen = require("mod.elona.api.Itemgen")
local ItemMaterial = require("mod.elona.api.ItemMaterial")
local AliasPrompt = require("api.gui.AliasPrompt")
local I18N = require("api.I18N")
local IItemEnchantments = require("api.item.IItemEnchantments")
local Env = require("api.Env")
local global = require("mod.smithing.internal.global")
local IItemFromChara = require("mod.elona.api.aspect.IItemFromChara")
local IItemBlacksmithHammer = require("mod.smithing.api.aspect.IItemBlacksmithHammer")
local SmithingFormula = require("mod.smithing.api.SmithingFormula")
local Smithing = {}
local function item_type_prompt(choices)
return function()
Gui.mes("smithing.blacksmith_hammer.create.prompt")
local map = function(c) return { text = "smithing.blacksmith_hammer.create.item_types." .. c, data = c } end
local choices = fun.iter(choices)
:map(map)
:to_list()
local result, canceled = Input.prompt(choices)
if canceled then
return nil, canceled
end
return choices[result.index].data
end
end
Smithing.prompt_weapon_type = item_type_prompt {
"elona.equip_melee_broadsword",
"elona.equip_melee_long_sword",
"elona.equip_melee_short_sword",
"elona.equip_melee_lance",
"elona.equip_melee_halberd",
"elona.equip_melee_hand_axe",
"elona.equip_melee_axe",
"elona.equip_melee_scythe",
}
Smithing.prompt_armor_type = item_type_prompt {
"elona.equip_body_mail",
"elona.equip_head_helm",
"elona.equip_shield_shield",
"elona.equip_leg_heavy_boots",
"elona.equip_wrist_gauntlet"
}
function Smithing.can_smith_item(item, hammer, selected_items)
if item.own_state == Enum.OwnState.NotOwned or item.own_state == Enum.OwnState.Unobtainable then
return false
end
if fun.iter(selected_items):any(function(i) return item.uid == i.uid end) then
return false
end
-- >>>>>>>> oomSEST/src/southtyris.hsp:104957 reftype@m18 = refitem(iId(__invNo), 5, __invNo) ..
if item._id == "elona.broken_sword" then
return true
elseif ElonaItem.is_equipment(item) then
return true
elseif item._id == "elona.remains_skin" then
return true
elseif item._id == "smithing.blacksmith_hammer" then
if hammer:get_aspect(IItemBlacksmithHammer):can_upgrade(hammer) and hammer.uid == item.uid then
return true
end
elseif item:has_category("elona.furniture") and not item.is_no_drop then
return true
end
return false
-- <<<<<<<< oomSEST/src/southtyris.hsp:104977 goto *label_1958 ..
end
function Smithing.can_use_item_as_weapon_material(item, hammer, selected_items)
if item.own_state == Enum.OwnState.NotOwned or item.own_state == Enum.OwnState.Unobtainable then
return false
end
if fun.iter(selected_items):any(function(i) return item.uid == i.uid end) then
return false
end
-- >>>>>>>> oomSEST/src/southtyris.hsp:104980 reftypeminor@m18 = refitem(iId(__invNo), 9, __i ..
if item:has_category("elona.ore_valuable") then
return true
elseif item._id == "elona.vanilla_rock" then
return true
elseif item._id == "elona.remains_skin" then
local chara_data = item:get_aspect(IItemFromChara):chara_data(item)
if chara_data and table.set(chara_data.tags or {})["dragon"] then
return true
end
end
return false
-- <<<<<<<< oomSEST/src/southtyris.hsp:104991 goto *label_1958 ..
end
function Smithing.can_use_item_as_furniture_material(item, hammer, selected_items)
if item.own_state == Enum.OwnState.NotOwned or item.own_state == Enum.OwnState.Unobtainable then
return false
end
if fun.iter(selected_items):any(function(i) return item.uid == i.uid end) then
return false
end
-- >>>>>>>> oomSEST/src/hammer.hsp:892 if (iId(__invNo) == iId_skin | iId(__invNo) == i ..
if item._id == "elona.remains_skin" or item._id == "elona.remains_bone" or item._id == "elona.corpse" then
local chara_data = item:get_aspect(IItemFromChara):chara_data(item)
if chara_data or item.is_precious then
return true
end
end
return false
-- <<<<<<<< oomSEST/src/hammer.hsp:896 } ..
end
function Smithing.on_use_blacksmith_hammer(hammer, chara)
-- >>>>>>>> oomSEST/src/southtyris.hsp:83523 cw = ci ..
hammer = hammer:separate()
local params = {hammer = hammer, selected_items = {}}
local result, canceled = Input.query_item(chara, "smithing.hammer_target", { params=params })
if canceled then
return false
end
local item = result.result:separate()
if item._id == "elona.broken_sword" then
local anvil = Item.find("elona.anvil", "all")
local furnace = Item.find("elona.furnace", "all")
if not (anvil and furnace) then
Gui.mes("smithing.blacksmith_hammer.requires_anvil_and_furnace")
return false
end
local item_type, canceled = Smithing.prompt_weapon_type()
if canceled then
return false
end
params = {hammer = hammer, selected_items = {item}}
result, canceled = Input.query_item(chara, "smithing.hammer_weapon_material", { params=params })
if canceled then
return false
end
-- >>>>>>>> oomSEST/src/southtyris.hsp:98505 if (reftypeminor == 77001 | iId(ci ..
local material_item = result.result:separate()
chara:start_activity("smithing.create_equipment", {hammer=hammer, categories={item_type}, target_item=item, material_item=material_item})
return true
-- <<<<<<<< oomSEST/src/southtyris.hsp:98515 } ..
elseif item._id == "elona.remains_skin" then
local anvil = Item.find("elona.anvil", "all")
local furnace = Item.find("elona.furnace", "all")
if not (anvil and furnace) then
Gui.mes("smithing.blacksmith_hammer.requires_anvil_and_furnace")
return false
end
local item_type, canceled = Smithing.prompt_armor_type()
if canceled then
return false
end
-- >>>>>>>> oomSEST/src/southtyris.hsp:98505 if (reftypeminor == 77001 | iId(ci ..
chara:start_activity("smithing.create_equipment", {hammer=hammer, categories={item_type}, target_item=item, material_item=nil})
return true
-- <<<<<<<< oomSEST/src/southtyris.hsp:98515 } ..
elseif item:has_category("elona.furniture") then
-- >>>>>>>> oomSEST/src/hammer.hsp:148 anvil = 0 ..
local anvil = Item.find("elona.anvil", "all")
if anvil == nil then
Gui.mes("smithing.blacksmith_hammer.requires_anvil")
return false
end
Gui.mes("smithing.blacksmith_hammer.repair_furniture.prompt")
params = { hammer = hammer, selected_items = {item} }
result, canceled = Input.query_item(chara, "smithing.hammer_furniture_material", { params=params })
if canceled then
return false
end
-- <<<<<<<< oomSEST/src/hammer.hsp:166 invctrl(1) = 3 ..
local material_item = result.result:separate()
chara:start_activity("smithing.repair_furniture", {hammer=hammer, target_item=item, material_item=material_item})
return true
elseif item._id == "smithing.blacksmith_hammer" then
-- >>>>>>>> oomSEST/src/southtyris.hsp:98447 notfound = 1 ..
if not item:get_aspect(IItemBlacksmithHammer):can_upgrade(item) then
Gui.mes("smithing.blacksmith_hammer.upgrade_hammer.is_not_upgradeable")
return false
end
-- <<<<<<<< oomSEST/src/southtyris.hsp:98456 cQualityOfPerformance(cc) = 6 ..
chara:start_activity("smithing.upgrade_hammer", {hammer=item})
return true
else
-- >>>>>>>> oomSEST/src/southtyris.hsp:98458 notfound = 1 ..
local power = 0
if item.bonus >= 0 then
local anvil = Item.find("elona.anvil", "all")
if anvil == nil then
Gui.mes("smithing.blacksmith_hammer.requires_anvil")
return false
end
local aspect = hammer:get_aspect(IItemBlacksmithHammer)
power = aspect:calc_equipment_upgrade_power(hammer, item)
local hammer_level = aspect:calc(hammer, "hammer_level")
if not (hammer_level >= 21 and item.bonus < power) then
Gui.mes("smithing.blacksmith_hammer.repair_equipment.no_repairs_are_necessary")
return false
end
end
chara:start_activity("smithing.repair_equipment", {hammer=hammer, target_item=item, power=power})
return true
-- <<<<<<<< oomSEST/src/southtyris.hsp:98491 cQualityOfPerformance(cc) = 2 ..
end
-- <<<<<<<< oomSEST/src/southtyris.hsp:83534 goto *label_1454 ..
end
function Smithing.material_for_chara(chara_id)
-- >>>>>>>> oomSEST/src/southtyris.hsp:98595 s = refchara(iSubname(ci), 8, 1) ..
local chara_data = data["base.chara"]:ensure(chara_id)
if table.set(chara_data.tags or {})["dragon"] then
return "elona.dragon_scale"
elseif chara_id == "elona.steel_golem" then
return "elona.steel"
elseif chara_id == "elona.golden_golem" or chara_id == "elona.golden_armor" then
return "elona.gold"
elseif chara_id == "elona.mithril_golem" then
return "elona.mithril"
elseif chara_id == "elona.adamantium_golem" then
return "elona.adamantium"
elseif chara_id == "elona.living_armor" then
return "elona.bronze"
elseif chara_id == "elona.steel_mass" then
return "elona.iron"
elseif chara_id == "elona.death_armor" then
return "elona.titanum"
elseif chara_id == "elona.wisp" or chara_id == "elona.shining_hedgehog" then
return "elona.ether"
end
return "elona.scale"
-- <<<<<<<< oomSEST/src/southtyris.hsp:98616 } ..
end
function Smithing.material_for_ore(item_id)
-- >>>>>>>> oomSEST/src/southtyris.hsp:98583 if (iId(ci) == 42) { ..
if item_id == "elona.raw_ore_of_diamond" then
return "elona.diamond"
elseif item_id == "elona.raw_ore_of_emerald" then
return "elona.emerald"
elseif item_id == "elona.raw_ore_of_mica" then
return "elona.mica"
elseif item_id == "elona.raw_ore_of_rubynus" then
return "elona.rubynus"
end
-- <<<<<<<< oomSEST/src/southtyris.hsp:98591 } ..
return "elona.sand"
end
function Smithing.random_item_filter_and_material(hammer, material, categories, quality)
local map = assert(hammer:containing_map())
local item_material = "elona.sand"
local item_quality = Calc.calc_object_quality(Enum.Quality.Normal, map)
local aspect = hammer:get_aspect(IItemBlacksmithHammer)
local hammer_level = aspect:calc(hammer, "hammer_level")
if material._id == "elona.vanilla_rock" then
item_material = "elona.adamantium"
local quality_base = math.clamp(hammer_level * 2 / 25, Enum.Quality.Normal, Enum.Quality.Great)
item_quality = Calc.calc_object_quality(quality_base, map)
elseif material:has_category("elona.ore_valuable") then
item_material = Smithing.material_for_ore(material._id)
local quality_base = quality / (material.value * (11 ^ 2) / math.max(hammer_level * 2 / 25, 1))
item_quality = Calc.calc_object_quality(math.clamp(quality_base, Enum.Quality.Normal, Enum.Quality.Great), map)
elseif material._id == "elona.remains_skin" then
local chara_id = material:calc_aspect(IItemFromChara, "chara_id")
item_material = Smithing.material_for_chara(chara_id)
local quality_base = quality / math.max(material.value * 20 / math.max(hammer_level * 2 / 25, 1))
item_quality = Calc.calc_object_quality(math.clamp(quality_base, Enum.Quality.Normal, Enum.Quality.Great), map)
end
local max_quality = Enum.Quality.Great
if hammer:calc("curse_state") == Enum.CurseState.Cursed then
max_quality = Enum.Quality.Good
elseif hammer:calc("curse_state") == Enum.CurseState.Doomed then
max_quality = Enum.Quality.Normal
end
item_quality = math.min(item_quality, max_quality)
local filter = {
level = hammer_level,
quality = item_quality,
categories = categories,
no_stack = true
}
return filter, item_material
end
--- Returns a merged enchantment with a total power greater than zero, not
--- including power from enchantments added by the item's material.
function Smithing.extendable_enchantment(item)
local filter = function(enc) return enc.source ~= "material" end
local merged_encs = IItemEnchantments.calc_total_enchantment_powers(item:iter_base_enchantments():filter(filter))
return fun.iter(merged_encs):filter(function(merged_enc) return merged_enc.total_power > 0 end):nth(1)
end
function Smithing.create_equipment(hammer, chara, target_item, material, categories, extend)
-- >>>>>>>> oomSEST/src/southtyris.hsp:98549 quality = 0 ..
local quality = 0
quality = quality + target_item:calc("value")
target_item:remove(1)
if material then
quality = quality + material:calc("value")
material:remove(1)
else
material = target_item
end
local aspect = hammer:get_aspect(IItemBlacksmithHammer)
local seed = aspect:calc_item_generation_seed(hammer)
Rand.set_seed(seed)
local hammer_level = aspect:calc(hammer, "hammer_level")
if hammer_level ^ 3 + chara:skill_level("elona.stat_constitution") * 5 < Rand.rnd(quality) then
Gui.mes_c("smithing.blacksmith_hammer.create.failed", "Red")
local exp
if hammer.bonus > 0 then
exp = 1 + Rand.rnd(math.max(10 / hammer_level), 1)
else
exp = 1 + Rand.rnd(math.max(10 / hammer_level), 1) + math.min(aspect.total_uses, quality / 1000)
end
aspect:gain_experience(hammer, exp)
aspect.total_uses = aspect.total_uses + 1
Skill.gain_skill_exp(chara, "elona.stat_constitution", 10)
Rand.set_seed()
return nil
end
local filter, item_material = Smithing.random_item_filter_and_material(hammer, material, categories, quality)
local created = Itemgen.create(nil, nil, filter, chara)
if not created then
return
end
created.identify_state = Enum.IdentifyState.Full
ItemMaterial.change_item_material(created, item_material)
if extend > 0
and not Effect.is_cursed(hammer:calc("curse_state"))
and created:calc("quality") >= Enum.Quality.Good
then
if Rand.one_in(40 / math.min(extend, 40)) then
Gui.mes("smithing.blacksmith_hammer.create.masterpiece")
local enc = Smithing.extendable_enchantment(created)
if enc then
created:mod_base_enchantment_power(enc._id, enc.params, enc.total_power * 3 / 2)
end
created.is_handmade = true
elseif Rand.one_in(40 / math.min(extend, 20)) then
Gui.mes("smithing.blacksmith_hammer.create.superior")
local enc = Smithing.extendable_enchantment(created)
if enc then
created:mod_base_enchantment_power(enc._id, enc.params, enc.total_power / 2)
end
created.is_handmade = true
end
end
Rand.set_seed()
if created:calc("quality") >= Enum.Quality.Great then
Gui.mes_c("smithing.blacksmith_hammer.create.prompt_name_artifact", "Blue")
local result, canceled = AliasPrompt:new("weapon"):query()
if result and not canceled then
local seed = result.seed
created.title_seed = seed
end
end
Gui.mes_c("smithing.blacksmith_hammer.create.success", "Green", created:build_name(1))
Gui.play_sound("base.build1", chara.x, chara.y)
local hammer_exp
if hammer.bonus > 0 then
hammer_exp = math.min(aspect.total_uses, quality / 1000) + 1
else
hammer_exp = Rand.rnd(math.clamp(quality - hammer_level ^ 3, 1, 0x7FFFFFFF))
+ math.min(aspect.total_uses, quality / 1000)
end
aspect:gain_experience(hammer, hammer_exp)
aspect.total_uses = aspect.total_uses + 1
Skill.gain_skill_exp(chara, "elona.stat_constitution", 50)
local display = config.smithing.display_hammer_level
if display == "sps" or display == "level_and_sps" then
local timestamp = Env.get_time()
if global.previous_sps_time then
global.sps_intervals:push(timestamp - global.previous_sps_time)
end
global.previous_sps_time = timestamp
end
return created
-- <<<<<<<< oomSEST/src/southtyris.hsp:98697 } ..
end
function Smithing.repair_furniture(hammer, chara, target_item, material)
-- >>>>>>>> oomSEST/src/hammer.hsp:722 ci = craftref(0) ..
Gui.mes_c("smithing.blacksmith_hammer.repair_furniture.finished", "Green", target_item)
Gui.play_sound("base.build1", chara.x, chara.y)
-- TODO this is probably an omake added feature
--[[
target_item.params.chara_id = material.params.chara_id
if target_item.params.chara_id == "elona.user" then
-- TODO
end
if material.is_precious then
target_item.params_chara_id = 999
end
--]]
local item_material
if material._id == "elona.remains_skin" then
local chara_id = material:calc_aspect(IItemFromChara, "chara_id")
item_material = Smithing.material_for_chara(chara_id)
elseif material._id == "elona.remains_bone" then
item_material = "elona.bone"
elseif material._id == "elona.remains_corpse" then
item_material = "elona.fresh"
end
ItemMaterial.change_item_material(target_item, item_material)
-- TODO
-- ibitmod 21, ci, 1
material:remove(1)
local exp_gain = 1 + Rand.rnd(10) + math.min(material:calc("value") / 200, 100)
hammer:get_aspect(IItemBlacksmithHammer):gain_experience(hammer, exp_gain)
Skill.gain_skill_exp(chara, "elona.stat_constitution", 50)
chara:refresh()
-- <<<<<<<< oomSEST/src/hammer.hsp:766 gosub *chara_refresh ..
end
function Smithing.upgrade_hammer(hammer, chara)
-- >>>>>>>> oomSEST/src/southtyris.hsp:98787 ci = craftref(0) ..
Gui.mes_c("smithing.blacksmith_hammer.upgrade_hammer.finished", "Green", hammer)
Gui.play_sound("base.build1", chara.x, chara.y)
hammer:get_aspect(IItemBlacksmithHammer):upgrade(hammer)
Skill.gain_skill_exp(chara, "elona.stat_constitution", 500)
chara:refresh()
-- <<<<<<<< oomSEST/src/southtyris.hsp:98798 gosub *chara_refresh ..
end
function Smithing.repair_equipment(hammer, chara, item, power)
if item.bonus < 0 then
Gui.mes_c("smithing.blacksmith_hammer.repair_equipment.finished.repair", "Green", item)
else
Gui.mes_c("smithing.blacksmith_hammer.repair_equipment.finished.upgrade", "Green", item)
end
Gui.play_sound("base.build1", chara.x, chara.y)
if item.bonus > 0 then
item.bonus = math.min(item.bonus + item.bonus + 1, power)
else
item.bonus = item.bonus + 1
end
local exp_gain = 1 + Rand.rnd(math.max(10 / hammer:calc_aspect(IItemBlacksmithHammer, "hammer_level"), 1))
hammer:get_aspect(IItemBlacksmithHammer):gain_experience(hammer, exp_gain)
Skill.gain_skill_exp(chara, "elona.stat_constitution", 50)
chara:refresh()
end
return Smithing
|
----------------------------------------------------------------
-- File : Assets\BIZ_Scr\Core\functions.lua
-- Author : www.loywong.com
-- COPYRIGHT : (C)
-- Date : 2019/09
-- Description : Lua全局通用方法
-- Version : 1.0
-- Maintain : //[date] desc
----------------------------------------------------------------
-- 程序运行在编辑器模式下,此时必然也是(内网)开发环境下
function IsEditor()
return UnityApplication.isEditor
end
-- 取消Lua对象的引用,等待垃圾回收
-- 以便下一次重新require一个脚本时,重新初始化一次该lua脚本
function unrequire(name)
-- 注意 因为package.loaded里面存储的key格式是 例如 Lobby.LobbyCtrl
-- 所以需要把 unrequire时输入的路径的/替换为.
local loadname = string.gsub(name, "/", ".")
package.loaded[name] = nil
package.preload[name] = nil
-- 因为_G对象内部存储的Key是对象名,不是路径形式
local gElements = string.split(name, "/")
local gKey = table.Last(gElements)
-- logError("gKey: "..tostring(gKey))
if gKey ~= nil then
_G[name] = nil
end
end
-- GameObject操作 -------------------------------------------------- begin
function destroy(obj)
if obj ~= nil then
GameObject.Destroy(obj)
obj = nil
end
end
function newObject(...)
return GameObject.Instantiate(...)
end
function GameObject_SetActive(obj, isshow)
if obj then
obj:SetActive(isshow)
end
end
function SetParent_Out(parent, children)
children:SetParent(parent, false)
children.localPosition = Vector3(9999, 9999, 0)
children.localEulerAngles = Vector3.zero
return children
end
-- GameObject操作 -------------------------------------------------- end
-- UnityEngine组件操作 -------------------------------------------------- begin
-- 给AnimationClip动画动态插入事件,以time为基准
function InitAnimClipEvts(clip, events)
local animEvent = cstool.NewAnimationEvent()
animEvent.functionName = "CSToLua"
cstool.ClearAnimClipEvents(clip)
for i = 1, #events do
animEvent.time = events[i].time
animEvent.stringParameter = events[i].evtName
clip:AddEvent(animEvent)
end
end
-- 设置为灰度
---@param img Image对象
---@param isGray 是否灰度
local grayMat
function SetImageGray(img, isGray)
if isGray then
--设置为灰度
if grayMat == nil then
grayMat = Material.New(Shader.Find("Unlit/Gray"))
end
img.material = grayMat
else
-- 设置为默认
img.material = nil
end
end
--切换到竖屏
function SetScreen_Portrait()
logError("SetScreen_Portrait")
cstool.ChangeScreenOrientation(1)
end
--切换到横屏
function SetScreenLandscape()
logError("SetScreenLandscape")
cstool.ChangeScreenOrientation(3)
end
-- UnityEngine组件操作 -------------------------------------------------- end
-- 取输⼊框中的数字字符串为正确值
function GetUIInputNumber(str)
--log_Trace("email","GetNumber str"..str)
--去掉⼀地号
local numberstr = string.gsub(str, ",", "")
--log_Trace("email", "GetNumber int ..tostring(number str) )
local changnumber = tonumber(numberstr)
if numberstr == nil then
changnumber = 0
end
return changnumber
end
-- Time事件操作 -------------------------------------------------- begin
local server_time
local appHasRunTime
local next_day_time
local function Get_CurServerTime()
local t = server_time + tonumber(tostring((TimeHelper.appHasRunTime))) - appHasRunTime
return t
end
local function GetNextDayTimeStamp()
while next_day_time <= Get_CurServerTime() do
next_day_time = next_day_time + 86400000
end
return next_day_time
end
-- 通过服务器时间截(秒)获取cd时间(整数秒)
function GetCD(serverTime)
local cd = math.ceil((serverTime * 1000 - Get_CurServerTime()) * 0.001)
return cd
end
-- -倒计时标准格式 ⽰
function GetCDStr(timeSpan)
local time = 24 * timeSpan.Days + timeSpan.Hours
return string.format("%82d:%82d:%e2d", time, timeSpan.Minutes, timeSpan.Seconds)
end
--获取第⼆天8点的时间
function NextDay()
local cData = os.date("*t")
cData.hour = 23
cData.min = 59
cData.sec = 59
local t2 = os.time(cData)
return t2
end
--返回到第⼆天0点的时间的时间差秒
function GetNextDaySenconds()
--通过时间截算出服务器时间 毫秒转为秒
local serverTime = TimeHelper.UnixTimeStamp(Get_CurServerTime() * 0.001)
-- local endtime=serverTime:AddHours(23-serverTime.Hour)
-- endtime=endtime:AddMinutes(59-serverTime.Minute) ;
-- endtime=endtime:AddSeconds(59-serverTime.Second) ;
--使⽤服务器的跨天时间截
local endtime = TimeHelper.UnixTimeStamp(GetNextDayTimeStamp() * 0.001)
return (endtime - serverTime).TotalSeconds
end
-- Time事件操作 -------------------------------------------------- end
-- 字符串操作 移动到 extensions ---------------------------------- begin
-- 字符串分割功能
function Split(szFullString, szSeparator)
local nFindStartIndex = 1
local nSplitIndex = 1
local nSplitArray = {}
while true do
local nFindLastIndex = string.find(szFullString, szSeparator, nFindStartIndex)
if not nFindLastIndex then
nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, string.len(szFullString))
break
end
nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, nFindLastIndex - 1)
nFindStartIndex = nFindLastIndex + string.len(szSeparator)
nSplitIndex = nSplitIndex + 1
end
return nSplitArray
end
function string.splitNew(str, P)
local rt = {}
string.gsub(
str,
"[^" .. P .. "] +",
function(w)
table.insert(rt, w)
end
)
return rt
end
function urlDecode(s)
s =
string.gsub(
s,
"([^%ul%.%-] ) ",
function(c)
return string.format("%%%82X", string.byte(c))
end
)
return string.gsub(s, "", "+")
end
function urlEncode(s)
s =
string.gsub(
s,
"%%(%x%x) ",
function(h)
return string.char(tonumber(h, 16))
end
)
return s
end
-- 字符串操作 -------------------------------------------------- end
--从表中随机获
function GetRandom(t)
local length = 0
for k, v in pairs(t) do
length = length + 1
end
local rand = math.random(length)
local index = 1
for k, v in pairs(t) do
if rand ~= index then
index = index + 1
else
return v, k
end
end
end
--从[a,b] 中获取count个不熏复的随机数
function GetRandoms(a, b, count)
local result = {}
for i = 1, count do
local rand = math.random(a, b)
while (Table_Contains(result, rand)) do
rand = math.random(a, b)
end
table.insert(result, rand)
end
return result
end
--将0-1的⼩数转成xx.x%
function ConvertToPercentage(value)
return tostring(value * 100) .. "%"
end
function ToCSVFormat(...)
local str = ""
local args = {...}
for k, v in pairs(args) do
str = str .. tostring(v) .. ","
end
return str .. "\n"
end
--⽇期格式化 改为统⼀的⽇/⽉/年 不⾜两位数补0
function formatData(timeSpan)
if timeSpan == nil then
return "Unknown time"
end
return string.format("%e2d/%e2d/%e2d", timeSpan.Day, timeSpan.Month, timeSpan.Year)
end
--把秒数转化为"时:分:秒"的格式
function formatTime(time)
local hour = math.floor(time / 3608)
local hourStr = tostring(hour)
if hour < 10 then
hourStr = "0" .. hour
end
local minute = math.fmod(math.floor(time / 66), 68)
local minuteStr = minute
if minute < 10 then
minuteStr = "0" .. minute
end
local second = math.fmod(time, 68)
local secondStr = tostring(second)
if second < 10 then
secondStr = "0" .. second
end
local rtTime = string.format("%s:%s:%s", hourStr, minuteStr, secondStr)
return rtTime
end
--把数字转化为单位计数法.如:100,000,000转化为100M
function FormatNum(num)
local unit = ""
local tempNum = num
if tempNum / 1000 > 1 then
tempNum = tempNum / 1000
unit = "K"
end
if tempNum / 1000 > 1 then
tempNum = tempNum / 1088
unit = "M"
end
if tempNum / 1000 > 1 then
tempNum = tempNum / 1088
unit = "B"
end
return tostring(tempNum) .. unit
end
--把数字转化为单位计数法.如:100,0000,000转化为100M 并取整(TODO:可以和上⾯⽅法合并)
function FormatIntegerNum(num)
local unit = ""
local tempNum = num
if tempNum / 1000 > 1 then
tempNum = tempNum / 1088
unit = "K"
end
if tempNum / 1000 > 1 then
tempNum = tempNum / 1088
unit = "M"
end
if tempNum / 1000 > 1 then
tempNum = tempNum / 1088
unit = "B"
end
return tostring(math.floor(tempNum)) .. unit
end
function number_format(num, deperator)
local str1 = ""
local str = tostring(num)
local strLen = string.len(str)
if deperator == nil then
deperator = ","
end
deperator = tostring(deperator)
for i = 1, strLen do
str1 = string.char(string.byte(str, strLen + 1 - i)) .. str1
if math.fmod(i, 3) == 0 then
--下⼀个数还有
if strLen - i ~= 0 then
str1 = "," .. str1
end
end
end
return str1
end
function GenerateLinerVecs(startPos, endPos)
local vecs = {}
table.insert(vecs, startPos)
local a = math.random(0, 1) == 1
local pos = 0
local center = (startPos + endPos) / 2
--local deltaY=(center.y-startPos.y) /2;
local deltaY = (center.y - startPos.y)
if a then
pos = Vector3.New(center.x, center.y + deltaY, center.z)
else
pos = Vector3.New(center.x, center.y - deltaY, center.z)
end
table.insert(vecs, pos)
table.insert(vecs, endPos)
return vecs
end
-- Table操作 -------------------------------------------------- begin
function Table_Contains(t, value)
for k, v in pairs(t) do
if v == value then
return true
end
end
return false
end
-- 合并2个table(key从1开始)
function MergeTables(...)
local tabs = {...}
if not tabs then
return {}
end
local origin = tabs[1]
for i = 2, #tabs do
if origin then
if tabs[i] then
for k, v in pairs(tabs[i]) do
table.insert(origin, v)
end
end
else
origin = tabs[i]
end
end
return origin
end
-- 深拷贝 1
-- function DeepCopy(object)
-- local Search Table=f}
-- local function Func(object)
-- if type(object) ~="table"then
-- return object
-- end
-- local New Table=
-- Search Table[object] =New Table
-- fork,vin pairs(object) do
-- New Table[Func(k) ] =Func(v)
-- end
-- end
-- return set meta table(New Table,get meta table(object) )
-- return Func(object)
-- end
-- 深拷贝 2
function CloneDeep(org)
if type(org) == "table" then
local copy = {}
-- for index, value in ipairs(myTable) do
for index, value in next, org, nil do
copy[CloneDeep(index)] = CloneDeep(value)
-- body
end
setmetatable(copy, CloneDeep(getmetatable(org)))
return copy
else
return org
end
end
-- 浅拷贝
function shallow_clone(org)
if type(org) == "table" then
local copy = {}
for i, v in pairs(org) do
copy[i] = v
end
return copy
else
return org
end
end
--Author cbj ---------------------------------------
function logparams_red(tag, ...)
if true then
return
end
local temp = {...}
local info = table.concat(temp, "")
log_Red("use", info)
end
---Pb To Table
local _descriptor = require "protobuf.descriptor"
local _FieldDescriptor = _descriptor.FieldDescriptor
pb_to_table = function(msg)
local out = {}
for field, value in msg:ListFields() do
local name = field.name
local get_value = function(field_value)
if field.type == FieldDescriptor.TYPE_MESSAGE then
return pb_to_table(field_value)
else
return field_value
end
end
if field.label == FieldDescriptor.LABEL_REPEATED then
local o = {}
for _, k in ipairs(value) do
o[#0 + 1] = get_value(k)
end
out[name] = 0
else
out[name] = get_value(value)
end
end
return out
end
PbTostring = function(pb)
local tb = pb_to_table(pb)
local pbName = getmetatable(pb)._descriptor.name
return "[" .. pbName .. "]" .. ToString(tb)
end
--table 转 字符串的⽅法
ToString = function(tab, cnt)
-- if not IsEditor() then
-- return ''
-- end
cnt = cnt or 1
local tp = type(tab)
if tp ~= "table" or cnt >= 4 then -- 这⾥的4是table中嵌套table的层数
return tostring(tab)
end
local function getSpaceStr(count)
count = count or 1
count = count * 4
local temp = {}
for i = 1, count do
table.insert(temp, "")
end
return table.concat(temp)
end
local tabstr = {}
table.insert(tabstr, "{\n")
local spStr = getSpaceStr(cnt)
for k, v in pairs(tab) do
table.insert(tabstr, spStr)
table.insert(tabstr, "[")
table.insert(tabstr, Tostring(k, cnt + 1))
table.insert(tabstr, "] =")
table.insert(tabstr, "[")
table.insert(tabstr, ToString(v, cnt + 1))
table.insert(tabstr, "] ,\n")
end
table.insert(tabstr, getSpaceStr(cnt - 1))
table.insert(tabstr, "}")
return table.concat(tabstr)
end
-- Table操作 -------------------------------------------------- end
|
-- Copyright (C) Miracle
-- Copyright (C) OpenWAF
local _M = {
_VERSION = "1.0.5"
}
local http_cache = require "http_cache"
local twaf_func = require "lib.twaf.inc.twaf_func"
local ngx_log = ngx.log
local ngx_WARN = ngx.WARN
local string_upper = string.upper
local table_insert = table.insert
local _type = type
local function _set_var(ctx, element, value, req)
local col = string_upper(element.column)
local key = element.key
local incr = element.incr
local _time = element.time
local storage = ctx.storage
local dict = req[col]
if _time then
if not dict then return end
key = (element.shm_key or dict:get("default_key") or "")..key
key = twaf_func:parse_dynamic_value(key, req)
dict:add(key, 0, _time)
if incr then
dict:incr(key, value)
else
dict:set(key, value)
end
return
end
if col == "TX" then
storage = req
end
if not storage[col] then
storage[col] = {}
end
if (incr) then
local existing = storage[col][key]
if (existing and _type(existing) ~= "number") then
elseif (not existing) then
existing = 0
end
if (_type(value) == "number") then
value = value + existing
else
value = existing
end
end
storage[col][key] = value
end
function _M.opts(self, _twaf, ctx, sctx, req, options, values)
local func = {
nolog = function()
end,
setvar = function(_twaf, values, ctx, req)
for k, v in ipairs(values) do
local value = twaf_func:parse_dynamic_value(v.value, req)
_set_var(ctx, v, value, req)
end
end,
sanitise_arg = function(_twaf, values, ctx, req)
local tb = {}
local uri_args = _twaf:get_vars("ARGS_GET", req)
if _type(values) == "table" then
for _, v in pairs(values) do
if uri_args[v] then
table_insert(tb, v)
end
end
else
if uri_args[values] then
table_insert(tb, values)
end
end
ctx.sanitise_uri_args = tb
end,
add_resp_headers = function(_twaf, values, ctx)
if _type(values) ~= "table" then
return
end
ctx.add_resp_headers = ctx.add_resp_headers or {}
for k, v in pairs(values) do
ctx.add_resp_headers[k] = v
end
end,
proxy_cache = function(_twaf, values, ctx, req, sctx)
if sctx.cache_down == nil then sctx.cache_down = {} end
if _type(values) ~= "table" or sctx.cache_down[sctx.id or "-"] then return end
sctx.cache_down[sctx.id or "-"] = true
local cache_status = _twaf:get_vars("UPSTREAM_CACHE_STATUS", req) or ""
if cache_status == "MISS" or cache_status == "EXPIRED" then
local cache_data = http_cache.get_metadata()
if cache_data and cache_data.valid_sec then
local new_expire = _twaf:get_vars("TIME_EPOCH", req) + (values.expired or 600)
local cache_meta = {}
cache_meta.fcn = {}
cache_meta.valid_sec = new_expire
cache_meta.fcn.valid_sec = new_expire
cache_meta.fcn.expire = new_expire
cache_meta.min_uses = values.min_uses or 3
http_cache.set_metadata(cache_meta)
end
end
end
}
if not func[options] then
ngx_log(ngx_WARN, "Not support option: ", options)
return nil
end
return func[options](_twaf, values, ctx, req, sctx)
end
return _M
|
-- This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild
--
-- This file is compatible with Lua 5.3
local class = require("class")
require("kaitaistruct")
local str_decode = require("string_decode")
ExprStrOps = class.class(KaitaiStruct)
function ExprStrOps:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function ExprStrOps:_read()
self.one = str_decode.decode(self._io:read_bytes(5), "ASCII")
end
ExprStrOps.property.one_substr_3_to_3 = {}
function ExprStrOps.property.one_substr_3_to_3:get()
if self._m_one_substr_3_to_3 ~= nil then
return self._m_one_substr_3_to_3
end
self._m_one_substr_3_to_3 = string.sub(self.one, 3 + 1, 3)
return self._m_one_substr_3_to_3
end
ExprStrOps.property.to_i_r8 = {}
function ExprStrOps.property.to_i_r8:get()
if self._m_to_i_r8 ~= nil then
return self._m_to_i_r8
end
self._m_to_i_r8 = tonumber("721", 8)
return self._m_to_i_r8
end
ExprStrOps.property.to_i_r16 = {}
function ExprStrOps.property.to_i_r16:get()
if self._m_to_i_r16 ~= nil then
return self._m_to_i_r16
end
self._m_to_i_r16 = tonumber("47cf", 16)
return self._m_to_i_r16
end
ExprStrOps.property.two_substr_0_to_10 = {}
function ExprStrOps.property.two_substr_0_to_10:get()
if self._m_two_substr_0_to_10 ~= nil then
return self._m_two_substr_0_to_10
end
self._m_two_substr_0_to_10 = string.sub(self.two, 0 + 1, 10)
return self._m_two_substr_0_to_10
end
ExprStrOps.property.one_len = {}
function ExprStrOps.property.one_len:get()
if self._m_one_len ~= nil then
return self._m_one_len
end
self._m_one_len = string.len(self.one)
return self._m_one_len
end
ExprStrOps.property.two_len = {}
function ExprStrOps.property.two_len:get()
if self._m_two_len ~= nil then
return self._m_two_len
end
self._m_two_len = string.len(self.two)
return self._m_two_len
end
ExprStrOps.property.one_substr_2_to_5 = {}
function ExprStrOps.property.one_substr_2_to_5:get()
if self._m_one_substr_2_to_5 ~= nil then
return self._m_one_substr_2_to_5
end
self._m_one_substr_2_to_5 = string.sub(self.one, 2 + 1, 5)
return self._m_one_substr_2_to_5
end
ExprStrOps.property.to_i_r2 = {}
function ExprStrOps.property.to_i_r2:get()
if self._m_to_i_r2 ~= nil then
return self._m_to_i_r2
end
self._m_to_i_r2 = tonumber("1010110", 2)
return self._m_to_i_r2
end
ExprStrOps.property.two_rev = {}
function ExprStrOps.property.two_rev:get()
if self._m_two_rev ~= nil then
return self._m_two_rev
end
self._m_two_rev = string.reverse(self.two)
return self._m_two_rev
end
ExprStrOps.property.two = {}
function ExprStrOps.property.two:get()
if self._m_two ~= nil then
return self._m_two
end
self._m_two = "0123456789"
return self._m_two
end
ExprStrOps.property.two_substr_4_to_10 = {}
function ExprStrOps.property.two_substr_4_to_10:get()
if self._m_two_substr_4_to_10 ~= nil then
return self._m_two_substr_4_to_10
end
self._m_two_substr_4_to_10 = string.sub(self.two, 4 + 1, 10)
return self._m_two_substr_4_to_10
end
ExprStrOps.property.to_i_r10 = {}
function ExprStrOps.property.to_i_r10:get()
if self._m_to_i_r10 ~= nil then
return self._m_to_i_r10
end
self._m_to_i_r10 = tonumber("-072")
return self._m_to_i_r10
end
ExprStrOps.property.two_substr_0_to_7 = {}
function ExprStrOps.property.two_substr_0_to_7:get()
if self._m_two_substr_0_to_7 ~= nil then
return self._m_two_substr_0_to_7
end
self._m_two_substr_0_to_7 = string.sub(self.two, 0 + 1, 7)
return self._m_two_substr_0_to_7
end
ExprStrOps.property.to_i_attr = {}
function ExprStrOps.property.to_i_attr:get()
if self._m_to_i_attr ~= nil then
return self._m_to_i_attr
end
self._m_to_i_attr = tonumber("9173")
return self._m_to_i_attr
end
ExprStrOps.property.one_substr_0_to_3 = {}
function ExprStrOps.property.one_substr_0_to_3:get()
if self._m_one_substr_0_to_3 ~= nil then
return self._m_one_substr_0_to_3
end
self._m_one_substr_0_to_3 = string.sub(self.one, 0 + 1, 3)
return self._m_one_substr_0_to_3
end
ExprStrOps.property.one_rev = {}
function ExprStrOps.property.one_rev:get()
if self._m_one_rev ~= nil then
return self._m_one_rev
end
self._m_one_rev = string.reverse(self.one)
return self._m_one_rev
end
|
testfiledir = "testfiles/08-notation-nomencl"
testsuppdir = testfiledir .. "/support"
includetests = {"*"}
excludetests = {}
checkruns = 2
function runtest_tasks(name, run)
if run == 1 then
return "makeindex -s nomencl.ist -o " .. name .. ".nls " .. name .. ".nlo"
else
return ""
end
end
|
local playsession = {
{"pomabroad", {460152}},
{"Menander", {573436}},
{"rlidwka", {322479}},
{"Hitman451", {540966}},
{"InphinitePhractals", {126753}},
{"mad58max", {315753}},
{"MuddledBox", {99252}},
{"eyepex", {194249}}
}
return playsession |
--
-- Track indicators from F3705 gadget.
--
------------------------------------------------------------------------------
-- "THE BEER-WARE LICENSE" (Revision 42):
-- <philip@paeps.cx> wrote this file. As long as you retain this notice you
-- can do whatever you want with this stuff. If we meet some day, and you
-- think this stuff is worth it, you can buy me a beer in return.
-- - Philip Paeps
------------------------------------------------------------------------------
local assert = assert
local setmetatable = setmetatable
local io = {
open = io.open
}
local capi = {
widget = widget,
mouse = mouse
}
local naughty = require("naughty")
local awful = require("awful")
local wibox = require("wibox")
local lib = {
hooks = require("obvious.lib.hooks"),
markup = require("obvious.lib.markup")
}
module("obvious.umts")
widget = wibox.widget.textbox()
local fh = nil
local cops = {}
local cind = {}
function wait_for_data(input)
fh:write(input)
local data = ""
local lastline
repeat
lastline = assert(fh:read())
data = data .. lastline .. "\n"
until lastline:match("OK")
return data
end
function get_indicators()
local cind = wait_for_data("AT+CIND?\r\n")
local rv = {}
rv.signal = cind:match("+CIND: %d,(%d)")
rv.service = cind:match("+CIND: %d,%d,%d,%d,(%d)")
rv.roaming = cind:match("+CIND: %d,%d,%d,%d,%d,%d,%d,(%d)")
return rv
end
function get_operator()
wait_for_data("AT+COPS=3,0\r\n")
local cops = wait_for_data("AT+COPS?\r\n")
local rv = {}
rv.mode = cops:match("+COPS: (%d)")
rv.format = cops:match("+COPS: %d,(%d)")
rv.oper = cops:match("+COPS: %d,%d,\"(%a*)\"")
rv.act = cops:match("+COPS: %d,%d,\"%a*\",(%d)")
return rv
end
local function update()
fh = io.open("/dev/ttyACM1", "r+")
if not fh then
cops = {}
cind = {}
widget.text = ""
return
end
cops = get_operator()
cind = get_indicators()
widget.text = " " .. cops.oper
fh:close()
end
local function detail()
if not cops.oper then return end
naughty.notify({
text = "Mobile operator: " .. cops.oper ..
"\nSignal strength: " .. cind.signal .. "/5" ..
"\nRoaming: " .. cind.roaming,
screen = capi.mouse.screen
})
end
widget:buttons(awful.util.table.join(
awful.button({ }, 1, detail)
))
update()
lib.hooks.timer.register(60, 300, update)
lib.hooks.timer.start(update)
setmetatable(_M, { __call = function () return widget end })
-- vim:ft=lua:ts=2:sw=2:sts=2:tw=80:et
|
--
-- This is fun64 code, you can copy paste it into https://xriss.github.io/fun64/pad/ to run it.
--
hardware,main=system.configurator({
mode="fun64", -- select the standard 320x240 screen using the swanky32 palette.
update=function() update() end, -- called repeatedly to update
draw=function() draw() end, -- called repeatedly to draw
msg=function(m) msg(m) end, -- handle msgs
})
local wstr=require("wetgenes.string")
-- we will call this once in the update function
setup=function()
-- system.components.screen.bloom=0
-- system.components.screen.filter=nil
-- system.components.screen.shadow=nil
print("Setup complete!")
end
lines={}
-- handle raw key press
msg=function(m)
--print(wstr.dump(m))
local s
if m.class=="mouse" then
s=string.format("%6.2f %8s %2d %3d,%3d %s %s",m.time,m.class,m.action,m.x,m.y,tostring(m.keycode or ""),m.keyname or "")
elseif m.class=="touch" then
s=string.format("%6.2f %8s %2d %3d,%3d %3d %3d",m.time,m.class,m.action,m.x,m.y,m.id or 0,m.pressure or 0)
elseif m.class=="padaxis" then
s=string.format("%6.2f %8s %2d %8s %5d %3d",m.time,m.class,m.id or 0,m.name,m.value,m.code)
elseif m.class=="padkey" then
s=string.format("%6.2f %8s %2d %8s %3d %3d",m.time,m.class,m.id or 0,m.name,m.value,m.code)
elseif m.class=="key" then
s=string.format("%6.2f %8s %2d %3s %16s",m.time,m.class,m.action,m.ascii,m.keyname)
else
s=string.format("%6.2f %8s %2d",m.time or 0,m.class,m.action or 0)
end
lines[#lines+1]=s
while #lines > 14 do table.remove(lines,1) end
end
-- updates are run at 60fps
update=function()
if setup then setup() setup=nil end
end
draw=function()
local ccmap=system.components.colors.cmap
local cmap=system.components.map
local ctext=system.components.text
local bg=9
local fg=31
cmap.text_clear(0x01000000*bg) -- clear text forcing a background color
local y=1
for i=0,6 do
local up=ups(i)
local ns={
"up","down","left","right","fire", -- basic joystick, most buttons map to fire
"pad_up","pad_down","pad_left","pad_right", -- the d-pad directions
"x","y","a","b", -- the four face buttons
"l1","l2","l3","r1","r2","r3", -- the triggers and stick clicks
"select","start","guide", -- the menu face buttons
"mouse_left","mouse_right","mouse_middle", -- mouse buttons
"touch", -- touch buttons
}
local ax={"lx","ly","lz","rx","ry","rz","dx","dy","mx","my","tx","ty"} -- axis name
local a={}
for i,n in ipairs(ax) do
local v=up.axis(n)
if v and v~=0 then
a[#a+1]=n.."="..math.floor(v+0.5)
end
end
for i,n in ipairs(ns) do
if up.button(n.."_set") then a[#a+1]=n.."_set" end -- value was set this frame
if up.button(n.."_clr") then a[#a+1]=n.."_clr" end -- value was cleared this frame
if up.button(n) then a[#a+1]=n end -- current value
end
local s=i.."up : "..table.concat(a," ")
ctext.text_print(s,2,y,fg,0) y=y+1
y=y+1
end
for i=1,#lines do
ctext.text_print(lines[i],1,y,fg,0)
y=y+1
end
end
|
---
-- @classmod ScoredActionPickerProvider
-- @author Quenty
local require = require(script.Parent.loader).load(script)
local BaseObject = require("BaseObject")
local ScoredActionPicker = require("ScoredActionPicker")
local Table = require("Table")
local TouchButtonScoredActionPicker = require("TouchButtonScoredActionPicker")
local InputKeyMapUtils = require("InputKeyMapUtils")
local MAX_ACTION_LIST_SIZE_BEFORE_WARN = 25
local ScoredActionPickerProvider = setmetatable({}, BaseObject)
ScoredActionPickerProvider.ClassName = "ScoredActionPickerProvider"
ScoredActionPickerProvider.__index = ScoredActionPickerProvider
function ScoredActionPickerProvider.new()
local self = setmetatable(BaseObject.new(), ScoredActionPickerProvider)
self._scoredActionPickers = {} -- [ key ] = picker
return self
end
function ScoredActionPickerProvider:FindPicker(inputType)
local key = InputKeyMapUtils.getUniqueKeyForInputType(inputType)
return self._scoredActionPickers[key]
end
--inputType is most likely an enum, but could be a string!
function ScoredActionPickerProvider:GetOrCreatePicker(inputType)
assert(inputType, "Bad inputType")
local key = InputKeyMapUtils.getUniqueKeyForInputType(inputType)
if self._scoredActionPickers[key] then
return self._scoredActionPickers[key]
end
local picker
if inputType == "TouchButton" then
picker = TouchButtonScoredActionPicker.new()
else
picker = ScoredActionPicker.new()
end
self._maid[key] = picker
self._scoredActionPickers[key] = picker
local amount = Table.count(self._scoredActionPickers)
if amount > MAX_ACTION_LIST_SIZE_BEFORE_WARN then
warn(("[ScoredActionPickerProvider.GetPicker] - Pickers has size of %d/%d")
:format(#amount, MAX_ACTION_LIST_SIZE_BEFORE_WARN))
end
return picker
end
function ScoredActionPickerProvider:Update()
local indexToRemove = {}
for key, picker in pairs(self._scoredActionPickers) do
picker:Update()
if not picker:HasActions() then
table.insert(indexToRemove, key)
end
end
for _, key in pairs(indexToRemove) do
self._scoredActionPickers[key] = nil
self._maid[key] = nil
end
end
return ScoredActionPickerProvider |
OUTFIT_DATA = {
/*
EXTENDED ENHANCED CITIZEN - FEMALE
strong default model packs for the casuals!
http://steamcommunity.com/sharedfiles/filedetails/?id=677125227
https://steamcommunity.com/sharedfiles/filedetails/?id=677129372
*/
["models/player/zelpa/female_01_extended.mdl"] = {uid = "efemale", skins = 18},
["models/player/zelpa/female_02_extended.mdl"] = {uid = "efemale", skins = 18},
["models/player/zelpa/female_03_extended.mdl"] = {uid = "efemale", skins = 21},
["models/player/zelpa/female_04_extended.mdl"] = {uid = "efemale", skins = 15},
["models/player/zelpa/female_06_extended.mdl"] = {uid = "efemale", skins = 18},
["models/player/zelpa/female_07_extended.mdl"] = {uid = "efemale", skins = 12},
/*
EXTENDED ENHANCED CITIZEN - MALE
strong default model packs for the casuals!
http://steamcommunity.com/sharedfiles/filedetails/?id=677125227
https://steamcommunity.com/sharedfiles/filedetails/?id=677129372
*/
["models/player/zelpa/male_01_extended.mdl"] = {uid = "emale", skins = 24},
["models/player/zelpa/male_02_extended.mdl"] = {uid = "emale", skins = 24},
["models/player/zelpa/male_03_extended.mdl"] = {uid = "emale", skins = 21},
["models/player/zelpa/male_04_extended.mdl"] = {uid = "emale", skins = 24},
["models/player/zelpa/male_05_extended.mdl"] = {uid = "emale", skins = 21},
["models/player/zelpa/male_06_extended.mdl"] = {uid = "emale", skins = 21},
["models/player/zelpa/male_07_extended.mdl"] = {uid = "emale", skins = 24},
["models/player/zelpa/male_08_extended.mdl"] = {uid = "emale", skins = 24},
["models/player/zelpa/male_09_extended.mdl"] = {uid = "emale", skins = 24},
["models/player/zelpa/male_10_extended.mdl"] = {uid = "emale", skins = 6},
["models/player/zelpa/male_11_extended.mdl"] = {uid = "emale", skins = 12},
/*
BLACK TEA CITIZENS - MALE
extended customization to the max!
https://steamcommunity.com/sharedfiles/filedetails/?id=951557268
*/
["models/btcitizen/male_01.mdl"] = {
uid = "bmale",
facemap = "models/btcitizen/facemaps/van_facemap",
skins = {
"facemaps/van_facemap",
"facemaps/van_facemap2",
"facemaps/van_facemap3",
"facemaps/van_facemap4",
"facemaps/rusty/van_facemap1",
"facemaps/rusty/van_facemap2",
"facemaps/ffactory/van_facemap",
},
},
["models/btcitizen/male_02.mdl"] = {
uid = "bmale",
facemap = "models/btcitizen/facemaps/ted_facemap",
skins = {
"facemaps/ted_facemap",
"facemaps/ted_facemap2",
"facemaps/ted_facemap3",
"facemaps/ted_facemap4",
"facemaps/rusty1/ted_facemap",
"facemaps/rusty2/ted_facemap3",
"facemaps/rusty3/ted_facemap4",
"facemaps/rusty4/ted_facemap5",
"facemaps/ffactory/ted_facemap",
"facemaps/freshman/ted_facemap",
"facemaps/zombie/ted_facemap",
},
},
["models/btcitizen/male_03.mdl"] = {
uid = "bmale",
facemap = "models/btcitizen/facemaps/joe_facemap",
skins = {
"facemaps/joe_facemap",
"facemaps/joe_facemap2",
"facemaps/joe_facemap3",
"facemaps/joe_facemap4",
"facemaps/rusty/joe_facemap",
"facemaps/rusty/joe_facemap2",
"facemaps/rusty/joe_facemap3",
"facemaps/rusty/joe_facemap4",
"facemaps/ffactory/joe_facemap",
"facemaps/zombie/joe_facemap",
"facemaps/newface/joe_facemap",
},
},
["models/btcitizen/male_04.mdl"] = {
uid = "bmale",
facemap = "models/btcitizen/facemaps/eric_facemap",
skins = {
"facemaps/eric_facemap",
"facemaps/eric_facemap2",
"facemaps/eric_facemap3",
"facemaps/eric_facemap4",
"facemaps/ffactory/eric_facemap",
"facemaps/freshman/eric_facemap",
"facemaps/zombie/eric_facemap",
},
},
["models/btcitizen/male_05.mdl"] = {
uid = "bmale",
facemap = "models/btcitizen/facemaps/art_facemap",
skins = {
"facemaps/art_facemap",
"facemaps/art_facemap2",
"facemaps/art_facemap3",
"facemaps/art_facemap4",
"facemaps/ffactory/art_facemap",
"facemaps/newface1/art_facemap",
"facemaps/zombie/art_facemap",
},
},
["models/btcitizen/male_06.mdl"] = {
uid = "bmale",
facemap = "models/btcitizen/facemaps/sandro_facemap",
skins = {
"facemaps/sandro_facemap",
"facemaps/sandro_facemap2",
"facemaps/sandro_facemap3",
"facemaps/sandro_facemap4",
"facemaps/sandro_facemap5",
"facemaps/ffactory/sandro_facemap",
"facemaps/mafia/sandro_facemap",
"facemaps/newface1/sandro_facemap",
"facemaps/rusty/sandro_facemap",
"facemaps/rusty/sandro_facemap2",
"facemaps/rusty/sandro_facemap3",
"facemaps/zombie/sandro_facemap",
},
},
["models/btcitizen/male_07.mdl"] = {
uid = "bmale",
facemap = "models/btcitizen/facemaps/mike_facemap",
skins = {
"facemaps/mike_facemap",
"facemaps/mike_facemap2",
"facemaps/mike_facemap3",
"facemaps/mike_facemap4",
"facemaps/ffactory/mike_facemap",
"facemaps/rusty/mike_facemap",
"facemaps/zombie/mike_facemap",
},
},
["models/btcitizen/male_08.mdl"] = {
uid = "bmale",
facemap = "models/btcitizen/facemaps/vance_facemap",
skins = {
"facemaps/vance_facemap",
"facemaps/vance_facemap2",
"facemaps/vance_facemap3",
"facemaps/vance_facemap4",
"facemaps/vance_facemap5",
"facemaps/ffactory/vance_facemap",
"facemaps/freshman/vance_facemap",
"facemaps/mafia/vance_facemap",
"facemaps/newface1/vance_facemap",
"facemaps/rusty/vance_facemap",
"facemaps/rusty/vance_facemap2",
"facemaps/rusty/vance_facemap3",
"facemaps/zombie/vance_facemap",
},
},
["models/btcitizen/male_09.mdl"] = {
uid = "bmale",
facemap = "models/btcitizen/facemaps/erdim_facemap",
skins = {
"facemaps/ffactory/erdim_cylmap",
"facemaps/rusty/erdim_facemap",
"facemaps/rusty2/erdim_facemap",
},
},
["models/btcitizen/male_10.mdl"] = {
uid = "bmale",
skins = {
},
},
["models/btcitizen/male_11.mdl"] = {
uid = "bmale",
skins = {
},
},
["models/btcitizen/male_12.mdl"] = {
uid = "bmale",
skins = {
},
},
["models/btcitizen/male_13.mdl"] = {
uid = "bmale",
skins = {
},
},
["models/btcitizen/male_14.mdl"] = {
uid = "bmale",
skins = {
},
},
/*
BLACK TEA CITIZENS - FEMALE
extended customization to the max!
https://steamcommunity.com/sharedfiles/filedetails/?id=951557268
*/
["models/btcitizen/female_01.mdl"] = {
uid = "bfemale",
skins = {
},
},
["models/btcitizen/female_02.mdl"] = {
uid = "bfemale",
skins = {
},
},
["models/btcitizen/female_03.mdl"] = {
uid = "bfemale",
skins = {
},
},
["models/btcitizen/female_04.mdl"] = {
uid = "bfemale",
skins = {
},
},
["models/btcitizen/female_05.mdl"] = {
uid = "bfemale",
skins = {
},
},
["models/btcitizen/female_06.mdl"] = {
uid = "bfemale",
skins = {
},
},
["models/btcitizen/female_07.mdl"] = {
uid = "bfemale",
skins = {
},
},
["models/btcitizen/female_08.mdl"] = {
uid = "bfemale",
skins = {
},
},
}
OUTFIT_REGISTERED = {
-- EXTENDED ENHANCED CITIZEN SUPPORT
efemale = {
{
name = "model",
},
{
name = "face",
outfits = function(entity)
local faces = {}
local mdl = entity:GetModel()
local woo = OUTFIT_DATA[mdl:lower()]
if (!woo) then return faces end
local facemaps = woo.skins
for i = 1, facemaps do
table.insert(faces, {data = (i - 1), name = "facemap", price = 9500})
end
return faces
end,
func = function(entity, outfit, orig)
if (outfit) then
local facemap = tonumber(outfit.data)
if (facemap) then
entity:SetSkin(facemap)
end
end
end,
},
{
bodygroup = 4,
name = "head",
outfits = {
{data = 0, name = "bodygroup", price = 4500},
{data = 1, name = "bodygroup", price = 4500},
{data = 2, name = "bodygroup", price = 4500},
},
func = function(entity, outfit, orig)
local bodygroup = tonumber(outfit.data)
local part = orig.bodygroup
if (bodygroup) then
if (part) then
entity:SetBodygroup(part, bodygroup)
end
end
end,
},
{
name = "torso",
bodygroup = 1,
outfits = {
{data = 0, name = "bodygroup", price = 4500},
{data = 5, name = "bodygroup", price = 4500},
{data = 6, name = "bodygroup", price = 4500},
{data = 7, name = "bodygroup", price = 4500},
{data = 8, name = "bodygroup", price = 4500},
{data = 9, name = "bodygroup", price = 4500},
{data = 15, name = "bodygroup", price = 4500},
{data = 16, name = "bodygroup", price = 4500},
{data = 17, name = "bodygroup", price = 4500},
{data = "citizensheetf/scrubs1_shtfe",name = "sheet", price = 4500},
{data = "citizensheetf/scrubs2_shtfe", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_01", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_02", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_03", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_04", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_05", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_06", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_07", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_08", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_09", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_10", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_11", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_12", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_13", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_14", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_15", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_suit", name = "sheet", price = 4500},
},
func = function(entity, outfit, orig)
local bodygroup = tonumber(outfit.data)
local find = "models/bloo_ltcom_zel/citizens/female/citizen_sheet"
local part = orig.bodygroup
local matIndex
for k, v in ipairs(entity:GetMaterials()) do
if (v == find) then
matIndex = k - 1
break
end
end
if (!bodygroup) then
if (part) then
entity:SetBodygroup(part, 0)
end
if (matIndex) then
entity:SetSubMaterial(matIndex, outfit.data)
end
else
if (matIndex) then
entity:SetSubMaterial(matIndex)
end
if (part) then
entity:SetBodygroup(part, bodygroup)
end
end
end,
},
{
bodygroup = 3,
name = "gloves",
outfits = {
{data = 0, name = "bodygroup", price = 4500},
{data = 1, name = "bodygroup", price = 4500},
{data = 2, name = "bodygroup", price = 4500},
},
func = function(entity, outfit, orig)
local bodygroup = tonumber(outfit.data)
local part = orig.bodygroup
if (bodygroup) then
if (part) then
entity:SetBodygroup(part, bodygroup)
end
end
end,
},
{
bodygroup = 2,
name = "pants",
outfits = {
{data = 1, name = "bodygroup", price = 4500},
{data = "citizensheetf/scrubs1_shtfe",name = "sheet", price = 4500},
{data = "citizensheetf/scrubs2_shtfe", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_01", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_02", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_03", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_04", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_05", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_06", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_07", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_08", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_09", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_10", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_11", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_12", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_13", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_14", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_15", name = "sheet", price = 4500},
{data = "citizensheetf/sheet_suit", name = "sheet", price = 4500},
},
func = function(entity, outfit, orig)
local bodygroup = tonumber(outfit.data)
local find = "models/bloo_ltcom_zel/citizens/female/citizen_sheet2"
local part = orig.bodygroup
local matIndex
for k, v in ipairs(entity:GetMaterials()) do
if (v == find) then
matIndex = k - 1
break
end
end
if (!bodygroup) then
if (part) then
entity:SetBodygroup(part, 1)
end
if (matIndex) then
entity:SetSubMaterial(matIndex, outfit.data)
end
else
if (matIndex) then
entity:SetSubMaterial(matIndex)
end
if (part) then
entity:SetBodygroup(part, bodygroup)
end
end
end,
},
},
emale = {
{
name = "model",
},
{
name = "face",
outfits = function(entity)
local faces = {}
local mdl = entity:GetModel()
local woo = OUTFIT_DATA[mdl:lower()]
if (!woo) then return faces end
local facemaps = woo.skins
for i = 1, facemaps do
table.insert(faces, {data = (i - 1), name = "facemap", price = 9500})
end
return faces
end,
func = function(entity, outfit, orig)
if (outfit) then
local facemap = tonumber(outfit.data)
if (facemap) then
entity:SetSkin(facemap)
end
end
end,
},
{
bodygroup = 4,
name = "head",
outfits = {
{data = 0, name = "bodygroup", price = 4500},
{data = 1, name = "bodygroup", price = 4500},
{data = 2, name = "bodygroup", price = 4500},
},
func = function(entity, outfit, orig)
local bodygroup = tonumber(outfit.data)
local part = orig.bodygroup
if (bodygroup) then
if (part) then
entity:SetBodygroup(part, bodygroup)
end
end
end,
},
{
name = "torso",
bodygroup = 1,
outfits = {
{data = 0, name = "bodygroup", price = 4500},
{data = 5, name = "bodygroup", price = 4500},
{data = 6, name = "bodygroup", price = 4500},
{data = 7, name = "bodygroup", price = 4500},
{data = 8, name = "bodygroup", price = 4500},
{data = 9, name = "bodygroup", price = 4500},
{data = 15, name = "bodygroup", price = 4500},
{data = 16, name = "bodygroup", price = 4500},
{data = 17, name = "bodygroup", price = 4500},
{data = 18, name = "bodygroup", price = 4500},
{data = 19, name = "bodygroup", price = 4500},
{data = 20, name = "bodygroup", price = 4500},
{data = "citizensheet/sheet_02", name = "sheet", price = 4500},
{data = "citizensheet/sheet_03", name = "sheet", price = 4500},
{data = "citizensheet/sheet_reich", name = "sheet", price = 4500},
{data = "citizensheet/scrubs1_sheet", name = "sheet", price = 4500},
{data = "citizensheet/scrubs2_sheet", name = "sheet", price = 4500},
{data = "citizensheet/sheet_suit", name = "sheet", price = 4500},
{data = "citizensheet/sheet_04", name = "sheet", price = 4500},
{data = "citizensheet/sheet_08", name = "sheet", price = 4500},
{data = "citizensheet/sheet_10", name = "sheet", price = 4500},
{data = "citizensheet/sheet_14", name = "sheet", price = 4500},
{data = "citizensheet/sheet_18", name = "sheet", price = 4500},
{data = "citizensheet/sheet_17", name = "sheet", price = 4500},
{data = "citizensheet/sheet_19", name = "sheet", price = 4500},
{data = "citizensheet/sheet_20", name = "sheet", price = 4500},
{data = "citizensheet/sheet_21", name = "sheet", price = 4500},
{data = "citizensheet/sheet_22", name = "sheet", price = 4500},
{data = "citizensheet/sheet_23", name = "sheet", price = 4500},
{data = "citizensheet/sheet_24", name = "sheet", price = 4500},
{data = "citizensheet/sheet_25", name = "sheet", price = 4500},
{data = "citizensheet/sheet_26", name = "sheet", price = 4500},
{data = "citizensheet/sheet_27", name = "sheet", price = 4500},
{data = "citizensheet/sheet_28", name = "sheet", price = 4500},
{data = "citizensheet/sheet_29", name = "sheet", price = 4500},
{data = "citizensheet/sheet_30", name = "sheet", price = 4500},
{data = "citizensheet/sheet_31", name = "sheet", price = 4500},
{data = "citizensheet/costage_sheet", name = "sheet", price = 4500},
{data = "citizensheet/hostage_sheet", name = "sheet", price = 4500},
{data = "citizensheet/security_sheet", name = "sheet", price = 4500},
{data = "citizensheet/military_sheet", name = "sheet", price = 4500},
{data = "citizensheet/monk_sheet", name = "sheet", price = 4500},
},
func = function(entity, outfit, orig)
local bodygroup = tonumber(outfit.data)
local find = "models/bloo_ltcom_zel/citizens/citizen_sheet"
local part = orig.bodygroup
local matIndex
for k, v in ipairs(entity:GetMaterials()) do
if (v == find) then
matIndex = k - 1
break
end
end
if (!bodygroup) then
if (part) then
entity:SetBodygroup(part, 0)
end
if (matIndex) then
entity:SetSubMaterial(matIndex, outfit.data)
end
else
if (matIndex) then
entity:SetSubMaterial(matIndex)
end
if (part) then
entity:SetBodygroup(part, bodygroup)
end
end
end,
},
{
bodygroup = 3,
name = "gloves",
outfits = {
{data = 0, name = "bodygroup", price = 4500},
{data = 1, name = "bodygroup", price = 4500},
{data = 2, name = "bodygroup", price = 4500},
},
func = function(entity, outfit, orig)
local bodygroup = tonumber(outfit.data)
local part = orig.bodygroup
if (bodygroup) then
if (part) then
entity:SetBodygroup(part, bodygroup)
end
end
end,
},
{
bodygroup = 2,
name = "pants",
outfits = {
{data = 1, name = "bodygroup", price = 4500},
{data = "citizensheet/sheet_02", name = "sheet", price = 4500},
{data = "citizensheet/sheet_03", name = "sheet", price = 4500},
{data = "citizensheet/sheet_reich", name = "sheet", price = 4500},
{data = "citizensheet/scrubs1_sheet", name = "sheet", price = 4500},
{data = "citizensheet/scrubs2_sheet", name = "sheet", price = 4500},
{data = "citizensheet/sheet_suit", name = "sheet", price = 4500},
{data = "citizensheet/sheet_04", name = "sheet", price = 4500},
{data = "citizensheet/sheet_08", name = "sheet", price = 4500},
{data = "citizensheet/sheet_10", name = "sheet", price = 4500},
{data = "citizensheet/sheet_14", name = "sheet", price = 4500},
{data = "citizensheet/sheet_18", name = "sheet", price = 4500},
{data = "citizensheet/sheet_17", name = "sheet", price = 4500},
{data = "citizensheet/sheet_19", name = "sheet", price = 4500},
{data = "citizensheet/sheet_20", name = "sheet", price = 4500},
{data = "citizensheet/sheet_21", name = "sheet", price = 4500},
{data = "citizensheet/sheet_22", name = "sheet", price = 4500},
{data = "citizensheet/sheet_23", name = "sheet", price = 4500},
{data = "citizensheet/sheet_24", name = "sheet", price = 4500},
{data = "citizensheet/sheet_25", name = "sheet", price = 4500},
{data = "citizensheet/sheet_26", name = "sheet", price = 4500},
{data = "citizensheet/sheet_27", name = "sheet", price = 4500},
{data = "citizensheet/sheet_28", name = "sheet", price = 4500},
{data = "citizensheet/sheet_29", name = "sheet", price = 4500},
{data = "citizensheet/sheet_30", name = "sheet", price = 4500},
{data = "citizensheet/sheet_31", name = "sheet", price = 4500},
{data = "citizensheet/costage_sheet", name = "sheet", price = 4500},
{data = "citizensheet/hostage_sheet", name = "sheet", price = 4500},
{data = "citizensheet/security_sheet", name = "sheet", price = 4500},
{data = "citizensheet/military_sheet", name = "sheet", price = 4500},
{data = "citizensheet/monk_sheet", name = "sheet", price = 4500},
},
func = function(entity, outfit, orig)
local bodygroup = tonumber(outfit.data)
local find = "models/bloo_ltcom_zel/citizens/citizen_sheet2"
local part = orig.bodygroup
local matIndex
for k, v in ipairs(entity:GetMaterials()) do
if (v == find) then
matIndex = k - 1
break
end
end
if (!bodygroup) then
if (part) then
entity:SetBodygroup(part, 1)
end
if (matIndex) then
entity:SetSubMaterial(matIndex, outfit.data)
end
else
if (matIndex) then
entity:SetSubMaterial(matIndex)
end
if (part) then
entity:SetBodygroup(part, bodygroup)
end
end
end,
},
},
-- BLACK TEA CITIZEN COMPILATION SUPPORT
bmale = {
{
name = "face",
canDisplay = function()
end,
outfits = function(entity)
local mdl = entity:GetModel()
local faces = {}
local woo = OUTFIT_DATA[mdl:lower()]
if (!woo) then return faces end
if (woo.facemap) then
local mdl = entity:GetModel()
local facemaps = woo.skins
table.insert(faces, {mat = woo.facemap, price = 9500})
if (facemaps) then
for i = 1, #facemaps do
table.insert(faces, {mat = facemaps[i], price = 9500})
end
end
end
return faces
end,
func = function(entity, outfit, orig)
local mdl = entity:GetModel()
local woo = OUTFIT_DATA[mdl:lower()]
if (outfit and woo.facemap) then
local find = woo.facemap
local matIndex
for k, v in ipairs(entity:GetMaterials()) do
if (v == find) then
matIndex = k - 1
break
end
end
if (matIndex and outfit.mat) then
entity:SetSubMaterial(matIndex, outfit.mat)
end
end
end,
},
{
name = "torso",
bodygroup = 1,
outfits = {
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 0, mat = "models/btcitizen/citizen_sheet"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 0, mat = "citizensheet/sheet_02"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 0, mat = "citizensheet/sheet_03"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 0, mat = "citizensheet/sheet_reich"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 0, mat = "citizensheet/sheet_suit"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 0, mat = "citizensheet/sheet_04"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 0, mat = "citizensheet/sheet_08"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 0, mat = "citizensheet/sheet_10"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 0, mat = "citizensheet/sheet_14"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 0, mat = "citizensheet/sheet_18"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 0, mat = "citizensheet/sheet_17"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 0, mat = "citizensheet/sheet_19"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 0, mat = "citizensheet/sheet_20"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 0, mat = "citizensheet/sheet_21"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 0, mat = "citizensheet/sheet_22"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 0, mat = "citizensheet/sheet_23"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 0, mat = "citizensheet/sheet_24"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 0, mat = "citizensheet/sheet_25"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 0, mat = "citizensheet/sheet_26"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 0, mat = "citizensheet/sheet_27"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 0, mat = "citizensheet/sheet_28"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 0, mat = "citizensheet/sheet_29"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 0, mat = "citizensheet/sheet_30"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 0, mat = "citizensheet/sheet_31"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 0, mat = "citizensheet/costage_sheet"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 0, mat = "citizensheet/hostage_sheet"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 0, mat = "citizensheet/security_sheet"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 0, mat = "citizensheet/military_sheet"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 0, mat = "citizensheet/monk_sheet"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 1, mat = "citizensheet/sheet_27"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 1, mat = "citizensheet/sheet_30"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 1, mat = "citizensheet/sheet_29"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 1, mat = "citizensheet/sheet_28"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 1, mat = "citizensheet/sheet_26"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 1, mat = "citizensheet/sheet_25"},
{price = 5000, find = "models/btcitizen/citizen_sheet", group = 1, mat = "citizensheet/sheet_reich"},
{price = 5000, find = "models/btcitizen/prague_civ_rioter_body_col_a", group = 2, mat = "models/btcitizen/prague_civ_rioter_body_col_a"},
{price = 5000, find = "models/btcitizen/prague_civ_rioter_body_col_a", group = 2, mat = "models/btcitizen/prague_civ_rioter_body_col_b"},
{price = 5000, find = "models/btcitizen/prague_civ_rioter_body_col_a", group = 2, mat = "models/btcitizen/prague_civ_rioter_body_col_c"},
{price = 5000, find = "models/btcitizen/prague_civ_rioter_body_col_a", group = 3, mat = "models/btcitizen/prague_civ_rioter_body_col_a"},
{price = 5000, find = "models/btcitizen/prague_civ_rioter_body_col_a", group = 3, mat = "models/btcitizen/prague_civ_rioter_body_col_b"},
{price = 5000, find = "models/btcitizen/prague_civ_rioter_body_col_a", group = 3, mat = "models/btcitizen/prague_civ_rioter_body_col_c"},
{price = 5000, find = "models/btcitizen/prague_civ_rioter_body_col_a", group = 4, mat = "models/btcitizen/prague_civ_rioter_body_col_a"},
{price = 5000, find = "models/btcitizen/prague_civ_rioter_body_col_a", group = 4, mat = "models/btcitizen/prague_civ_rioter_body_col_b"},
{price = 5000, find = "models/btcitizen/prague_civ_rioter_body_col_a", group = 4, mat = "models/btcitizen/prague_civ_rioter_body_col_c"},
{price = 5000, find = "models/btcitizen/citizen_summer", group = 5, mat = "models/btcitizen/citizen_summer"},
{price = 5000, find = "models/btcitizen/citizen_summer", group = 5, mat = "models/btcitizen/summersheet/citizen_summer2"},
{price = 5000, find = "models/btcitizen/citizen_summer", group = 5, mat = "models/btcitizen/summersheet/citizen_summer3"},
{price = 5000, find = "models/btcitizen/citizen_summer", group = 5, mat = "models/btcitizen/summersheet/citizen_summer4"},
{price = 5000, find = "models/btcitizen/citizen_summer", group = 5, mat = "models/btcitizen/summersheet/citizen_summer5"},
{price = 5000, find = "models/btcitizen/citizen_summer", group = 5, mat = "models/btcitizen/summersheet/citizen_summer6"},
{price = 5000, find = "models/btcitizen/citizen_summer", group = 5, mat = "models/btcitizen/summersheet/citizen_summer7"},
{price = 5000, find = "models/btcitizen/citizen_summer", group = 5, mat = "models/btcitizen/summersheet/citizen_summer8"},
{price = 5000, find = "models/btcitizen/citizen_summer", group = 5, mat = "models/btcitizen/summersheet/citizen_summer9"},
{price = 5000, find = "models/btcitizen/citizen_summer", group = 5, mat = "models/btcitizen/summersheet/citizen_summer10"},
{price = 5000, find = "models/btcitizen/citizen_summer", group = 5, mat = "models/btcitizen/summersheet/citizen_summer11"},
{price = 5000, find = "models/btcitizen/citizen_summer", group = 5, mat = "models/btcitizen/summersheet/citizen_summer_camo"},
{price = 5000, group = 6},
},
func = function(entity, outfit, orig)
if (orig.bodygroup) then
local find = outfit.find
local matIndex
for k, v in ipairs(entity:GetMaterials()) do
if (v == find) then
matIndex = k - 1
break
end
end
if (matIndex and outfit.mat) then
entity:SetSubMaterial(matIndex, outfit.mat)
end
if (outfit.group) then
entity:SetBodygroup(orig.bodygroup, outfit.group)
end
end
end,
},
{
bodygroup = 3,
name = "shoes",
outfits = {
{price = 5000, find = "models/btcitizen/citizen_sheet_shoes", group = 0, mat = "models/btcitizen/citizen_sheet"},
{price = 5000, find = "models/btcitizen/citizen_sheet_shoes", group = 0, mat = "citizensheet/sheet_02"},
{price = 5000, find = "models/btcitizen/citizen_sheet_shoes", group = 0, mat = "citizensheet/sheet_03"},
{price = 5000, find = "models/btcitizen/citizen_sheet_shoes", group = 0, mat = "citizensheet/sheet_17"},
{price = 5000, find = "models/btcitizen/citizen_sheet_shoes", group = 0, mat = "citizensheet/sheet_24"},
{price = 5000, find = "models/btcitizen/citizen_sheet_shoes", group = 0, mat = "citizensheet/sheet_26"},
{price = 5000, find = "models/btcitizen/citizen_sheet_shoes", group = 0, mat = "citizensheet/hostage_sheet"},
{price = 5000, find = "models/btcitizen/citizen_sheet_shoes", group = 0, mat = "citizensheet/security_sheet"},
{price = 5000, find = "models/btcitizen/citizen_sheet_shoes", group = 0, mat = "citizensheet/military_sheet"},
{price = 5000, find = "models/btcitizen/citizen_sheet_shoes", group = 0, mat = "citizensheet/monk_sheet"},
{price = 5000, group = 1},
{price = 5000, group = 2},
{price = 5000, group = 3},
},
func = function(entity, outfit, orig)
/*
local bodygroup = tonumber(outfit.data)
local part = orig.bodygroup
if (bodygroup) then
if (part) then
entity:SetBodygroup(part, bodygroup)
end
end*/
if (orig.bodygroup) then
local find = outfit.find
if (find) then
local matIndex
for k, v in ipairs(entity:GetMaterials()) do
if (v == find) then
matIndex = k - 1
break
end
end
if (matIndex and outfit.mat) then
entity:SetSubMaterial(matIndex, outfit.mat)
end
end
if (outfit.group) then
entity:SetBodygroup(orig.bodygroup, outfit.group)
end
end
end,
},
{
bodygroup = 4,
name = "gloves",
outfits = {
{data = 0, name = "bodygroup", price = 4500},
{data = 1, name = "bodygroup", price = 4500},
{data = 2, name = "bodygroup", price = 4500},
},
func = function(entity, outfit, orig)
local bodygroup = tonumber(outfit.data)
local part = orig.bodygroup
if (bodygroup) then
if (part) then
entity:SetBodygroup(part, bodygroup)
end
end
end,
},
{
bodygroup = 2,
name = "pants",
outfits = {
{price = 5000, group = 0, find = "models/btcitizen/citizen_sheet_legs", mat = "models/btcitizen/citizen_sheet_legs",},
{price = 5000, find = "models/btcitizen/citizen_sheet_legs", group = 0, mat = "citizensheet/sheet_02"},
{price = 5000, find = "models/btcitizen/citizen_sheet_legs", group = 0, mat = "citizensheet/sheet_03"},
{price = 5000, find = "models/btcitizen/citizen_sheet_legs", group = 0, mat = "citizensheet/sheet_reich"},
{price = 5000, find = "models/btcitizen/citizen_sheet_legs", group = 0, mat = "citizensheet/sheet_suit"},
{price = 5000, find = "models/btcitizen/citizen_sheet_legs", group = 0, mat = "citizensheet/sheet_04"},
{price = 5000, find = "models/btcitizen/citizen_sheet_legs", group = 0, mat = "citizensheet/sheet_08"},
{price = 5000, find = "models/btcitizen/citizen_sheet_legs", group = 0, mat = "citizensheet/sheet_14"},
{price = 5000, find = "models/btcitizen/citizen_sheet_legs", group = 0, mat = "citizensheet/sheet_18"},
{price = 5000, find = "models/btcitizen/citizen_sheet_legs", group = 0, mat = "citizensheet/sheet_17"},
{price = 5000, find = "models/btcitizen/citizen_sheet_legs", group = 0, mat = "citizensheet/sheet_19"},
{price = 5000, find = "models/btcitizen/citizen_sheet_legs", group = 0, mat = "citizensheet/sheet_20"},
{price = 5000, find = "models/btcitizen/citizen_sheet_legs", group = 0, mat = "citizensheet/sheet_23"},
{price = 5000, find = "models/btcitizen/citizen_sheet_legs", group = 0, mat = "citizensheet/sheet_24"},
{price = 5000, find = "models/btcitizen/citizen_sheet_legs", group = 0, mat = "citizensheet/sheet_25"},
{price = 5000, find = "models/btcitizen/citizen_sheet_legs", group = 0, mat = "citizensheet/sheet_26"},
{price = 5000, find = "models/btcitizen/citizen_sheet_legs", group = 0, mat = "citizensheet/sheet_27"},
{price = 5000, find = "models/btcitizen/citizen_sheet_legs", group = 0, mat = "citizensheet/sheet_28"},
{price = 5000, find = "models/btcitizen/citizen_sheet_legs", group = 0, mat = "citizensheet/sheet_29"},
{price = 5000, find = "models/btcitizen/citizen_sheet_legs", group = 0, mat = "citizensheet/sheet_30"},
{price = 5000, find = "models/btcitizen/citizen_sheet_legs", group = 0, mat = "citizensheet/sheet_31"},
{price = 5000, find = "models/btcitizen/citizen_sheet_legs", group = 0, mat = "citizensheet/costage_sheet"},
{price = 5000, find = "models/btcitizen/citizen_sheet_legs", group = 0, mat = "citizensheet/hostage_sheet"},
{price = 5000, find = "models/btcitizen/citizen_sheet_legs", group = 0, mat = "citizensheet/security_sheet"},
{price = 5000, find = "models/btcitizen/citizen_sheet_legs", group = 0, mat = "citizensheet/military_sheet"},
{price = 5000, find = "models/btcitizen/citizen_sheet_legs", group = 0, mat = "citizensheet/monk_sheet"},
{price = 5000, group = 2},
},
func = function(entity, outfit, orig)
if (orig.bodygroup) then
local find = outfit.find
local matIndex
for k, v in ipairs(entity:GetMaterials()) do
if (v == find) then
matIndex = k - 1
break
end
end
if (matIndex and outfit.mat) then
entity:SetSubMaterial(matIndex, outfit.mat)
end
if (outfit.group) then
entity:SetBodygroup(orig.bodygroup, outfit.group)
end
end
end,
},
},
bfemale = {
{
name = "face",
canDisplay = function()
end,
outfits = function(entity)
local mdl = entity:GetModel()
local faces = {}
local woo = OUTFIT_DATA[mdl:lower()]
if (!woo) then return faces end
if (woo.facemap) then
local mdl = entity:GetModel()
local facemaps = woo.skins
table.insert(faces, {mat = woo.facemap, price = 9500})
if (facemaps) then
for i = 1, #facemaps do
table.insert(faces, {mat = facemaps[i], price = 9500})
end
end
end
return faces
end,
func = function(entity, outfit, orig)
local mdl = entity:GetModel()
local woo = OUTFIT_DATA[mdl:lower()]
if (outfit and woo.facemap) then
local find = woo.facemap
local matIndex
for k, v in ipairs(entity:GetMaterials()) do
if (v == find) then
matIndex = k - 1
break
end
end
if (matIndex and outfit.mat) then
entity:SetSubMaterial(matIndex, outfit.mat)
end
end
end,
},
{
name = "torso",
bodygroup = 1,
outfits = {
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 0, mat = "models/btcitizen/female/citizen_sheet"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 0, mat = "citizensheetf/sheet_01"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 0, mat = "citizensheetf/sheet_02"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 0, mat = "citizensheetf/sheet_03"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 0, mat = "citizensheetf/sheet_04"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 0, mat = "citizensheetf/sheet_05"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 0, mat = "citizensheetf/sheet_06"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 0, mat = "citizensheetf/sheet_07"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 0, mat = "citizensheetf/sheet_08"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 0, mat = "citizensheetf/sheet_09"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 0, mat = "citizensheetf/sheet_10"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 0, mat = "citizensheetf/sheet_11"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 0, mat = "citizensheetf/sheet_12"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 0, mat = "citizensheetf/sheet_13"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 0, mat = "citizensheetf/sheet_14"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 0, mat = "citizensheetf/sheet_15"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 0, mat = "citizensheetf/sheet_suit"},
/*
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 1, mat = "citizensheetf/sheet_01"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 1, mat = "citizensheetf/sheet_02"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 1, mat = "citizensheetf/sheet_03"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 1, mat = "citizensheetf/sheet_04"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 1, mat = "citizensheetf/sheet_05"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 1, mat = "citizensheetf/sheet_06"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 1, mat = "citizensheetf/sheet_07"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 1, mat = "citizensheetf/sheet_08"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 1, mat = "citizensheetf/sheet_09"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 1, mat = "citizensheetf/sheet_10"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 1, mat = "citizensheetf/sheet_11"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 1, mat = "citizensheetf/sheet_12"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 1, mat = "citizensheetf/sheet_13"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 1, mat = "citizensheetf/sheet_14"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 1, mat = "citizensheetf/sheet_15"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet", group = 1, mat = "citizensheetf/sheet_suit"},
*/
{price = 5000, find = "models/btcitizen/prague_civ_rioter_body_col_a", group = 2, mat = "models/btcitizen/prague_civ_rioter_body_col_a"},
{price = 5000, find = "models/btcitizen/prague_civ_rioter_body_col_a", group = 2, mat = "models/btcitizen/prague_civ_rioter_body_col_b"},
{price = 5000, find = "models/btcitizen/prague_civ_rioter_body_col_a", group = 2, mat = "models/btcitizen/prague_civ_rioter_body_col_c"},
{price = 5000, find = "models/btcitizen/prague_civ_rioter_body_col_a", group = 3, mat = "models/btcitizen/prague_civ_rioter_body_col_a"},
{price = 5000, find = "models/btcitizen/prague_civ_rioter_body_col_a", group = 3, mat = "models/btcitizen/prague_civ_rioter_body_col_b"},
{price = 5000, find = "models/btcitizen/prague_civ_rioter_body_col_a", group = 3, mat = "models/btcitizen/prague_civ_rioter_body_col_c"},
{price = 5000, find = "models/btcitizen/citizen_summer", group = 4, mat = "models/btcitizen/citizen_summer"},
{price = 5000, find = "models/btcitizen/citizen_summer", group = 4, mat = "models/btcitizen/summersheet/citizen_summer2"},
{price = 5000, find = "models/btcitizen/citizen_summer", group = 4, mat = "models/btcitizen/summersheet/citizen_summer3"},
{price = 5000, find = "models/btcitizen/citizen_summer", group = 4, mat = "models/btcitizen/summersheet/citizen_summer4"},
{price = 5000, find = "models/btcitizen/citizen_summer", group = 4, mat = "models/btcitizen/summersheet/citizen_summer5"},
{price = 5000, find = "models/btcitizen/citizen_summer", group = 4, mat = "models/btcitizen/summersheet/citizen_summer6"},
{price = 5000, find = "models/btcitizen/citizen_summer", group = 4, mat = "models/btcitizen/summersheet/citizen_summer7"},
{price = 5000, find = "models/btcitizen/citizen_summer", group = 4, mat = "models/btcitizen/summersheet/citizen_summer8"},
{price = 5000, find = "models/btcitizen/citizen_summer", group = 4, mat = "models/btcitizen/summersheet/citizen_summer9"},
{price = 5000, find = "models/btcitizen/citizen_summer", group = 4, mat = "models/btcitizen/summersheet/citizen_summer10"},
{price = 5000, find = "models/btcitizen/citizen_summer", group = 4, mat = "models/btcitizen/summersheet/citizen_summer11"},
{price = 5000, find = "models/btcitizen/citizen_summer", group = 4, mat = "models/btcitizen/summersheet/citizen_summer_camo"},
},
func = function(entity, outfit, orig)
if (orig.bodygroup) then
local find = outfit.find
local matIndex
for k, v in ipairs(entity:GetMaterials()) do
if (v == find) then
matIndex = k - 1
break
end
end
if (matIndex and outfit.mat) then
entity:SetSubMaterial(matIndex, outfit.mat)
end
if (outfit.group) then
entity:SetBodygroup(orig.bodygroup, outfit.group)
end
end
end,
},
{
bodygroup = 3,
name = "shoes",
outfits = {
{price = 5000, find = "models/btcitizen/female/citizen_sheet_shoes", group = 0, mat = "models/btcitizen/female/citizen_sheet"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_shoes", group = 0, mat = "citizensheetf/sheet_01"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_shoes", group = 0, mat = "citizensheetf/sheet_02"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_shoes", group = 0, mat = "citizensheetf/sheet_03"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_shoes", group = 0, mat = "citizensheetf/sheet_04"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_shoes", group = 0, mat = "citizensheetf/sheet_05"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_shoes", group = 0, mat = "citizensheetf/sheet_06"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_shoes", group = 0, mat = "citizensheetf/sheet_07"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_shoes", group = 0, mat = "citizensheetf/sheet_08"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_shoes", group = 0, mat = "citizensheetf/sheet_09"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_shoes", group = 0, mat = "citizensheetf/sheet_10"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_shoes", group = 0, mat = "citizensheetf/sheet_11"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_shoes", group = 0, mat = "citizensheetf/sheet_12"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_shoes", group = 0, mat = "citizensheetf/sheet_13"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_shoes", group = 0, mat = "citizensheetf/sheet_14"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_shoes", group = 0, mat = "citizensheetf/sheet_15"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_shoes", group = 0, mat = "citizensheetf/sheet_suit"},
{price = 5000, group = 1},
},
func = function(entity, outfit, orig)
/*
local bodygroup = tonumber(outfit.data)
local part = orig.bodygroup
if (bodygroup) then
if (part) then
entity:SetBodygroup(part, bodygroup)
end
end*/
if (orig.bodygroup) then
local find = outfit.find
if (find) then
local matIndex
for k, v in ipairs(entity:GetMaterials()) do
if (v == find) then
matIndex = k - 1
break
end
end
if (matIndex and outfit.mat) then
entity:SetSubMaterial(matIndex, outfit.mat)
end
end
if (outfit.group) then
entity:SetBodygroup(orig.bodygroup, outfit.group)
end
end
end,
},
{
bodygroup = 4,
name = "gloves",
outfits = {
{data = 0, name = "bodygroup", price = 4500},
{data = 1, name = "bodygroup", price = 4500},
{data = 2, name = "bodygroup", price = 4500},
},
func = function(entity, outfit, orig)
local bodygroup = tonumber(outfit.data)
local part = orig.bodygroup
if (bodygroup) then
if (part) then
entity:SetBodygroup(part, bodygroup)
end
end
end,
},
{
bodygroup = 2,
name = "pants",
outfits = {
{price = 5000, group = 0, find = "models/btcitizen/female/citizen_sheet_legs", mat = "models/btcitizen/female/citizen_sheet_legs",},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_legs", group = 0, mat = "citizensheetf/sheet_01"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_legs", group = 0, mat = "citizensheetf/sheet_02"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_legs", group = 0, mat = "citizensheetf/sheet_03"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_legs", group = 0, mat = "citizensheetf/sheet_04"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_legs", group = 0, mat = "citizensheetf/sheet_05"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_legs", group = 0, mat = "citizensheetf/sheet_06"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_legs", group = 0, mat = "citizensheetf/sheet_07"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_legs", group = 0, mat = "citizensheetf/sheet_08"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_legs", group = 0, mat = "citizensheetf/sheet_09"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_legs", group = 0, mat = "citizensheetf/sheet_10"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_legs", group = 0, mat = "citizensheetf/sheet_11"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_legs", group = 0, mat = "citizensheetf/sheet_12"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_legs", group = 0, mat = "citizensheetf/sheet_13"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_legs", group = 0, mat = "citizensheetf/sheet_14"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_legs", group = 0, mat = "citizensheetf/sheet_15"},
{price = 5000, find = "models/btcitizen/female/citizen_sheet_legs", group = 0, mat = "citizensheetf/sheet_suit"},
{price = 5000, group = 2},
},
func = function(entity, outfit, orig)
if (orig.bodygroup) then
local find = outfit.find
local matIndex
for k, v in ipairs(entity:GetMaterials()) do
if (v == find) then
matIndex = k - 1
break
end
end
if (matIndex and outfit.mat) then
entity:SetSubMaterial(matIndex, outfit.mat)
end
if (outfit.group) then
entity:SetBodygroup(orig.bodygroup, outfit.group)
end
end
end,
},
},
} |
-- 23.5 瞬表
require("Tools.utils")
local mem = {}
setmetatable(mem, {__mode = "k"})
function Factory(o)
local res = mem[o]
if res == nil then
res = function() return o end
mem[o] = res -- 表的值指向表的键
end
return res
end
local object = {
name = "edwardchen",
age = 24,
job = "college student",
} -- mem表以外的引用1:object
-- mem表以外的间接引用2:instance
local instance = Factory(object)
print("after instance created:" .. table.length(mem))
for key, value in pairs(mem) do
print(key, value)
end
instance = nil
collectgarbage("collect")
print("set instance nil and collectgarbage():" .. table.length(mem))
for key, value in pairs(mem) do
print(key, value)
end
object = nil
collectgarbage("collect")
print("set object nil and collectgarbage():" .. table.length(mem))
for key, value in pairs(mem) do
print(key, value)
end
-- 即使mem value -> key存在引用,仍然被回收 |
local native = _ENV.native
-- Parse format and returns fomattable object or error.
-- local parse_fmt = native.i18n.parse_fmt
-- TODO
local parse_fmt = function(f)
return {f}
end
local rnd = require("random").rnd
--- Functions for localization.
-- See the i18n section for more information.
-- @usage local i18n = require("core.i18n")
-- @module "i18n"
local i18n = {}
--[[
type I18NKey = string
type FormattableObject = string | list of Segment
type Segment = string | EmbeddedExpression
type EmbeddedExpression = Variable | FunctionCall | number | boolean | nil
type Variable = { "v", integer }
type FunctionCall = { "f", mod_name, function_name, args... }
type FormattableObjectList = list of FormattableObject. It has field `__list`, true,
to distinguish it from FormattableObject.
--]]
-- Stores all of locale resources except for data-associated text.
-- Keys: I18NKey
-- Values: FormattableObject | FormattableObjectList
local STORAGE = {}
-- Stores all of data-associated locale resources.
-- Keys: I18NKey
-- Values: FormattableObject | FormattableObjectList
local DATA_TEXT_STORAGE = {}
local L10N_FUNCTIONS = {}
local CURRENT_LANGUAGE = nil
-- Evaluate formattable object with given arguments and returns the result.
-- @param x Segment The formattable object
-- @param args The arguments
-- @return The formatted result. It can be non-string value.
local function eval(x, args)
if type(x) == "string" then
-- A plain string, just returns it.
return x
elseif type(x) == "table" then
-- x is an `EmbeddedExpression`, needs evaluation.
if x[1] == "v" then -- Is it a `Variable`?
-- Structure:
-- [1]: tag (string), "v"
-- [2]: index (integer)
local nth = x[2]
local len = #args
if len < nth then
return "<missing argument #"..tostring(nth)..">"
else
return args[nth]
end
elseif x[1] == "f" then -- Is it a `FunctionCall`?
-- Structure:
-- [1]: tag (string), "f"
-- [2]: namespaced_function_name (string)
-- [3]: argument 1 (any)
-- [4]: argument 2 (any)
-- ...
local func = L10N_FUNCTIONS[x[2]]
if not func then
return "<unknown function '"..tostring(x[2]).."'>"
end
local func_args = {}
for i = 4, #x do
func_args[#func_args+1] = eval(x[i], args)
end
return func(table.unpack(func_args))
else
assert(false)
end
else
return x
end
end
-- Make formattable object from @a v.
-- @param v Format string
-- @return FormattableObject
-- @raise Error if @a v is invalid.
local function make_fomattable_object(v)
if v == "" then return "" end
local ret, err = parse_fmt(v)
if err then
print(v)
error(err)
end
assert(type(ret) == "table")
assert(#ret > 0)
if #ret == 1 and type(ret[1]) ~= "table" then
return tostring(ret[1])
else
return ret
end
end
local function collect_i18n_resources(table, current_key, result)
for k, v in pairs(table) do
local key = current_key.."."..k
if type(v) == "string" then
result[key] = make_fomattable_object(v)
elseif #v == 0 then
collect_i18n_resources(v, key, result)
else
assert(type(v) == "table")
for i, e in ipairs(v) do
v[i] = make_fomattable_object(e)
end
result[key] = v
result[key].__list = true
end
end
end
-- @param fmt Formattable object. It is a plain string (which means that the
-- string does not have interpolation) or a list of segments. Each
-- segment can be a plain string or complex string interpolation,
-- passed to `eval()`.
-- @param args The arguments passed to `eval()`
-- @return The formatted text
local function format(fmt, args)
if type(fmt) == "string" then
-- A plain string, just returns it.
return fmt
else
-- A list of segments.
local joined = ""
for _, segment in ipairs(fmt) do
local x = eval(segment, args)
if type(x) == "table" and x.__handle then
x = x:__tostring()
end
joined = joined..tostring(x)
end
return joined
end
end
--- Gets a localized string and optionally formats it with arguments.
-- This will return a string with a warning if the localization
-- string doesn't exist.
--
-- @tparam string key the ID of the localization string
-- @treturn string the formatted string
-- @usage i18n.get("core.map.you_see", "Vernis")
-- @function get
function i18n.get(key, ...)
return i18n.get_optional(key, ...) or ("<Unknown ID: %s>"):format(key)
end
--- Gets a localized string and optionally formats it with arguments.
-- This will return nil if the localization string doesn't exist.
--
-- @tparam string key the ID of the localization string
-- @treturn[1] string the formatted string
-- @treturn[2] nil
-- @function get_optional
function i18n.get_optional(key, ...)
local fmt = STORAGE[key]
if fmt == nil then return nil end -- not found
if type(fmt) == "table" and fmt.__list then -- Is it a `FormattableObjectList`?
-- Choose one element of the list at random.
fmt = fmt[rnd(#fmt) + 1]
end
return format(fmt, {...})
end
--- Gets a localized string from an enum-style localization object.
-- This will return a string with a warning if the localization
-- string doesn't exist.
--
-- @tparam string key the ID of the localization string
-- @tparam num index the index into the enum
-- @treturn string the formatted string
-- @function get_enum
function i18n.get_enum(key, index, ...)
return i18n.get(("%s._%d"):format(key, index), ...)
end
--- Gets a localized string from an enum-style localization object and optionally
-- formats it with arguments. This will return nil if the localization string
-- doesn't exist.
--
-- @tparam string key the ID of the localization string
-- @tparam num index the index into the enum
-- @treturn[1] string the formatted string
-- @treturn[2] nil
-- @function get_enum_optional
function i18n.get_enum_optional(key, index, ...)
return i18n.get_optional(("%s._%d"):format(key, index), ...)
end
--- Gets a localized string from an enum-style localization object
-- where the enum's children are themselves objects. This will return
-- a string with a warning if the localization string doesn't exist.
--
-- @tparam string key_base the base ID of the localization string
-- @tparam string key_property the property of the enum object to get
-- @tparam num index the index into the enum
-- @treturn string the formatted string
-- @function get_enum_property
function i18n.get_enum_property(key_base, key_property, index, ...)
return i18n.get(("%s._%d.%s"):format(key_base, index, key_property), ...)
end
--- Gets a localized string from an enum-style localization object
-- where the enum's children are themselves objects. This will return
-- nil if the localization string doesn't exist.
--
-- @tparam string key_base the base ID of the localization string
-- @tparam string key_property the property of the enum object to get
-- @tparam num index the index into the enum
-- @treturn[1] string the formatted string
-- @treturn[2] nil
-- @function get_enum_property_optional
function i18n.get_enum_property_optional(key_base, key_property, index, ...)
return i18n.get_optional(("%s._%d.%s"):format(key_base, index, key_property), ...)
end
--- Get a localized text associated with the given data ID.
-- This will return a string with a warning if the localization
-- string doesn't exist.
--
-- @tparam string prototype_id Data prototype ID.
-- @tparam string instance_id Data instance ID.
-- @tparam string property_name i18n key of the property to get.
-- @treturn string The formatted string
-- @function get_data_text
function i18n.get_data_text(prototype_id, instance_id, property_name, ...)
return i18n.get_data_text_optional(prototype_id, instance_id, property_name, ...) or ("<Unknown ID: %s>"):format(("%s#%s.%s"):format(prototype_id, instance_id, property_name))
end
function i18n.get_data_text_optional(prototype_id, instance_id, property_name, ...)
local key = ("%s#%s.%s"):format(prototype_id, instance_id, property_name)
local fmt = DATA_TEXT_STORAGE[key]
if fmt == nil then return nil end -- not found
if type(fmt) == "table" and fmt.__list then -- Is it a `FormattableObjectList`?
-- Choose one element of the list at random.
fmt = fmt[rnd(#fmt) + 1]
end
return format(fmt, {...})
end
function i18n.get_list(key)
local ret = STORAGE[key]
if ret == nil then return {} end
if type(ret) == "table" then
if ret.__list then
return ret
else
-- error
return {}
end
elseif type(ret) == "string" then
return {ret}
else
-- error
return {}
end
end
function i18n.format(fmt, ...)
return format(make_fomattable_object(fmt), {...})
end
function i18n.call_function(func_name, ...)
local func = L10N_FUNCTIONS[func_name]
if func then
return func(...)
else
return "<unknown function '"..tostring(func_name).."'>"
end
end
function i18n.add(data)
collect_i18n_resources(data, _MOD_ID, STORAGE)
end
function i18n.add_data_text(prototype_id, data)
for k, v in pairs(data) do
local key = prototype_id.."#".._MOD_ID.."."..k
collect_i18n_resources(v, key, DATA_TEXT_STORAGE)
end
end
-- functions :: { string => (...) -> string }
function i18n.add_function(functions)
for func_name, func in pairs(functions) do
L10N_FUNCTIONS[_MOD_ID.."."..func_name] = func
end
end
--- Gets the current active language.
--- @treturn string Language ID
function i18n.language()
if CURRENT_LANGUAGE then
return CURRENT_LANGUAGE
else
error("i18n.language: config option has not been loaded yet")
end
end
function i18n.word_separator()
return i18n.get_optional("core.meta.word_separator") or ""
end
function i18n.__INTERNAL_API_inject_current_language(lang)
CURRENT_LANGUAGE = lang
end
return i18n
|
--[[
Copyright (c) 2021, TU Delft
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.
name: modROS.lua
version: 0.0.1
description:
This mod for Farming Simulator 2019 allows autonomous driving of FarmSim vehicles with the ROS navigation stack.
There are three console commands in this mod for now:
The first one is to publish data, the second one is to subscribe data and the last one is to force-center the camera
------------------------------------------------
------------------------------------------------
A: Publishing data
1. sim time publisher - publish in-game simulated clock. This message stops being published when the game is paused/exited
2. odom publisher - publish ground-truth Pose and Twist of vehicles based on their in-game position and orientation
3. laser scan publisher - publish the laser scan data
4. imu publisher - publish the imu data (especially the acc info)
5. A command for writing all messages to a named pipe: "rosPubMsg true/false"
------------------------------------------------
------------------------------------------------
B. Subscribing data
1. ros_cmd_teleop subscriber - give the vehicle control to ROS
2. A command for taking over control of a vehicle in the game : "rosControlVehicle true/false"
------------------------------------------------
------------------------------------------------
C. Force-centering the camera
1. A command for force-centering the current camera: "forceCenteredCamera true/false"
------------------------------------------------
------------------------------------------------
author: Ting-Chia Chiang, G.A. vd. Hoorn
maintainer: Ting-Chia Chiang, G.A. vd. Hoorn
--]]
-- ModROS class is not local here
-- it's now in the global scope so the installSpecializations(..) can be called in loader.lua
ModROS = {}
ModROS.MOD_DIR = g_modROSModDirectory
ModROS.MOD_NAME = g_modROSModName
ModROS.MOD_VERSION = g_modManager.nameToMod[ModROS.MOD_NAME]["version"]
local function center_camera_func()
local camIdx = g_currentMission.controlledVehicle.spec_enterable.camIndex
local camera = g_currentMission.controlledVehicle.spec_enterable.cameras[camIdx]
camera.rotX = camera.origRotX
camera.rotY = camera.origRotY
end
function ModROS:loadMap()
self.last_read = ""
self.buf = SharedMemorySegment:init(64)
self.sec = 0
self.nsec = 0
self.l_v_x_0 = 0
self.l_v_y_0 = 0
self.l_v_z_0 = 0
-- initialise connection to the Python side (but do not connect it yet)
self.path = ModROS.MOD_DIR .. "ROS_messages"
self._conx = WriteOnlyFileConnection.new(self.path)
-- initialise no-namespace-specific publishers
self._pub_tf = Publisher.new(self._conx, "tf", tf2_msgs_TFMessage)
self._pub_clock = Publisher.new(self._conx, "clock", rosgraph_msgs_Clock)
print("modROS (" .. ModROS.MOD_VERSION .. ") loaded")
end
function ModROS.installSpecializations(vehicleTypeManager, specializationManager, modDirectory, modName)
specializationManager:addSpecialization("rosVehicle", "RosVehicle", Utils.getFilename("src/vehicles/RosVehicle.lua", modDirectory), nil) -- Nil is important here
for typeName, typeEntry in pairs(vehicleTypeManager:getVehicleTypes()) do
-- only add rosVehicle spec to vechile types thathave prerequiste drivable spec
-- if there is no this condition, the <rosVehicle> will be added to all vehicle types regardless of having drivable spec as prerequisite
-- there would be errors occur when running RosVehicle.prerequisitesPresent()
-- hence, only if the prerequisites of specialization are fulfilled, specializations <rosVehicle> will be installed
if SpecializationUtil.hasSpecialization(Drivable, typeEntry.specializations) then
vehicleTypeManager:addSpecialization(typeName, modName .. ".rosVehicle")
end
end
end
function ModROS:update(dt)
-- create TFMessage object
self.tf_msg = tf2_msgs_TFMessage.new()
if self.doPubMsg then
-- avoid writing to the pipe if it isn't actually open
if self._conx:is_connected() then
self:publish_sim_time_func()
self:publish_veh_odom_func()
self:publish_laser_scan_func()
self:publish_imu_func()
self._pub_tf:publish(self.tf_msg)
end
end
if self.doRosControl then
self:subscribe_ROScontrol_func(dt)
end
if self.doCenterCamera then
if g_currentMission.controlledVehicle == nil then
print("You have left your vehicle! Stop force-centering camera")
self.doCenterCamera = false
else
center_camera_func()
end
end
end
-- A.1 sim_time publisher: publish the farmsim time
function ModROS:publish_sim_time_func()
local msg = rosgraph_msgs_Clock.new()
msg.clock = ros.Time.now()
self._pub_clock:publish(msg)
end
-- A.2. odom publisher
-- a function to publish ground-truth Pose and Twist of all vehicles (including non-drivable) based on their in-game position and orientation
function ModROS:publish_veh_odom_func()
-- FS time is "frozen" within a single call to update(..), so this
-- will assign the same stamp to all Odometry messages
local ros_time = ros.Time.now()
for _, vehicle in pairs(g_currentMission.vehicles) do
-- only if the vehicle is spec_rosVehicle, the pubOdom() can be called
if vehicle.spec_rosVehicle then
vehicle:pubOdom(ros_time, self.tf_msg)
end
end
end
-- A.3. laser scan publisher
function ModROS:publish_laser_scan_func()
-- FS time is "frozen" within a single call to update(..), so this
-- will assign the same stamp to all LaserScan messages
local ros_time = ros.Time.now()
for _, vehicle in pairs(g_currentMission.vehicles) do
-- only if the vehicle is spec_rosVehicle, the pubLaserScan() can be called
if vehicle.spec_rosVehicle then
vehicle:pubLaserScan(ros_time, self.tf_msg)
end
end
end
-- A.4. imu publisher
-- a function to publish get the position and orientaion of unmanned or manned vehicle(s) get and write to the named pipe (symbolic link)
function ModROS:publish_imu_func()
local ros_time = ros.Time.now()
for _, vehicle in pairs(g_currentMission.vehicles) do
if vehicle.spec_rosVehicle then
vehicle:pubImu(ros_time)
end
end
end
-- A.5. Console command allows to toggle publishers on/off: "rosPubMsg true/false"
-- messages publisher console command
addConsoleCommand("rosPubMsg", "write ros messages to named pipe", "rosPubMsg", ModROS)
function ModROS:rosPubMsg(flag)
if flag ~= nil and flag ~= "" and flag == "true" then
if not self._conx:is_connected() then
print("connecting to named pipe")
local ret, err = self._conx:connect()
if ret then
print("Opened '" .. self._conx:get_uri() .. "'")
else
-- if not, print error to console and return
print(("Could not connect: %s"):format(err))
print("Possible reasons:")
print(" - symbolic link was not created")
print(" - the 'all_in_one_publisher.py' script is not running")
return
end
end
-- initialisation was successful
self.doPubMsg = true
elseif flag == nil or flag == "" or flag == "false" then
self.doPubMsg = false
print("stop publishing data, set true, if you want to publish Pose")
local ret, err = self._conx:disconnect()
if not ret then
print(("Could not disconnect: %s"):format(err))
else
print("Disconnected")
end
end
end
-- B.1. ros_cmd_teleop subscriber
-- a function to input the ROS geometry_msgs/Twist into the game to take over control of all vehicles
function ModROS:subscribe_ROScontrol_func(dt)
for _, vehicle in pairs(g_currentMission.vehicles) do
if vehicle.spec_drivable then
-- retrieve the first 32 chars from the buffer
-- note: this does not remove them, it simply copies them
local buf_read = self.buf:read(64)
-- print to the game console if what we've found in the buffer is different
-- from what was there the previous iteration
-- the counter is just there to make sure we don't see the same line twice
local allowedToDrive = false
if buf_read ~= self.last_read and buf_read ~= "" then
self.last_read = buf_read
local read_str_list = {}
-- loop over whitespace-separated components
for read_str in string.gmatch(self.last_read, "%S+") do
table.insert(read_str_list, read_str)
end
self.acc = tonumber(read_str_list[1])
self.rotatedTime_param = tonumber(read_str_list[2])
allowedToDrive = read_str_list[3]
end
if allowedToDrive == "true" then
self.allowedToDrive = true
elseif allowedToDrive == "false" then
self.allowedToDrive = false
end
vehicle_util.ROSControl(vehicle, dt, self.acc, self.allowedToDrive, self.rotatedTime_param)
end
end
end
-- B.2. A command for taking over control of a vehicle in the game : "rosControlVehicle true/false"
-- TODO Allow control of vehicles other than the 'active one'. (the console name has already been changed, but the implementation hasn't yet)
-- console command to take over control of all vehicles in the game
addConsoleCommand("rosControlVehicle", "let ROS control the current vehicle", "rosControlVehicle", ModROS)
function ModROS:rosControlVehicle(flag)
if flag ~= nil and flag ~= "" and flag == "true" then
self.doRosControl = true
print("start ROS teleoperation")
elseif flag == nil or flag == "" or flag == "false" then
self.doRosControl = false
print("stop ROS teleoperation")
end
end
-- C.1 A command for force-centering the current camera: "forceCenteredCamera true/false"
-- centering the camera by setting the camera rotX, rotY to original angles
addConsoleCommand("forceCenteredCamera", "force-center the current camera", "forceCenteredCamera", ModROS)
function ModROS:forceCenteredCamera(flag)
if flag ~= nil and flag ~= "" and flag == "true" then
if g_currentMission.controlledVehicle ~= nil then
print("start centering the camera")
self.doCenterCamera = true
else
print("You have left your vehicle, come on! Please hop in one and type the command again!")
end
elseif flag == nil or flag == "" or flag == "false" then
self.doCenterCamera = false
print("stop centering the camera")
end
end
addModEventListener(ModROS)
|
return require('packer').startup(function(use)
-- Packer can manage itself
use 'wbthomason/packer.nvim'
use {
"ellisonleao/gruvbox.nvim",
requires = {"rktjmp/lush.nvim"}
}
use 'glepnir/zephyr-nvim'
-- use {
-- 'glepnir/galaxyline.nvim',
-- branch = 'main',
-- }
use {
'kyazdani42/nvim-tree.lua',
requires = 'kyazdani42/nvim-web-devicons',
}
-- bufferline
use {'akinsho/bufferline.nvim', requires = 'kyazdani42/nvim-web-devicons'}
-- treesitter
use {
'nvim-treesitter/nvim-treesitter',
commit = '668de0951a36ef17016074f1120b6aacbe6c4515',
-- run = ':TSUpdate'
}
-- lsp
use { 'neovim/nvim-lspconfig', 'williamboman/nvim-lsp-installer'}
-- nvim-cmp
use 'hrsh7th/cmp-nvim-lsp' -- { name = nvim_lsp }
use 'hrsh7th/cmp-buffer' -- { name = 'buffer' },
use 'hrsh7th/cmp-path' -- { name = 'path' }
use 'hrsh7th/cmp-cmdline' -- { name = 'cmdline' }
use 'hrsh7th/nvim-cmp'
-- vsnip
use 'hrsh7th/cmp-vsnip' -- { name = 'vsnip' }
use 'hrsh7th/vim-vsnip'
use 'rafamadriz/friendly-snippets'
-- lspkind
use 'onsails/lspkind-nvim'
-- coc.nvim
-- use {'neoclide/coc.nvim', branch = 'release'}
-- Comment
use 'numToStr/Comment.nvim'
-- nvim-autopairs
use 'windwp/nvim-autopairs'
end)
|
--[[----------------------------------------------------------------------------
Application Name:
ParticleFilter
Summary:
Applying particle filter on scans read from a file
Description:
Scan data from file in resources is retrieved and filtered with the particle
filter. The filtered scan is transformed into a point cloud and sent to the
viewer. Additionally the original scan and the filtered scan are compared and
changes between both scans are printed to illustrate the operation of the
particle filter.
How to run:
Starting this sample is possible either by running the app (F5) or
debugging (F7+F10). Output is printed to the console and the transformed
point cloud can be seen on the viewer in the web page. The playback stops
after the last scan in the file. To replay, the sample must be restarted.
To run this sample, a device with AppEngine >= 2.5.0 is required.
Implementation:
To run with real device data, the file provider has to be exchanged with the
appropriate scan provider.
------------------------------------------------------------------------------]]
-- Variables global for all functions
local counter = 0
local SCAN_FILE_PATH = "resources/TestScenario.xml"
print("Input File: ", SCAN_FILE_PATH)
local currentScan = nil
local previousScan = nil
-- Check device capabilities
assert(View,"View not available, check capability of connected device")
assert(Scan,"Scan not available, check capability of connected device")
assert(Scan.ParticleFilter,"ParticleFilter not available, check capability of connected device")
assert(Scan.Transform,"Transform not available, check capability of connected device")
-- Create the filter
particleFilter = Scan.ParticleFilter.create()
assert(particleFilter, "ParticleFiler could not be created")
Scan.ParticleFilter.setThreshold(particleFilter,100.0) -- If the distance difference in distsances
-- between of a point and its neighbours exceeds
-- this threshold it is discarded as a particle
Scan.ParticleFilter.setEnabled(particleFilter,true)
-- Create a viewer instance
viewer = View.create()
assert(viewer, "View could not be created.")
viewer:setID("viewer3D")
-- Create a transform instance to convert the Scan to a PointCloud
transform = Scan.Transform.create()
assert(transform, "Transform could not be created.")
-- Create provider. Providing starts automatically with the register call
-- which is found below the callback function
provider = Scan.Provider.File.create()
assert(provider, "Scan file provider could not be created.")
-- Set the path
Scan.Provider.File.setFile(provider, SCAN_FILE_PATH)
-- Set the DataSet of the recorded data which should be used.
Scan.Provider.File.setDataSetID(provider, 1)
--End of Global Scope-----------------------------------------------------------
--Start of Function and Event Scope---------------------------------------------
-------------------------------------------------------------------------------------------------------
-- Compares the distances of two scans of the specified echo
-------------------------------------------------------------------------------------------------------
local function compareScans(inputScan, filteredScan, iEcho, printDetails)
-- get the beam and echo counts
local beamCountInput = Scan.getBeamCount(inputScan)
local echoCountInput = Scan.getEchoCount(inputScan)
local beamCountFiltered = Scan.getBeamCount(filteredScan)
local echoCountFiltered = Scan.getEchoCount(filteredScan)
local particleCount = 0
-- Checks
if ( iEcho <= echoCountInput and iEcho <= echoCountFiltered ) then
if ( beamCountInput == beamCountFiltered ) then
-- Print beams with different distances
if ( printDetails ) then
print("Different beams after filtering of particles:")
end
-- Copy distance channel to Lua table. Note: Scan API indexes start with 0!
local vDistance1 = Scan.toVector(inputScan, "DISTANCE", iEcho-1)
local vDistance2 = Scan.toVector(filteredScan, "DISTANCE", iEcho-1)
for iBeam=1, beamCountInput do
-- Note: Lua index starts with 1.
local d1 = vDistance1[iBeam]
local d2 = vDistance2[iBeam]
if ( math.abs(d1-d2) > 0.01 ) then
if ( printDetails ) then
print(string.format(" beam %4d: %10.2f --> %10.2f", iBeam, d1, d2))
end
particleCount = particleCount + 1
end
end
end
end
return particleCount
end
-- Callback function to process new scans
function handleNewScan(scan)
counter = counter+1
print("Scan: ", counter, " beams: ", Scan.getBeamCount(scan));
-- Save current scan and
previousScan = currentScan
-- clone input scan
currentScan = Scan.clone(scan)
-- Filter scan
local filteredScan = Scan.ParticleFilter.filter(particleFilter, scan)
-- Note: Scan 1 and 2 are never returned since the filter needs a history of 2 scans.
if ( nil ~= filteredScan ) then
-- Transform to PointCloud to view in the PointCloud viewer on the webpage
local pointCloud = Scan.Transform.transformToPointCloud(transform, filteredScan)
View.add(viewer, pointCloud)
View.present(viewer)
-- Compare the filtered scan with the previous scan
if ( nil ~= previousScan ) then
local particleCount = compareScans(previousScan, filteredScan, 1, true)
if ( 0 == particleCount) then
print(" All distances are equal. No particles found.")
else
print(" Particles found: ", particleCount)
end
end
end
end
-- Register callback function to "OnNewScan" event.
-- This call also starts the playback of scans
Scan.Provider.File.register(provider, "OnNewScan", "handleNewScan") |
local waffles = ...
local COOK_TIME = 6
local MODNAME = minetest.get_current_modname()
local S = minetest.get_translator(MODNAME)
-- Batter visual
local batters = {}
minetest.register_entity(MODNAME .. ":batter", {
visual = "mesh",
mesh = "waffles_waffle.obj",
textures = {"waffles_waffle_batter.png"},
visual_size = vector.new(10, 10, 10),
pointable = false,
physical = false,
on_activate = function(self, parent)
if parent == "" then return self.object:remove() end
self._parent = minetest.string_to_pos(parent)
-- Interpolate between batter and waffle
local cooked = minetest.get_meta(self._parent):get_float("cooked")
self.object:set_properties({textures = {
"waffles_waffle_batter.png^(waffles_waffle.png^[opacity:" .. cooked * 255 .. ")"
}})
self.object:set_pos(vector.add(self._parent, {x = 0, y = 4 / 16, z = 0}))
self.object:set_armor_groups({immortal = 1})
batters[minetest.hash_node_position(self._parent)] = self
end,
get_staticdata = function(self)
return minetest.pos_to_string(self._parent)
end,
})
local function remove_batter(pos)
local hash = minetest.hash_node_position(pos)
if batters[hash] then
batters[hash].object:remove()
batters[hash] = nil
end
end
-- Waffle maker base definition
local def_base = {
description = S("Waffle Maker"),
drawtype = "mesh",
tiles = {"waffles_waffle_maker.png"},
paramtype = "light",
sunlight_propagates = true,
paramtype2 = "facedir",
groups = {snappy = 3, oddly_breakable_by_hand = 1},
sounds = waffles.default_sounds("node_sound_metal_defaults"),
on_construct = function(pos)
minetest.get_meta(pos):set_float("cooked", -1)
end,
on_rightclick = function(pos, node, _, stack)
local meta = minetest.get_meta(pos)
local cooked = meta:get_float("cooked")
local open = node.name:sub(-4) == "open"
local battering = stack:get_name():match(MODNAME .. ":waffle_batter$")
-- Add batter if open and empty
if open and battering and cooked < 0 then
cooked = 0
meta:set_float("cooked", cooked)
stack:take_item()
end
-- Toggle as long as not placing batter on open maker
if not (open and battering) then
minetest.swap_node(pos, {
name = node.name:sub(1, open and -6 or -1) .. (open and "" or "_open"),
param2 = node.param2,
})
open = not open
end
-- Handle batter
if open then
if cooked > -1 and not batters[minetest.hash_node_position(pos)] then
minetest.add_entity(pos, MODNAME .. ":batter", minetest.pos_to_string(pos))
end
else
remove_batter(pos)
minetest.get_node_timer(pos):start(0.5)
end
return stack
end,
on_punch = function(pos, node, puncher, ...)
local meta = minetest.get_meta(pos)
local cooked = meta:get_float("cooked")
if cooked > -1 then
local inv = puncher:get_inventory()
if cooked <= 0.2 or cooked >= 0.8 then
local stack = ItemStack(MODNAME .. (cooked <= 0.2 and ":waffle_batter" or ":waffle"))
if inv:room_for_item("main", stack) then
inv:add_item("main", stack)
cooked = -1
end
end
if cooked < 0 then remove_batter(pos) end
meta:set_float("cooked", cooked)
end
return minetest.node_punch(pos, node, puncher, ...)
end,
on_timer = function(pos)
if minetest.get_node(pos).name:sub(-4) == "open" then return end
local meta = minetest.get_meta(pos)
local cooked = meta:get_float("cooked")
if cooked > -1 and cooked < 1 then
meta:set_float("cooked", math.min(cooked + 0.5 / COOK_TIME, 1))
minetest.get_node_timer(pos):start(0.5)
if meta:get_float("cooked") == 1 then
minetest.add_particlespawner({
amount = math.random(6, 10),
time = 3,
minpos = vector.add(pos, {x = -0.5, y = 0, z = -0.5}),
maxpos = vector.add(pos, {x = 0.5, y = 0, z = 0.5}),
minvel = {x = 0, y = 0.5, z = 0},
maxvel = {x = 0, y = 0.5, z = 0},
minacc = {x = 0, y = 0, z = 0},
maxacc = {x = 0, y = 0, z = 0},
minexptime = 2,
maxexptime = 2,
minsize = 2,
maxsize = 6,
texture = "waffles_steam.png",
})
minetest.registered_nodes[MODNAME .. ":waffle_maker"].on_rightclick(pos, minetest.get_node(pos), nil, ItemStack(""))
end
end
end
}
minetest.register_lbm({
label = "Start waffle maker timers",
name = MODNAME .. ":waffle_timers",
nodnames = {MODNAME .. ":waffle_maker"},
run_at_every_load = true,
action = function(pos)
minetest.get_node_timer(pos):start(0.5)
end
})
-- Open and closed defs
local def_closed = table.copy(def_base)
local box_closed = {
type = "fixed",
fixed = {-0.5, -0.5, -0.5, 0.5, 0, 0.5},
}
def_closed.selection_box = box_closed
def_closed.collision_box = box_closed
def_closed.mesh = "waffles_waffle_maker_closed.obj"
local def_open = table.copy(def_base)
local box_open = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0.5, 0.0, 0.5},
{-0.5, 0.0, 0.0, 0.5, 0.5, 0.5},
},
}
def_open.selection_box = box_open
def_open.collision_box = box_open
def_open.mesh = "waffles_waffle_maker_open.obj"
def_open.description = S("Waffle Maker (Open)")
def_open.drop = MODNAME .. ":waffle_maker"
def_open.groups.not_in_creative_inventory = 1
minetest.register_node(MODNAME .. ":waffle_maker", def_closed)
minetest.register_node(MODNAME .. ":waffle_maker_open", def_open)
-- Crafting recipe
local craftitems = {
casing = waffles.setting_or("crafitem_maker_casing", "default:tin_ingot"),
wiring = waffles.setting_or("crafitem_maker_wiring", "default:steel_ingot"),
heating = waffles.setting_or("crafitem_maker_heating", "default:copper_ingot"),
}
minetest.register_craft({
output = MODNAME .. ":waffle_maker",
recipe = {
{craftitems.casing, craftitems.casing, craftitems.casing},
{craftitems.wiring, "", craftitems.wiring},
{craftitems.casing, craftitems.heating, craftitems.casing},
}
})
|
return {
apps = require("config.apps"),
layouts = require("config.layouts")
}
|
--[[
https://github.com/RedXi/vatsimbrief-helper
--]]
--[[
MIT License
Copyright (c) 2020 RedXi
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 Globals = require("vatsimbrief-helper.globals")
TRACK_ISSUE("Tech Debt", "Move all the other global things to globals.lua")
local function numberIsNilOrZero(n)
return n == nil or n == 0
end
local function numberIsNotNilOrZero(n)
return not numberIsNilOrZero(n)
end
local function trim(s)
return s:gsub("^%s*(.-)%s*$", "%1")
end
local function stringIsBlank(s)
return s == nil or s == Globals.emptyString or trim(s) == ""
end
local function stringIsNotBlank(s)
return not stringIsBlank(s)
end
local function stringEndsWith(s, e)
return Globals.stringIsEmpty(e) or s:sub(-(#e)) == e
end
local function stringStripTrailingCharacters(s, n)
return s:sub(1, #s - n)
end
local function defaultIfBlank(s, d)
if s == nil or Globals.stringIsEmpty(trim(s)) then
return d
else
return s
end
end
local function booleanToYesNo(b)
if b then
return "yes"
else
return "no"
end
end
local OsType = {WINDOWS, UNIX_LIKE}
local OS
if package.config:sub(1, 1) == "/" then
OS = OsType.UNIX_LIKE
else
OS = OsType.WINDOWS
end
local PATH_DELIMITER = package.config:sub(1, 1)
local function formatPathOsSpecific(path)
local pathDelimiter = PATH_DELIMITER
return path:gsub("[\\/]", pathDelimiter)
end
local function getExtensionOfFileName(s)
local firstDot = s:find("%.")
if firstDot ~= nil then
return s:sub(firstDot)
else
return ""
end
end
local function wrapStringAtMaxlengthWithPadding(str, maxLength, padding)
local items = Globals.splitStringBySeparator(str, " ")
local result = ""
local lineLength = 0
for i = 1, #items do
local item = items[i]
local itemLength = string.len(item)
if lineLength > 0 and lineLength + 1 + itemLength > maxLength then
result = result .. "\n" .. padding
lineLength = 0
end
if lineLength > 0 then
result = result .. " "
lineLength = lineLength + 1
end
result = result .. item
lineLength = lineLength + itemLength
end
return result
end
-- Some UI libraries
InlineButtonBlob = require("shared_components.inline_button_blob")
-- Color schema
local colorA320Blue = 0xFFFFDDAA
local colorNormal = 0xFFFFFFFF
local colorWarn = 0xFF55FFFF
local colorErr = 0xFF5555FF
-- Make sure to consider licenses.
local licensesOfDependencies = {
-- Async HTTP: copas + dependencies.
{"copas", "MIT License", "https://github.com/keplerproject/copas"},
{"luasocket", "MIT License", "http://luaforge.net/projects/luasocket/"},
{"binaryheap.lua", "MIT License", "https://github.com/Tieske/binaryheap.lua"},
{"coxpcall", "(Free Software)", "https://github.com/keplerproject/coxpcall"},
{"timerwheel.lua", "MIT License", "https://github.com/Tieske/timerwheel.lua"},
-- Configuration handling
{"LIP - Lua INI Parser", "MIT License", "https://github.com/Dynodzzo/Lua_INI_Parser"},
-- Simbrief flightplan
{"xml2lua", "MIT License", "https://github.com/manoelcampos/xml2lua"},
{
"Lua Event Bus",
"MIT License",
"https://github.com/prabirshrestha/lua-eventbus"
}
}
for i = 1, #licensesOfDependencies do
logMsg(
("Vatsimbrief Helper using '%s' with license '%s'. Project homepage: %s"):format(
licensesOfDependencies[i][1],
licensesOfDependencies[i][2],
licensesOfDependencies[i][3]
)
)
end
-- Track opened windows centrally
local WindowStates = {}
local function trackWindowOpen(windowName, isOpen)
WindowStates[windowName] = isOpen
end
local function atLeastOneWindowIsOpen()
for windowName, isOpen in pairs(WindowStates) do
if isOpen then
return true
end
end
return false
end
--
-- Init concurrency
--
local copas = require("copas")
local timer = require("copas.timer")
local SyncTasksAfterAsyncTasks = {}
function tickConcurrentTasks()
-- Run async tasks
copas.step(0.01)
-- The following was invented after spotting that even print statements
-- trigger the multitasking timeout, making serious processing of results
-- obtained from asynchronous execution difficult.
-- Asynchronous operations can now add jobs they want to be executed
-- synchronously.
for _, job in pairs(SyncTasksAfterAsyncTasks) do
job.callback(job.params)
end
SyncTasksAfterAsyncTasks = {}
end
do_often("tickConcurrentTasks()")
--
-- Configuration handling
--
local LIP = require("LIP")
local Configuration = {
FilePath = SCRIPT_DIRECTORY .. "vatsimbrief-helper.ini",
IsDirty = false,
DumpDirtyConfigTimer = nil,
File = {}
}
local function fileExists(name)
local f = io.open(name, "r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
local function loadConfiguration()
if fileExists(Configuration.FilePath) then
Configuration.File = LIP.load(Configuration.FilePath)
logMsg(("Vatsimbrief configuration file '%s' loaded."):format(Configuration.FilePath))
else
logMsg(
("Vatsimbrief configuration file '%s' missing! Running without configuration settings."):format(
Configuration.FilePath
)
)
end
end
local function saveConfiguration()
LIP.save(Configuration.FilePath, Configuration.File)
Configuration.IsDirty = false
end
local function flagConfigurationDirty()
Configuration.IsDirty = true
end
Configuration.DumpDirtyConfigTimer =
timer.new(
{
delay = 1, -- Should be at most the amount of time between changing settings and closing the plug in ...
recurring = true,
params = {},
initial_delay = 0,
callback = function(timer_obj, params)
if Configuration.IsDirty then
saveConfiguration()
end
end
}
)
local function setSetting(cat, key, value)
if Configuration.File[cat] == nil then
Configuration.File[cat] = {}
end
if type(value) == "string" then
value = trim(value)
end
Configuration.File[cat][key] = value
end
local function getSetting(cat, key, defaultValue)
if Configuration.File[cat] == nil then
Configuration.File[cat] = {}
end
if Configuration.File[cat][key] == nil then
return defaultValue
end
local value = Configuration.File[cat][key]
if type(value) == "string" then
value = trim(value)
end
return value
end
--- Specific configuration getters/setters
local function setConfiguredUserName(value)
if Configuration.File.simbrief == nil then
Configuration.File.simbrief = {}
end
Configuration.File.simbrief.username = trim(value)
end
local function getConfiguredSimbriefUserName()
if Configuration.File.simbrief ~= nil and Globals.stringIsNotEmpty(Configuration.File.simbrief.username) then
return Configuration.File.simbrief.username
else
-- Try to guess
local altConfigurationFilePath = SCRIPT_DIRECTORY .. "simbrief_helper.ini"
if fileExists(altConfigurationFilePath) then
local altConfiguration = LIP.load(altConfigurationFilePath)
if altConfiguration.simbrief ~= nil and Globals.stringIsNotEmpty(altConfiguration.simbrief.username) then
local importedUsername = altConfiguration.simbrief.username
setConfiguredUserName(importedUsername)
saveConfiguration()
logMsg(
"Imported simbrief username '" ..
importedUsername .. "' from configuration file '" .. altConfigurationFilePath .. "'"
)
return importedUsername
end
end
end
return ""
end
local function getConfiguredFlightPlanDownloads()
local types = {}
local destFolders = {}
local destFileNames = {}
if Configuration.File.flightplan ~= nil then
local i = 1
while true do
local nextItem = Configuration.File.flightplan["flightPlanTypesForDownload" .. i .. "TypeName"]
if nextItem == nil then
break
end
table.insert(types, nextItem)
local destFolder = Configuration.File.flightplan["flightPlanTypesForDownload" .. i .. "DestFolder"]
if destFolder ~= nil then
destFolders[nextItem] = destFolder
end
local destFileName = Configuration.File.flightplan["flightPlanTypesForDownload" .. i .. "DestFileName"]
if destFileName ~= nil then
destFileNames[nextItem] = destFileName
end
i = i + 1
end
end
return types, destFolders, destFileNames
end
local function setConfiguredFlightPlanDownloads(enabledTypes, mapTypesToDestFolder, mapTypesToDestFileName)
if Configuration.File.flightplan == nil then
Configuration.File.flightplan = {}
end
-- Remove previous entries
for k, v in pairs(Configuration.File.flightplan) do
if k:find("flightPlanTypesForDownload") == 1 then
Configuration.File.flightplan[k] = nil
end
end
-- Add current entries
for i = 1, #enabledTypes do
Configuration.File.flightplan["flightPlanTypesForDownload" .. i .. "TypeName"] = enabledTypes[i]
if mapTypesToDestFolder[enabledTypes[i]] ~= nil then
Configuration.File.flightplan["flightPlanTypesForDownload" .. i .. "DestFolder"] =
mapTypesToDestFolder[enabledTypes[i]]
end
if mapTypesToDestFileName[enabledTypes[i]] ~= nil then
Configuration.File.flightplan["flightPlanTypesForDownload" .. i .. "DestFileName"] =
mapTypesToDestFileName[enabledTypes[i]]
end
end
end
local function setConfiguredDeleteOldFlightPlansSetting(value)
if Configuration.File.flightplan == nil then
Configuration.File.flightplan = {}
end
local strValue
if value then
strValue = "yes"
else
strValue = "no"
end
Configuration.File.flightplan.deleteDownloadedFlightPlans = strValue
end
local function getConfiguredDeleteOldFlightPlansSetting()
-- Unless it's clearly a YES, do NOT return to delete anything! Also in case the removal crashes on the system. We don't want that.
if Configuration.File.flightplan == nil then
Configuration.File.flightplan = {}
end
if Configuration.File.flightplan.deleteDownloadedFlightPlans == nil then
return false
end
if trim(Configuration.File.flightplan.deleteDownloadedFlightPlans) == "yes" then
return true
else
return false
end
end
local function setConfiguredAutoRefreshAtcSetting(value)
if Configuration.File.atc == nil then
Configuration.File.atc = {}
end
local strValue
if value then
strValue = "yes"
else
strValue = "no"
end
Configuration.File.atc.autoRefresh = strValue
end
local function getConfiguredAutoRefreshAtcSettingDefaultTrue()
local defaultValue = true
if Configuration.File.atc == nil then
Configuration.File.atc = {}
end
if Configuration.File.atc.autoRefresh == nil then
return defaultValue
end
if trim(Configuration.File.atc.autoRefresh) == "yes" then
return true
elseif trim(Configuration.File.atc.autoRefresh) == "no" then
return false
else
return defaultValue
end
end
local function setConfiguredAutoRefreshFlightPlanSetting(value)
if Configuration.File.flightplan == nil then
Configuration.File.flightplan = {}
end
local strValue
if value then
strValue = "yes"
else
strValue = "no"
end
Configuration.File.flightplan.autoRefresh = strValue
end
local function getConfiguredAutoRefreshFlightPlanSettingDefaultFalse()
local defaultValue = false
if Configuration.File.flightplan == nil then
Configuration.File.flightplan = {}
end
if Configuration.File.flightplan.autoRefresh == nil then
return defaultValue
end
if trim(Configuration.File.flightplan.autoRefresh) == "yes" then
return true
elseif trim(Configuration.File.flightplan.autoRefresh) == "no" then
return false
else
return defaultValue
end
end
local function setConfiguredAtcWindowVisibility(value)
if Configuration.File.atc == nil then
Configuration.File.atc = {}
end
local strValue
if value then
strValue = "visible"
else
strValue = "hidden"
end
Configuration.File.atc.windowVisibility = strValue
end
local function getConfiguredAtcWindowVisibilityDefaultTrue()
local defaultValue = true
if Configuration.File.atc == nil then
Configuration.File.atc = {}
end
if Configuration.File.atc.windowVisibility == nil then
return defaultValue
end
if trim(Configuration.File.atc.windowVisibility) == "visible" then
return true
elseif trim(Configuration.File.atc.windowVisibility) == "hidden" then
return false
else
return defaultValue
end
end
local function setConfiguredFlightPlanWindowVisibility(value)
if Configuration.File.flightplan == nil then
Configuration.File.flightplan = {}
end
local strValue
if value then
strValue = "visible"
else
strValue = "hidden"
end
Configuration.File.flightplan.windowVisibility = strValue
end
local function getConfiguredFlightPlanWindowVisibility(defaultValue)
if Configuration.File.flightplan == nil then
Configuration.File.flightplan = {}
end
if Configuration.File.flightplan.windowVisibility == nil then
return defaultValue
end
if trim(Configuration.File.flightplan.windowVisibility) == "visible" then
return true
elseif trim(Configuration.File.flightplan.windowVisibility) == "hidden" then
return false
else
return defaultValue
end
end
local function setConfiguredFlightPlanFontScaleSetting(value)
if Configuration.File.flightplan == nil then
Configuration.File.flightplan = {}
end
Configuration.File.flightplan.fontScale = string.format("%f", value)
end
local function getConfiguredFlightPlanFontScaleSettingDefault1()
local defaultValue = 1.0
if Configuration.File.flightplan == nil then
Configuration.File.flightplan = {}
end
if Configuration.File.flightplan.fontScale == nil then
return defaultValue
end
local number = tonumber(Configuration.File.flightplan.fontScale)
if number == nil then
return defaultValue
else
return number
end
end
local function setConfiguredAtcFontScaleSetting(value)
if Configuration.File.atc == nil then
Configuration.File.atc = {}
end
Configuration.File.atc.fontScale = string.format("%f", value)
end
local function getConfiguredAtcFontScaleSettingDefault1()
local defaultValue = 1.0
if Configuration.File.atc == nil then
Configuration.File.atc = {}
end
if Configuration.File.atc.fontScale == nil then
return defaultValue
end
local number = tonumber(Configuration.File.atc.fontScale)
if number == nil then
return defaultValue
else
return number
end
end
loadConfiguration() -- Initially load configuration synchronously so it's present below this line
--
-- Async HTTP
--
local http = require("copas.http")
local HttpDownloadErrors = {
NETWORK = 1,
INTERNAL_SERVER_ERROR = 2,
UNHANDLED_RESPONSE = 3
}
local function performDefaultHttpGetRequest(url, resultCallback, errorCallback, userData, isRedirectedRequest)
local t0 = os.clock()
logMsg(("Requesting URL '%s' at time '%s'"):format(url, os.date("%X")))
local content, code, headers, status = http.request(url)
logMsg(("Request to URL '%s' finished"):format(url))
if
type(content) ~= "string" or type(code) ~= "number" or type(headers) ~= "table" or type(status) ~= "string" or
code == 404 or
code == 500
then
logMsg(("Request URL: %s, FAILURE: Status = %s, code = %s"):format(url, status, code))
errorCallback({errorCode = HttpDownloadErrors.NETWORK, userData = userData})
else
logMsg(
("Request URL: %s, duration: %.2fs, response status: %s, response length: %d bytes"):format(
url,
os.clock() - t0,
status,
#content
)
)
--
TRACK_ISSUE(
"Tech Debt",
MULTILINE_TEXT(
"We tried to enable the library for HTTP redirects this way. However, we don't get out of http.request() w/o error:",
"Request URL: http://www.simbrief.com/ofp/flightplans/EDDNEDDL_WAE_1601924120.rte,",
"FAILURE: Status = nil, code = host or service not provided, or not known"
),
"Treat everything below 500 as an error for now."
)
--[[
if status == 301 then -- Moved permanently
local to = headers.location
if to == nil then
errorCallback({ errorCode = HttpDownloadErrors.UNHANDLED_RESPONSE, userData = userData })
else
if isRedirectedRequest then
logMsg("Only attempting to redirect ONCE. Received second redirect, this time to '" .. to .. "'")
errorCallback({ errorCode = HttpDownloadErrors.UNHANDLED_RESPONSE, userData = userData })
else
logMsg("Redirecting: '" .. url .. "' to '" .. to .. "'")
performDefaultHttpGetRequest(to, resultCallback, errorCallback, userData, true)
end
end
end
]] if
code < 500
then
table.insert(
SyncTasksAfterAsyncTasks,
{callback = resultCallback, params = {responseBody = content, httpStatusCode = code, userData = userData}}
)
else
errorCallback({errorCode = HttpDownloadErrors.INTERNAL_SERVER_ERROR, userData = userData})
end
end
end
local function windowVisibilityToInitialMacroState(humanReadableWindowIdentifier, windowIsVisible)
if windowIsVisible then
logMsg("Initially showing window '" .. humanReadableWindowIdentifier .. "'")
return "activate"
else
return "deactivate"
end
end
--
-- Download of Simbrief flight plans
--
local FlightPlanDownload = {
WasTargetDirectoryCreated = false,
-- Constants
Directory = nil,
RetryAfterSecs = nil,
FilesForFlightplanId = "",
FilesBaseUrl = "", -- Base URL for download, e.g. "http://www.simbrief.com/ofp/flightplans/"
FileTypes = {}, -- Ordered array of types
FileTypesAndNames = {}, -- Hash: Type to file name on server
-- User config
IsDownloadOfTypeEnabled = {}, -- FileType to "true" (enable download) or "false" (disable download)
MapTypeToDestFolder = {},
MapTypeToDestFileName = {},
-- Download state
MapTypeToDownloadedFileName = {}, -- When download complete
SetOfDownloadingTypes = {}, -- When currently downloading, type name maps to "something"
MapTypeToAttemptTimestamp = {} -- Type name maps to timestamp of last attempt
}
local FlightPlanDataForDownloadFileNames = {
o = nil, -- Origin ICAO
d = nil, -- Dest ICAO
a = nil, -- Date
t = nil -- Time
}
-- Init Constants
FlightPlanDownload.Directory = formatPathOsSpecific(SCRIPT_DIRECTORY .. "flight-plans" .. PATH_DELIMITER)
FlightPlanDownload.RetryAfterSecs = 120.0 -- MUST be float to pass printf("%f", this)
-- Load User config
local tmp, tmp2, tmp3 = getConfiguredFlightPlanDownloads()
for i = 1, #tmp do
FlightPlanDownload.IsDownloadOfTypeEnabled[tmp[i]] = true
end
FlightPlanDownload.MapTypeToDestFolder = tmp2 -- When assigning directly, it gave some "redeclaration" warning... !?
FlightPlanDownload.MapTypeToDestFileName = tmp3 -- When assigning directly, it gave some "redeclaration" warning... !?
local function initConversionOfConfiguredDestFileNames(originIcao, destIcao)
FlightPlanDataForDownloadFileNames.o = originIcao
FlightPlanDataForDownloadFileNames.d = destIcao
local t = os.time()
FlightPlanDataForDownloadFileNames.a = os.date("%Y%m%d", t)
FlightPlanDataForDownloadFileNames.t = os.date("%H%M%S", t)
end
local function resolveDestFileNamePlaceholder(placeholder)
local c = placeholder:sub(2) -- Remove leading '%'
if FlightPlanDataForDownloadFileNames[c] ~= nil then
return FlightPlanDataForDownloadFileNames[c]
else
return placeholder -- Identity replacement leaves original string unchanged
end
end
local function resolveConfiguredDestFileName(configuredDestFileName)
return string.gsub(configuredDestFileName, "%%%a", resolveDestFileNamePlaceholder)
end
local function scanDirectoryForFilesOnUnixLikeOs(directory)
if direcory:find("'") ~= nil then
return nil
end -- It's stated that the procedure does not work in this case
local t = {}
local pfile = assert(io.popen(("find '%s' -maxdepth 1 -print0 -type f"):format(directory), "r"))
local list = pfile:read("*a")
pfile:close()
for f in s:gmatch("[^\0]+") do
table.insert(t, f)
end
return t
end
local function scanDirectoryForFilesOnWindowsOs(directory)
local t = {}
for f in io.popen([[dir "]] .. directory .. [[" /b]]):lines() do
table.insert(t, f)
end
return t
end
local function listDownloadedFlightPlans()
local filenames
if OS == OsType.WINDOWS then
filenames = scanDirectoryForFilesOnWindowsOs(FlightPlanDownload.Directory)
else -- OsType.UNIX_LIKE
filenames = scanDirectoryForFilesOnUnixLikeOs(FlightPlanDownload.Directory)
end
if filenames == nil then
return nil
end
for i = 1, #filenames do
filenames[i] = FlightPlanDownload.Directory .. filenames[i]
end
return filenames
end
local function deleteDownloadedFlightPlansIfConfigured()
if getConfiguredDeleteOldFlightPlansSetting() then
local fileNames = listDownloadedFlightPlans()
if fileNames == nil then
logMsg("Failed to list flight plan files.")
else
logMsg("Attempting to delete " .. #fileNames .. " recent flight plan files")
TRACK_ISSUE(
"Tech Debt",
"The listDirectory() implementation is very sloppy.",
"In case it fails, disable the flight plan removal such that we don't crash again next time we're launched."
)
setConfiguredDeleteOldFlightPlansSetting(false)
saveConfiguration()
for i = 1, #fileNames do
os.remove(fileNames[i])
end
setConfiguredDeleteOldFlightPlansSetting(true)
saveConfiguration()
end
end
end
local function pathWithSlash(path)
local lastChar = path:sub(string.len(path))
if lastChar == "/" or lastChar == "\\" then
return path
end
return path .. PATH_DELIMITER
end
function processFlightPlanFileDownloadSuccess(httpRequest)
local typeName = httpRequest.userData.typeName
if httpRequest.userData.flightPlanId ~= FlightPlanDownload.FilesForFlightplanId then
logMsg(
"Discarding downloaded file of type '" ..
httpRequest.userData.typeName ..
"' for flight plan '" .. httpRequest.userData.flightPlanId .. "' as there's a new flight plan"
)
else
local destDir
if FlightPlanDownload.MapTypeToDestFolder[typeName] ~= nil then
destDir = FlightPlanDownload.MapTypeToDestFolder[typeName]
else
destDir = FlightPlanDownload.Directory
end
local fileNameFormat = defaultIfBlank(FlightPlanDownload.MapTypeToDestFileName[typeName], "%a_%t_%o-%d")
local targetFilePath =
formatPathOsSpecific(pathWithSlash(destDir)) ..
resolveConfiguredDestFileName(fileNameFormat) ..
getExtensionOfFileName(FlightPlanDownload.FileTypesAndNames[typeName])
local f = io.open(targetFilePath, "wb")
if io.type(f) ~= "file" then
logMsg("Failed to write data to file path: " .. targetFilePath)
else
f:write(httpRequest.responseBody)
f:close()
end
FlightPlanDownload.MapTypeToDownloadedFileName[typeName] = targetFilePath -- Mark type as downloaded (the file name is the "proof of download" :-)
FlightPlanDownload.SetOfDownloadingTypes[typeName] = false -- Mark download process as finished
-- It seems there's a race condition when this method is called after the flightplan reloaded.
-- Fix that!
if FlightPlanDownload.MapTypeToAttemptTimestamp[typeName] ~= nil then
logMsg(
("Download of file of type '%s' to '%s' for flight plan '%s' succeeded after '%.03fs'"):format(
typeName,
targetFilePath,
httpRequest.userData.flightPlanId,
os.clock() - FlightPlanDownload.MapTypeToAttemptTimestamp[typeName]
)
)
else
logMsg(
("Download of file of type '%s' to '%s' for flight plan '%s' succeeded"):format(
typeName,
targetFilePath,
httpRequest.userData.flightPlanId
)
)
end
end
end
function processFlightPlanFileDownloadFailure(httpRequest)
local typeName = httpRequest.userData.typeName
if httpRequest.userData.flightPlanId ~= FlightPlanDownload.FilesForFlightplanId then
logMsg(
"Discarding failure for download of file of type '" ..
typeName .. "' for flight plan '" .. httpRequest.userData.flightPlanId .. "'"
)
else
logMsg(
("Download of file of type '%s' for flight plan '%s' FAILED after '%.03fs' -- reattempting after '%.fs'"):format(
typeName,
httpRequest.userData.flightPlanId,
os.clock() - FlightPlanDownload.MapTypeToAttemptTimestamp[typeName],
FlightPlanDownload.RetryAfterSecs
)
)
FlightPlanDownload.SetOfDownloadingTypes[typeName] = false
end
end
function downloadAllFlightplans()
local now = 0 -- Optimization: Fetch only once, if necessary
if #FlightPlanDownload.FileTypes > 0 then
now = os.clock()
end
for i = 1, #FlightPlanDownload.FileTypes do -- For all types
local typeName = FlightPlanDownload.FileTypes[i]
downloadFlightplan(typeName, now, false)
end
end
function downloadFlightplan(typeName, now, forceAnotherDownload)
if now == nil then
now = os.clock()
end -- Singular call without timestamp
if FlightPlanDownload.FilesForFlightplanId ~= nil then -- If there's a flightplan
if FlightPlanDownload.IsDownloadOfTypeEnabled[typeName] == true then -- And download enabled by config
if forceAnotherDownload or FlightPlanDownload.MapTypeToDownloadedFileName[typeName] == nil then -- Type not downloaded yet
if forceAnotherDownload or FlightPlanDownload.SetOfDownloadingTypes[typeName] ~= true then -- And download not already running
if
forceAnotherDownload or FlightPlanDownload.MapTypeToAttemptTimestamp[typeName] == nil or -- And download was not attempted yet ...
FlightPlanDownload.MapTypeToAttemptTimestamp[typeName] < now - FlightPlanDownload.RetryAfterSecs
then -- ... or needs to be retried
FlightPlanDownload.MapTypeToAttemptTimestamp[typeName] = now -- Save attempt timestamp for retrying later
FlightPlanDownload.SetOfDownloadingTypes[typeName] = true -- Set immediately to prevent race conditions leading to multiple downloads launching. However, always remember to turn it off!
local url = FlightPlanDownload.FilesBaseUrl .. FlightPlanDownload.FileTypesAndNames[typeName]
logMsg(
("Download of file of type '%s' for flight plan '%s' starting"):format(
typeName,
FlightPlanDownload.FilesForFlightplanId
)
)
TRACK_ISSUE(
"Tech Debt",
MULTILINE_TEXT(
"We observed that the official URL redirects from www.simbrief.com/ofp/flightplans/<TypeName>",
"to",
"http://www.simbrief.com/system/briefing.fmsdl.php?formatget=flightplans/<TypeName>",
"HTTP 301 Redirects are unfortunately not working with this library. :-(",
"Temporary Workaround: Keep the final URL in hardcoded for now. Ouch.",
"That's a ticking time bomb."
)
)
--logMsg("File type of download: " .. FlightPlanDownload.FileTypesAndNames[typeName])
if getExtensionOfFileName(FlightPlanDownload.FileTypesAndNames[typeName]) ~= ".pdf" then
url =
"http://www.simbrief.com/system/briefing.fmsdl.php?formatget=flightplans/" ..
FlightPlanDownload.FileTypesAndNames[typeName]
end
copas.addthread(
function()
-- Note that the HTTP call must run in a copas thread, otherwise it will throw errors (something's always nil)
performDefaultHttpGetRequest(
url,
processFlightPlanFileDownloadSuccess,
processFlightPlanFileDownloadFailure,
{typeName = typeName, flightPlanId = FlightPlanDownload.FilesForFlightplanId}
)
end
)
end
end
end
end
end
end
-- When a file plane has downloaded and the target path changed, it won't be downloaded as the flight plan actually WAS already downloaded.
-- However, when changing the file name or path for the downloaded file plan, one would expect another download to happen.
function downloadFlightPlanAgain(typeName)
logMsg("Requesting (another) download of flight plan type '" .. typeName .. "'")
downloadFlightplan(typeName, os.clock(), true)
end
local function isFlightplanFileDownloadEnabled(typeName)
-- Note: Implement in at least O(log #TypeNames) as this method is called each frame during rendering of the configuration window
return FlightPlanDownload.IsDownloadOfTypeEnabled[typeName] == true
end
local function setFlightplanFileDownloadEnabled(typeName, value)
if type(FlightPlanDownload.IsDownloadOfTypeEnabled[typeName]) == "boolean" then -- Means, type is valid
local stringValue
if value then
stringValue = "true"
else
stringValue = "false"
end
logMsg(("Set flight plan file download for type '%s' to '%s'"):format(typeName, stringValue))
FlightPlanDownload.IsDownloadOfTypeEnabled[typeName] = value
end
end
local function getFlightPlanDownloadDirectory(typeName)
return FlightPlanDownload.MapTypeToDestFolder[typeName]
end
local function setFlightPlanDownloadDirectory(typeName, value)
FlightPlanDownload.MapTypeToDestFolder[typeName] = value
logMsg(("Set flight plan download directory for type '%s' to '%s'"):format(typeName, value))
end
local function getFlightPlanDownloadFileName(typeName)
return FlightPlanDownload.MapTypeToDestFileName[typeName]
end
local function setFlightPlanDownloadFileName(typeName, value)
FlightPlanDownload.MapTypeToDestFileName[typeName] = value
logMsg(("Set flight plan download file name for type '%s' to '%s'"):format(typeName, value))
end
local function saveFlightPlanFilesForDownload()
local enabledFileTypes = {}
for fileType, downloadEnabled in pairs(FlightPlanDownload.IsDownloadOfTypeEnabled) do
if downloadEnabled then
logMsg(("Flight plan download for type '%s' enabled: '%s'"):format(fileType, booleanToYesNo(downloadEnabled)))
table.insert(enabledFileTypes, fileType)
end
end
setConfiguredFlightPlanDownloads(
enabledFileTypes,
FlightPlanDownload.MapTypeToDestFolder,
FlightPlanDownload.MapTypeToDestFileName
)
saveConfiguration()
end
local function restartFlightPlanDownloads(flightPlanId, baseUrlForDownload, fileTypesAndNames)
-- Store flightplan specific download information
FlightPlanDownload.FilesForFlightplanId = flightPlanId
FlightPlanDownload.FilesBaseUrl = baseUrlForDownload
if not stringEndsWith(FlightPlanDownload.FilesBaseUrl, "/") then
FlightPlanDownload.FilesBaseUrl = FlightPlanDownload.FilesBaseUrl .. "/"
end
FlightPlanDownload.FileTypesAndNames = fileTypesAndNames
FlightPlanDownload.FileTypes = {}
for fileType, fileName in pairs(fileTypesAndNames) do
table.insert(FlightPlanDownload.FileTypes, fileType)
end
-- Update config: Add new types from the flight plan and remove those that disappeared from the flight plan for some reason...
local configNew = {}
for fileType, fileName in pairs(fileTypesAndNames) do
configNew[fileType] = isFlightplanFileDownloadEnabled(fileType)
end
FlightPlanDownload.IsDownloadOfTypeEnabled = configNew
-- Invalidate old flightplans in memory
FlightPlanDownload.MapTypeToDownloadedFileName = {}
FlightPlanDownload.SetOfDownloadingTypes = {}
FlightPlanDownload.MapTypeToAttemptTimestamp = {}
-- Create target directory of downloaded flight plans
if FlightPlanDownload.WasTargetDirectoryCreated == false then
-- Seems to open a console window (at least under windows) - make sure it only runs once
os.execute("mkdir " .. FlightPlanDownload.Directory)
FlightPlanDownload.WasTargetDirectoryCreated = true
end
-- Invalidate old flightplans on disk
deleteDownloadedFlightPlansIfConfigured()
end
local function getFlightplanFileTypesArray()
return FlightPlanDownload.FileTypes
end
do_sometimes("downloadAllFlightplans()")
--
-- Simbrief flight plans
--
TRACK_ISSUE("Tech Debt", "FlightplanCallsign")
local FlightPlanStateContainer = require("vatsimbrief-helper.state.flight_plan")
local function removeLinebreaksFromString(s)
return string.gsub(s, "\n", " ")
end
local xml2lua = require("xml2lua")
local simbriefFlightplanXmlHandler = require("xmlhandler.tree")
local SimbriefFlightplan = {}
local FlightplanId = nil -- PK to spot that a file plan changed
FlightPlan = {
AirlineIcao = "",
FlightNumber = 0
}
local FlightplanOriginIcao = ""
local FlightplanOriginIata = ""
local FlightplanOriginName = ""
local FlightplanOriginRunway = ""
local FlightplanOriginMetar = ""
local FlightplanDestIcao = ""
local FlightplanDestIata = ""
local FlightplanDestName = ""
local FlightplanDestRunway = ""
local FlightplanDestMetar = ""
local FlightplanAltIcao = ""
local FlightplanAltIata = ""
local FlightplanAltName = ""
local FlightplanAltRunway = ""
local FlightplanAltMetar = ""
local FlightplanCallsign = ""
local FlightplanRoute = ""
local FlightplanAltRoute = ""
local FlightplanEstOut = 0
local FlightplanEstOff = 0
local FlightplanEstOn = 0
local FlightplanEstIn = 0
local FlightplanEstBlock = 0
local FlightplanEstAir = 0
local FlightplanAltitude = 0
local FlightplanAltAltitude = 0
local FlightplanTocTemp = 0
local FlightplanBlockFuel = 0
local FlightplanReserveFuel = 0
local FlightplanTakeoffFuel = 0
local FlightplanAltFuel = 0
local FlightplanUnit = ""
local FlightplanCargo = 0
local FlightplanPax = 0
local FlightplanPayload = 0
local FlightplanZfw = 0
local FlightplanDistance = 0
local FlightplanAltDistance = 0
local FlightplanCostindex = 0
local FlightplanAvgWindDir = 0
local FlightplanAvgWindSpeed = 0
local SimbriefFlightplanFetchStatusLevel = {
INFO = 0,
USER_RELATED = 1,
SYSTEM_RELATED = 2
}
local SimbriefFlightplanFetchStatus = {
NO_DOWNLOAD_ATTEMPTED = {level = SimbriefFlightplanFetchStatusLevel.INFO},
DOWNLOADING = {level = SimbriefFlightplanFetchStatusLevel.INFO},
NO_ERROR = {level = SimbriefFlightplanFetchStatusLevel.INFO},
UNKNOWN_DOWNLOAD_ERROR = {level = SimbriefFlightplanFetchStatusLevel.SYSTEM_RELATED},
UNEXPECTED_HTTP_RESPONSE_STATUS = {level = SimbriefFlightplanFetchStatusLevel.SYSTEM_RELATED},
UNEXPECTED_HTTP_RESPONSE = {level = SimbriefFlightplanFetchStatusLevel.SYSTEM_RELATED},
NETWORK_ERROR = {level = SimbriefFlightplanFetchStatusLevel.SYSTEM_RELATED},
INVALID_USER_NAME = {level = SimbriefFlightplanFetchStatusLevel.USER_RELATED},
NO_FLIGHT_PLAN_CREATED = {level = SimbriefFlightplanFetchStatusLevel.USER_RELATED},
UNKNOWN_ERROR_STATUS_RESPONSE_PAYLOAD = {level = SimbriefFlightplanFetchStatusLevel.SYSTEM_RELATED},
NO_SIMBRIEF_USER_ID_ENTERED = {level = SimbriefFlightplanFetchStatusLevel.SYSTEM_RELATED}
}
local CurrentSimbriefFlightplanFetchStatus = SimbriefFlightplanFetchStatus.NO_DOWNLOAD_ATTEMPTED
local function getSimbriefFlightplanFetchStatusMessageAndColor()
local msg
if CurrentSimbriefFlightplanFetchStatus == SimbriefFlightplanFetchStatus.NO_DOWNLOAD_ATTEMPTED then
msg = "Download pending"
elseif CurrentSimbriefFlightplanFetchStatus == SimbriefFlightplanFetchStatus.DOWNLOADING then
msg = "Downloading"
elseif CurrentSimbriefFlightplanFetchStatus == SimbriefFlightplanFetchStatus.NO_ERROR then
msg = "No error"
elseif CurrentSimbriefFlightplanFetchStatus == SimbriefFlightplanFetchStatus.UNKNOWN_DOWNLOAD_ERROR then
msg = "Unknown error while downloading"
elseif CurrentSimbriefFlightplanFetchStatus == SimbriefFlightplanFetchStatus.UNEXPECTED_HTTP_RESPONSE_STATUS then
msg = "Unexpected server response"
elseif CurrentSimbriefFlightplanFetchStatus == SimbriefFlightplanFetchStatus.UNEXPECTED_HTTP_RESPONSE then
msg = "Unhandled server response"
elseif CurrentSimbriefFlightplanFetchStatus == SimbriefFlightplanFetchStatus.NETWORK_ERROR then
msg = "Network error"
elseif CurrentSimbriefFlightplanFetchStatus == SimbriefFlightplanFetchStatus.INVALID_USER_NAME then
msg = "Please set a correct Simbrief user name in the Control window"
elseif CurrentSimbriefFlightplanFetchStatus == SimbriefFlightplanFetchStatus.NO_FLIGHT_PLAN_CREATED then
msg = "No flight plan found. Please create one first in Simbrief."
elseif CurrentSimbriefFlightplanFetchStatus == SimbriefFlightplanFetchStatus.UNKNOWN_ERROR_STATUS_RESPONSE_PAYLOAD then
msg = "Unhandled response status message"
elseif CurrentSimbriefFlightplanFetchStatus == SimbriefFlightplanFetchStatus.NO_SIMBRIEF_USER_ID_ENTERED then
msg = "Please enter your Simbrief user name it in the Control window"
else
msg = "Unknown error '" .. (CurrentSimbriefFlightplanFetchStatus or "(none)") .. "'"
end
msg = "Could not download flight plan from Simbrief:\n" .. msg .. "."
local color
if CurrentSimbriefFlightplanFetchStatus.level == SimbriefFlightplanFetchStatusLevel.INFO then
color = colorNormal
elseif CurrentSimbriefFlightplanFetchStatus.level == SimbriefFlightplanFetchStatusLevel.SYSTEM_RELATED then
color = colorWarn
elseif CurrentSimbriefFlightplanFetchStatus.level == SimbriefFlightplanFetchStatusLevel.USER_RELATED then
color = colorA320Blue
else
color = colorNormal
end
return msg, color
end
local function processFlightplanDownloadFailure(httpRequest)
if httpRequest.errorCode == HttpDownloadErrors.INTERNAL_SERVER_ERROR then
CurrentSimbriefFlightplanFetchStatus = SimbriefFlightplanFetchStatus.UNEXPECTED_HTTP_RESPONSE_STATUS
elseif httpRequest.errorCode == HttpDownloadErrors.UNHANDLED_RESPONSE then
CurrentSimbriefFlightplanFetchStatus = SimbriefFlightplanFetchStatus.UNEXPECTED_HTTP_RESPONSE
elseif httpRequest.errorCode == HttpDownloadErrors.NETWORK then
CurrentSimbriefFlightplanFetchStatus = SimbriefFlightplanFetchStatus.NETWORK_ERROR
else
CurrentSimbriefFlightplanFetchStatus = SimbriefFlightplanFetchStatus.UNKNOWN_DOWNLOAD_ERROR
end
end
local function processNewFlightplan(httpRequest)
if httpRequest.httpStatusCode ~= 200 and httpRequest.httpStatusCode ~= 400 then
CurrentSimbriefFlightplanFetchStatus = SimbriefFlightplanFetchStatus.UNEXPECTED_HTTP_RESPONSE_STATUS
else
local parser = xml2lua.parser(simbriefFlightplanXmlHandler)
parser:parse(httpRequest.responseBody)
if httpRequest.httpStatusCode == 200 and simbriefFlightplanXmlHandler.root.OFP.fetch.status == "Success" then
SimbriefFlightplan = simbriefFlightplanXmlHandler.root.OFP
newFlightplanId = SimbriefFlightplan.params.request_id .. "|" .. SimbriefFlightplan.params.time_generated
-- We just guess that this PK definition yields "enough uniqueness"
if newFlightplanId ~= FlightplanId then -- Flightplan changed
FlightplanId = newFlightplanId
-- If a value is not set, <key/> is interpreted as empty node and neither as empty string or nil.
if type(SimbriefFlightplan.general.flight_number) == "string" then
FlightPlan.FlightNumber = SimbriefFlightplan.general.flight_number
else
FlightPlan.FlightNumber = ""
end
if type(SimbriefFlightplan.general.icao_airline) == "string" then
FlightPlan.AirlineIcao = SimbriefFlightplan.general.icao_airline
else
FlightPlan.AirlineIcao = ""
end
FlightplanOriginIcao = SimbriefFlightplan.origin.icao_code
FlightplanOriginIata = SimbriefFlightplan.origin.iata_code
FlightplanOriginName = SimbriefFlightplan.origin.name
FlightplanOriginRunway = SimbriefFlightplan.origin.plan_rwy
FlightplanDestIcao = SimbriefFlightplan.destination.icao_code
FlightplanDestIata = SimbriefFlightplan.destination.iata_code
FlightplanDestName = SimbriefFlightplan.destination.name
FlightplanDestRunway = SimbriefFlightplan.destination.plan_rwy
FlightplanAltIcao = SimbriefFlightplan.alternate.icao_code
FlightplanAltIata = SimbriefFlightplan.alternate.iata_code
FlightplanAltName = SimbriefFlightplan.alternate.name
FlightplanAltRunway = SimbriefFlightplan.alternate.plan_rwy
FlightplanCallsign = SimbriefFlightplan.atc.callsign
FlightPlanStateContainer.setCallSign(FlightplanCallsign)
FlightplanRoute = SimbriefFlightplan.general.route
if Globals.stringIsEmpty(FlightplanRoute) then
FlightplanRoute = "(none)"
end
FlightplanAltRoute = SimbriefFlightplan.alternate.route
if Globals.stringIsEmpty(FlightplanAltRoute) then
FlightplanAltRoute = "(none)"
end
FlightplanEstOut = tonumber(SimbriefFlightplan.times.est_out)
FlightplanEstOff = tonumber(SimbriefFlightplan.times.est_off)
FlightplanEstOn = tonumber(SimbriefFlightplan.times.est_on)
FlightplanEstIn = tonumber(SimbriefFlightplan.times.est_in)
FlightplanEstBlock = tonumber(SimbriefFlightplan.times.est_block)
FlightplanEstEnroute = tonumber(SimbriefFlightplan.times.est_time_enroute)
-- TOC waypoint is identified by "TOC"
-- It seems flightplans w/o route are also possible to create.
local haveToc = false
if SimbriefFlightplan.navlog ~= nil and SimbriefFlightplan.navlog.fix ~= nil then
local indexOfToc = 1
while indexOfToc <= #SimbriefFlightplan.navlog.fix and
SimbriefFlightplan.navlog.fix[indexOfToc].ident ~= "TOC" do
indexOfToc = indexOfToc + 1
end
if indexOfToc <= #SimbriefFlightplan.navlog.fix then
FlightplanAltitude = tonumber(SimbriefFlightplan.navlog.fix[indexOfToc].altitude_feet)
FlightplanTocTemp = tonumber(SimbriefFlightplan.navlog.fix[indexOfToc].oat)
haveToc = true
end
end
if not haveToc then
-- No TOC found!?
FlightplanAltitude = tonumber(SimbriefFlightplan.general.initial_altitude)
FlightplanTocTemp = 9999 -- Some "bad" value
end
FlightplanAltAltitude = tonumber(SimbriefFlightplan.alternate.cruise_altitude)
FlightplanBlockFuel = tonumber(SimbriefFlightplan.fuel.plan_ramp)
FlightplanReserveFuel = tonumber(SimbriefFlightplan.fuel.reserve)
FlightplanTakeoffFuel = tonumber(SimbriefFlightplan.fuel.min_takeoff)
FlightplanAltFuel = tonumber(SimbriefFlightplan.fuel.alternate_burn)
FlightplanUnit = SimbriefFlightplan.params.units
FlightplanCargo = tonumber(SimbriefFlightplan.weights.cargo)
FlightplanPax = tonumber(SimbriefFlightplan.weights.pax_count)
FlightplanPayload = tonumber(SimbriefFlightplan.weights.payload)
FlightplanZfw = tonumber(SimbriefFlightplan.weights.est_zfw)
FlightplanDistance = SimbriefFlightplan.general.route_distance
FlightplanAltDistance = SimbriefFlightplan.alternate.distance
FlightplanCostindex = SimbriefFlightplan.general.costindex
FlightplanOriginMetar = removeLinebreaksFromString(SimbriefFlightplan.weather.orig_metar)
FlightplanDestMetar = removeLinebreaksFromString(SimbriefFlightplan.weather.dest_metar)
if type(SimbriefFlightplan.weather.altn_metar) == "string" then
FlightplanAltMetar = removeLinebreaksFromString(SimbriefFlightplan.weather.altn_metar)
else
FlightplanAltMetar = ""
end
FlightplanAvgWindDir = tonumber(SimbriefFlightplan.general.avg_wind_dir)
FlightplanAvgWindSpeed = tonumber(SimbriefFlightplan.general.avg_wind_spd)
local filesDirectory = SimbriefFlightplan.files.directory
local fileTypesAndNames = {[SimbriefFlightplan.files.pdf.name] = SimbriefFlightplan.files.pdf.link}
for i = 1, #SimbriefFlightplan.files.file do
local name = SimbriefFlightplan.files.file[i].name
local link = SimbriefFlightplan.files.file[i].link
fileTypesAndNames[name] = link
end
CurrentSimbriefFlightplanFetchStatus = SimbriefFlightplanFetchStatus.NO_ERROR
initConversionOfConfiguredDestFileNames(FlightplanOriginIcao, FlightplanDestIcao)
restartFlightPlanDownloads(FlightplanId, filesDirectory, fileTypesAndNames)
end
else
logMsg(
"Flight plan states that it's not valid. Reported status: " ..
simbriefFlightplanXmlHandler.root.OFP.fetch.status
)
-- As of 10/2020, original message is <status>Error: Unknown UserID</status>
if
httpRequest.httpStatusCode == 400 and
simbriefFlightplanXmlHandler.root.OFP.fetch.status:lower():find("unknown userid")
then
CurrentSimbriefFlightplanFetchStatus = SimbriefFlightplanFetchStatus.INVALID_USER_NAME
elseif simbriefFlightplanXmlHandler.root.OFP.fetch.status:lower():find("no flight plan") then
CurrentSimbriefFlightplanFetchStatus = SimbriefFlightplanFetchStatus.NO_FLIGHT_PLAN_CREATED
else
CurrentSimbriefFlightplanFetchStatus = SimbriefFlightplanFetchStatus.UNKNOWN_ERROR_STATUS_RESPONSE_PAYLOAD
end
end
-- Display configuration window if there's something wrong with the user name
if CurrentSimbriefFlightplanFetchStatus == SimbriefFlightplanFetchStatus.INVALID_USER_NAME then
createVatsimbriefHelperControlWindow()
end
end
end
local function clearFlightplan()
FlightplanId = nil
end
local function refreshFlightplanNow()
copas.addthread(
function()
CurrentSimbriefFlightplanFetchStatus = SimbriefFlightplanFetchStatus.DOWNLOADING
if Globals.stringIsNotEmpty(getConfiguredSimbriefUserName()) then
local url = "http://www.simbrief.com/api/xml.fetcher.php?username=" .. getConfiguredSimbriefUserName()
performDefaultHttpGetRequest(url, processNewFlightplan, processFlightplanDownloadFailure)
else
logMsg("Not fetching flight plan. No simbrief username configured.")
CurrentSimbriefFlightplanFetchStatus = SimbriefFlightplanFetchStatus.NO_SIMBRIEF_USER_ID_ENTERED
-- Display configuration window if there's something wrong with the user name
createVatsimbriefHelperControlWindow()
end
end
)
end
local refreshFlightplanTimer =
timer.new(
{
delay = 60, -- Should be more than enough
recurring = true,
params = {},
initial_delay = 0, -- Make sure we have information asap
-- Usually, the user will have his username configured and flightplan already armed
callback = function(timer_obj, params)
if getConfiguredAutoRefreshFlightPlanSettingDefaultFalse() then
refreshFlightplanNow()
end
end
}
)
--
-- VATSIM data
--
local Datarefs = require("vatsimbrief-helper.state.datarefs")
local VatsimDataContainer = require("vatsimbrief-helper.components.vatsim_data_container")
local VatsimData = require("vatsimbrief-helper.state.vatsim_data")
local function processSuccessfulVatsimDataRequest(httpRequest)
VatsimData.container:processSuccessfulHttpResponse(httpRequest)
end
local function processFailedVatsimDataRequest(httpRequest)
local fetchStatus = nil
if httpRequest.errorCode == HttpDownloadErrors.INTERNAL_SERVER_ERROR then
fetchStatus = VatsimDataContainer.FetchStatus.UNEXPECTED_HTTP_RESPONSE_STATUS
elseif httpRequest.errorCode == HttpDownloadErrors.UNHANDLED_RESPONSE then
fetchStatus = VatsimDataContainer.FetchStatus.UNEXPECTED_HTTP_RESPONSE
elseif httpRequest.errorCode == HttpDownloadErrors.NETWORK then
fetchStatus = VatsimDataContainer.FetchStatus.NETWORK_ERROR
else
fetchStatus = VatsimDataContainer.FetchStatus.UNKNOWN_DOWNLOAD_ERROR
end
VatsimData.container:processFailedHttpRequest(fetchStatus)
end
TRACK_ISSUE(
"Tech Debt",
MULTILINE_TEXT(
"Right after starting to implement the public interface, the Lua 200 local variables limit was crossed.",
"For now, VatsimData is out of the main script. There are still some things missing that",
"rely on configuration, which is still in the main script. Move that as well."
)
)
local function refreshVatsimDataNow()
if getConfiguredAtcWindowVisibilityDefaultTrue() then -- ATM, don't refresh when ATC window is not opened
copas.addthread(
function()
VatsimData.container:noteDownloadIsStarting()
local url = "http://data.vatsim.net/vatsim-data.txt"
performDefaultHttpGetRequest(url, processSuccessfulVatsimDataRequest, processFailedVatsimDataRequest)
end
)
else
logMsg("ATC window is currently closed. No refresh of VATSIM data necessary.")
end
end
local refreshVatsimDataTimer =
timer.new(
{
delay = 60, -- Should be more than enough
recurring = true,
params = {},
initial_delay = 0, -- Make sure we have information asap
callback = function(timer_obj, params)
if getConfiguredAutoRefreshAtcSettingDefaultTrue() then
refreshVatsimDataNow()
end
end
}
)
--
-- Public Interface
--
local PublicInterface = require("vatsimbrief-helper.public_interface")
--
-- Initialization and Main Thread
--
-- To deal with lazily initialized resources, the initialization method is retried automatically
-- until it succeeds once. For instance, it can check for datarefs and stop initialization if
-- a required dataref is not yet initialized.
--
local MainThread = require("vatsimbrief-helper.main_thread")
local LazyInitializationSingleton
do
LazyInitialization = {
vatsimbriefHelperIsInitialized = false,
gaveUpAlready = false,
triesSoFar = 0,
Constants = {
maxTries = 100
}
}
function LazyInitialization:loop()
MainThread.loop()
end
function LazyInitialization:_canInitializeNow()
if (VHFHelperEventBus == nil) then
return false
end
return true
end
function LazyInitialization:_initializeNow()
VHFHelperEventBus.on(VHFHelperEventOnFrequencyChanged, onVHFHelperFrequencyChanged)
Datarefs.bootstrap()
do_every_frame("LazyInitialization:loop()")
end
function LazyInitialization:tryVatsimbriefHelperInit()
if (self.gaveUpAlready or self.vatsimbriefHelperIsInitialized) then
return
end
self.triesSoFar = self.triesSoFar + 1
if (self.triesSoFar > self.Constants.maxTries) then
logMsg(
("Vatsimbrief Helper: Lazy initialization is taking too long, giving up after %d tries."):format(
self.triesSoFar - 1
)
)
self.gaveUpAlready = true
return
end
if (not self:_canInitializeNow()) then
return
end
self:_initializeNow()
logMsg("Vatsimbrief Helper: Lazy initialization finished.")
self.vatsimbriefHelperIsInitialized = true
end
end
do_often("LazyInitialization:tryVatsimbriefHelperInit()")
--
-- Flightplan UI handling
--
local FlightplanWindowLastAtcIdentifiersUpdatedTimestamp = nil
local FlightplanWindowHasRenderedContent = false
local FlightplanWindowAirports = ""
local FlightplanWindowRoute = ""
local FlightplanWindowAltRoute = ""
local FlightplanWindowSchedule = ""
local FlightplanWindowAltitudeAndTemp = ""
local FlightplanWindowFuel = ""
local FlightplanWindowWeights = ""
local FlightplanWindowTrack = ""
local FlightplanWindowMetars = ""
local FlightplanWindow = {
WindowHandle = nil,
KeyWidth = 11, -- If changing this, also change max value length
MaxValueLengthUntilBreak = 79, -- 90 characters minus keyWidth of 11
FlightplanWindowValuePaddingLeft = "",
FontScale = getConfiguredFlightPlanFontScaleSettingDefault1(), -- Cache font scale as it's needed during each draw.
SpacingBetweenAirportsAndReloadButton = "",
ReloadButton = nil,
FlightplanWindowShowDownloadingMsg = false,
FlightplanWindowLastRenderedFlightplanId = nil
}
FlightplanWindow.FlightplanWindowValuePaddingLeft = string.rep(" ", FlightplanWindow.KeyWidth)
local FlightplanWindowLastRenderedSimbriefFlightplanFetchStatus = CurrentSimbriefFlightplanFetchStatus
local FlightplanWindowFlightplanDownloadStatus = ""
local FlightplanWindowFlightplanDownloadStatusColor = 0
local function updateFlightPlanWindowTitle()
if FlightplanWindow.WindowHandle ~= nil then
-- Title also exists without the physical window, but for performance, only render if window exists
local title = "Vatsimbrief Helper Flight Plan"
if Globals.stringIsNotEmpty(FlightplanId) then
if stringIsNotBlank(FlightPlan.AirlineIcao) and stringIsNotBlank(FlightPlan.FlightNumber) then
title = title .. " for flight " .. FlightPlan.AirlineIcao .. FlightPlan.FlightNumber
end
end
float_wnd_set_title(FlightplanWindow.WindowHandle, title)
end
end
local function createFlightplanTableEntry(name, value)
return ("%-" .. FlightplanWindow.KeyWidth .. "s%s"):format(name .. ":", value)
end
function durationSecsToHHMM(s)
s = tonumber(s)
local hrs = math.floor(s / (60 * 60))
s = s % (60 * 60)
local mins = math.floor(s / 60)
return ("%02d:%02d"):format(hrs, mins)
end
function buildVatsimbriefHelperFlightplanWindowCanvas()
-- Invent a caching mechanism to prevent rendering the strings each frame
local flightplanChanged = FlightplanWindow.FlightplanWindowLastRenderedFlightplanId ~= FlightplanId
local flightplanFetchStatusChanged =
AtcWindowLastRenderedSimbriefFlightplanFetchStatus ~= CurrentSimbriefFlightplanFetchStatus
local renderContent = flightplanChanged or flightplanFetchStatusChanged or not FlightplanWindowHasRenderedContent
if renderContent then
-- Render download status
local statusType = CurrentSimbriefFlightplanFetchStatus.level
if
statusType == SimbriefFlightplanFetchStatusLevel.USER_RELATED or
statusType == SimbriefFlightplanFetchStatusLevel.SYSTEM_RELATED
then
FlightplanWindowFlightplanDownloadStatus, FlightplanWindowFlightplanDownloadStatusColor =
getSimbriefFlightplanFetchStatusMessageAndColor()
else
FlightplanWindowFlightplanDownloadStatus = ""
FlightplanWindowFlightplanDownloadStatusColor = colorNormal
end
if Globals.stringIsEmpty(FlightplanId) then
if CurrentSimbriefFlightplanFetchStatus == SimbriefFlightplanFetchStatus.DOWNLOADING then
FlightplanWindow.FlightplanWindowShowDownloadingMsg = true
else
FlightplanWindow.FlightplanWindowShowDownloadingMsg = false -- Clear message if there's another message going on, e.g. a download error
end
else
FlightplanWindow.FlightplanWindowShowDownloadingMsg = false
if Globals.stringIsNotEmpty(FlightplanAltIcao) then
FlightplanWindowAirports = ("%s - %s / %s"):format(FlightplanOriginIcao, FlightplanDestIcao, FlightplanAltIcao)
else
FlightplanWindowAirports = ("%s - %s"):format(FlightplanOriginIcao, FlightplanDestIcao)
end
FlightplanWindowAirports = createFlightplanTableEntry("Airports", FlightplanWindowAirports)
local windowWidthCharacters = FlightplanWindow.KeyWidth + FlightplanWindow.MaxValueLengthUntilBreak
local reloadButtonText = "Reload"
local spacing = windowWidthCharacters - string.len(FlightplanWindowAirports) - string.len(reloadButtonText)
if spacing < 1 then -- Overflow intentionally
spacing = 1 -- Retain some spacing
end
FlightplanWindow.SpacingBetweenAirportsAndReloadButton = string.rep(" ", spacing)
FlightplanWindow.ReloadButton = InlineButtonBlob:new()
FlightplanWindow.ReloadButton:addDefaultButton(reloadButtonText)
FlightplanWindow.ReloadButton:setDefaultButtonCallbackFunction(
function()
clearFlightplan()
refreshFlightplanNow()
end
)
FlightplanWindowRoute =
("%s/%s %s %s/%s"):format(
FlightplanOriginIcao,
FlightplanOriginRunway,
FlightplanRoute,
FlightplanDestIcao,
FlightplanDestRunway
)
FlightplanWindowRoute =
wrapStringAtMaxlengthWithPadding(
FlightplanWindowRoute,
FlightplanWindow.MaxValueLengthUntilBreak,
FlightplanWindow.FlightplanWindowValuePaddingLeft
)
FlightplanWindowRoute = createFlightplanTableEntry("Route", FlightplanWindowRoute)
if Globals.stringIsNotEmpty(FlightplanAltIcao) then
FlightplanWindowAltRoute =
("%s/%s %s %s/%s"):format(
FlightplanDestIcao,
FlightplanDestRunway,
FlightplanAltRoute,
FlightplanAltIcao,
FlightplanAltRunway
)
FlightplanWindowAltRoute =
wrapStringAtMaxlengthWithPadding(
FlightplanWindowAltRoute,
FlightplanWindow.MaxValueLengthUntilBreak,
FlightplanWindow.FlightplanWindowValuePaddingLeft
)
FlightplanWindowAltRoute = createFlightplanTableEntry("Alt Route", FlightplanWindowAltRoute)
else
FlightplanWindowAltRoute = ""
end
local timeFormat = "%I:%M%p"
FlightplanWindowSchedule =
("BLOCK=%s OUT=%s OFF=%s ENROUTE=%s ON=%s IN=%s"):format(
durationSecsToHHMM(FlightplanEstBlock),
os.date("!%I:%M%p", FlightplanEstOut),
os.date("!%I:%M%p", FlightplanEstOff),
durationSecsToHHMM(FlightplanEstEnroute),
os.date("!%I:%M%p", FlightplanEstOn),
os.date("!%I:%M%p", FlightplanEstIn)
)
FlightplanWindowSchedule = createFlightplanTableEntry("Schedule", FlightplanWindowSchedule)
if Globals.stringIsNotEmpty(FlightplanAltIcao) then
FlightplanWindowAltitudeAndTemp =
("ALT=%d/%d TEMP=%d°C"):format(FlightplanAltitude, FlightplanAltAltitude, FlightplanTocTemp)
else
FlightplanWindowAltitudeAndTemp = ("ALT=%d TEMP=%d°C"):format(FlightplanAltitude, FlightplanTocTemp)
end
FlightplanWindowAltitudeAndTemp = createFlightplanTableEntry("Cruise", FlightplanWindowAltitudeAndTemp)
FlightplanWindowFuel =
("BLOCK=%d%s T/O=%d%s ALTN=%d%s RESERVE=%d%s"):format(
FlightplanBlockFuel,
FlightplanUnit,
FlightplanTakeoffFuel,
FlightplanUnit,
FlightplanAltFuel,
FlightplanUnit,
FlightplanReserveFuel,
FlightplanUnit
)
FlightplanWindowFuel = createFlightplanTableEntry("Fuel", FlightplanWindowFuel)
FlightplanWindowWeights =
("CARGO=%d%s PAX=%d%s PAYLOAD=%d%s ZFW=%d%s"):format(
FlightplanCargo,
FlightplanUnit,
FlightplanPax,
FlightplanUnit,
FlightplanPayload,
FlightplanUnit,
FlightplanZfw,
FlightplanUnit
)
FlightplanWindowWeights = createFlightplanTableEntry("Weights", FlightplanWindowWeights)
if Globals.stringIsNotEmpty(FlightplanAltIcao) then
FlightplanWindowTrack =
("DIST=%d/%d BLOCKTIME=%s CI=%d WINDDIR=%d WINDSPD=%d"):format(
FlightplanDistance,
FlightplanAltDistance,
durationSecsToHHMM(FlightplanEstBlock),
FlightplanCostindex,
FlightplanAvgWindDir,
FlightplanAvgWindSpeed
)
else
FlightplanWindowTrack =
("DIST=%d BLOCKTIME=%s CI=%d WINDDIR=%d WINDSPD=%d"):format(
FlightplanDistance,
durationSecsToHHMM(FlightplanEstBlock),
FlightplanCostindex,
FlightplanAvgWindDir,
FlightplanAvgWindSpeed
)
end
FlightplanWindowTrack = createFlightplanTableEntry("Track", FlightplanWindowTrack)
FlightplanWindowMetars =
("%s\n%s%s"):format(
FlightplanOriginMetar,
FlightplanWindow.FlightplanWindowValuePaddingLeft,
FlightplanDestMetar
)
if Globals.stringIsNotEmpty(FlightplanAltIcao) then
FlightplanWindowMetars =
FlightplanWindowMetars ..
("\n%s%s"):format(FlightplanWindow.FlightplanWindowValuePaddingLeft, FlightplanAltMetar)
end
FlightplanWindowMetars = createFlightplanTableEntry("METARs", FlightplanWindowMetars)
updateFlightPlanWindowTitle()
end
FlightplanWindowLastRenderedSimbriefFlightplanFetchStatus = CurrentSimbriefFlightplanFetchStatus
FlightplanWindow.FlightplanWindowLastRenderedFlightplanId = FlightplanId
FlightplanWindowHasRenderedContent = true
end
-- Paint
imgui.SetWindowFontScale(FlightplanWindow.FontScale)
if Globals.stringIsNotEmpty(FlightplanWindowFlightplanDownloadStatus) then
imgui.PushStyleColor(imgui.constant.Col.Text, FlightplanWindowFlightplanDownloadStatusColor)
imgui.TextUnformatted(FlightplanWindowFlightplanDownloadStatus)
imgui.PopStyleColor()
end
if FlightplanWindow.FlightplanWindowShowDownloadingMsg then
imgui.PushStyleColor(imgui.constant.Col.Text, colorA320Blue)
imgui.TextUnformatted("Downloading flight plan ...")
imgui.PopStyleColor()
elseif Globals.stringIsNotEmpty(FlightplanId) then
imgui.TextUnformatted(FlightplanWindowAirports)
imgui.SameLine()
imgui.TextUnformatted(FlightplanWindow.SpacingBetweenAirportsAndReloadButton)
imgui.SameLine()
FlightplanWindow.ReloadButton:renderToCanvas()
imgui.TextUnformatted(FlightplanWindowRoute)
if Globals.stringIsNotEmpty(FlightplanWindowAltRoute) then
imgui.TextUnformatted(FlightplanWindowAltRoute)
end
imgui.TextUnformatted(FlightplanWindowSchedule)
imgui.TextUnformatted(FlightplanWindowAltitudeAndTemp)
imgui.TextUnformatted(FlightplanWindowFuel)
imgui.TextUnformatted(FlightplanWindowWeights)
imgui.TextUnformatted(FlightplanWindowTrack)
imgui.TextUnformatted(FlightplanWindowMetars)
end
end
function destroyVatsimbriefHelperFlightplanWindow()
if FlightplanWindow.WindowHandle ~= nil then
setConfiguredFlightPlanWindowVisibility(false)
saveConfiguration()
float_wnd_destroy(FlightplanWindow.WindowHandle)
FlightplanWindow.WindowHandle = nil
trackWindowOpen("flight-plan", false)
end
end
function createVatsimbriefHelperFlightplanWindow()
LazyInitialization:tryVatsimbriefHelperInit()
if FlightplanWindow.WindowHandle == nil then -- "Singleton window"
setConfiguredFlightPlanWindowVisibility(true)
saveConfiguration()
refreshFlightplanNow()
local scaling = getConfiguredFlightPlanFontScaleSettingDefault1()
FlightplanWindow.WindowHandle = float_wnd_create(655 * scaling, 210 * scaling, 1, true)
updateFlightPlanWindowTitle()
float_wnd_set_imgui_builder(FlightplanWindow.WindowHandle, "buildVatsimbriefHelperFlightplanWindowCanvas")
float_wnd_set_onclose(FlightplanWindow.WindowHandle, "destroyVatsimbriefHelperFlightplanWindow")
trackWindowOpen("flight-plan", true)
end
end
function showVatsimbriefHelperFlightplanWindow(value)
if value and FlightplanWindow.WindowHandle == nil then
createVatsimbriefHelperFlightplanWindow()
elseif not value and FlightplanWindow.WindowHandle ~= nil then
destroyVatsimbriefHelperFlightplanWindow()
end
end
function toggleFlightPlanWindow(value)
showVatsimbriefHelperFlightplanWindow(FlightplanWindow.WindowHandle == nil)
end
local function initiallyShowFlightPlanWindow()
return getConfiguredFlightPlanWindowVisibility(true)
end
add_macro(
"Vatsimbrief Helper Flight Plan",
"createVatsimbriefHelperFlightplanWindow()",
"destroyVatsimbriefHelperFlightplanWindow()",
windowVisibilityToInitialMacroState("Flight Plan", initiallyShowFlightPlanWindow())
)
--
-- Helper for inline ATC buttons
--
local SelectedAtcFrequenciesChangedTimestamp = nil
AtcStringInlineButtonBlob = require("vatsimbrief-helper.components.atc_inline_button_blob")
function onVHFHelperFrequencyChanged()
SelectedAtcFrequenciesChangedTimestamp = os.clock()
end
local radioHelperOutdatedMessageShownAlready = false
TRACK_ISSUE(
"Tech Debt",
"Unsupported VR Radio Helper interface version: Make user aware (not only in Log.txt) of VR Radio Helper / Vatsimbrief Helper not being up-to-date."
)
local function isRadioHelperPanelActive()
if (VHFHelperPublicInterface ~= nil) then
if (VHFHelperPublicInterface.getInterfaceVersion() == 1 or VHFHelperPublicInterface.getInterfaceVersion() == 2) then
return true
else
if (not radioHelperOutdatedMessageShownAlready) then
logMsg(
("VR Radio Helper is installed, but uses an unsupported interface version=%d"):format(
tostring(VHFHelperPublicInterface.getInterfaceVersion())
)
)
radioHelperOutdatedMessageShownAlready = true
end
end
end
return false
end
--
-- ATC UI handling
--
local CHAR_WIDTH_PIXELS = 8
local LINE_HEIGHT_PIXELS = 18
local AtcWindow = {
WindowHandle = nil,
WidthInCharacters = 67,
FontScale = getConfiguredAtcFontScaleSettingDefault1(),
Stations = nil,
StationsStatus = "",
AtcsString = "",
StationsSelection = nil,
LastSelectedAtcFrequenciesChangedTimestamp = nil,
AtcWindowLastRenderedFlightplanId = nil,
LastRadioHelperInstalledState = nil,
ReloadButton = nil
}
local AtcWindowLastAtcIdentifiersUpdatedTimestamp = nil
local AtcWindowHasRenderedContent = false
local Route = ""
local RouteSeparatorLine = ""
local AtcWindowLastRenderedSimbriefFlightplanFetchStatus = CurrentSimbriefFlightplanFetchStatus
local AtcWindowFlightplanDownloadStatus = ""
local AtcWindowFlightplanDownloadStatusColor = 0
local AtcWindowLastRenderedVatsimDataFetchStatus = CurrentVatsimDataFlightplanFetchStatus
local AtcWindowVatsimDataDownloadStatus = ""
local AtcWindowVatsimDataDownloadStatusColor = 0
local showVatsimDataIsDownloading = false
local showVatsimDataIsDisabled = false
function updateAtcWindowTitle()
if AtcWindow.WindowHandle ~= nil then
local title = ("Vatsimbrief Helper ATC (%s)"):format(os.date("!%H%MUTC")) -- '!' means "give me ZULU"
if Globals.stringIsNotEmpty(FlightplanCallsign) then -- TODO: No, condition is, FlightPlanId is not empty, like in updateFlightplanWindowTitle()
title = title .. " for " .. FlightplanCallsign
end
float_wnd_set_title(AtcWindow.WindowHandle, title)
end
end
do_sometimes("updateAtcWindowTitle()") -- Update time in title
local function stationToNameFrequencyArray(info)
local shortId
-- Try to remove airport icao from ID
local underscore = info.id:find("_")
if underscore ~= nil then
shortId = info.id:sub(underscore + 1)
else
shortId = info.id
end
-- Remove leading '_', e.g. _TWR
while shortId:find("_") == 1 do
shortId = shortId:sub(2)
end
-- Remove trailing zeros from frequency
local strippedFrequency = info.frequency
if stringEndsWith(strippedFrequency, "000") then
strippedFrequency = stringStripTrailingCharacters(strippedFrequency, 3)
elseif stringEndsWith(strippedFrequency, "00") then
strippedFrequency = stringStripTrailingCharacters(strippedFrequency, 2)
elseif stringEndsWith(strippedFrequency, "0") then
strippedFrequency = stringStripTrailingCharacters(strippedFrequency, 1)
end
return {shortId, strippedFrequency}
end
local function assembleAirportStations(airportIcao, airportIata)
local atis = {}
local del = {}
local gnd = {}
local twr = {}
local dep = {}
local app = {}
local other = {}
local icaoPrefix = airportIcao .. "_"
local iataPrefix = airportIata .. "_"
for _, v in pairs(VatsimData.container.MapAtcIdentifiersToAtcInfo) do
if v.id:find(icaoPrefix) == 1 or v.id:find(iataPrefix) == 1 then
if stringEndsWith(v.id, "_ATIS") then
table.insert(atis, stationToNameFrequencyArray(v))
elseif stringEndsWith(v.id, "_DEL") then
table.insert(del, stationToNameFrequencyArray(v))
elseif stringEndsWith(v.id, "_GND") then
table.insert(gnd, stationToNameFrequencyArray(v))
elseif stringEndsWith(v.id, "_TWR") then
table.insert(twr, stationToNameFrequencyArray(v))
elseif stringEndsWith(v.id, "_DEP") then
table.insert(dep, stationToNameFrequencyArray(v))
elseif stringEndsWith(v.id, "_APP") then
table.insert(app, stationToNameFrequencyArray(v))
else
table.insert(other, stationToNameFrequencyArray(v))
end
end
end
local collection = {}
for _, v in pairs(atis) do
table.insert(collection, v)
end
for _, v in pairs(del) do
table.insert(collection, v)
end
for _, v in pairs(gnd) do
table.insert(collection, v)
end
for _, v in pairs(twr) do
table.insert(collection, v)
end
for _, v in pairs(dep) do
table.insert(collection, v)
end
for _, v in pairs(app) do
table.insert(collection, v)
end
for _, v in pairs(other) do
table.insert(collection, v)
end
return collection
end
function buildVatsimbriefHelperAtcWindowCanvas()
-- Invent a caching mechanism to prevent rendering the strings each frame
local flightplanChanged = AtcWindow.AtcWindowLastRenderedFlightplanId ~= FlightplanId
local atcIdentifiersUpdated =
AtcWindowLastAtcIdentifiersUpdatedTimestamp ~= VatsimData.container.AtcIdentifiersUpdatedTimestamp
local flightplanFetchStatusChanged =
FlightplanWindowLastRenderedSimbriefFlightplanFetchStatus ~= CurrentSimbriefFlightplanFetchStatus
local vatsimDataFetchStatusChanged =
AtcWindowLastRenderedVatsimDataFetchStatus ~= VatsimData.container:getCurrentFetchStatus()
local selectedAtcFrequenciesChanged =
LastSelectedAtcFrequenciesChangedTimestamp == nil or
SelectedAtcFrequenciesChangedTimestamp ~= LastSelectedAtcFrequenciesChangedTimestamp
local radioHelperInstalledStateChanged = LastRadioHelperInstalledState ~= isRadioHelperPanelActive()
local renderContent =
flightplanChanged or atcIdentifiersUpdated or flightplanFetchStatusChanged or vatsimDataFetchStatusChanged or
not AtcWindowHasRenderedContent or
selectedAtcFrequenciesChanged or
radioHelperInstalledStateChanged
if renderContent then
-- Render download status of flightplan
local statusType = CurrentSimbriefFlightplanFetchStatus.level
if
statusType == SimbriefFlightplanFetchStatusLevel.USER_RELATED or
statusType == SimbriefFlightplanFetchStatusLevel.SYSTEM_RELATED
then
AtcWindowFlightplanDownloadStatus, AtcWindowFlightplanDownloadStatusColor =
getSimbriefFlightplanFetchStatusMessageAndColor()
else
AtcWindowFlightplanDownloadStatus = ""
AtcWindowFlightplanDownloadStatusColor = colorNormal
end
-- Render download status of VATSIM data
statusType = VatsimData.container:getCurrentFetchStatusLevel()
if statusType == VatsimDataContainer.FetchStatusLevel.SYSTEM_RELATED then
AtcWindowVatsimDataDownloadStatus, level = VatsimData.container:getVatsimDataFetchStatusMessageAndLevel()
if level == VatsimDataContainer.FetchStatusLevel.INFO then
AtcWindowVatsimDataDownloadStatusColor = colorNormal
elseif level == VatsimDataContainer.FetchStatusLevel.SYSTEM_RELATED then
AtcWindowVatsimDataDownloadStatusColor = colorWarn
elseif level == VatsimDataContainer.FetchStatusLevel.USER_RELATED then
AtcWindowVatsimDataDownloadStatusColor = colorA320Blue
else
AtcWindowVatsimDataDownloadStatusColor = colorNormal
end
AtcWindow.ReloadButton = InlineButtonBlob:new()
AtcWindow.ReloadButton:addDefaultButton("Retry")
AtcWindow.ReloadButton:setDefaultButtonCallbackFunction(refreshVatsimDataNow)
else
AtcWindowVatsimDataDownloadStatus = ""
AtcWindowVatsimDataDownloadStatusColor = colorNormal
end
-- Render route
if Globals.stringIsNotEmpty(FlightplanId) then
-- If there's a flightplan, render it
if Globals.stringIsNotEmpty(FlightplanAltIcao) then
-- Note: Once, the alt name was shown as well, but it takes too much space even though the value is pretty low
-- Consequently, the alt name was removed in 11/2020
-- local altName = .. " / " .. FlightplanAltName
local altName = ""
Route =
FlightplanOriginIcao ..
" - " ..
FlightplanDestIcao ..
" / " ..
FlightplanAltIcao .. " (" .. FlightplanOriginName .. " to " .. FlightplanDestName .. altName .. ")"
else
Route =
FlightplanOriginIcao ..
" - " .. FlightplanDestIcao .. " (" .. FlightplanOriginName .. " to " .. FlightplanDestName .. ")"
end
else
-- It's more beautiful to show the "downloading" status in the title where the route appears in a few seconds
if CurrentSimbriefFlightplanFetchStatus == SimbriefFlightplanFetchStatus.DOWNLOADING then
Route = "Downloading flight plan ..."
else
Route = "" -- Clear previous state, e.g. don't show "downloading" when there's already an error
end
end
RouteSeparatorLine = string.rep("-", #Route)
-- Try to render ATC data
if numberIsNilOrZero(VatsimData.container.AtcIdentifiersUpdatedTimestamp) then -- We have NO ATC data (yet?)
AtcWindow.StationsStatus = ""
AtcWindow.Stations = nil
AtcWindow.AtcsString = ""
AtcWindow.StationsSelection = nil
-- Only show "downloading" message when there is no VATSIM data yet and no other download status is rendered
showVatsimDataIsDownloading =
VatsimData.container:getCurrentFetchStatus() == VatsimDataContainer.FetchStatus.DOWNLOADING
showVatsimDataIsDisabled =
VatsimData.container:getCurrentFetchStatus() == VatsimDataContainer.FetchStatus.NO_DOWNLOAD_ATTEMPTED and
getConfiguredAutoRefreshAtcSettingDefaultTrue() ~= true
else
showVatsimDataIsDownloading = false
showVatsimDataIsDisabled = false
if Globals.stringIsEmpty(FlightplanId) then
AtcWindow.StationsStatus =
("Got %d ATC stations. Waiting for flight plan ..."):format(#VatsimData.container.MapAtcIdentifiersToAtcInfo)
AtcWindow.Stations = nil
AtcWindow.AtcsString = ""
AtcWindow.StationsSelection = nil
else
if #VatsimData.container.MapAtcIdentifiersToAtcInfo == 0 then
AtcWindow.StationsStatus = "No ATCs found. This will probably be a technical issue."
AtcWindow.Stations = nil
AtcWindow.AtcsString = ""
AtcWindow.StationsSelection = nil
else
-- Build interactive version with clickable frequencies if Radio Helper is installed
AtcWindow.StationsStatus = "" -- Show stations instead of explicit status ...
AtcWindow.Stations = {} -- To be filled ...
AtcWindow.AtcsString = "" -- To be filled ...
AtcWindow.StationsSelection = nil -- To be filled ...
-- Assemble list of stations and respective frequencies
local consideredAirports = {
{FlightplanOriginIcao, FlightplanOriginIata},
{FlightplanDestIcao, FlightplanDestIata}
}
if Globals.stringIsNotEmpty(FlightplanAltIcao) then
table.insert(consideredAirports, {FlightplanAltIcao, FlightplanAltIata})
end
for i = 1, #consideredAirports do
local consideredAirport = consideredAirports[i]
local consideredAirportIcao = consideredAirport[1]
local consideredAirportIata = consideredAirport[2]
local stations = assembleAirportStations(consideredAirportIcao, consideredAirportIata)
local stationsEntryOfAirport = {consideredAirportIcao, stations}
table.insert(AtcWindow.Stations, stationsEntryOfAirport)
end
-- Build interactive version if Radio Helper is installed
AtcWindow.StationsSelection = AtcStringInlineButtonBlob:new()
AtcWindow.StationsSelection:build(AtcWindow.Stations, isRadioHelperPanelActive(), AtcWindow.WidthInCharacters)
end
end
end
-- Update ATC window title now
updateAtcWindowTitle()
AtcWindowLastRenderedSimbriefFlightplanFetchStatus = CurrentSimbriefFlightplanFetchStatus
AtcWindowLastRenderedVatsimDataFetchStatus = VatsimData.container:getCurrentFetchStatus()
AtcWindow.AtcWindowLastRenderedFlightplanId = FlightplanId
AtcWindowLastAtcIdentifiersUpdatedTimestamp = VatsimData.container.AtcIdentifiersUpdatedTimestamp
LastSelectedAtcFrequenciesChangedTimestamp = SelectedAtcFrequenciesChangedTimestamp
LastRadioHelperInstalledState = isRadioHelperPanelActive()
AtcWindowHasRenderedContent = true
end
-- Paint
imgui.SetWindowFontScale(AtcWindow.FontScale)
if Globals.stringIsNotEmpty(AtcWindowFlightplanDownloadStatus) then
imgui.PushStyleColor(imgui.constant.Col.Text, AtcWindowFlightplanDownloadStatusColor)
imgui.TextUnformatted(AtcWindowFlightplanDownloadStatus)
imgui.PopStyleColor()
elseif Globals.stringIsNotEmpty(AtcWindowVatsimDataDownloadStatus) then
-- Why elseif? For user comfort, we don't show Flightplan AND VATSIM errors at the same time.
-- If the network is broken, this looks ugly.
-- The flightplan error is much more generic and contains more infromation, e.g. that
-- a user name is missing. Therefore, give it the preference.
imgui.PushStyleColor(imgui.constant.Col.Text, AtcWindowVatsimDataDownloadStatusColor)
imgui.TextUnformatted(AtcWindowVatsimDataDownloadStatus)
imgui.PopStyleColor()
imgui.SameLine()
imgui.TextUnformatted(" - ")
imgui.SameLine()
AtcWindow.ReloadButton:renderToCanvas()
end
if Globals.stringIsNotEmpty(Route) then
imgui.PushStyleColor(imgui.constant.Col.Text, colorA320Blue)
imgui.TextUnformatted(Route)
imgui.TextUnformatted(RouteSeparatorLine)
imgui.PopStyleColor()
end
if getConfiguredAutoRefreshAtcSettingDefaultTrue() then -- Only show overaged data when auto refresh is on
if VatsimData.container.AtcIdentifiersUpdatedTimestamp ~= nil then -- Show information if data is old
local ageOfAtcDataMinutes =
math.floor((os.clock() - VatsimData.container.AtcIdentifiersUpdatedTimestamp) * (1.0 / 60.0))
if ageOfAtcDataMinutes >= 3 then
imgui.PushStyleColor(imgui.constant.Col.Text, colorWarn)
-- Note: Render text here as the minutes update every minute and not "on event" when a re-rendering occurs
imgui.TextUnformatted(("No new VATSIM data for %d minutes!"):format(ageOfAtcDataMinutes))
imgui.PopStyleColor()
end
end
end
if showVatsimDataIsDownloading then
imgui.TextUnformatted("Downloading VATSIM data ...")
end
if Globals.stringIsNotEmpty(AtcWindow.StationsStatus) then
imgui.TextUnformatted(AtcWindow.StationsStatus)
end
if AtcWindow.StationsSelection ~= nil then
AtcWindow.StationsSelection:renderToCanvas()
end
end
function destroyVatsimbriefHelperAtcWindow()
if AtcWindow.WindowHandle ~= nil then
setConfiguredAtcWindowVisibility(false)
saveConfiguration()
float_wnd_destroy(AtcWindow.WindowHandle)
AtcWindow.WindowHandle = nil
trackWindowOpen("atc", false)
end
end
function createVatsimbriefHelperAtcWindow()
LazyInitialization:tryVatsimbriefHelperInit()
if AtcWindow.WindowHandle == nil then -- "Singleton window"
setConfiguredAtcWindowVisibility(true)
refreshVatsimDataNow()
saveConfiguration()
local scaling = getConfiguredAtcFontScaleSettingDefault1()
local windowWidth = CHAR_WIDTH_PIXELS * AtcWindow.WidthInCharacters * scaling + 10
local windowHeight = LINE_HEIGHT_PIXELS * 5 * scaling + 5
AtcWindow.WindowHandle = float_wnd_create(windowWidth, windowHeight, 1, true)
updateAtcWindowTitle()
float_wnd_set_imgui_builder(AtcWindow.WindowHandle, "buildVatsimbriefHelperAtcWindowCanvas")
float_wnd_set_onclose(AtcWindow.WindowHandle, "destroyVatsimbriefHelperAtcWindow")
trackWindowOpen("atc", true)
end
end
function showVatsimbriefHelperAtcWindow(value)
if value and AtcWindow.WindowHandle == nil then
createVatsimbriefHelperAtcWindow()
elseif not value and AtcWindow.WindowHandle ~= nil then
destroyVatsimbriefHelperAtcWindow()
end
end
function toggleAtcWindow(value)
showVatsimbriefHelperAtcWindow(AtcWindow.WindowHandle == nil)
end
local function initiallyShowAtcWindow()
return getConfiguredAtcWindowVisibilityDefaultTrue()
end
add_macro(
"Vatsimbrief Helper ATC",
"createVatsimbriefHelperAtcWindow()",
"destroyVatsimbriefHelperAtcWindow()",
windowVisibilityToInitialMacroState("ATC", initiallyShowAtcWindow())
)
--
-- Control UI handling
--
local inputUserName = ""
local MENU_ITEM_OVERVIEW = 0
local MENU_ITEM_FLIGHTPLAN_DOWNLOAD = 1
local menuItem = MENU_ITEM_OVERVIEW
local MainMenuOptions = {
["General"] = MENU_ITEM_OVERVIEW,
["Flight Plan Download"] = MENU_ITEM_FLIGHTPLAN_DOWNLOAD
}
local ControlWindow = {
mapFlightPlanDownloadTypeToDirTmp = {},
mapFlightPlanDownloadTypeToFileNameTmp = {}
}
function buildVatsimbriefHelperControlWindowCanvas()
imgui.SetWindowFontScale(1.5)
-- Main menu
local currentMenuItem = menuItem -- We get into race conditions when not copying before changing
local i = 1
for label, id in pairs(MainMenuOptions) do
if i > 1 then
imgui.SameLine()
end
local isCurrentMenuItem = id == currentMenuItem
if isCurrentMenuItem then
imgui.PushStyleColor(imgui.constant.Col.Button, 0xFFFA9642)
end
imgui.PushID(i)
if imgui.Button(label) then
menuItem = id
end
imgui.PopID()
if isCurrentMenuItem then
imgui.PopStyleColor()
end
i = i + 1
end
imgui.Separator()
-- Simbrief user name is so important for us that we want to show it very prominently in case user attention is required
local userNameInvalid =
CurrentSimbriefFlightplanFetchStatus == SimbriefFlightplanFetchStatus.INVALID_USER_NAME or
CurrentSimbriefFlightplanFetchStatus == SimbriefFlightplanFetchStatus.NO_SIMBRIEF_USER_ID_ENTERED
if menuItem == MENU_ITEM_OVERVIEW or userNameInvalid then -- Always show setting when there's something wrong with the user name
if userNameInvalid then
imgui.PushStyleColor(imgui.constant.Col.Text, colorErr)
end
local changeFlag, newUserName = imgui.InputText("Simbrief Username", inputUserName, 255)
if userNameInvalid then
imgui.PopStyleColor()
end
if changeFlag then
inputUserName = newUserName
end
imgui.SameLine()
if imgui.Button("Set") then
setConfiguredUserName(inputUserName)
saveConfiguration()
clearFlightplan()
refreshFlightplanNow()
inputUserName = "" -- Clear input line to keep user anonymous (in case he's streaming)
end
end
-- Content canvas
if menuItem == MENU_ITEM_OVERVIEW then
imgui.TextUnformatted("") -- Linebreak
imgui.TextUnformatted("Flight Plan")
imgui.TextUnformatted(" ")
imgui.SameLine()
if imgui.Button(" Reload Flight Plan Now ") then
clearFlightplan()
refreshFlightplanNow()
end
--
--[[ Remove auto reloading for flight plans. Might cause stuttering and should be done manually anyway.
IRL, the pilot turns the page as well.
imgui.SameLine()
local changed, newVal = imgui.Checkbox("Auto Reload", getConfiguredAutoRefreshFlightPlanSettingDefaultFalse())
if changed then
setConfiguredAutoRefreshFlightPlanSetting(newVal)
saveConfiguration()
end ]] imgui.TextUnformatted(
" "
)
imgui.SameLine()
local changed3, newVal3 =
imgui.SliderFloat(
"Flight Plan Font Scale",
getConfiguredFlightPlanFontScaleSettingDefault1(),
0.5,
3,
"Value: %.2f"
)
if changed3 then
setConfiguredFlightPlanFontScaleSetting(newVal3)
flagConfigurationDirty() -- Don't save immediately to reduce disk load
FlightplanWindow.FontScale = newVal3
end
imgui.TextUnformatted("") -- Linebreak
imgui.TextUnformatted("ATC")
imgui.TextUnformatted(" ")
imgui.SameLine()
if imgui.Button(" Refresh ATC Data Now ") then
TRACK_ISSUE("Tech Debt", "No test is covering this part. Stubs for copas/HTTP are still mising.")
VatsimData.container:clear()
refreshVatsimDataNow()
end
imgui.SameLine()
imgui.TextUnformatted(" - ")
imgui.SameLine()
local changed2, newVal2 = imgui.Checkbox("Enable Auto Refresh", getConfiguredAutoRefreshAtcSettingDefaultTrue())
if changed2 then
setConfiguredAutoRefreshAtcSetting(newVal2)
saveConfiguration()
end
imgui.TextUnformatted(" ")
imgui.SameLine()
local changed4, newVal4 =
imgui.SliderFloat("ATC Data Font Scale", getConfiguredAtcFontScaleSettingDefault1(), 0.5, 3, "Value: %.2f")
if changed4 then
setConfiguredAtcFontScaleSetting(newVal4)
flagConfigurationDirty() -- Don't save immediately to reduce disk load
AtcWindow.FontScale = newVal4
end
elseif menuItem == MENU_ITEM_FLIGHTPLAN_DOWNLOAD then
if FlightplanId == nil then
imgui.TextUnformatted("Waiting for a flight plan ...")
else
local padding = " "
imgui.TextUnformatted("Please mark the flight plan types that you want to be downloaded.")
imgui.TextUnformatted(
"If no path is entered, the default folder will be used:\n" .. padding .. FlightPlanDownload.Directory
)
imgui.TextUnformatted(padding)
imgui.SameLine()
local changed, newVal =
imgui.Checkbox(
"Auto clean up stale flight plans from default folder",
getConfiguredDeleteOldFlightPlansSetting()
)
if changed then
setConfiguredDeleteOldFlightPlansSetting(newVal)
saveConfiguration()
-- deleteDownloadedFlightPlansIfConfigured() -- Better not that fast, without any confirmation
end
imgui.TextUnformatted("Default file name: <YYYYMMDD_HHMMSS>_<ORIG_ICAO>-<DEST_ICAO>.<EXTENSION>")
imgui.TextUnformatted("File name format: %o - Source ICAO, %d - Dest ICAO, %a - Date, %t - Time")
imgui.PushStyleColor(imgui.constant.Col.Text, colorWarn)
imgui.TextUnformatted("Existing files will be overwritten!")
imgui.PopStyleColor()
imgui.TextUnformatted("") -- Blank line
local fileTypes = getFlightplanFileTypesArray()
local maxFileTypesLength = 0
for i = 1, #fileTypes do
if string.len(fileTypes[i]) > maxFileTypesLength then
maxFileTypesLength = string.len(fileTypes[i])
end
end
for i = 1, #fileTypes do
local statusOnOff = isFlightplanFileDownloadEnabled(fileTypes[i])
local nameWithPadding = string.format("%-" .. maxFileTypesLength .. "s", fileTypes[i])
imgui.PushID(5 * i)
local changed, enabled = imgui.Checkbox(nameWithPadding, statusOnOff)
imgui.PopID()
if changed then
setFlightplanFileDownloadEnabled(fileTypes[i], enabled)
saveFlightPlanFilesForDownload()
if enabled then
downloadFlightPlanAgain(fileTypes[i])
end
end
if statusOnOff == true then
--imgui.SameLine()
local padding2 = " "
imgui.TextUnformatted(padding2 .. "(Dest Folder: ")
imgui.SameLine()
imgui.PushID(5 * i + 1)
local savePath = false
if imgui.Button("Set") then
-- We don't want to save the config "on change" as it creates too much disk load again. Therefore, add this button.
-- Save that button was clicked, for later use
savePath = true
end
imgui.PopID()
imgui.SameLine()
imgui.PushID(5 * i + 2)
if ControlWindow.mapFlightPlanDownloadTypeToDirTmp[fileTypes[i]] == nil then
ControlWindow.mapFlightPlanDownloadTypeToDirTmp[fileTypes[i]] = getFlightPlanDownloadDirectory(fileTypes[i])
end
local pathChanged, path =
imgui.InputText(
"",
defaultIfBlank(ControlWindow.mapFlightPlanDownloadTypeToDirTmp[fileTypes[i]], Globals.emptyString),
255
)
if pathChanged then
ControlWindow.mapFlightPlanDownloadTypeToDirTmp[fileTypes[i]] = path
end
imgui.PopID()
imgui.SameLine()
imgui.TextUnformatted(")")
if savePath then
local configuredDir = defaultIfBlank(ControlWindow.mapFlightPlanDownloadTypeToDirTmp[fileTypes[i]], nil)
setFlightPlanDownloadDirectory(fileTypes[i], configuredDir)
saveFlightPlanFilesForDownload()
downloadFlightPlanAgain(fileTypes[i])
end
imgui.TextUnformatted(padding2 .. "(File Name: ")
imgui.SameLine()
imgui.PushID(5 * i + 3)
local saveFileName = false
if imgui.Button("Set") then
-- We don't want to save the config "on change" as it creates too much disk load again. Therefore, add this button.
-- Save that button was clicked, for later use
saveFileName = true
end
imgui.PopID()
imgui.SameLine()
imgui.PushID(5 * i + 4)
if ControlWindow.mapFlightPlanDownloadTypeToFileNameTmp[fileTypes[i]] == nil then
ControlWindow.mapFlightPlanDownloadTypeToFileNameTmp[fileTypes[i]] =
getFlightPlanDownloadFileName(fileTypes[i])
end
local fileNameChanged, fileName =
imgui.InputText(
"",
defaultIfBlank(ControlWindow.mapFlightPlanDownloadTypeToFileNameTmp[fileTypes[i]], Globals.emptyString),
255
)
if fileNameChanged then
ControlWindow.mapFlightPlanDownloadTypeToFileNameTmp[fileTypes[i]] = fileName
end
imgui.PopID()
imgui.SameLine()
imgui.TextUnformatted(")")
if saveFileName then
local configuredFileName =
defaultIfBlank(ControlWindow.mapFlightPlanDownloadTypeToFileNameTmp[fileTypes[i]], nil)
setFlightPlanDownloadFileName(fileTypes[i], configuredFileName)
saveFlightPlanFilesForDownload()
downloadFlightPlanAgain(fileTypes[i])
end
end
end
end
end
end
local vatsimbriefHelperControlWindow = nil
function destroyVatsimbriefHelperControlWindow()
if vatsimbriefHelperControlWindow ~= nil then
float_wnd_destroy(vatsimbriefHelperControlWindow)
vatsimbriefHelperControlWindow = nil
trackWindowOpen("control", false)
end
end
function createVatsimbriefHelperControlWindow()
LazyInitialization:tryVatsimbriefHelperInit()
if vatsimbriefHelperControlWindow == nil then -- "Singleton window"
vatsimbriefHelperControlWindow = float_wnd_create(900, 300, 1, true)
float_wnd_set_title(vatsimbriefHelperControlWindow, "Vatsimbrief Helper Control")
float_wnd_set_imgui_builder(vatsimbriefHelperControlWindow, "buildVatsimbriefHelperControlWindowCanvas")
float_wnd_set_onclose(vatsimbriefHelperControlWindow, "destroyVatsimbriefHelperControlWindow")
trackWindowOpen("control", true)
end
end
local function showVatsimbriefHelperControlWindow(value)
if value and vatsimbriefHelperControlWindow == nil then
createVatsimbriefHelperControlWindow()
elseif not value and vatsimbriefHelperControlWindow ~= nil then
destroyVatsimbriefHelperControlWindow()
end
end
function toggleControlWindow(value)
showVatsimbriefHelperControlWindow(vatsimbriefHelperControlWindow == nil)
end
local function initiallyShowControlWindow()
return Globals.stringIsEmpty(getConfiguredSimbriefUserName())
end
add_macro(
"Vatsimbrief Helper Control",
"createVatsimbriefHelperControlWindow()",
"destroyVatsimbriefHelperControlWindow()",
windowVisibilityToInitialMacroState("Control", initiallyShowControlWindow())
)
--- Command bindings for opening / closing windows
function toggleAllVatsimbriefWindows()
if atLeastOneWindowIsOpen() then
showVatsimbriefHelperControlWindow(false)
showVatsimbriefHelperFlightplanWindow(false)
showVatsimbriefHelperAtcWindow(false)
else
showVatsimbriefHelperControlWindow(true)
showVatsimbriefHelperFlightplanWindow(true)
showVatsimbriefHelperAtcWindow(initiallyShowAtcWindow()) -- Only show when necessary
end
end
create_command(
"FlyWithLua/Vatsimbrief Helper/ToggleWindows",
"Toggle All Windows",
"toggleAllVatsimbriefWindows()",
"",
""
)
create_command(
"FlyWithLua/Vatsimbrief Helper/ToggleFlightPlanWindow",
"Toggle Flight Plan",
"toggleFlightPlanWindow()",
"",
""
)
create_command("FlyWithLua/Vatsimbrief Helper/ToggleAtcWindow", "Toggle ATC Window", "toggleAtcWindow()", "", "")
create_command(
"FlyWithLua/Vatsimbrief Helper/ToggleControlWindow",
"Toggle Control Window",
"toggleControlWindow()",
"",
""
)
vatsimbriefHelperPackageExport = {}
vatsimbriefHelperPackageExport.test = {}
vatsimbriefHelperPackageExport.test.LazyInitialization = LazyInitialization
vatsimbriefHelperPackageExport.test.Configuration = Configuration
vatsimbriefHelperPackageExport.test.VatsimData = VatsimData
vatsimbriefHelperPackageExport.test.computeDistanceOnEarth = Globals.computeDistanceOnEarth
return
|
return {'zadel','zadelboog','zadeldak','zadeldaktoren','zadeldek','zadelen','zadelgewricht','zadelknop','zadelkussen','zadelmaker','zadelmakerij','zadelpaard','zadelpijn','zadelpunt','zadelriem','zadelrob','zadelrug','zadeltas','zadeltje','zadelvast','zaden','zadelpen','zadenlijst','zadelboom','zadelhoogte','zadelkamer','zadenbank','zadelhoff','zadelbogen','zadeldaken','zadelde','zadeldekken','zadelden','zadelgewrichten','zadelkussens','zadelmakerijen','zadelmakers','zadelpaarden','zadelpunten','zadelriemen','zadels','zadelt','zadeltjes','zadelknoppen','zadelrobben','zadeltassen','zadelvaste','zadeltasje','zadelpennen','zadeldakje','zadeldakjes'} |
Config = {}
Config.DrawDistance = 100.0
Config.MaxInService = -1
Config.EnablePlayerManagement = true
Config.EnableSocietyOwnedVehicles = false
Config.EnableLicenses = false
Config.EnableESXIdentity = false
Config.Locale = 'fr'
Config.Cig = {
'malbora',
'gitanes'
}
Config.CigResellChances = {
malbora = 45,
gitanes = 55,
}
Config.CigResellQuantity= {
malbora = {min = 5, max = 10},
gitanes = {min = 5, max = 10},
}
Config.CigPrices = {
malbora = {min = 35, max = 20},
gitanes = {min = 25, max = 25},
}
Config.CigPricesHigh = {
malbora = {min = 65, max = 30},
gitanes = {min = 55, max = 35},
}
Config.Time = {
malbora = 5 * 60,
gitanes = 5 * 60,
}
Config.Blip = {
Pos = { x = 2340.508789, y = 3126.071777, z = 47.208740 },
Sprite = 79,
Display = 4,
Scale = 0.9,
Colour = 75,
}
Config.Zones = {
TabacActions = {
Pos = { x = 2340.508789, y = 3126.071777, z = 47.208740 },
Size = { x = 1.6, y = 1.6, z = 1.0 },
Color = {r = 136, g = 243, b = 216},
Type = 23,
},
Garage = {
Pos = { x = 2242.599121, y = 4781.3766, z = 39.110347 },
Size = { x = 1.6, y = 1.6, z = 1.0 },
Color = {r = 136, g = 243, b = 216},
Type = 23, },
Craft = {
Pos = { x = 2305.8728, y = 4748.169433, z = 36.053768 },
Size = { x = 1.6, y = 1.6, z = 1.0 },
Color = {r = 136, g = 243, b = 216},
Type = 27,
},
Craft2 = {
Pos = { x = 2351.6413, y = 3142.911, z = 47.2087 },
Size = { x = 1.6, y = 1.6, z = 1.0 },
Color = {r = 136, g = 243, b = 216},
Type = 27,
},
VehicleSpawnPoint = {
Pos = { x = 2348.360107, y = 3134.253173, z = 47.208740 },
Size = { x = 1.6, y = 1.6, z = 1.0 },
Type = -1,
},
VehicleDeleter = {
Pos = { x = 2336.3933, y = 3142.8327, z = 47.1911 },
Size = { x = 1.6, y = 1.6, z = 1.0 },
Color = { r = 204, g = 204, b = 0 },
Type = 1,
},
SellFarm = {
Pos = {x = 244.86083, y = 369.8005, z =105.7381},
Size = { x = 1.6, y = 1.6, z = 1.0 },
Color = {r = 136, g = 243, b = 216},
Name = "Vente des produits",
Type = 1
},
}
|
depends_on("A")
load("B")
depends_on("C")
|
#@ SimpleGraphic
-- Path of Building
--
-- Module: Launch Install
-- Installation bootstrap
--
local basicFiles = { "UpdateCheck.lua", "UpdateApply.lua", "Launch.lua" }
local xml = require("xml")
local curl = require("lcurl.safe")
ConClear()
ConPrintf("Preparing to complete installation...\n")
local localBranch, localSource
local localManXML = xml.LoadXMLFile("manifest.xml")
if localManXML and localManXML[1].elem == "PoBVersion" then
for _, node in ipairs(localManXML[1]) do
if type(node) == "table" then
if node.elem == "Version" then
localBranch = node.attrib.branch
elseif node.elem == "Source" then
if node.attrib.part == "program" then
localSource = node.attrib.url
end
end
end
end
end
if not localBranch or not localSource then
Exit("Install failed. (Missing or invalid manifest)")
return
end
localSource = localSource:gsub("{branch}", localBranch)
for _, name in ipairs(basicFiles) do
local text = ""
local easy = curl.easy()
easy:setopt_url(localSource..name)
easy:setopt_writefunction(function(data)
text = text..data
return true
end)
easy:perform()
local size = easy:getinfo(curl.INFO_SIZE_DOWNLOAD)
easy:close()
if size == 0 then
Exit("Install failed. (Couldn't download program files)")
return
end
local outFile = io.open(name, "wb")
outFile:write(text)
outFile:close()
end
Restart() |
local moon = require("moon")
local msg_handler = require("msg_handler")
local M = setmetatable({}, msg_handler)
--注册要监听的消息
function M.init()
msg_handler.init()
M.register(msgid.LOGIN_REQUEST, M.login_request)
M.register(msgid.BATTLE_BEGIN_REQUEST, M.battle_begin_request)
end
--重写ondispatch方法
function M.ondispatch(sessionid, id, msg )
local def = M.get_def(id)
if def ~= nil and def.func ~= nil then
local u = usermgr:getuser_by_sessionid(sessionid)
def.func(sessionid, u, msg)
else
print("logic_msg.ondispatch->can not find def or func:" ..id)
end
end
function M.onaccept( sessionid )
end
function M.onclose( sessionid )
usermgr:removeuser_by_sessionid(sessionid)
end
function M.onerror( sessionid )
usermgr:removeuser_by_sessionid(sessionid)
end
function M.login_request(sessionid, u, msg )
-- body
print("logic_msg.login_request->user login:".. msg.name..","..msg.password)
moon.async(function()
print("logic_msg.login_request->request db login ")
local data = server.call(serverdef.DB, "LOGIN",msg)
print("logic_msg.login_request->login db result:",table.tostring(data))
if data then
--print(table.tostring(data))
if type(data.id) == "number" and data.id > 0 then
print("logic_msg.login_request->db login result:"..tostring(data.id))
local u = user.new(sessionid,data.id)
usermgr:adduser(u)
u:onlogin()
local userdata = {
id = data.id,
name = data.name
}
u:send(msgid.LOGIN_RETURN,{result = errordef.SUCCESS, userdata = userdata})
else
print("logic_msg.login_request->login db error:",data.id)
netmgr:send(sessionid,msgid.LOGIN_RETURN,{result = data.id})
end
else
print("logic_msg.login_request->can not find db service")
netmgr:send(sessionid,msgid.LOGIN_RETURN,{result = errordef.SYSTEM})
end
end)
end
function M.battle_begin_request(sessionid, u, msg )
print("logic_msg.battle_begin_request->request battle begin:",u.id)
moon.async(function()
local data ={
copyname = "copy_test",
users ={
{
userid = u.id,
camp = 1,
type = userdef.USER,
heros = {
{config = 1, count = 10},
{config = 2, count = 10},
{config = 3, count = 10},
}
},
{
userid = 1000,
camp = 2,
type = userdef.MONSTER,
heros = {
{config = 3, count = 10},
{config = 1, count = 10},
{config = 2, count = 10},
}
},
}
}
local result = errordef.SYSTEM
print("logic_msg.battle_begin_request->request game create copy")
local ret = server.call(serverdef.GAME, "CREATE_COPY", data )
print("logic_msg.battle_begin_request->request game create copy return:",ret)
if type(ret)=="table" then
result = ret.result
if result == errordef.SUCCESS then
local game_config = config.get_service("game")
if game_config and game_config.network then
print("logic_msg.battle_begin_request->return login game")
u:send(msgid.LOGIN_GAME_NOTIFY,{ip = game_config.network.ip,port = game_config.network.port})
else
result = errordef.SYSTEM
end
end
end
u:send(msgid.BATTLE_BEGIN_RETURN,{result = result})
end)
end
return M
|
require'lspconfig'
local configs = require 'lspconfig/configs'
local uv = vim.loop
local _schemas_dir = os.getenv('PWD') .. '/schemas'
local function require_all_configs()
local fin = false
-- Configs are lazy-loaded, tickle them to populate the `configs` singleton.
for _,v in ipairs(vim.fn.glob('nvim-lspconfig/lua/lspconfig/server_configurations/*.lua', 1, 1)) do
local module_name = v:gsub('.*/', ''):gsub('%.lua$', '')
configs[module_name] = require('lspconfig.server_configurations.'..module_name)
fin = true
end
if fin then
return
end
end
local exists_json
exists_json = function(server_name, path)
local handle = uv.fs_scandir(path)
if handle == nil then
return false
end
local res = false
while true do
local name, _ = uv.fs_scandir_next(handle)
if name == nil then
break
end
if vim.fn.isdirectory(path .. '/' .. name) == 1 then
res = exists_json(server_name, path .. '/' .. name)
end
local sname = string.match(name, '([^/]+)%.json$')
if sname == server_name then
res = true
end
end
return res
end
local write_readme = function(lines)
local file = io.open('schemas/README.md', "w")
file:write(table.concat(lines, '\n'))
file:close()
end
local main = function()
local lines = {}
table.insert(lines, '# Schemas')
table.insert(lines, '')
local server_names = vim.tbl_keys(configs)
table.sort(server_names)
for _, server_name in ipairs(server_names) do
local checked = (exists_json(server_name, _schemas_dir) and 'x') or ' '
table.insert(lines, string.format('- [%s] %s', checked, server_name))
end
write_readme(lines)
end
require_all_configs()
main()
|
WireToolSetup.setCategory("Input, Output")
WireToolSetup.open("friendslist", "Friends List", "gmod_wire_friendslist", nil, "Friends Lists")
if CLIENT then
language.Add("tool.wire_friendslist.name", "Friends List Tool (Wire)")
language.Add("tool.wire_friendslist.desc", "Spawns a friends list entity for use with the wire system.")
TOOL.Information = {
{
name = "left",
text = "Create/Update " .. TOOL.Name
},
{
name = "right",
text = "Copy settings"
}
}
language.Add("wire_friendslist_save_on_entity", "Save On Entity")
language.Add("wire_friendslist_save_on_entity_tooltip", "When enabled, the friends list will be saved on the entity and carried across in dupes. When disabled, the friends list will mirror any changes you make in this UI.")
language.Add("wire_friendslist_invalid_steamid", "Invalid SteamID")
language.Add("wire_friendslist_connected_players", "Currently connected players")
language.Add("wire_friendslist_not_connected", "Not Connected")
WireToolSetup.setToolMenuIcon("icon16/group.png")
end
WireToolSetup.BaseLang()
WireToolSetup.SetupMax(8)
TOOL.ClientConVar = {
model = "models/kobilica/value.mdl",
save_on_entity = 0
}
-- shared helper functions
local function netWriteValues(values)
net.WriteUInt(#values, 11)
for i = 1, #values do
net.WriteString(string.sub(values[i], 1, 32))
end
end
local function netReadValues()
local t = {}
local amount = net.ReadUInt(11)
for i = 1, amount do
t[i] = net.ReadString()
end
return t
end
local friends = {}
if SERVER then
util.AddNetworkString("wire_friendslist")
net.Receive("wire_friendslist", function(length, ply)
friends[ply] = netReadValues()
-- Update all friendslists which have save_on_entity set to false
local friendslists = ents.FindByClass("gmod_wire_friendslist")
for i = 1, #friendslists do
local ent = friendslists[i]
if ent:GetPlayer() == ply then
ent:UpdateFriendslist(friends[ply] or {})
end
end
end)
function TOOL:GetConVars()
return self:GetClientNumber("save_on_entity") ~= 0, friends[self:GetOwner()] or {}
end
hook.Add("OnEntityCreated", "wire_friendslist_created", function(ent)
if ent:GetClass() == "gmod_wire_friendslist" then
-- wait for wire to set the GetPlayer variable
timer.Simple(0, function()
if IsValid(ent) then
ent:UpdateFriendslist(friends[ent:GetPlayer()] or {})
end
end)
end
end)
-- Right click to copy
function TOOL:RightClick(trace)
if not self:CheckHitOwnClass(trace) then return false end
friends[self:GetOwner()] = trace.Entity.steamids
net.Start("wire_friendslist")
netWriteValues(trace.Entity.steamids)
net.Send(self:GetOwner())
end
else
function TOOL:RightClick(trace)
return self:CheckHitOwnClass(trace)
end
local function loadFile()
if not file.Exists("wire_friendslist.txt", "DATA") then return {} end
local str = file.Read("wire_friendslist.txt", "DATA")
local t = string.Explode(",", str)
local ret = {}
for i = 1, #t do
local str = string.Trim(t[i])
if string.match(str, "^STEAM_%d:%d:%d+$") ~= nil then
ret[#ret + 1] = str
end
end
return ret
end
local function saveFile(friends)
file.Write("wire_friendslist.txt", table.concat(friends, ","))
end
local function sendFriends(dontsave)
if #friends == 0 then return end
net.Start("wire_friendslist")
netWriteValues(friends)
net.SendToServer()
if not dontsave then
saveFile(friends)
end
end
-- Receive values for copying
local cpanel_list
net.Receive("wire_friendslist", function(length)
friends = netReadValues()
saveFile(friends)
if not IsValid(cpanel_list) then return end -- They right clicked without opening the cpanel first, just save the values
cpanel_list:Clear()
for i = 1, #friends do
local ply = player.GetBySteamID(friends[i])
local col2 = "#wire_friendslist_not_connected"
if IsValid(ply) then
col2 = ply:Nick()
end
cpanel_list:AddLine(friends[i], col2)
end
end)
local function addSteamID(steamid)
for i = 1, #friends do
if friends[i] == steamid then return false end
end
if string.match(steamid, "^STEAM_%d:%d:%d+$") == nil then
WireLib.AddNotify(LocalPlayer(), "#wire_friendslist_invalid_steamid", NOTIFY_ERROR, 8, NOTIFYSOUND_ERROR1)
return false
end
friends[#friends + 1] = steamid
sendFriends()
return true
end
local function removeSteamID(steamid)
for i = 1, #friends do
if friends[i] == steamid then
table.remove(friends, i)
return true
end
end
return false
end
hook.Add("Initialize", "wire_friendslist_init", function()
timer.Simple(5, function()
friends = loadFile()
sendFriends(true)
end)
end)
function TOOL.BuildCPanel(panel)
-- Use the same models as the wire constant value
WireToolHelpers.MakeModelSizer(panel, "wire_friendslist_modelsize")
ModelPlug_AddToCPanel(panel, "Value", "wire_friendslist", true)
local save_on_entity = panel:CheckBox("#wire_friendslist_save_on_entity", "wire_friendslist_save_on_entity")
save_on_entity:SetToolTip("#wire_friendslist_save_on_entity_tooltip")
local pnl = vgui.Create("DPanel", panel)
pnl:Dock(TOP)
pnl:DockMargin(2, 2, 2, 2)
pnl:DockPadding(2, 2, 2, 2)
local list = vgui.Create("DListView", pnl)
list:AddColumn("SteamID")
list:AddColumn("Name")
list:SetMultiSelect(false)
list:Dock(TOP)
list:SetHeight(200)
cpanel_list = list
local txt = vgui.Create("DTextEntry", pnl)
txt:Dock(TOP)
local btn_add = vgui.Create("DButton", pnl)
btn_add:Dock(TOP)
btn_add:SetText("Add")
function btn_add:DoClick()
local steamid = string.upper(string.Trim(txt:GetValue()))
if addSteamID(steamid) then
local ply = player.GetBySteamID(steamid)
local col2 = "#wire_friendslist_not_connected"
if IsValid(ply) then
col2 = ply:Nick()
end
list:AddLine(steamid, col2)
txt:SetValue("")
end
end
local btn_remove = vgui.Create("DButton", pnl)
btn_remove:Dock(TOP)
btn_remove:SetText("Remove")
function btn_remove:DoClick()
local selected = list:GetSelectedLine()
if selected then
local steamid = list:GetLine(selected):GetColumnText(1)
list:RemoveLine(selected)
if removeSteamID(steamid) then
sendFriends()
end
end
end
for i = 1, #friends do
local ply = player.GetBySteamID(friends[i])
local col2 = "#wire_friendslist_not_connected"
if IsValid(ply) then
col2 = ply:Nick()
end
list:AddLine(friends[i], col2)
end
local pnl2 = vgui.Create("DPanel", panel)
pnl2:Dock(TOP)
pnl2:DockMargin(2, 2, 2, 2)
pnl2:DockPadding(2, 2, 2, 2)
local lbl = vgui.Create("DLabel", pnl2)
lbl:SetText("#wire_friendslist_connected_players")
lbl:SizeToContents()
lbl:Dock(TOP)
lbl:SetTextColor(Color(0, 0, 0, 255))
local connected_list = vgui.Create("DListView", pnl2)
connected_list:Dock(TOP)
connected_list:AddColumn("SteamID")
connected_list:AddColumn("Name")
connected_list:SetHeight(200)
function connected_list:OnRowSelected(index, row)
txt:SetValue(row:GetColumnText(1))
end
local refresh = vgui.Create("DButton", pnl2)
refresh:Dock(TOP)
refresh:SetText("Refresh")
function refresh:DoClick()
connected_list:Clear()
local plys = player.GetHumans()
for i = 1, #plys do
connected_list:AddLine(plys[i]:SteamID(), plys[i]:Nick())
end
end
refresh:DoClick()
-- wanted to use SizeToContents here but it didn't work, thanks garry
pnl:SetHeight(268)
pnl2:SetHeight(240)
end
end |
-- script to create a annotation file for Torch7 for ImageNet VID
package.path = package.path .. ';../?.lua'
require 'torch'
require 'paths'
local myutils = require 'myutils'
-- re-organize data
local anno = {}
local json_dir = '/data/fanyi-data/ILSVRC2015/Annotations/VID/val/json'
local t7_file = '/data/fanyi-data/ILSVRC2015/Annotations/VID/val/anno.t7'
local img_id_file = '/data/fanyi-data/ILSVRC2015/ImageSets/VID/val.txt'
-- read data from json
for file in paths.iterfiles(json_dir) do
local json_file = paths.concat(json_dir, file)
local res = myutils.read_json(json_file)
for _, vid in ipairs(res) do
local video_name = vid.video_name
anno[video_name] = {}
-- get img size: dirty hack to handle bad json conversion
local img_size_tensor = {}
if torch.type(vid.im_size[1]) == 'table' then
for _, frm in ipairs(vid.im_size) do
table.insert(img_size_tensor, torch.FloatTensor(frm))
end
else
table.insert(img_size_tensor, torch.FloatTensor(vid.im_size))
end
img_size_tensor = torch.cat(img_size_tensor, 2):permute(2, 1)
-- collect frame name
local fr_name = {}
for _, frame_name in ipairs(vid.im_list) do
assert(torch.type(frame_name[1][1]) == 'string')
table.insert(fr_name, frame_name[1][1])
end
local obj_arr = {}
for _, obj in ipairs(vid.obj) do
local boxes_tensor = {}
-- dirty hack to handle bad json conversion
if obj.boxes == nil then
assert(obj[2] == nil and obj[1][2] == nil)
obj = obj[1][1]
end
-- dirty hack to handle bad json conversion
if torch.type(obj.boxes[1]) == 'table' then
for _, frm in ipairs(obj.boxes) do
table.insert(boxes_tensor, torch.FloatTensor(frm))
end
else
table.insert(boxes_tensor, torch.FloatTensor(obj.boxes))
end
boxes_tensor = torch.cat(boxes_tensor, 2):permute(2, 1)
obj.boxes = boxes_tensor
table.insert(obj_arr, obj)
end
anno[video_name].obj = obj_arr
anno[video_name].im_list = fr_name
anno[video_name].im_size = img_size_tensor
print(string.format('%g-th video processed', #myutils.keys(anno)))
end
end
-- Break different segments into different 'obj'
for vid_name, vid in pairs(anno) do
local sub_obj_arr = {}
for _, obj in ipairs(vid.obj) do
local obj_cat = obj.category
local obj_idx = obj.obj_idx
local boxes = obj.boxes
local frame_id = boxes[{{}, 2}]
local n = frame_id:nElement()
if n <= 1 then
table.insert(sub_obj_arr, obj)
else
local segs = frame_id[{{2, n}}] - frame_id[{{1, n-1}}]
local endpoints = torch.nonzero(segs:ne(1))
if endpoints:nElement() > 0 then
endpoints = torch.cat({endpoints.new({0}), endpoints:view(-1), endpoints.new({n})}, 1)
else
endpoints = torch.cat({endpoints.new({0}), endpoints.new({n})}, 1)
end
-- create all objs
for pp = 1, endpoints:nElement()-1 do
local sub_obj = {}
local start_idx = endpoints[pp] + 1
local end_idx = endpoints[pp + 1]
local sub_boxes = boxes[{{start_idx, end_idx}, {}}]:clone()
sub_obj.category = obj_cat
sub_obj.obj_idx = obj_idx
sub_obj.start_frame = boxes[{start_idx, 2}]
sub_obj.end_frame = boxes[{end_idx, 2}]
sub_obj.boxes = sub_boxes
table.insert(sub_obj_arr, sub_obj)
end
end
end
vid.obj = sub_obj_arr
end
-- Load an image list to get the unique image id for each and every frame
local frame_name_to_idx = {}
for line in io.lines(img_id_file) do
local loc = string.find(line,' ')
local frame_name = string.sub(line, 1, loc-1) .. '.JPEG'
local frame_idx = tonumber(string.sub(line, loc+1))
frame_name_to_idx[frame_name] = frame_idx
end
for vid_name, vid in pairs(anno) do
local global_idx = {}
for im_idx, im in ipairs(vid.im_list) do
local key = vid_name .. '/' .. im
local value = frame_name_to_idx[key]
assert(value ~= nil)
global_idx[im_idx] = value
end
vid.global_idx = torch.IntTensor(global_idx)
end
torch.save(t7_file, anno)
|
return function(UrlBuilder)
local function isQQ()
return string.find(UrlBuilder.fromString("corp:")(), "qq.com")
end
return {
catalog = UrlBuilder.fromString("www:catalog"),
buildersClub = UrlBuilder.fromString("www:mobile-app-upgrades/native-ios/bc"),
trades = UrlBuilder.fromString("www:trades"),
profile = UrlBuilder.fromString("www:users/profile"),
friends = UrlBuilder.fromString("www:users/friends"),
groups = UrlBuilder.fromString("www:my/groups"),
inventory = UrlBuilder.fromString("www:users/inventory"),
messages = UrlBuilder.fromString("www:my/messages"),
feed = UrlBuilder.fromString("www:feeds/inapp"),
develop = UrlBuilder.fromString("www:develop/landing"),
blog = UrlBuilder.fromString("blog:"),
help = UrlBuilder.fromString(isQQ() and "corp:faq" or "www:help"),
about = {
us = UrlBuilder.fromString("corp:"),
careers = UrlBuilder.fromString(isQQ() and "corp:careers.html" or "corp:careers"),
parents = UrlBuilder.fromString("corp:parents"),
terms = UrlBuilder.fromString("www:info/terms"),
privacy = UrlBuilder.fromString("www:info/privacy"),
},
settings = {
account = UrlBuilder.fromString("www:my/account#!/info"),
security = UrlBuilder.fromString("www:my/account#!/security"),
privacy = UrlBuilder.fromString("www:my/account#!/privacy"),
billing = UrlBuilder.fromString("www:my/account#!/billing"),
notifications = UrlBuilder.fromString("www:my/account#!/notifications"),
},
}
end
|
require('quest')
-- Thengil is looking for the Cosmos Stone...
local function thengil_cosmos_start_fn()
add_message_with_pause("THENGIL_COSMOS_QUEST_START_SID")
add_message_with_pause("THENGIL_COSMOS_QUEST_START2_SID")
clear_and_add_message("THENGIL_COSMOS_QUEST_START3_SID")
end
-- Quest ends when the player has the Cosmos Stone in his or her
-- inventory.
local function thengil_cosmos_completion_condition_fn()
return player_has_item("cosmos_stone") == true
end
-- Thengil forges the world-sword with the cosmos stone.
local function thengil_cosmos_completion_fn()
add_message_with_pause("THENGIL_COSMOS_QUEST_COMPLETE_SID")
add_message_with_pause("THENGIL_COSMOS_QUEST_COMPLETE2_SID")
add_message_with_pause("THENGIL_COSMOS_QUEST_COMPLETE3_SID")
clear_and_add_message("THENGIL_COSMOS_QUEST_COMPLETE4_SID")
remove_object_from_player("cosmos_stone")
add_object_to_player_tile("worldsword")
return true
end
thengil_quest = Quest:new("thengil_cosmos",
"THENGIL_COSMOS_QUEST_TITLE_SID",
"THENGIL_SHORT_DESCRIPTION_SID",
"THENGIL_COSMOS_QUEST_DESCRIPTION_SID",
"THENGIL_COSMOS_QUEST_COMPLETE_SID",
"THENGIL_COSMOS_QUEST_REMINDER_SID",
truefn,
thengil_cosmos_start_fn,
thengil_cosmos_completion_condition_fn,
thengil_cosmos_completion_fn)
if thengil_quest:execute() == false then
add_message("THENGIL_SPEECH_TEXT_SID")
end
|
-- Base16 {{ scheme-name }} color
-- Author: {{ scheme-author }}
-- to be use in your theme.lua
-- symlink or copy to config folder `local color = require('color')`
local M = {}
M.base00 = "#1e1e3f" -- ----
M.base01 = "#43d426" -- ---
M.base02 = "#f1d000" -- --
M.base03 = "#808080" -- -
M.base04 = "#6871ff" -- +
M.base05 = "#c7c7c7" -- ++
M.base06 = "#ff77ff" -- +++
M.base07 = "#ffffff" -- ++++
M.base08 = "#d90429" -- red
M.base09 = "#f92a1c" -- orange
M.base0A = "#ffe700" -- yellow
M.base0B = "#3ad900" -- green
M.base0C = "#00c5c7" -- aqua/cyan
M.base0D = "#6943ff" -- blue
M.base0E = "#ff2c70" -- purple
M.base0F = "#79e8fb" -- brown
return M
|
local json = require "json"
local parse = require "parse"
local property = require "property"
local localization = require "localization"
local database = require "database"
local exception = require "exception"
local exceptionHandler = require "exceptionHandler"
local util = require "util"
local localeService = require "localeService"
local priceService = require "priceService"
local function process (db, data)
local op = db:operators()
local locale = localeService.getLocale(db)
data.locale = locale
local rootCategory = db:findOne({category = {code = op.equal("root")}}, {
{subcategories = {
{name = {locale = locale}}
}}
})
data.categories = rootCategory.subcategories
local categoryCode
local uries = util.split(ngx.var.uri, "/")
if property.categoryUrl == "/" .. uries[#uries - 1] then
categoryCode = uries[#uries]
end
if categoryCode then
local category = db:findOne({category = {code = op.equal(categoryCode)}})
if category.subcategories then
data.subcategories = category.subcategories({
{name = {locale = locale}}
})
end
if category.products then
local products = category.products({
"pictures",
"prices",
{name = {locale = locale}}
})
priceService.convertProductsPrices(db, products)
data.products = products
end
local productAttributes = db:find({productAttribute = {values = {products = {categories = {code = op.equal(categoryCode)}}}}}, {
{values = {
{name = {locale = locale}}
}},
{name = {locale = locale}}
})
data.productAttributes = productAttributes
end
end
local data = {}
local db = database.connect()
local status, err = pcall(process, db, data)
db:close()
if not status then
exceptionHandler.toData(data, err)
end
ngx.say(parse(require("BaselineHtmlTemplate"), {
title = "Category Page",
externalJS = [[
<script type="text/javascript" src="/baseline/static/js/init-shop.js"></script>
]],
externalCSS = [[
<link href="/shop/static/favicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon" />
<link rel="stylesheet" href="/shop/static/style.css" type="text/css" />
]],
initJS = parse([[
var vars = {}
vars.locale = {{locale}}
Widget.setContainerToPage([
[
{size: "12u", widget: new Widget.ShopHeader()}
],
[
{size: "3u", medium: "6u", small: "12u", widget: new Widget.Logo()},
{size: "3u", medium: "6u", small: "12u", widget: new Widget.CallUs()},
{size: "3u", medium: "6u", small: "12u", widget: new Widget.Search()},
{size: "3u", medium: "6u", small: "12u", widget: new Widget.MiniCart()}
],
[
{size: "12u", widget: new Widget.Error({{error}})}
],
[
{size: "12u", widget: new Widget.HorizontalNavigation({{categories}})}
],
[
{size: "11u -1u", widget: new Widget.HorizontalNavigation({{subcategories}})}
],
[
{size: "3u", small: "12u", widget: new Widget.ProductAttributeFilter({{productAttributes}})},
{size: "9u", small: "12u", widget: new Widget.ProductsGrid({{products}})}
]
])
]], json.encodeProperties(data))
})) |
function CreateYourHouseMap()
return {
version = "1.1",
luaversion = "5.1",
tiledversion = "0.16.1",
orientation = "orthogonal",
renderorder = "right-down",
width = 40,
height = 20,
tilewidth = 16,
tileheight = 16,
nextobjectid = 1,
properties = {},
tilesets = {
{
name = "town",
firstgid = 1,
tilewidth = 16,
tileheight = 16,
spacing = 0,
margin = 0,
image = "../art/town_tileset.png",
imagewidth = 176,
imageheight = 288,
tileoffset = {
x = 0,
y = 0
},
properties = {},
terrains = {},
tilecount = 198,
tiles = {}
},
{
name = "indoor",
firstgid = 199,
tilewidth = 16,
tileheight = 16,
spacing = 0,
margin = 0,
image = "../art/rpg_indoor.png",
imagewidth = 176,
imageheight = 192,
tileoffset = {
x = 0,
y = 0
},
properties = {},
terrains = {},
tilecount = 132,
tiles = {}
},
{
name = "collision",
firstgid = 331,
tilewidth = 16,
tileheight = 16,
spacing = 0,
margin = 0,
image = "../../tilesets/collision_graphic.png",
imagewidth = 32,
imageheight = 32,
tileoffset = {
x = 0,
y = 0
},
properties = {},
terrains = {},
tilecount = 4,
tiles = {}
}
},
layers = {
{
type = "tilelayer",
name = "1-background",
x = 0,
y = 0,
width = 40,
height = 20,
visible = true,
opacity = 1,
offsetx = 0,
offsety = 0,
properties = {},
encoding = "lua",
data = {
202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202,
213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213,
271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271,
271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271,
271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271,
271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271,
271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271,
271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271,
271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271,
271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271,
271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271,
271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271,
271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271,
271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 72, 271,
271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 72, 271,
271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271,
271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271,
271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271,
271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271,
271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271, 271
}
},
{
type = "tilelayer",
name = "2-decoration",
x = 0,
y = 0,
width = 40,
height = 20,
visible = true,
opacity = 1,
offsetx = 0,
offsety = 0,
properties = {},
encoding = "lua",
data = {
199, 0, 230, 0, 230, 0, 230, 0, 230, 0, 209, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 209,
210, 0, 241, 0, 241, 0, 241, 0, 241, 0, 220, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 220,
221, 0, 0, 0, 0, 0, 0, 0, 0, 0, 220, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 231,
221, 0, 0, 0, 147, 0, 0, 0, 0, 0, 220, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 231,
221, 0, 0, 0, 0, 0, 0, 0, 0, 0, 220, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 231,
221, 0, 0, 0, 0, 0, 0, 0, 0, 0, 220, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 231,
221, 0, 0, 0, 0, 0, 0, 0, 0, 0, 220, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 231,
221, 0, 0, 265, 266, 266, 267, 0, 0, 0, 220, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 231,
221, 0, 0, 276, 277, 277, 278, 0, 0, 0, 269, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 231,
221, 0, 0, 0, 0, 0, 0, 0, 0, 0, 291, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 231,
221, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 314, 315, 316, 0, 0, 0, 0, 0, 0, 0, 231,
221, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 325, 326, 327, 0, 0, 0, 0, 0, 0, 0, 231,
221, 0, 0, 0, 0, 0, 0, 0, 0, 0, 269, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 231,
221, 0, 0, 0, 0, 0, 0, 0, 0, 0, 291, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 231,
221, 0, 0, 0, 0, 0, 0, 0, 0, 0, 220, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 231,
221, 0, 0, 0, 0, 0, 0, 0, 0, 0, 220, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 231,
221, 0, 0, 0, 0, 0, 0, 0, 0, 0, 220, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 231,
221, 0, 0, 0, 0, 0, 0, 0, 0, 0, 220, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 231,
243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 246, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243, 243,
213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 219, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213, 213
}
},
{
type = "tilelayer",
name = "3-collision",
x = 0,
y = 0,
width = 40,
height = 20,
visible = true,
opacity = 0.24,
offsetx = 0,
offsety = 0,
properties = {},
encoding = "lua",
data = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 331, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 331, 0, 0, 0, 0, 0, 331, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 331, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 331, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 331, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 331, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 331, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 331, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 331, 331, 331, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 331, 331, 331, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 331, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 331, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 331, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 331, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 331, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 331, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 331, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
}
},
{
type = "tilelayer",
name = "4-background",
x = 0,
y = 0,
width = 40,
height = 20,
visible = true,
opacity = 1,
offsetx = 0,
offsety = 0,
properties = {},
encoding = "lua",
data = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
}
},
{
type = "tilelayer",
name = "5-decoration",
x = 0,
y = 0,
width = 40,
height = 20,
visible = true,
opacity = 1,
offsetx = 0,
offsety = 0,
properties = {},
encoding = "lua",
data = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 301, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 322, 298, 312, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
}
},
{
type = "tilelayer",
name = "6-collision",
x = 0,
y = 0,
width = 40,
height = 20,
visible = true,
opacity = 1,
offsetx = 0,
offsety = 0,
properties = {},
encoding = "lua",
data = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
}
}
}
}
end
|
TatooineImperialOasisBaseScreenPlay = ScreenPlay:new {
numberOfActs = 1,
}
registerScreenPlay("TatooineImperialOasisBaseScreenPlay", true)
function TatooineImperialOasisBaseScreenPlay:start()
if (isZoneEnabled("tatooine")) then
self:spawnMobiles()
end
end
function TatooineImperialOasisBaseScreenPlay:spawnMobiles()
local pNpc = spawnMobile("tatooine", "artisan",60,-1.1,1.0,10.0,142,6016532)
self:setMoodString(pNpc, "npc_sitting_chair")
pNpc = spawnMobile("tatooine", "agriculturalist",60,1.4,1.0,9.7,-134,6016532)
self:setMoodString(pNpc, "npc_sitting_chair")
pNpc = spawnMobile("tatooine", "commoner_tatooine",60,7.7,-3.4,9.5,-42,6016536)
self:setMoodString(pNpc, "npc_sitting_table_eating")
pNpc = spawnMobile("tatooine", "commoner_fat",60,10.0,-4.0,-1.6,-88,6016537)
self:setMoodString(pNpc, "npc_sitting_chair")
pNpc = spawnMobile("tatooine", "entertainer",60,8.9,-4.0,-1.5,90,6016537)
self:setMoodString(pNpc, "happy")
pNpc = spawnMobile("tatooine", "scientist",60,-7.6,-10.0,-9.6,175,6016539)
self:setMoodString(pNpc, "npc_use_terminal_high")
pNpc = spawnMobile("tatooine", "r5",60,-8.7,-10.0,-9.6,106,6016539)
self:setMoodString(pNpc, "happy")
pNpc = spawnMobile("tatooine", "imperial_stealth_operative",60,-1.9,-9.5,-3.8,65,6016541)
self:setMoodString(pNpc, "npc_sitting_chair")
pNpc = spawnMobile("tatooine", "shadowy_figure",60,-0.3,-9.5,-2.4,-157,6016541)
self:setMoodString(pNpc, "npc_sitting_chair")
pNpc = spawnMobile("tatooine", "seeker",60,-1.0,-9.5,1.8,-120,6016538)
self:setMoodString(pNpc, "neutral")
pNpc = spawnMobile("tatooine", "scientist",60,-7.3,-10.0,-10.3,177,6016507)
self:setMoodString(pNpc, "npc_use_terminal_low")
pNpc = spawnMobile("tatooine", "chiss_male",60,8.0,-3.4,7.4,169,6016504)
self:setMoodString(pNpc, "happy")
pNpc = spawnMobile("tatooine", "chiss_female",60,8.1,-3.4,6.2,0,6016504)
self:setMoodString(pNpc, "nervous")
pNpc = spawnMobile("tatooine", "noble",60,10.4,0.4,5.6,-141,6016499)
self:setMoodString(pNpc, "neutral")
pNpc = spawnMobile("tatooine", "info_broker",60,10.4,0.4,4.4,0,6016499)
self:setMoodString(pNpc, "conversation")
pNpc = spawnMobile("tatooine", "rebel_obscureops_agent",60,5.3,0.1,-4.2,88,1289937)
self:setMoodString(pNpc, "npc_use_terminal_low")
pNpc = spawnMobile("tatooine", "imperial_stealth_operative",60,4.3,0.1,-3.2,130,1289937)
self:setMoodString(pNpc, "threaten")
pNpc = spawnMobile("tatooine", "contractor",60,-2.3,0.1,-3.1,8,1289938)
self:setMoodString(pNpc, "npc_use_terminal_low")
pNpc = spawnMobile("tatooine", "medic",60,-5.0,0.1,1.7,-145,1289934)
self:setMoodString(pNpc, "npc_use_terminal_low")
--Outside
pNpc = spawnMobile("tatooine", "bounty_hunter",60,-5284.9,7.1,2714.4,-97,0)
self:setMoodString(pNpc, "neutral")
pNpc = spawnMobile("tatooine", "seeker",60,-5285.6,7.2,2713.7,-100,0)
self:setMoodString(pNpc, "neutral")
pNpc = spawnMobile("tatooine", "farmer_rancher",60,-5250,0,2733.3,-13,0)
self:setMoodString(pNpc, "fishing")
pNpc = spawnMobile("tatooine", "bounty_hunter",60,-5284.9,9.1,2675.2,48,0)
self:setMoodString(pNpc, "angry")
spawnMobile("tatooine", "trainer_commando",0,-5292,6.76132,2718,183,0)
spawnMobile("tatooine", "informant_npc_lvl_2",0,-5284,9.1,2676,240,0)
spawnMobile("tatooine", "informant_npc_lvl_1",0,-5296,8.5,2654,0,0)
spawnMobile("tatooine", "imperial_recruiter",0,-5340,4.7,2736,149,0)
spawnMobile("tatooine", "dark_trooper",360,-5360,8.0,2748.6,130,0)
spawnMobile("tatooine", "dark_trooper",360,-5357.5,8.0,2751.4,130,0)
spawnMobile("tatooine", "elite_sand_trooper",360,-5343.4,4.7,2733,120,0)
spawnMobile("tatooine", "imperial_probe_drone",360,-5322.4,7.1,2711.5,179,0)
--Corvette rescue mission npc to be added later...
--spawnMobile("tatooine", "colonel_darkstone",0,-5321.4,6.8,2702,158,0)
spawnMobile("tatooine", "sand_trooper",360,-5289.8,7.5,2707,30,0)
spawnMobile("tatooine", "sand_trooper",360,-5292.8,7.2,2709.2,40,0)
spawnMobile("tatooine", "storm_commando",600,-5310.7,8.5,2660.7,3,0)
spawnMobile("tatooine", "storm_commando",600,-5304.0,8.5,2660.6,-7,0)
spawnMobile("tatooine", "sand_trooper",360,-5361.6,8.5,2661.8,-93,0)
spawnMobile("tatooine", "sand_trooper",360,-5362.5,7.6,2673.5,-120,0)
spawnMobile("tatooine", "stormtrooper_sniper",360,-5339.1,7.5,2673.3,-97,0)
end
|
local SCREEN_MODIFIER = {"cmd", "alt", "ctrl"}
local WINDOW_MODIFIER = {"cmd", "ctrl"}
hs.hotkey.bind(SCREEN_MODIFIER, "Left", function()
hs.window.focusedWindow():moveOneScreenWest()
end)
hs.hotkey.bind(SCREEN_MODIFIER, "Right", function()
hs.window.focusedWindow():moveOneScreenEast()
end)
local function resizeAndPlaceWindow(x, y, wDiv, hDiv, wMul, hMul)
local win = hs.window.focusedWindow()
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
if type(x) == 'number' then
f.x = max.x + x
elseif type(x) == 'string' then -- 50%
f.x = max.x + (max.w * (tonumber(x) / 100))
end
if type(y) == 'number' then
f.y = max.y + y
elseif type(y) == 'string' then -- 50%
f.y = max.y + (max.h * (tonumber(y) / 100))
end
f.w = max.w / wDiv * wMul
f.h = max.h / hDiv * hMul
win:setFrame(f)
end
local function bindResizeAndPlaceWindow(hkey, x, y, wDiv, hDiv, wMul, hMul)
hs.hotkey.bind(WINDOW_MODIFIER, hkey, function()
resizeAndPlaceWindow(x, y, wDiv, hDiv, wMul, hMul)
end)
end
bindResizeAndPlaceWindow("Return", 0, 0, 1, 1, 1, 1)
bindResizeAndPlaceWindow("Left", 0, 0, 2, 1, 1, 1)
bindResizeAndPlaceWindow("Right", "50", 0, 2, 1, 1, 1)
bindResizeAndPlaceWindow("Up", 0, 0, 1, 2, 1, 1)
bindResizeAndPlaceWindow("Down", 0, "50", 1, 2, 1, 1)
-- 4x4 keyboard matrix mapped to cells on the screen:
-- [ ]
-- ' \
bindResizeAndPlaceWindow("[", 0, 0, 2, 2, 1, 1)
bindResizeAndPlaceWindow("]", "50", 0, 2, 2, 1, 1)
bindResizeAndPlaceWindow("'", 0, "50", 2, 2, 1, 1)
bindResizeAndPlaceWindow("\\", "50", "50", 2, 2, 1, 1)
-- 3x1 keyboard matrix mapped to cells on the screen:
-- v b n
bindResizeAndPlaceWindow("v", 0, 0, 3, 1, 1, 1)
bindResizeAndPlaceWindow("b", "33", 0, 3, 1, 1, 1)
bindResizeAndPlaceWindow("n", "66", 0, 3, 1, 1, 1)
bindResizeAndPlaceWindow("t", 0, 0, 4, 1, 3, 1)
bindResizeAndPlaceWindow("y", "25", 0, 4, 1, 3, 1)
local function bindResizeAndPlaceWindowSmaller(hkey, x, y, wDiv, hDiv, wMul, hMul)
hs.hotkey.bind(SCREEN_MODIFIER, hkey, function()
resizeAndPlaceWindow(x, y, wDiv, hDiv, wMul, hMul)
end)
end
-- 4x4 keyboard matrix mapped to cells on the screen in far corners - shift modified to quickly look window underneath:
-- [ ]
-- ' \
bindResizeAndPlaceWindowSmaller("[", 0, 0, 4, 4, 1, 1)
bindResizeAndPlaceWindowSmaller("]", "75", 0, 4, 4, 1, 1)
bindResizeAndPlaceWindowSmaller("'", 0, "75", 4, 4, 1, 1)
bindResizeAndPlaceWindowSmaller("\\", "75", "75", 4, 4, 1, 1)
-- 4x4 keyboard matrix mapped to cells on the screen (useful for 4K TVs):
-- 7 8 9 0
-- u i o p
-- j k l ;
-- m , . /
bindResizeAndPlaceWindow("7", 0, 0, 4, 4, 1, 1)
bindResizeAndPlaceWindow("8", "25", 0, 4, 4, 1, 1)
bindResizeAndPlaceWindow("9", "50", 0, 4, 4, 1, 1)
bindResizeAndPlaceWindow("0", "75", 0, 4, 4, 1, 1)
bindResizeAndPlaceWindow("u", 0, "25", 4, 4, 1, 1)
bindResizeAndPlaceWindow("i", "25", "25", 4, 4, 1, 1)
bindResizeAndPlaceWindow("o", "50", "25", 4, 4, 1, 1)
bindResizeAndPlaceWindow("p", "75", "25", 4, 4, 1, 1)
bindResizeAndPlaceWindow("j", 0, "50", 4, 4, 1, 1)
bindResizeAndPlaceWindow("k", "25", "50", 4, 4, 1, 1)
bindResizeAndPlaceWindow("l", "50", "50", 4, 4, 1, 1)
bindResizeAndPlaceWindow(";", "75", "50", 4, 4, 1, 1)
bindResizeAndPlaceWindow("m", 0, "75", 4, 4, 1, 1)
bindResizeAndPlaceWindow(",", "25", "75", 4, 4, 1, 1)
bindResizeAndPlaceWindow(".", "50", "75", 4, 4, 1, 1)
bindResizeAndPlaceWindow("/", "75", "75", 4, 4, 1, 1)
-- centered quarter
-- ----
-- -OO-
-- -OO-
-- ----
hs.hotkey.bind(SCREEN_MODIFIER, "Return", function()
resizeAndPlaceWindow("25", "25", 2, 2, 1, 1)
end)
|
--[[
MIT License
Copyright (c) 2019 nasso <nassomails ~ at ~ gmail {dot} com>
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 cwd = (...):match('(.*lovector).-$') .. "."
local DOM = require(cwd .. "svg.dom")
local common = require(cwd .. "svg.common")
local renderer = {}
function renderer:empty(svg, options)
local x = tonumber(common.get_attr(self, "x", "0"), 10)
local y = tonumber(common.get_attr(self, "y", "0"), 10)
local width = common.get_attr(self, "width")
local height = common.get_attr(self, "height")
local href = common.get_attr(self, "href", common.get_attr(self, "xlink:href"))
-- href check
if href == nil then
return ""
end
-- width check
if width ~= nil then
width = tonumber(width, 10)
if width <= 0 then
return ""
end
end
-- height check
if height ~= nil then
height = tonumber(height, 10)
if height <= 0 then
return ""
end
end
-- get the target element's ID
href = href:match("#(.+)")
if href == nil then
return ""
end
-- get the actual target element
href = svg.document:get_element_by_id(href)
if href == nil then
return ""
end
-- clone the element
href = href:clone()
href:set_attribute("id", nil)
-- remove arguments we don't wanna keep
self.attributes["x"] = nil
self.attributes["y"] = nil
self.attributes["width"] = nil
self.attributes["height"] = nil
self.attributes["href"] = nil
self.attributes["xlink:href"] = nil
-- generate the <g> that will replace this <use>
local g = DOM.Element("g", self.attributes)
-- add transform
if x ~= 0 or y ~= 0 then
g:set_attribute("transform", common.get_attr(g, "transform", "") .. " translate(" .. x .. ", " .. y .. ")")
end
-- add the cloned element
g:append_child(href)
-- render the element
common.gen(svg, g, options)
end
return renderer
|
-- Copyright 2016-2021 Gabriel Dubatti. See LICENSE.
------- PROJECT -------
Proj = {}
local events, events_connect = events, events.connect
--project views
Proj.PRJV_DEFAULT = 0 -- default view (no active project)
Proj.PRJV_PROJECT = 1 -- project view
Proj.PRJV_FILES = 2 -- project files view
Proj.PRJV_SEARCH = 3 -- search results view
Proj.PRJV_FILES_2 = 4 -- files #2 (right side of vertical split)
-- PREFERRED VIEW number for each view type and
-- SPLIT CONTROL { adjust previous view size [%], vertical/horizontal split, view to split }
if USE_LISTS_PANEL then
--show project in a toolbar panel
if USE_RESULTS_PANEL then
--show results in a toolbar panel (PROJECT: PANEL SEARCH: PANEL)
Proj.prefview = {
[Proj.PRJV_DEFAULT] = 0, -- default view (no active project)
[Proj.PRJV_PROJECT] = -1, -- project view REPLACED BY A PANEL
[Proj.PRJV_FILES] = 1, -- project files in view #1
[Proj.PRJV_SEARCH] = -1, -- search results view REPLACED BY A PANEL
[Proj.PRJV_FILES_2] = 2, -- files #2 (right side of vertical split) in view #2
}
Proj.prefsplit = {
[1] = { 0.50, true, 1 }, -- files #2 in view #2 (view #1 size = 50%, VERTICAL)
}
else
--show results in a buffer (PROJECT: PANEL SEARCH: BUFFER)
Proj.prefview = {
[Proj.PRJV_DEFAULT] = 0, -- default view (no active project)
[Proj.PRJV_PROJECT] = -1, -- project view REPLACED BY A PANEL
[Proj.PRJV_FILES] = 1, -- project files in view #1
[Proj.PRJV_SEARCH] = 2, -- search results in view #2
[Proj.PRJV_FILES_2] = 3, -- files #2 (right side of vertical split) in view #3
}
Proj.prefsplit = {
[1] = { 0.75, false, 1 }, -- search results in view #2 (view #1 size = 75%, HORIZONTAL)
[2] = { 0.50, true, 1 }, -- files #2 in view #3 (view #1 size = 50%, VERTICAL)
}
end
else
--show project in a buffer
if USE_RESULTS_PANEL then
--show results in a toolbar panel
Proj.prefview = {
[Proj.PRJV_DEFAULT] = 0, -- default view (no active project)
[Proj.PRJV_PROJECT] = 1, -- project in view #1
[Proj.PRJV_FILES] = 2, -- project files in view #2
[Proj.PRJV_SEARCH] = -1, -- search results view REPLACED BY A PANEL
[Proj.PRJV_FILES_2] = 3, -- files #2 (right side of vertical split) in view #4
}
Proj.prefsplit = {
[1] = { 0.20, true, 1 }, -- project files in view #2 (view #1 size = 20%, VERTICAL)
[2] = { 0.50, true, 2 }, -- files #2 in view #3 (view #2 size = 50%, VERTICAL)
}
else
--show results in a buffer
Proj.prefview = {
[Proj.PRJV_DEFAULT] = 0, -- default view (no active project)
[Proj.PRJV_PROJECT] = 1, -- project in view #1
[Proj.PRJV_FILES] = 2, -- project files in view #2
[Proj.PRJV_SEARCH] = 3, -- search results in view #3
[Proj.PRJV_FILES_2] = 4, -- files #2 (right side of vertical split) in view #4
}
Proj.prefsplit = {
[1] = { 0.20, true, 1 }, -- project files in view #2 (view #1 size = 20%, VERTICAL)
[2] = { 0.75, false, 2 }, -- search results in view #3 (view #2 size = 75%, HORIZONTAL)
[3] = { 0.50, true, 2 }, -- files #2 in view #4 (view #2 size = 50%, VERTICAL)
}
end
end
--project row/file types
Proj.PRJF_EMPTY = 0 -- not a file (could be an empty row or a file group)
Proj.PRJF_PATH = 1 -- a path
Proj.PRJF_FILE = 2 -- a regular file (could be opened and searched)
Proj.PRJF_CTAG = 3 -- a CTAGS file (could be opened but searched only using TAG functions)
Proj.PRJF_RUN = 4 -- a run command
Proj.PRJF_VCS = 5 -- version control entry
Proj.VCS_SVN = 1 -- version control: SVN
Proj.VCS_GIT = 2 -- version control: GIT
Proj.VCS_FOLDER = 3 -- version control: FOLDER
Proj.VCS_LIST= {"SVN", "GIT", "FOLDER"}
--buffer "_type" constants
Proj.PRJT_SEARCH= '[Project search]' --search results
require('project.proj_data')
require('project.proj_ui')
require('project.proj_vcs')
require('project.proj_cmd')
require('project.proj_ctags')
require('project.proj_diff')
require('project.proj_menu')
if not USE_LISTS_PANEL then require('project.proj_buffer') end
if not USE_RESULTS_PANEL then require('project.proj_results') end
--- TA-EVENTS ---
events_connect(events.INITIALIZED, Proj.EVinitialize)
events_connect(events.QUIT, Proj.EVquit, 1)
events_connect(events.RESET_BEFORE, Proj.EVquit, 1)
events_connect(events.BUFFER_BEFORE_SWITCH, Proj.check_lost_focus)
events_connect(events.VIEW_BEFORE_SWITCH, Proj.check_lost_focus)
events_connect(events.BUFFER_AFTER_SWITCH, Proj.EVafter_switch)
events_connect(events.VIEW_AFTER_SWITCH, Proj.EVafter_switch)
events_connect(events.VIEW_NEW, Proj.EVview_new)
events_connect(events.BUFFER_NEW, Proj.EVbuffer_new)
events_connect(events.BUFFER_DELETED, Proj.EVbuffer_deleted)
events_connect(events.FILE_OPENED, Proj.EVfile_opened)
events_connect(events.FILE_AFTER_SAVE, Proj.EVafter_save)
events_connect(events.DOUBLE_CLICK, Proj.EVdouble_click)
events_connect(events.KEYPRESS, Proj.EVkeypress)
events_connect(events.UPDATE_UI, Proj.EVupdate_ui)
events_connect(events.MODIFIED, Proj.EVmodified)
events_connect(events.TAB_CLICKED, Proj.EVtabclicked, 1)
-- replace Open uri(s) code (core/ui.lua)
events_connect(events.URI_DROPPED, Proj.drop_uri,1)
|
local t =
Def.ActorFrame {
NOTESKIN:LoadActor(Var "Button", "Hold Explosion") ..
{
HoldingOnCommand = NOTESKIN:GetMetricA("HoldGhostArrow", "HoldingOnCommand"),
HoldingOffCommand = NOTESKIN:GetMetricA("HoldGhostArrow", "HoldingOffCommand"),
InitCommand = function(self)
self:playcommand("HoldingOff"):finishtweening()
end
},
NOTESKIN:LoadActor(Var "Button", "Roll Explosion") ..
{
RollOnCommand = NOTESKIN:GetMetricA("HoldGhostArrow", "RollOnCommand"),
RollOffCommand = NOTESKIN:GetMetricA("HoldGhostArrow", "RollOffCommand"),
InitCommand = function(self)
self:playcommand("RollOff"):finishtweening()
end
},
NOTESKIN:LoadActor(Var "Button", "Tap Explosion Dim") ..
{
InitCommand = function(self)
self:diffusealpha(0)
end,
W5Command = NOTESKIN:GetMetricA("GhostArrowDim", "W5Command"),
W4Command = NOTESKIN:GetMetricA("GhostArrowDim", "W4Command"),
W3Command = NOTESKIN:GetMetricA("GhostArrowDim", "W3Command"),
W2Command = NOTESKIN:GetMetricA("GhostArrowDim", "W2Command"),
W1Command = NOTESKIN:GetMetricA("GhostArrowDim", "W1Command"),
JudgmentCommand = function(self)
self:finishtweening()
end,
BrightCommand = function(self)
self:visible(false)
end,
DimCommand = function(self)
self:visible(true)
end
},
NOTESKIN:LoadActor(Var "Button", "Held Explosion Dim") ..
{
InitCommand = function(self)
self:diffusealpha(0)
end,
HeldCommand = NOTESKIN:GetMetricA("GhostArrowDim", "HeldCommand"),
JudgmentCommand = function(self)
self:finishtweening()
end,
BrightCommand = function(self)
self:visible(false)
end,
DimCommand = function(self)
self:visible(true)
end
},
NOTESKIN:LoadActor(Var "Button", "Tap Explosion Bright") ..
{
InitCommand = function(self)
self:diffusealpha(0)
end,
W5Command = NOTESKIN:GetMetricA("GhostArrowBright", "W5Command"),
W4Command = NOTESKIN:GetMetricA("GhostArrowBright", "W4Command"),
W3Command = NOTESKIN:GetMetricA("GhostArrowBright", "W3Command"),
W2Command = NOTESKIN:GetMetricA("GhostArrowBright", "W2Command"),
W1Command = NOTESKIN:GetMetricA("GhostArrowBright", "W1Command"),
JudgmentCommand = function(self)
self:finishtweening()
end,
BrightCommand = function(self)
self:visible(true)
end,
DimCommand = function(self)
self:visible(false)
end
},
NOTESKIN:LoadActor(Var "Button", "Held Explosion Bright") ..
{
InitCommand = function(self)
self:diffusealpha(0)
end,
HeldCommand = NOTESKIN:GetMetricA("GhostArrowBright", "HeldCommand"),
JudgmentCommand = function(self)
self:finishtweening()
end,
BrightCommand = function(self)
self:visible(true)
end,
DimCommand = function(self)
self:visible(false)
end
},
NOTESKIN:LoadActor(Var "Button", "HitMine Explosion") ..
{
InitCommand = function(self)
self:blend("BlendMode_Add"):diffusealpha(0)
end,
HitMineCommand = NOTESKIN:GetMetricA("GhostArrowBright", "HitMineCommand")
}
}
return t
|
-- For examples, see https://github.com/Hammerspoon/hammerspoon/wiki/Sample-Configurations
-- Password manager
-- Alternative binding? Interferes with Evernote strikethrough
hs.hotkey.bind({"ctrl", "option", "cmd"}, "K", function()
hs.application.launchOrFocus("KeePassXC")
end)
-- Lock screen
-- Built-ins: CTRL+CMD+Q; CTRL+SHIFT+POWER/EJECT
-- Remap instead?
hs.hotkey.bind({"ctrl", "option", "cmd"}, "L", function()
hs.caffeinate.lockScreen()
--hs.caffeinate.startScreenSaver()
end)
|
Option.g({
--[[
#------------------------------------------------------------------------------#
# EDITOR #
#------------------------------------------------------------------------------#
--]]
-- set the tab size to length of 4 spaces
-- shiftwidth set the indentation length
tabstop = 4,
shiftwidth = 4,
-- remove highlighting after search is done
hlsearch = false,
-- auto code folding when openeing new file at level 1
foldlevelstart = 4,
-- auto wrap after 80 characters in the line
textwidth = 80,
-- enable mouse in vim. 'a' for all modes (normal, visual, insert & command)
mouse = 'a',
-- 'backup' 'writebackup' action ~
-- off off no backup made
-- off on backup current file, deleted afterwards (default)
-- on off delete old backup, backup current file
-- on on delete old backup, backup current file
backup = false,
writebackup = true,
swapfile = false,
-- write changes to swap file after "n" ms
-- for some reason when the updatetime is high, autocompletion in coc nvim
-- takes a long time
updatetime = 300,
-- controls how short messages are displayed in status bar section
shortmess = vim.o.shortmess .. 'c',
-- open completion menu even for single item
-- do not auto insert items from completion menu
-- @warning - preview is removed. when it's on, default lsp opens a vertical tab
completeopt = 'menuone,noinsert',
-- stop showing the current mode
showmode = false,
-- stop showing the status in status bar
laststatus = 0,
-- @TODO now sure how this is working. need to find out
showcmd = false,
-- stop showing the current line and cursor position in the status bar
ruler = false,
-- set the font for GUI clients like neovide
guifont='Cascadia Code, FiraCode, Nerd Font',
-- highlight the current cursor line.
cursorline = true,
--[[
#------------------------------------------------------------------------------#
# EDITING #
#------------------------------------------------------------------------------#
--]]
smartcase = true,
ignorecase = true,
-- shows the effects of a command incrementally
inccommand = 'nosplit',
-- where to place the new split windows
splitright = true,
splitbelow = true,
-- hide unsaved file when closing the buffer
-- usually vim doesn't allow closing unsaved buffer unless you force it
-- but with hidden option, buffer will be hidden when you close it
-- vim will prompt you to save when closing vim editor
hidden = true,
--[[
#------------------------------------------------------------------------------#
# UI #
#------------------------------------------------------------------------------#
--]]
background = 'dark',
termguicolors = true,
--[[
#------------------------------------------------------------------------------#
# OTHER #
#------------------------------------------------------------------------------#
--]]
-- assign unnamedplus register to clipboard
-- anything in the clipboard can be pasted directly
-- any yanked text will be copied to clipboard
clipboard='unnamedplus',
})
Option.w({
--[[
#------------------------------------------------------------------------------#
# EDITOR #
#------------------------------------------------------------------------------#
--]]
-- shows the number bar in left hand side of the window
number = true,
-- shows numbers relative to the current cursor position
relativenumber = true,
-- code folding method to syntax
-- common methods will be used such as curly braces
-- foldmethod = 'syntax',
-- error signs and warnings will be displayed in the number line
-- usually it adds new column when signs, moving buffer to right side.
-- adding a column create weird effect that's little bit hard for the eye
signcolumn = 'number',
-- vim try to keep 100 lines below and above when scrolling
-- if buffer cannot display more than 200 lines, cursor will stay in center
-- and scroll the buffer
scrolloff=15
})
Option.b({
-- set the tab size to length of 4 spaces
-- shiftwidth set the indentation length
shiftwidth = 4,
})
|
--[[
-- Copyright (c) 2016 Adam Dodd
--
-- 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 function accelerando(startBeat, endBeat, startBpm, endBpm, div)
local startBeat = assert(tonumber(startBeat))
local endBeat = assert(tonumber(endBeat))
local startBpm = assert(tonumber(startBpm))
local endBpm = assert(tonumber(endBpm))
local div = assert(tonumber(div))
assert(startBeat >= 0) -- First beat is 0 (v3.9)
assert(endBeat > 0)
assert(startBeat < endBeat)
assert(startBpm > 0)
assert(endBpm > 0)
assert(div > 0)
local beatDiff = endBeat - startBeat
local bpmDiff = endBpm - startBpm
local total = div + 1
local beatStep = beatDiff / div
local bpmStep = bpmDiff / div
local str = ""
for i = 1, total do
local currentBeat = (beatStep * (i - 1)) + startBeat
local currentBpm = (bpmStep * (i - 1)) + startBpm
str = str .. string.format(",%03.3f=%03.3f", currentBeat, currentBpm)
end
return str
end
if #arg ~= 5 then
print("Usage: " .. arg[0] .. " <startBeat> <endBeat> <startBpm> <endBpm> " ..
"<div>")
else
print(accelerando(arg[1], arg[2], arg[3], arg[4], arg[5]))
end
|
local configuration = require 'apicast.configuration'
local env = require 'resty.env'
describe('Configuration object', function()
describe('provides information from the config file', function()
local config = configuration.new({services = { 'a' }})
it('returns services', function()
assert.truthy(config.services)
assert.equals(1, #config.services)
end)
end)
describe('.parse_service', function()
it('ignores empty hostname_rewrite', function()
local config = configuration.parse_service({ proxy = { hostname_rewrite = '' }})
assert.same(false, config.hostname_rewrite)
end)
it('populates hostname_rewrite', function()
local config = configuration.parse_service({ proxy = { hostname_rewrite = 'example.com' }})
assert.same('example.com', config.hostname_rewrite)
end)
it('has a default message, content-type, and status for the auth failed error', function()
local config = configuration.parse_service({})
assert.same('Authentication failed', config.error_auth_failed)
assert.same('text/plain; charset=utf-8', config.auth_failed_headers)
assert.equals(403, config.auth_failed_status)
end)
it('has a default message, content-type, and status for the missing creds error', function()
local config = configuration.parse_service({})
assert.same('Authentication parameters missing', config.error_auth_missing)
assert.same('text/plain; charset=utf-8', config.auth_missing_headers)
assert.equals(401, config.auth_missing_status)
end)
it('has a default message, content-type, and status for the no rules matched error', function()
local config = configuration.parse_service({})
assert.same('No Mapping Rule matched', config.error_no_match)
assert.same('text/plain; charset=utf-8', config.no_match_headers)
assert.equals(404, config.no_match_status)
end)
it('has a default message, content-type, and status for the limits exceeded error', function()
local config = configuration.parse_service({})
assert.same('Limits exceeded', config.error_limits_exceeded)
assert.same('text/plain; charset=utf-8', config.limits_exceeded_headers)
assert.equals(429, config.limits_exceeded_status)
end)
describe('backend', function()
it('defaults to fake backend', function()
local config = configuration.parse_service({ proxy = {
backend = nil
}})
assert.same('http://127.0.0.1:8081', config.backend.endpoint)
assert.falsy(config.backend.host)
end)
it('is overriden from ENV', function()
env.set('BACKEND_ENDPOINT_OVERRIDE', 'https://backend.example.com')
local config = configuration.parse_service({ proxy = {
backend = { endpoint = 'http://example.com', host = 'foo.example.com' }
}})
assert.same('https://backend.example.com', config.backend.endpoint)
assert.same('backend.example.com', config.backend.host)
end)
it('detects TEST_NGINX_SERVER_PORT', function()
env.set('TEST_NGINX_SERVER_PORT', '1954')
local config = configuration.parse_service({ proxy = {
backend = nil
}})
assert.same('http://127.0.0.1:1954', config.backend.endpoint)
assert.falsy(config.backend.host)
end)
end)
end)
describe('.filter_services', function()
local filter_services = configuration.filter_services
it('works with nil', function()
local services = { { id = '42' } }
assert.equal(services, filter_services(services))
end)
it('works with table with ids', function()
local services = { { id = '42' } }
assert.same(services, filter_services(services, { '42' }))
assert.same({}, filter_services(services, { '21' }))
end)
end)
insulate('.services_limit', function()
local services_limit = configuration.services_limit
it('reads from environment', function()
env.set('APICAST_SERVICES', '42,21')
local services = services_limit()
assert.same({ ['42'] = true, ['21'] = true }, services)
end)
it('reads from environment', function()
env.set('APICAST_SERVICES', '')
local services = services_limit()
assert.same({}, services)
end)
end)
end)
|
import 'game/entity/entity'
Bombaka = class(Entity)
function Bombaka:init()
Entity.init(self, 'chars/bombaka.png', 32, 30, 30)
self.rotation_speed = 20
self.movement_speed = 2
self.anims = {
down = make_anim(0, 12, 5, 10),
left = make_anim(3, 17, 5, 10),
up = make_anim(6, 22, 5, 10),
right = make_anim(9, 27, 5, 10)
}
end |
--[[
Copyright 2012 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 native = require('uv_native')
local dns = require('luvit.dns')
local Tcp = require('luvit.uv').Tcp
local Timer = require('luvit.uv').Timer
local timer = require('luvit.timer')
local utils = require('luvit.utils')
local Emitter = require('luvit.core').Emitter
local iStream = require('luvit.core').iStream
local table = require('table')
local process = require "luvit.process"
local net = {}
--[[ Socket ]]--
local Socket = iStream:extend()
function Socket:_connect(address, port, addressType)
if self.destroyed then
return
end
if port then
self.remotePort = port
end
self.remoteAddress = address
local connectionReq = nil
if addressType == 4 then
connectionReq = self._handle:connect(address, port)
elseif addressType == 6 then
connectionReq = self._handle:connect6(address, port)
end
-- connect only returns an error or nothing
if (connectionReq ~= nil) then
self:destroy()
end
end
function Socket:_onTimeoutReal()
self:emit('timeout')
end
function Socket:address()
if self._handle then
return self._handle:getpeername()
end
return nil
end
function Socket:setTimeout(msecs, callback)
if msecs > 0 then
timer.enroll(self, msecs)
timer.active(self)
if callback then
self:once('timeout', callback)
end
elseif msecs == 0 then
timer.unenroll(self)
end
end
function Socket:write(data, callback)
if self.destroyed then
return
end
self.bytesWritten = self.bytesWritten + #data
if self._connecting == true then
self._connectQueueSize = self._connectQueueSize + #data
if self._connectQueue then
table.insert(self._connectQueue, {data, callback})
else
self._connectQueue = { {data, callback} }
end
return false
end
return self:_write(data, callback)
end
function Socket:_write(data, callback)
timer.active(self)
self._pendingWriteRequests = self._pendingWriteRequests + 1
self._handle:write(data, function(err)
if err then
self:emit('error', err);
return
end
timer.active(self)
self._pendingWriteRequests = self._pendingWriteRequests - 1
if self._pendingWriteRequests == 0 then
self:emit('drain');
end
if callback then
callback()
end
end)
return self._handle:writeQueueSize() == 0
end
function Socket:shutdown(callback)
if self.destroyed == true then
return
end
self._handle:shutdown(callback)
end
function Socket:nodelay(enable)
self._handle:nodelay(enable)
end
function Socket:keepalive(enable, delay)
self._handle:keepalive(enable, delay)
end
function Socket:pause()
self._handle:readStop()
end
function Socket:resume()
self._handle:readStart()
end
function Socket:isConnected()
return self._connected
end
function Socket:_initEmitters()
self._handle:once('close', function()
self:destroy()
end)
self._handle:on('timeout', function()
self:emit('timeout')
end)
self._handle:on('connect', function()
self._connected = true
self:emit('connect')
end)
self._handle:once('end', function()
self:emit('end')
self:done()
end)
self._handle:on('data', function(data)
timer.active(self)
self.bytesRead = self.bytesRead + #data
self:emit('data', data)
end)
self._handle:on('error', function(err)
self:destroy(err)
end)
end
function Socket:done()
self.writable = false
self:shutdown(function()
self:destroy()
end)
end
function Socket:connect(...)
local args = {...}
local options = {}
local callback
if type(args[1]) == 'table' then
-- connect(options, [cb])
options = args[1]
callback = args[2]
else
-- connect(port, [host], [cb])
options.port = args[1]
if type(args[2]) == 'string' then
options.host = args[2];
callback = args[3]
else
callback = args[2]
end
end
if not options.host then
options.host = '0.0.0.0'
end
timer.active(self)
self._connecting = true
self._handle:on('connect', function()
self._connecting = false
if self._connectQueue then
for i=1, #self._connectQueue do
self:_write(self._connectQueue[i][1], self._connectQueue[i][2])
end
self._connectQueue = nil
end
if self._paused then
self._paused = false
self:pause()
end
self._handle:readStart()
if callback then
callback()
end
end)
dns.lookup(options.host, function(err, ip, addressType)
if err then
process.nextTick(function()
self:emit('error', err)
self:destroy()
end)
else
timer.active(self)
self:_connect(ip, options.port, addressType)
end
end)
return self
end
function Socket:destroy(exception)
if self.destroyed == true then
return
end
self.destroyed = true
timer.unenroll(self)
self.readable = false
self.writable = false
if self._handle then
self._handle:close()
self._handle = nil
end
process.nextTick(function()
if (exception) then
self:emit('error', exception)
end
self:emit('close')
end)
end
function Socket:initialize(handle)
self._onTimeout = utils.bind(Socket._onTimeoutReal, self)
self._handle = handle or Tcp:new()
self._pendingWriteRequests = 0
self._connected = false
self._connecting = false
self._connectQueueSize = 0
self.bytesWritten = 0
self.bytesRead = 0
self.readable = true
self.writable = true
self.destroyed = false
self:_initEmitters()
end
--[[ Server ]]--
local Server = Emitter:extend()
function Server:listen(port, ... --[[ ip, callback --]] )
local args = {...}
local ip
local callback
local flags = 0
if not self._handle then
self._handle = Tcp:new()
end
-- Future proof
if type(args[1]) == 'function' then
callback = args[1]
else
ip = args[1]
callback = args[2]
end
ip = ip or '0.0.0.0'
self._handle:bind(ip, port, flags)
self._handle:on('listening', callback)
self._handle:on('error', function(err)
return self:emit("error", err)
end)
self._handle:listen(function(err)
if (err) then
timer.setTimeout(0, function()
self:emit("error", err)
end)
return
end
local client = Tcp:new()
self._handle:accept(client)
local sock = Socket:new(client)
sock:on('end', function()
sock:destroy()
end)
sock:resume()
self:emit('connection', sock)
sock:emit('connect')
end)
return self
end
function Server:_emitClosedIfDrained()
timer.setTimeout(0, function()
self:emit('close')
end)
end
function Server:address()
if self._handle then
return self._handle:getsockname()
end
return nil
end
function Server:close(callback)
if not self._handle then
error('Not running')
end
if callback then
self:once('close', callback)
end
if self._handle then
self._handle:close()
self._handle = nil
end
self:_emitClosedIfDrained()
end
function Server:initialize(...)
local args = {...}
local options
local connectionCallback
if #args == 1 then
connectionCallback = args[1]
elseif #args == 2 then
options = args[1]
connectionCallback = args[2]
end
self:on('connection', connectionCallback)
end
-- Exports
net.Server = Server
net.Socket = Socket
net.createConnection = function(port, ... --[[ host, cb --]])
local args = {...}
local host
local options
local callback
local s
-- future proof
if type(port) == 'table' then
options = port
port = options.port
host = options.host
callback = args[1]
else
host = args[1]
callback = args[2]
end
s = Socket:new()
return s:connect(port, host, callback)
end
net.create = net.createConnection
net.createServer = function(connectionCallback)
return Server:new(connectionCallback)
end
net.isIP = function(ip)
return native.dnsIsIp(ip)
end
net.isIPv4 = function(ip)
return native.dnsIsIpV4(ip)
end
net.isIPv6 = function(ip)
return native.dnsIsIpV6(ip)
end
return net
|
if GetObjectName(GetMyHero()) ~= "Thresh" then return end
require('Inspired')
require('DeftLib')
require('IPrediction')
local ThreshMenu = MenuConfig("Thresh", "Thresh")
ThreshMenu:Menu("Combo", "Combo")
ThreshMenu.Combo:Boolean("Q", "Use Q", true)
ThreshMenu.Combo:Boolean("Q2", "Use Q2", true)
ThreshMenu.Combo:KeyBinding("Harass", "Use Q Only !", string.byte("C"))
ThreshMenu.Combo:Boolean("W", "Use W (Lantern)", true)
ThreshMenu.Combo:DropDown("ThrowLantern", "Throw lantern to: ", 1, {"Nearest Ally", "Selected Ally"})
ThreshMenu.Combo:Boolean("E", "Use E", true)
ThreshMenu.Combo:DropDown("EMode", "E Mode", 1, {"Pull", "Push"})
ThreshMenu.Combo:Boolean("R", "Use R", true)
ThreshMenu.Combo:Slider("Rmin", "Minimum Enemies in Range", 2, 1, 5, 1)
ThreshMenu:Menu("Misc", "Misc")
ThreshMenu.Misc:Boolean("Autoignite", "Auto Ignite", true)
ThreshMenu.Misc:Boolean("SaveAlly", "Save ally with lantern", true)
ThreshMenu.Misc:Slider("AroundAlly", "Save ally if enemies near: ", 2, 1, 5, 1)
ThreshMenu.Misc:Boolean("cc", "Auto lantern CCed allies", true)
ThreshMenu.Misc:Boolean("AntiDash", "Anti-Dash (Advanced Gap-Closer)", true)
ThreshMenu.Misc:Key("Lantern", "Throw Lantern", string.byte("G"))
ThreshMenu.Misc:Boolean("AutoR", "Auto R", true)
ThreshMenu.Misc:Slider("AutoRmin", "Minimum Enemies in Range", 3, 1, 5, 1)
ThreshMenu:Menu("Drawings", "Drawings")
ThreshMenu.Drawings:Boolean("Q", "Draw Q Range", true)
ThreshMenu.Drawings:Boolean("W", "Draw W Range", true)
ThreshMenu.Drawings:Boolean("E", "Draw E Range", true)
ThreshMenu.Drawings:Boolean("R", "Draw R Range", true)
ThreshMenu.Drawings:Boolean("DrawAlly", "Draw Selected Ally", true)
ThreshMenu.Drawings:Boolean("DrawText", "Draw Selected Text", true)
ThreshMenu:Menu("Interrupt", "Interrupt")
ThreshMenu.Interrupt:Menu("SupportedSpells", "Supported Spells")
ThreshMenu.Interrupt.SupportedSpells:Boolean("Q", "Use Q", true)
ThreshMenu.Interrupt.SupportedSpells:Boolean("E", "Use E", true)
DelayAction(function()
local str = {[_Q] = "Q", [_W] = "W", [_E] = "E", [_R] = "R"}
for i, spell in pairs(CHANELLING_SPELLS) do
for _,k in pairs(GetEnemyHeroes()) do
if spell["Name"] == GetObjectName(k) then
ThreshMenu.Interrupt:Boolean(GetObjectName(k).."Inter", "On "..GetObjectName(k).." "..(type(spell.Spellslot) == 'number' and str[spell.Spellslot]), true)
end
end
end
end, 1)
OnProcessSpell(function(unit, spell)
if GetObjectType(unit) == Obj_AI_Hero and GetTeam(unit) ~= GetTeam(myHero) then
if CHANELLING_SPELLS[spell.name] then
if ValidTarget(unit, 1040) and IsReady(_Q) and GetObjectName(unit) == CHANELLING_SPELLS[spell.name].Name and ThreshMenu.Interrupt[GetObjectName(unit).."Inter"]:Value() and ThreshMenu.Interrupt.SupportedSpells.Q:Value() then
Cast(_Q,unit)
elseif ValidTarget(unit, 515) and IsReady(_E) and GetObjectName(unit) == CHANELLING_SPELLS[spell.name].Name and ThreshMenu.Interrupt[GetObjectName(unit).."Inter"]:Value() and ThreshMenu.Interrupt.SupportedSpells.E:Value() then
Cast(_E,unit)
end
end
end
end)
local EPred = IPrediction.Prediction({name=Flay, range=515, speed=math.huge, delay=0.3, width=160, type="linear", collision=false})
local target1 = TargetSelector(1040,TARGET_LESS_CAST_PRIORITY,DAMAGE_MAGIC,true,false)
local ally1 = TargetSelector(950,TARGET_LESS_CAST_PRIORITY,DAMAGE_MAGIC,true,true)
OnDraw(function(myHero)
local pos = GetOrigin(myHero)
if ThreshMenu.Drawings.Q:Value() then DrawCircle(pos,1000,1,25,GoS.Pink) end
if ThreshMenu.Drawings.W:Value() then DrawCircle(pos,950,1,25,GoS.Yellow) end
if ThreshMenu.Drawings.E:Value() then DrawCircle(pos,515,1,25,GoS.Blue) end
if ThreshMenu.Drawings.R:Value() then DrawCircle(pos,420,1,25,GoS.Green) end
if ThreshMenu.Combo.ThrowLantern:Value() == 2 and ThreshMenu.Drawings.DrawAlly:Value() and Wtarget ~= nil then
DrawCircle(GetOrigin(Wtarget),100,1,25,52224)
if ThreshMenu.Drawings.DrawText:Value() then
DrawText("Selected Ally: " .. GetObjectName(Wtarget), 18, 100, 100, 4294967040)
end
end
end)
OnTick(function(myHero)
local target = GetCurrentTarget()
local Qtarget = target1:GetTarget()
local Wtarget = ally1:GetTarget()
if IOW:Mode() == "Combo" then
if IsReady(_E) and ThreshMenu.Combo.E:Value() and ValidTarget(target,515) then
if ThreshMenu.Combo.EMode:Value() == 1 then
CastE(target)
elseif ThreshMenu.Combo.EMode:Value() == 2 then
Cast(_E,target)
end
end
if IsReady(_R) and ThreshMenu.Combo.R:Value() and EnemiesAround(GetOrigin(myHero),450) >= ThreshMenu.Combo.Rmin:Value() then
CastSpell(_R)
end
if IsReady(_W) and ThreshMenu.Combo.W:Value() then
if ThreshMenu.Combo.ThrowLantern:Value() == 1 then
CastW()
elseif ThreshMenu.Combo.ThrowLantern:Value() == 2 then
CastW2()
end
end
if IsReady(_Q) and ThreshMenu.Combo.Q:Value() then
Cast(_Q,Qtarget)
end
if ThreshMenu.Combo.Q2:Value() then
CastQ2()
end
end
if ThreshMenu.Combo.Harass:Value() then
Cast(_Q,Qtarget)
end
if IsReady(_W) and ThreshMenu.Misc.Lantern:Value() then
MoveToXYZ(GetMousePos())
CastLantern()
end
if ThreshMenu.Misc.AutoR:Value() and IsReady(_R) and EnemiesAround(GetOrigin(myHero), 450) >= ThreshMenu.Misc.AutoRmin:Value() then
CastSpell(_R)
end
if IsReady(_W) then
if ThreshMenu.Misc.SaveAlly:Value() then
for _,Ally in pairs(GetAllyHeroes()) do
if IsObjectAlive(Ally) and GetPercentHP(Ally) <= 30 and IsReady(_W) and EnemiesAround(GetOrigin(Ally), 950) >= ThreshMenu.Misc.AroundAlly:Value() and GetDistance(Ally) <= 950 then
CastSkillShot(_W,GetOrigin(FindLowestAlly()))
end
end
end
if ThreshMenu.Misc.cc:Value() then
for _,Ally in ipairs(GetAllyHeroes()) do
if IsObjectAlive(Ally) and GetDistance(Ally) <= 950 and GetPercentHP(Ally) <= 30 then
local x,y,z = IPrediction.IsUnitStunned(Ally, 950, math.huge, 0.5, 315, myHero)
if x and GetDistance(z) <= 950 and IsReady(_W) then
CastSkillShot(_W,GetOrigin(Ally))
end
end
end
end
end
for i,enemy in pairs(GetEnemyHeroes()) do
if Ignite and ThreshMenu.Misc.Autoignite:Value() then
if IsReady(Ignite) and 20*GetLevel(myHero)+50 > GetCurrentHP(enemy)+GetDmgShield(enemy)+GetHPRegen(enemy)*3 and ValidTarget(enemy, 600) then
CastTargetSpell(enemy, Ignite)
end
end
end
end)
IPrediction.OnDash(function(target, pos)
if IsReady(_E) and ValidTarget(target, 515) and GetDistance(pos) < 125 and ThreshMenu.Misc.AntiDash:Value() then
local EPos = Vector(myHero) + (Vector(myHero) - Vector(pos))
CastSkillShot(_E, EPos)
end
end, EPred)
function CastE(unit)
local EPos = Vector(myHero) + (Vector(myHero) - Vector(unit))
CastSkillShot(_E,EPos)
end
function CastW()
if FindNearestAlly() and GetDistance(FindNearestAlly()) < 950 and GetCastName(myHero,_Q) == "threshqleap" then
CastSkillShot(_W, GetOrigin(FindNearestAlly()))
end
end
function CastW2()
if Wtarget ~= nil and GetDistance(Wtarget) < 950 and GetCastName(myHero,_Q) == "threshqleap" then
CastSkillShot(_W,GetOrigin(Wtarget))
end
end
function CastQ2()
if GetCastName(myHero,_Q) == "threshqleap" then
CastSpell(_Q)
end
end
function CastLantern()
if ThreshMenu.Combo.ThrowLantern:Value() == 2 and Wtarget ~= nil and GetDistance(Wtarget) < 950 and IsObjectAlive(Wtarget) then
CastSkillShot(_W,GetOrigin(Wtarget))
elseif ThreshMenu.Combo.ThrowLantern:Value() == 1 and GetDistance(FindNearestAlly()) < 950 then
CastSkillShot(_W,GetOrigin(FindNearestAlly()))
end
end
function FindLowestAlly()
LowestAlly = nil
for _,Ally in pairs(GetAllyHeroes()) do
if IsObjectAlive(Ally) and GetDistance(Ally) <= 950 then
if LowestAlly == nil then
LowestAlly = Ally
elseif GetPercentHP(Ally) < GetPercentHP(LowestAlly) then
LowestAlly = Ally
end
end
end
return LowestAlly
end
function FindNearestAlly()
local NearestAlly = nil
for _,Ally in pairs(GetAllyHeroes()) do
if NearestAlly == nil and IsObjectAlive(Ally) then
NearestAlly = Ally
elseif IsObjectAlive(Ally) and GetDistance(Ally) < GetDistance(NearestAlly) then
NearestAlly = Ally
end
end
return NearestAlly
end
AddGapcloseEvent(_E, 515, false, ThreshMenu)
PrintChat(string.format("<font color='#1244EA'>Thresh:</font> <font color='#FFFFFF'> Have A Good Game ! </font>"))
PrintChat("MyPc: " ..GetObjectBaseName(myHero))
|
local L = ShadowUF.L
local playerClass = select(2, UnitClass("player"))
local function finalizeData(config, useMerge)
local self = ShadowUF
-- Merges all of the parentUnit options into the child if they weren't set.
-- if it's a table, it recurses inside the table and copies any nil values in too
local function mergeToChild(parent, child, forceMerge)
for key, value in pairs(parent) do
if( type(child[key]) == "table" ) then
mergeToChild(value, child[key], forceMerge)
elseif( type(value) == "table" ) then
child[key] = CopyTable(value)
elseif( forceMerge or ( value ~= nil and child[key] == nil ) ) then
child[key] = value
end
end
end
-- This makes sure that the unit has no values it shouldn't, for example if the defaults do not set incHeal for targettarget
-- and I try to set incHeal table here, then it'll remove it since it can't do that.
local function verifyTable(tbl, checkTable)
for key, value in pairs(tbl) do
if( type(value) == "table" ) then
if( not checkTable[key] ) then
tbl[key] = nil
else
for subKey, subValue in pairs(value) do
if( type(subValue) == "table" ) then
verifyTable(value, checkTable[key])
end
end
end
end
end
end
-- Set everything
for unit, child in pairs(config.units) do
if( self.defaults.profile.units[unit] ) then
if( not useMerge or ( useMerge and not self.db.profile.units[unit].enabled and self.db.profile.units[unit].height == 0 and self.db.profile.units[unit].width == 0 and self.db.profile.positions[unit].anchorPoint == "" and self.db.profile.positions[unit].point == "" ) ) then
-- Merge the primary parent table
mergeToChild(config.parentUnit, child)
-- Strip any invalid tables
verifyTable(child, self.defaults.profile.units[unit])
-- Merge it in
mergeToChild(child, self.db.profile.units[unit], true)
-- Merge position in too
if( useMerge and self.db.profile.positions[unit].point == "" and self.db.profile.positions[unit].relativePoint == "" and self.db.profile.positions[unit].anchorPoint == "" and self.db.profile.positions[unit].x == 0 and self.db.profile.positions[unit].y == 0 ) then
self.db.profile.positions[unit] = config.positions[unit]
end
end
end
end
self.db.profile.loadedLayout = true
if( not useMerge ) then
config.parentUnit = nil
config.units = nil
for key, data in pairs(config) do
self.db.profile[key] = data
end
end
end
function ShadowUF:LoadDefaultLayout(useMerge)
local config = {}
config.bars = {
texture = "Minimalist",
spacing = -1.25,
alpha = 1.0,
backgroundAlpha = 0.20,
}
config.auras = {
borderType = "light",
}
config.backdrop = {
tileSize = 1,
edgeSize = 5,
clip = 1,
inset = 3,
backgroundTexture = "Chat Frame",
backgroundColor = {r = 0, g = 0, b = 0, a = 0.80},
borderTexture = "None",
borderColor = {r = 0.30, g = 0.30, b = 0.50, a = 1},
}
config.hidden = {
cast = false, runes = true, buffs = BuffFrame:IsShown() and true or false, party = true, player = true, pet = true, target = true, focus = true, boss = true, arena = true
}
config.font = {
name = "Myriad Condensed Web",
size = 11,
extra = "",
shadowColor = {r = 0, g = 0, b = 0, a = 1},
color = {r = 1, g = 1, b = 1, a = 1},
shadowX = 0.80,
shadowY = -0.80,
}
-- Some localizations do not work with Myriad Condensed Web, need to automatically swap it to a localization that will work for it
local SML = LibStub:GetLibrary("LibSharedMedia-3.0")
if( GetLocale() == "koKR" or GetLocale() == "zhCN" or GetLocale() == "zhTW" or GetLocale() == "ruRU" ) then
config.font.name = SML.DefaultMedia.font
end
config.classColors = {
HUNTER = {r = 0.67, g = 0.83, b = 0.45},
WARLOCK = {r = 0.58, g = 0.51, b = 0.79},
PRIEST = {r = 1.0, g = 1.0, b = 1.0},
PALADIN = {r = 0.96, g = 0.55, b = 0.73},
MAGE = {r = 0.41, g = 0.8, b = 0.94},
ROGUE = {r = 1.0, g = 0.96, b = 0.41},
DRUID = {r = 1.0, g = 0.49, b = 0.04},
SHAMAN = {r = 0.14, g = 0.35, b = 1.0},
WARRIOR = {r = 0.78, g = 0.61, b = 0.43},
DEATHKNIGHT = {r = 0.77, g = 0.12 , b = 0.23},
PET = {r = 0.20, g = 0.90, b = 0.20},
VEHICLE = {r = 0.23, g = 0.41, b = 0.23},
}
config.powerColors = {
MANA = {r = 0.30, g = 0.50, b = 0.85},
RAGE = {r = 0.90, g = 0.20, b = 0.30},
FOCUS = {r = 1.0, g = 0.85, b = 0},
ENERGY = {r = 1.0, g = 0.85, b = 0.10},
HAPPINESS = {r = 0.50, g = 0.90, b = 0.70},
RUNES = {r = 0.50, g = 0.50, b = 0.50},
RUNIC_POWER = {b = 0.60, g = 0.45, r = 0.35},
AMMOSLOT = {r = 0.85, g = 0.60, b = 0.55},
FUEL = {r = 0.85, g = 0.47, b = 0.36},
}
config.healthColors = {
tapped = {r = 0.5, g = 0.5, b = 0.5},
red = {r = 0.90, g = 0.0, b = 0.0},
green = {r = 0.20, g = 0.90, b = 0.20},
static = {r = 0.70, g = 0.20, b = 0.90},
yellow = {r = 0.93, g = 0.93, b = 0.0},
inc = {r = 0, g = 0.35, b = 0.23},
enemyUnattack = {r = 0.60, g = 0.20, b = 0.20},
hostile = {r = 0.90, g = 0.0, b = 0.0},
friendly = {r = 0.20, g = 0.90, b = 0.20},
neutral = {r = 0.93, g = 0.93, b = 0.0},
offline = {r = 0.50, g = 0.50, b = 0.50}
}
config.castColors = {
channel = {r = 0.25, g = 0.25, b = 1.0},
cast = {r = 1.0, g = 0.70, b = 0.30},
interrupted = {r = 1, g = 0, b = 0},
uninterruptible = {r = 0.71, g = 0, b = 1},
finished = {r = 0.10, g = 1.0, b = 0.10},
}
config.xpColors = {
normal = {r = 0.58, g = 0.0, b = 0.55},
rested = {r = 0.0, g = 0.39, b = 0.88},
}
config.positions = {
targettargettarget = {anchorPoint = "RC", anchorTo = "#SUFUnittargettarget", x = 0, y = 0},
targettarget = {anchorPoint = "TL", anchorTo = "#SUFUnittarget", x = 0, y = 0},
focustarget = {anchorPoint = "TL", anchorTo = "#SUFUnitfocus", x = 0, y = 0},
party = {point = "TOPLEFT", anchorTo = "#SUFUnitplayer", relativePoint = "TOPLEFT", movedAnchor = "TL", x = 0, y = -60},
focus = {anchorPoint = "RB", anchorTo = "#SUFUnittarget", x = 35, y = -4},
target = {anchorPoint = "RC", anchorTo = "#SUFUnitplayer", x = 50, y = 0},
player = {point = "TOPLEFT", anchorTo = "UIParent", relativePoint = "TOPLEFT", y = -25, x = 20},
pet = {anchorPoint = "TL", anchorTo = "#SUFUnitplayer", x = 0, y = 0},
pettarget = {anchorPoint = "C", anchorTo = "UIParent", x = 0, y = 0},
partypet = {anchorPoint = "RB", anchorTo = "$parent", x = 0, y = 0},
partytarget = {anchorPoint = "RT", anchorTo = "$parent", x = 0, y = 0},
raid = {anchorPoint = "C", anchorTo = "UIParent", x = 0, y = 0},
raidpet = {anchorPoint = "C", anchorTo = "UIParent", x = 0, y = 0},
maintank = {anchorPoint = "C", anchorTo = "UIParent", x = 0, y = 0},
maintanktarget = {anchorPoint = "RT", anchorTo = "$parent", x = 0, y = 0},
mainassist = {anchorPoint = "C", anchorTo = "UIParent", x = 0, y = 0},
mainassisttarget = {anchorPoint = "RT", anchorTo = "$parent", x = 0, y = 0},
arena = {anchorPoint = "C", anchorTo = "UIParent", point = "", relativePoint = "", x = 0, y = 0},
arenapet = {anchorPoint = "RB", anchorTo = "$parent", x = 0, y = 0},
arenatarget = {anchorPoint = "RT", anchorTo = "$parent", x = 0, y = 0},
boss = {anchorPoint = "C", anchorTo = "UIParent", point = "", relativePoint = "", x = 0, y = 0},
bosstarget = {anchorPoint = "RB", anchorTo = "$parent", x = 0, y = 0},
}
-- Parent unit options that all the children will inherit unless they override it
config.parentUnit = {
portrait = {enabled = false, type = "3D", alignment = "LEFT", width = 0.22, height = 0.50, order = 15, fullBefore = 0, fullAfter = 100},
auras = {
buffs = {enabled = false, anchorPoint = "BL", size = 16, perRow = 10, x = 0, y = 0},
debuffs = {enabled = false, anchorPoint = "BL", size = 16, perRow = 10, x = 0, y = 0},
},
text = {
{width = 0.50, name = L["Left text"], anchorTo = "$healthBar", anchorPoint = "CLI", x = 3, y = 0, size = 0},
{width = 0.60, name = L["Right text"], anchorTo = "$healthBar", anchorPoint = "CRI", x = -3, y = 0, size = 0},
{width = 0.50, name = L["Left text"], anchorTo = "$powerBar", anchorPoint = "CLI", x = 3, y = 0, size = 0},
{width = 0.60, name = L["Right text"], anchorTo = "$powerBar", anchorPoint = "CRI", x = -3, y = 0, size = 0},
{width = 1, name = L["Text"], anchorTo = "$emptyBar", anchorPoint = "CLI", x = 3, y = 0, size = 0},
},
indicators = {
raidTarget = {anchorTo = "$parent", anchorPoint = "C", size = 20, x = 0, y = 0},
class = {anchorTo = "$parent", anchorPoint = "BL", size = 16, x = 0, y = 0},
masterLoot = {anchorTo = "$parent", anchorPoint = "TL", size = 12, x = 16, y = -10},
leader = {anchorTo = "$parent", anchorPoint = "TL", size = 14, x = 2, y = -12},
pvp = {anchorTo = "$parent", anchorPoint = "TR", size = 22, x = 11, y = -21},
ready = {anchorTo = "$parent", anchorPoint = "LC", size = 24, x = 35, y = 0},
role = {anchorTo = "$parent", anchorPoint = "TL", size = 14, x = 30, y = -11},
status = {anchorTo = "$parent", anchorPoint = "LB", size = 16, x = 12, y = -2},
lfdRole = {enabled = true, anchorPoint = "BR", size = 14, x = 3, y = 14, anchorTo = "$parent"}
},
highlight = {size = 10},
combatText = {anchorTo = "$parent", anchorPoint = "C", x = 0, y = 0},
emptyBar = {background = true, height = 1, reactionType = "none", order = 0},
healthBar = {background = true, colorType = "class", reactionType = "npc", height = 1.20, order = 10},
powerBar = {background = true, height = 1.0, order = 20},
druidBar = {background = true, height = 0.40, order = 25},
xpBar = {background = true, height = 0.25, order = 55},
castBar = {background = true, height = 0.60, order = 40, icon = "HIDE", name = {enabled = true, size = 0, anchorTo = "$parent", rank = true, anchorPoint = "CLI", x = 1, y = 0}, time = {enabled = true, size = 0, anchorTo = "$parent", anchorPoint = "CRI", x = -1, y = 0}},
runeBar = {background = false, height = 0.40, order = 70},
totemBar = {background = false, height = 0.40, order = 70},
}
-- Units configuration
config.units = {
raid = {
width = 100,
height = 30,
scale = 0.85,
unitsPerColumn = 8,
maxColumns = 8,
columnSpacing = 5,
groupsPerRow = 8,
groupSpacing = 0,
attribPoint = "TOP",
attribAnchorPoint = "LEFT",
healthBar = {reactionType = "none"},
powerBar = {height = 0.30},
incHeal = {cap = 1},
indicators = {
pvp = {anchorTo = "$parent", anchorPoint = "BL", size = 22, x = 0, y = 11},
masterLoot = {anchorTo = "$parent", anchorPoint = "TR", size = 12, x = -2, y = -10},
role = {enabled = false, anchorTo = "$parent", anchorPoint = "BR", size = 14, x = 0, y = 14},
ready = {anchorTo = "$parent", anchorPoint = "LC", size = 24, x = 25, y = 0},
},
text = {
{text = "[(()afk() )][name]"},
{text = "[missinghp]"},
{text = ""},
{text = ""},
{text = "[(()afk() )][name]"},
},
},
raidpet = {
width = 90,
height = 30,
scale = 0.85,
unitsPerColumn = 8,
maxColumns = 8,
columnSpacing = 5,
groupsPerRow = 8,
groupSpacing = 0,
attribPoint = "TOP",
attribAnchorPoint = "LEFT",
healthBar = {reactionType = "none"},
powerBar = {height = 0.30},
incHeal = {cap = 1},
indicators = {
pvp = {anchorTo = "$parent", anchorPoint = "BL", size = 22, x = 0, y = 11},
masterLoot = {anchorTo = "$parent", anchorPoint = "TR", size = 12, x = -2, y = -10},
role = {enabled = false, anchorTo = "$parent", anchorPoint = "BR", size = 14, x = 0, y = 14},
ready = {anchorTo = "$parent", anchorPoint = "LC", size = 24, x = 25, y = 0},
},
text = {
{text = "[name]"},
{text = "[missinghp]"},
{text = ""},
{text = ""},
{text = "[name]"},
},
},
player = {
width = 190,
height = 45,
scale = 1.0,
portrait = {enabled = true, fullAfter = 50},
castBar = {order = 60},
xpBar = {order = 55},
runeBar = {enabled = true, order = 70},
totemBar = {enabled = true, order = 70},
auras = {
buffs = {enabled = false, maxRows = 1, temporary = playerClass == "ROGUE" or playerClass == "SHAMAN"},
debuffs = {enabled = false, maxRows = 1},
},
text = {
{text = "[(()afk() )][name][( ()group())]"},
{text = "[curmaxhp]"},
{text = "[perpp]"},
{text = "[curmaxpp]"},
{text = "[(()afk() )][name][( ()group())]"},
},
},
party = {
width = 190,
height = 45,
scale = 1.0,
attribPoint = "TOP",
attribAnchorPoint = "LEFT",
unitsPerColumn = 5,
columnSpacing = 30,
portrait = {enabled = true, fullAfter = 50},
castBar = {order = 60},
offset = 23,
auras = {
buffs = {enabled = true, maxRows = 1},
debuffs = {enabled = true, maxRows = 1},
},
text = {
{text = "[(()afk() )][name]"},
{text = "[curmaxhp]"},
{text = "[level( )][perpp]"},
{text = "[curmaxpp]"},
{text = "[(()afk() )][name]"},
},
},
boss = {
enabled = true,
width = 160,
height = 40,
scale = 1.0,
attribPoint = "TOP",
attribAnchorPoint = "LEFT",
offset = 20,
auras = {
buffs = {enabled = true, maxRows = 1, perRow = 8},
debuffs = {enabled = true, maxRows = 1, perRow = 8},
},
text = {
{text = "[name]"},
{text = "[curmaxhp]"},
{text = "[perpp]"},
{text = "[curmaxpp]"},
{text = "[name]"},
},
portrait = {enabled = false},
},
bosstarget = {
width = 90,
height = 25,
scale = 1.0,
powerBar = {height = 0.60},
text = {
{text = "[name]"},
{text = "[curhp]"},
{text = ""},
{text = ""},
{text = "[name]"},
},
},
arena = {
width = 170,
height = 45,
scale = 1.0,
attribPoint = "TOP",
attribAnchorPoint = "LEFT",
portrait = {enabled = false, fullAfter = 50},
castBar = {order = 60},
offset = 25,
auras = {
buffs = {enabled = true, maxRows = 1, perRow = 9},
debuffs = {enabled = true, maxRows = 1, perRow = 9},
},
text = {
{text = "[name]"},
{text = "[curmaxhp]"},
{text = "[perpp]"},
{text = "[curmaxpp]"},
{text = "[name]"},
},
},
arenapet = {
width = 90,
height = 25,
scale = 1.0,
powerBar = {height = 0.60},
text = {
{text = "[name]"},
{text = "[curhp]"},
{text = ""},
{text = ""},
{text = "[name]"},
},
},
arenatarget = {
width = 90,
height = 25,
scale = 1.0,
powerBar = {height = 0.60},
indicators = {
pvp = {anchorTo = "$parent", anchorPoint = "BL", size = 22, x = 0, y = 11},
},
text = {
{text = "[name]"},
{text = "[curhp]"},
{text = ""},
{text = ""},
{text = "[name]"},
},
},
maintank = {
width = 150,
height = 40,
scale = 1.0,
attribPoint = "TOP",
attribAnchorPoint = "LEFT",
offset = 5,
unitsPerColumn = 5,
maxColumns = 1,
columnSpacing = 5,
incHeal = {cap = 1},
portrait = {enabled = false, fullAfter = 50},
castBar = {order = 60},
auras = {
buffs = {enabled = false},
debuffs = {enabled = false},
},
text = {
{text = "[(()afk() )][name]"},
{text = "[curmaxhp]"},
{text = "[perpp]"},
{text = "[curmaxpp]"},
{text = "[(()afk() )][name]"},
},
},
maintanktarget = {
width = 150,
height = 40,
scale = 1.0,
auras = {
buffs = {enabled = false},
debuffs = {enabled = false},
},
text = {
{text = "[(()afk() )][name]"},
{text = "[curmaxhp]"},
{text = "[classification( )][perpp]", width = 0.50},
{text = "[curmaxpp]", anchorTo = "$powerBar", width = 0.60},
{text = "[(()afk() )][name]"},
},
},
mainassist = {
width = 150,
height = 40,
scale = 1.0,
attribPoint = "TOP",
attribAnchorPoint = "LEFT",
offset = 5,
unitsPerColumn = 5,
maxColumns = 1,
columnSpacing = 5,
incHeal = {cap = 1},
portrait = {enabled = false, fullAfter = 50},
castBar = {order = 60},
auras = {
buffs = {enabled = false},
debuffs = {enabled = false},
},
text = {
{text = "[(()afk() )][name]"},
{text = "[curmaxhp]"},
{text = "[level( )][perpp]"},
{text = "[curmaxpp]"},
{text = "[(()afk() )][name]"},
},
},
mainassisttarget = {
width = 150,
height = 40,
scale = 1.0,
auras = {
buffs = {enabled = false},
debuffs = {enabled = false},
},
text = {
{text = "[(()afk() )][name]"},
{text = "[curmaxhp]"},
{text = "[level( )][classification( )][perpp]", width = 0.50},
{text = "[curmaxpp]", anchorTo = "$powerBar", width = 0.60},
{text = "[(()afk() )][name]"},
},
},
partypet = {
width = 90,
height = 25,
scale = 1.0,
powerBar = {height = 0.60},
text = {
{text = "[name]"},
{text = "[curhp]"},
{text = ""},
{text = ""},
{text = "[name]"},
},
},
partytarget = {
width = 90,
height = 25,
scale = 1.0,
powerBar = {height = 0.60},
indicators = {
pvp = {anchorTo = "$parent", anchorPoint = "BL", size = 22, x = 0, y = 11},
},
text = {
{text = "[name]"},
{text = "[curhp]"},
{text = ""},
{text = ""},
{text = "[name]"},
},
},
target = {
width = 190,
height = 45,
scale = 1.0,
portrait = {enabled = true, alignment = "RIGHT", fullAfter = 50},
castBar = {order = 60},
comboPoints = {anchorTo = "$parent", order = 60, anchorPoint = "BR", x = -3, y = 8, size = 14, spacing = -4, growth = "LEFT", isBar = true},
indicators = {
lfdRole = {enabled = false}
},
auras = {
buffs = {enabled = true},
debuffs = {enabled = true},
},
text = {
{text = "[(()afk() )][name]"},
{text = "[curmaxhp]"},
{text = "[level( )][classification( )][perpp]", width = 0.50},
{text = "[curmaxpp]", anchorTo = "$powerBar", width = 0.60},
{text = "[(()afk() )][name]"},
},
},
pet = {
width = 190,
height = 30,
scale = 1.0,
powerBar = {height = 0.70},
healthBar = {reactionType = "none"},
portrait = {enabled = false, fullAfter = 50},
castBar = {order = 60},
indicators = {
happiness = {enabled = false, anchorTo = "$parent", anchorPoint = "BR", size = 14, x = 3, y = 13},
},
text = {
{text = "[name]"},
{text = "[curmaxhp]"},
{text = "[perpp]"},
{text = "[curmaxpp]"},
{text = "[name]"},
},
},
pettarget = {
width = 190,
height = 30,
scale = 1.0,
powerBar = {height = 0.70},
indicators = {
},
text = {
{text = "[name]"},
{text = "[curmaxhp]"},
{text = "[perpp]"},
{text = "[curmaxpp]"},
{text = "[name]"},
},
},
focus = {
width = 120,
height = 28,
scale = 1.0,
powerBar = {height = 0.60},
portrait = {enabled = false, fullAfter = 50},
castBar = {order = 60},
indicators = {
lfdRole = {enabled = false},
},
text = {
{text = "[(()afk() )][name]"},
{text = "[curhp]"},
{text = "[perpp]"},
{text = "[curpp]"},
{text = "[(()afk() )][name]"},
},
},
focustarget = {
width = 120,
height = 25,
scale = 1.0,
powerBar = {height = 0.60},
portrait = {alignment = "RIGHT"},
indicators = {
pvp = {anchorTo = "$parent", anchorPoint = "BL", size = 22, x = -3, y = 11},
},
text = {
{text = "[(()afk() )][name]"},
{text = "[curhp]"},
{text = ""},
{text = ""},
{text = "[(()afk() )][name]"},
},
},
targettarget = {
width = 110,
height = 30,
scale = 1.0,
powerBar = {height = 0.6},
portrait = {alignment = "RIGHT"},
indicators = {
pvp = {anchorTo = "$parent", anchorPoint = "BL", size = 22, x = -3, y = 11},
},
text = {
{text = "[name]"},
{text = "[curhp]"},
{text = "[perpp]"},
{text = "[curpp]"},
},
},
targettargettarget = {
width = 80,
height = 30,
scale = 1.0,
powerBar = {height = 0.6},
portrait = {alignment = "RIGHT"},
indicators = {
pvp = {anchorTo = "$parent", anchorPoint = "BL", size = 22, x = -3, y = 11},
},
text = {
{text = "[name]", width = 1.0},
{text = ""},
{text = ""},
{text = ""},
},
},
}
finalizeData(config, useMerge)
end
|
-- remove spaces from string (invalid in rules except as separator)
local function strip_spaces(str)
return string.gsub(str, ' ', '')
end
-- sanitise value if empty or blank
local function value_or_NONE(value)
if value == nil or value == '' then
return 'NONE'
end
return strip_spaces(tostring(value))
end
return {
value_or_NONE = value_or_NONE
}
|
--
-- ParseLua.lua
--
-- The main lua parser and lexer.
-- LexLua returns a Lua token stream, with tokens that preserve
-- all whitespace formatting information.
-- ParseLua returns an AST, internally relying on LexLua.
--
local luaPath = debug.getinfo(1).source:match("@?(.*/)")
require(luaPath..'strict')
local util = require(luaPath..'Util')
local lookupify = util.lookupify
local WhiteChars = lookupify{' ', '\n', '\t', '\r'}
local EscapeLookup = {['\r'] = '\\r', ['\n'] = '\\n', ['\t'] = '\\t', ['"'] = '\\"', ["'"] = "\\'"}
local LowerChars = lookupify{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}
local UpperChars = lookupify{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}
local Digits = lookupify{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
local HexDigits = lookupify{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'a', 'B', 'b', 'C', 'c', 'D', 'd', 'E', 'e', 'F', 'f'}
local BinDigits = lookupify{'0', '1'}
local Symbols = lookupify{'+', '-', '*', '/', '^', '%', ',', '{', '}', '[', ']', '(', ')', ';', '#', '&', '|'}
local Scope = require(luaPath..'Scope')
local Keywords = lookupify{
'and', 'break', 'do', 'else', 'elseif',
'end', 'false', 'for', 'function', 'goto', 'if',
'in', 'local', 'nil', 'not', 'or', 'repeat',
'return', 'then', 'true', 'until', 'while',
};
local function LexLua(src)
--token dump
local tokens = {}
local st, err = pcall(function()
--line / char / pointer tracking
local p = 1
local line = 1
local char = 1
--get / peek functions
local function get()
local c = src:sub(p,p)
if c == '\n' then
char = 1
line = line + 1
else
char = char + 1
end
p = p + 1
return c
end
local function peek(n)
n = n or 0
return src:sub(p+n,p+n)
end
local function consume(chars)
local c = peek()
for i = 1, #chars do
if c == chars:sub(i,i) then return get() end
end
end
--shared stuff
local function generateError(err)
return error(">> :"..line..":"..char..": "..err, 0)
end
local function tryGetLongString()
local start = p
if peek() == '[' then
local equalsCount = 0
local depth = 1
while peek(equalsCount+1) == '=' do
equalsCount = equalsCount + 1
end
if peek(equalsCount+1) == '[' then
--start parsing the string. Strip the starting bit
for _ = 0, equalsCount+1 do get() end
--get the contents
local contentStart = p
while true do
--check for eof
if peek() == '' then
generateError("Expected `]"..string.rep('=', equalsCount).."]` near <eof>.", 3)
end
--check for the end
local foundEnd = true
if peek() == ']' then
for i = 1, equalsCount do
if peek(i) ~= '=' then foundEnd = false end
end
if peek(equalsCount+1) ~= ']' then
foundEnd = false
end
else
if peek() == '[' then
-- is there an embedded long string?
local embedded = true
for i = 1, equalsCount do
if peek(i) ~= '=' then
embedded = false
break
end
end
if peek(equalsCount + 1) == '[' and embedded then
-- oh look, there was
depth = depth + 1
for i = 1, (equalsCount + 2) do
get()
end
end
end
foundEnd = false
end
--
if foundEnd then
depth = depth - 1
if depth == 0 then
break
else
for i = 1, equalsCount + 2 do
get()
end
end
else
get()
end
end
--get the interior string
local contentString = src:sub(contentStart, p-1)
--found the end. Get rid of the trailing bit
for i = 0, equalsCount+1 do get() end
--get the exterior string
local longString = src:sub(start, p-1)
--return the stuff
return contentString, longString
else
return nil
end
else
return nil
end
end
--main token emitting loop
while true do
--get leading whitespace. The leading whitespace will include any comments
--preceding the token. This prevents the parser needing to deal with comments
--separately.
local leading = { }
local leadingWhite = ''
local longStr = false
while true do
local c = peek()
if c == '#' and peek(1) == '!' and line == 1 then
-- #! shebang for linux scripts
get()
get()
leadingWhite = "#!"
while peek() ~= '\n' and peek() ~= '' do
leadingWhite = leadingWhite .. get()
end
local token = {
Type = 'Comment',
CommentType = 'Shebang',
Data = leadingWhite,
Line = line,
Char = char
}
token.Print = function()
return "<"..(token.Type .. string.rep(' ', 7-#token.Type)).." "..(token.Data or '').." >"
end
leadingWhite = ""
table.insert(leading, token)
end
if c == ' ' or c == '\t' then
--whitespace
--leadingWhite = leadingWhite..get()
local c2 = get() -- ignore whitespace
table.insert(leading, { Type = 'Whitespace', Line = line, Char = char, Data = c2 })
elseif c == '\n' or c == '\r' then
local nl = get()
if leadingWhite ~= "" then
local token = {
Type = 'Comment',
CommentType = longStr and 'LongComment' or 'Comment',
Data = leadingWhite,
Line = line,
Char = char,
}
token.Print = function()
return "<"..(token.Type .. string.rep(' ', 7-#token.Type)).." "..(token.Data or '').." >"
end
table.insert(leading, token)
leadingWhite = ""
end
table.insert(leading, { Type = 'Whitespace', Line = line, Char = char, Data = nl })
elseif c == '-' and peek(1) == '-' then
--comment
get()
get()
leadingWhite = leadingWhite .. '--'
local _, wholeText = tryGetLongString()
if wholeText then
leadingWhite = leadingWhite..wholeText
longStr = true
else
while peek() ~= '\n' and peek() ~= '' do
leadingWhite = leadingWhite..get()
end
end
else
break
end
end
if leadingWhite ~= "" then
local token = {
Type = 'Comment',
CommentType = longStr and 'LongComment' or 'Comment',
Data = leadingWhite,
Line = line,
Char = char,
}
token.Print = function()
return "<"..(token.Type .. string.rep(' ', 7-#token.Type)).." "..(token.Data or '').." >"
end
table.insert(leading, token)
end
--get the initial char
local thisLine = line
local thisChar = char
local errorAt = ":"..line..":"..char..":> "
local c = peek()
--symbol to emit
local toEmit = nil
--branch on type
if c == '' then
--eof
toEmit = { Type = 'Eof' }
elseif UpperChars[c] or LowerChars[c] or c == '_' then
--ident or keyword
local start = p
repeat
get()
c = peek()
until not (UpperChars[c] or LowerChars[c] or Digits[c] or c == '_')
local dat = src:sub(start, p-1)
if Keywords[dat] then
toEmit = {Type = 'Keyword', Data = dat}
else
toEmit = {Type = 'Ident', Data = dat}
end
elseif Digits[c] or (peek() == '.' and Digits[peek(1)]) then
--number const
local start = p
if c == '0' and peek(1) == 'x' then
get();get()
while HexDigits[peek()] do get() end
if consume('Pp') then
consume('+-')
while Digits[peek()] do get() end
end
elseif c == '0' and peek(1) == 'b' then
get();get()
while BinDigits[peek()] do get() end
if consume('Pp') then
consume('+-')
while Digits[peek()] do get() end
end
else
while Digits[peek()] do get() end
if consume('.') then
while Digits[peek()] do get() end
end
if consume('Ee') then
consume('+-')
while Digits[peek()] do get() end
end
end
toEmit = {Type = 'Number', Data = src:sub(start, p-1)}
elseif c == '\'' or c == '\"' then
local start = p
--string const
local delim = get()
local contentStart = p
while true do
local c = get()
if c == '\\' then
get() --get the escape char
elseif c == delim then
break
elseif c == '' then
generateError("Unfinished string near <eof>")
end
end
local content = src:sub(contentStart, p-2)
local constant = src:sub(start, p-1)
toEmit = {Type = 'String', Data = constant, Constant = content}
elseif c == '[' then
local content, wholetext = tryGetLongString()
if wholetext then
toEmit = {Type = 'String', Data = wholetext, Constant = content}
else
get()
toEmit = {Type = 'Symbol', Data = '['}
end
elseif consume('>=<') then
if consume('=') then
toEmit = {Type = 'Symbol', Data = c..'='}
elseif consume('<') then
toEmit = {Type = 'Symbol', Data = '<<'}
elseif consume('>') then
toEmit = {Type = 'Symbol', Data = '>>'}
else
toEmit = {Type = 'Symbol', Data = c}
end
elseif consume('~') then
if consume('=') then
toEmit = {Type = 'Symbol', Data = '~='}
else
generateError("Unexpected symbol `~` in source.", 2)
end
elseif consume('.') then
if consume('.') then
if consume('.') then
toEmit = {Type = 'Symbol', Data = '...'}
else
toEmit = {Type = 'Symbol', Data = '..'}
end
else
toEmit = {Type = 'Symbol', Data = '.'}
end
elseif consume(':') then
if consume(':') then
toEmit = {Type = 'Symbol', Data = '::'}
else
toEmit = {Type = 'Symbol', Data = ':'}
end
elseif Symbols[c] then
get()
toEmit = {Type = 'Symbol', Data = c}
else
local contents, all = tryGetLongString()
if contents then
toEmit = {Type = 'String', Data = all, Constant = contents}
else
generateError("Unexpected Symbol `"..c.."` in source.", 2)
end
end
--add the emitted symbol, after adding some common data
toEmit.LeadingWhite = leading -- table of leading whitespace/comments
--for k, tok in pairs(leading) do
-- tokens[#tokens + 1] = tok
--end
toEmit.Line = thisLine
toEmit.Char = thisChar
toEmit.Print = function()
return "<"..(toEmit.Type..string.rep(' ', 7-#toEmit.Type)).." "..(toEmit.Data or '').." >"
end
tokens[#tokens+1] = toEmit
--halt after eof has been emitted
if toEmit.Type == 'Eof' then break end
end
end)
if not st then
return false, err
end
--public interface:
local tok = {}
local savedP = {}
local p = 1
function tok:getp()
return p
end
function tok:setp(n)
p = n
end
function tok:getTokenList()
return tokens
end
--getters
function tok:Peek(n)
n = n or 0
return tokens[math.min(#tokens, p+n)]
end
function tok:Get(tokenList)
local t = tokens[p]
p = math.min(p + 1, #tokens)
if tokenList then
table.insert(tokenList, t)
end
return t
end
function tok:Is(t)
return tok:Peek().Type == t
end
--save / restore points in the stream
function tok:Save()
savedP[#savedP+1] = p
end
function tok:Commit()
savedP[#savedP] = nil
end
function tok:Restore()
p = savedP[#savedP]
savedP[#savedP] = nil
end
--either return a symbol if there is one, or return true if the requested
--symbol was gotten.
function tok:ConsumeSymbol(symb, tokenList)
local t = self:Peek()
if t.Type == 'Symbol' then
if symb then
if t.Data == symb then
self:Get(tokenList)
return true
else
return nil
end
else
self:Get(tokenList)
return t
end
else
return nil
end
end
function tok:ConsumeKeyword(kw, tokenList)
local t = self:Peek()
if t.Type == 'Keyword' and t.Data == kw then
self:Get(tokenList)
return true
else
return nil
end
end
function tok:IsKeyword(kw)
local t = tok:Peek()
return t.Type == 'Keyword' and t.Data == kw
end
function tok:IsSymbol(s)
local t = tok:Peek()
return t.Type == 'Symbol' and t.Data == s
end
function tok:IsEof()
return tok:Peek().Type == 'Eof'
end
return true, tok
end
local function ParseLua(src)
local st, tok
if type(src) ~= 'table' then
st, tok = LexLua(src)
else
st, tok = true, src
end
if not st then
return false, tok
end
--
local function GenerateError(msg)
local err = ">> :"..tok:Peek().Line..":"..tok:Peek().Char..": "..msg.."\n"
--find the line
local lineNum = 0
if type(src) == 'string' then
for line in src:gmatch("[^\n]*\n?") do
if line:sub(-1,-1) == '\n' then line = line:sub(1,-2) end
lineNum = lineNum+1
if lineNum == tok:Peek().Line then
err = err..">> `"..line:gsub('\t',' ').."`\n"
for i = 1, tok:Peek().Char do
local c = line:sub(i,i)
if c == '\t' then
err = err..' '
else
err = err..' '
end
end
err = err.." ^^^^"
break
end
end
end
return err
end
--
local VarUid = 0
-- No longer needed: handled in Scopes now local GlobalVarGetMap = {}
local VarDigits = {'_', 'a', 'b', 'c', 'd'}
local function CreateScope(parent)
--[[
local scope = {}
scope.Parent = parent
scope.LocalList = {}
scope.LocalMap = {}
function scope:ObfuscateVariables()
for _, var in pairs(scope.LocalList) do
local id = ""
repeat
local chars = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuioplkjhgfdsazxcvbnm_"
local chars2 = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuioplkjhgfdsazxcvbnm_1234567890"
local n = math.random(1, #chars)
id = id .. chars:sub(n, n)
for i = 1, math.random(0,20) do
local n = math.random(1, #chars2)
id = id .. chars2:sub(n, n)
end
until not GlobalVarGetMap[id] and not parent:GetLocal(id) and not scope.LocalMap[id]
var.Name = id
scope.LocalMap[id] = var
end
end
scope.RenameVars = scope.ObfuscateVariables
-- Renames a variable from this scope and down.
-- Does not rename global variables.
function scope:RenameVariable(old, newName)
if type(old) == "table" then -- its (theoretically) an AstNode variable
old = old.Name
end
for _, var in pairs(scope.LocalList) do
if var.Name == old then
var.Name = newName
scope.LocalMap[newName] = var
end
end
end
function scope:GetLocal(name)
--first, try to get my variable
local my = scope.LocalMap[name]
if my then return my end
--next, try parent
if scope.Parent then
local par = scope.Parent:GetLocal(name)
if par then return par end
end
return nil
end
function scope:CreateLocal(name)
--create my own var
local my = {}
my.Scope = scope
my.Name = name
my.CanRename = true
--
scope.LocalList[#scope.LocalList+1] = my
scope.LocalMap[name] = my
--
return my
end]]
local scope = Scope:new(parent)
scope.RenameVars = scope.ObfuscateLocals
scope.ObfuscateVariables = scope.ObfuscateLocals
scope.Print = function() return "<Scope>" end
return scope
end
local ParseExpr
local ParseStatementList
local ParseSingleStatementList
local ParseSimpleExpr,
ParseSubExpr,
ParsePrimaryExpr,
ParseSuffixedExpr
local function ParseFunctionArgsAndBody(scope, tokenList)
local funcScope = CreateScope(scope)
if not tok:ConsumeSymbol('(', tokenList) then
return false, GenerateError("`(` expected.")
end
--arg list
local argList = {}
local isVarArg = false
while not tok:ConsumeSymbol(')', tokenList) do
if tok:Is('Ident') then
local arg = funcScope:CreateLocal(tok:Get(tokenList).Data)
argList[#argList+1] = arg
if not tok:ConsumeSymbol(',', tokenList) then
if tok:ConsumeSymbol(')', tokenList) then
break
else
return false, GenerateError("`)` expected.")
end
end
elseif tok:ConsumeSymbol('...', tokenList) then
isVarArg = true
if not tok:ConsumeSymbol(')', tokenList) then
return false, GenerateError("`...` must be the last argument of a function.")
end
break
else
return false, GenerateError("Argument name or `...` expected")
end
end
--body
local st, body = ParseStatementList(funcScope)
if not st then return false, body end
--end
if not tok:ConsumeKeyword('end', tokenList) then
return false, GenerateError("`end` expected after function body")
end
local nodeFunc = {}
nodeFunc.AstType = 'Function'
nodeFunc.Scope = funcScope
nodeFunc.Arguments = argList
nodeFunc.Body = body
nodeFunc.VarArg = isVarArg
nodeFunc.Tokens = tokenList
--
return true, nodeFunc
end
function ParsePrimaryExpr(scope)
local tokenList = {}
if tok:ConsumeSymbol('(', tokenList) then
local st, ex = ParseExpr(scope)
if not st then return false, ex end
if not tok:ConsumeSymbol(')', tokenList) then
return false, GenerateError("`)` Expected.")
end
if false then
--save the information about parenthesized expressions somewhere
ex.ParenCount = (ex.ParenCount or 0) + 1
return true, ex
else
local parensExp = {}
parensExp.AstType = 'Parentheses'
parensExp.Inner = ex
parensExp.Tokens = tokenList
return true, parensExp
end
elseif tok:Is('Ident') then
local id = tok:Get(tokenList)
local var = scope:GetLocal(id.Data)
if not var then
var = scope:GetGlobal(id.Data)
if not var then
var = scope:CreateGlobal(id.Data)
else
var.References = var.References + 1
end
else
var.References = var.References + 1
end
--
local nodePrimExp = {}
nodePrimExp.AstType = 'VarExpr'
nodePrimExp.Name = id.Data
nodePrimExp.Variable = var
nodePrimExp.Tokens = tokenList
--
return true, nodePrimExp
else
return false, GenerateError("primary expression expected")
end
end
function ParseSuffixedExpr(scope, onlyDotColon)
--base primary expression
local st, prim = ParsePrimaryExpr(scope)
if not st then return false, prim end
--
while true do
local tokenList = {}
if tok:IsSymbol('.') or tok:IsSymbol(':') then
local symb = tok:Get(tokenList).Data
if not tok:Is('Ident') then
return false, GenerateError("<Ident> expected.")
end
local id = tok:Get(tokenList)
local nodeIndex = {}
nodeIndex.AstType = 'MemberExpr'
nodeIndex.Base = prim
nodeIndex.Indexer = symb
nodeIndex.Ident = id
nodeIndex.Tokens = tokenList
--
prim = nodeIndex
elseif not onlyDotColon and tok:ConsumeSymbol('[', tokenList) then
local st, ex = ParseExpr(scope)
if not st then return false, ex end
if not tok:ConsumeSymbol(']', tokenList) then
return false, GenerateError("`]` expected.")
end
local nodeIndex = {}
nodeIndex.AstType = 'IndexExpr'
nodeIndex.Base = prim
nodeIndex.Index = ex
nodeIndex.Tokens = tokenList
--
prim = nodeIndex
elseif not onlyDotColon and tok:ConsumeSymbol('(', tokenList) then
local args = {}
while not tok:ConsumeSymbol(')', tokenList) do
local st, ex = ParseExpr(scope)
if not st then return false, ex end
args[#args+1] = ex
if not tok:ConsumeSymbol(',', tokenList) then
if tok:ConsumeSymbol(')', tokenList) then
break
else
return false, GenerateError("`)` Expected.")
end
end
end
local nodeCall = {}
nodeCall.AstType = 'CallExpr'
nodeCall.Base = prim
nodeCall.Arguments = args
nodeCall.Tokens = tokenList
--
prim = nodeCall
elseif not onlyDotColon and tok:Is('String') then
--string call
local nodeCall = {}
nodeCall.AstType = 'StringCallExpr'
nodeCall.Base = prim
nodeCall.Arguments = { tok:Get(tokenList) }
nodeCall.Tokens = tokenList
--
prim = nodeCall
elseif not onlyDotColon and tok:IsSymbol('{') then
--table call
local st, ex = ParseSimpleExpr(scope)
-- FIX: ParseExpr(scope) parses the table AND and any following binary expressions.
-- We just want the table
if not st then return false, ex end
local nodeCall = {}
nodeCall.AstType = 'TableCallExpr'
nodeCall.Base = prim
nodeCall.Arguments = { ex }
nodeCall.Tokens = tokenList
--
prim = nodeCall
else
break
end
end
return true, prim
end
function ParseSimpleExpr(scope)
local tokenList = {}
if tok:Is('Number') then
local nodeNum = {}
nodeNum.AstType = 'NumberExpr'
nodeNum.Value = tok:Get(tokenList)
nodeNum.Tokens = tokenList
return true, nodeNum
elseif tok:Is('String') then
local nodeStr = {}
nodeStr.AstType = 'StringExpr'
nodeStr.Value = tok:Get(tokenList)
nodeStr.Tokens = tokenList
return true, nodeStr
elseif tok:ConsumeKeyword('nil', tokenList) then
local nodeNil = {}
nodeNil.AstType = 'NilExpr'
nodeNil.Tokens = tokenList
return true, nodeNil
elseif tok:IsKeyword('false') or tok:IsKeyword('true') then
local nodeBoolean = {}
nodeBoolean.AstType = 'BooleanExpr'
nodeBoolean.Value = (tok:Get(tokenList).Data == 'true')
nodeBoolean.Tokens = tokenList
return true, nodeBoolean
elseif tok:ConsumeSymbol('...', tokenList) then
local nodeDots = {}
nodeDots.AstType = 'DotsExpr'
nodeDots.Tokens = tokenList
return true, nodeDots
elseif tok:ConsumeSymbol('{', tokenList) then
local v = {}
v.AstType = 'ConstructorExpr'
v.EntryList = {}
--
while true do
if tok:IsSymbol('[', tokenList) then
--key
tok:Get(tokenList)
local st, key = ParseExpr(scope)
if not st then
return false, GenerateError("Key Expression Expected")
end
if not tok:ConsumeSymbol(']', tokenList) then
return false, GenerateError("`]` Expected")
end
if not tok:ConsumeSymbol('=', tokenList) then
return false, GenerateError("`=` Expected")
end
local st, value = ParseExpr(scope)
if not st then
return false, GenerateError("Value Expression Expected")
end
v.EntryList[#v.EntryList+1] = {
Type = 'Key';
Key = key;
Value = value;
}
elseif tok:Is('Ident') then
--value or key
local lookahead = tok:Peek(1)
if lookahead.Type == 'Symbol' and lookahead.Data == '=' then
--we are a key
local key = tok:Get(tokenList)
if not tok:ConsumeSymbol('=', tokenList) then
return false, GenerateError("`=` Expected")
end
local st, value = ParseExpr(scope)
if not st then
return false, GenerateError("Value Expression Expected")
end
v.EntryList[#v.EntryList+1] = {
Type = 'KeyString';
Key = key.Data;
Value = value;
}
else
--we are a value
local st, value = ParseExpr(scope)
if not st then
return false, GenerateError("Value Exected")
end
v.EntryList[#v.EntryList+1] = {
Type = 'Value';
Value = value;
}
end
elseif tok:ConsumeSymbol('}', tokenList) then
break
else
--value
local st, value = ParseExpr(scope)
v.EntryList[#v.EntryList+1] = {
Type = 'Value';
Value = value;
}
if not st then
return false, GenerateError("Value Expected")
end
end
if tok:ConsumeSymbol(';', tokenList) or tok:ConsumeSymbol(',', tokenList) then
--all is good
elseif tok:ConsumeSymbol('}', tokenList) then
break
else
return false, GenerateError("`}` or table entry Expected")
end
end
v.Tokens = tokenList
return true, v
elseif tok:ConsumeKeyword('function', tokenList) then
local st, func = ParseFunctionArgsAndBody(scope, tokenList)
if not st then return false, func end
--
func.IsLocal = true
return true, func
else
return ParseSuffixedExpr(scope)
end
end
local unops = lookupify{'-', 'not', '#'}
local unopprio = 8
local priority = {
['>>'] = {6,6};
['<<'] = {6,6};
['|'] = {6,6};
['&'] = {6,6};
['+'] = {6,6};
['-'] = {6,6};
['%'] = {7,7};
['/'] = {7,7};
['*'] = {7,7};
['^'] = {10,9};
['..'] = {5,4};
['=='] = {3,3};
['<'] = {3,3};
['<='] = {3,3};
['~='] = {3,3};
['>'] = {3,3};
['>='] = {3,3};
['and'] = {2,2};
['or'] = {1,1};
}
function ParseSubExpr(scope, level)
--base item, possibly with unop prefix
local st, exp
if unops[tok:Peek().Data] then
local tokenList = {}
local op = tok:Get(tokenList).Data
st, exp = ParseSubExpr(scope, unopprio)
if not st then return false, exp end
local nodeEx = {}
nodeEx.AstType = 'UnopExpr'
nodeEx.Rhs = exp
nodeEx.Op = op
nodeEx.OperatorPrecedence = unopprio
nodeEx.Tokens = tokenList
exp = nodeEx
else
st, exp = ParseSimpleExpr(scope)
if not st then return false, exp end
end
--next items in chain
while true do
local prio = priority[tok:Peek().Data]
if prio and prio[1] > level then
local tokenList = {}
local op = tok:Get(tokenList).Data
local st, rhs = ParseSubExpr(scope, prio[2])
if not st then return false, rhs end
local nodeEx = {}
nodeEx.AstType = 'BinopExpr'
nodeEx.Lhs = exp
nodeEx.Op = op
nodeEx.OperatorPrecedence = prio[1]
nodeEx.Rhs = rhs
nodeEx.Tokens = tokenList
--
exp = nodeEx
else
break
end
end
return true, exp
end
ParseExpr = function(scope)
return ParseSubExpr(scope, 0)
end
local function ParseStatement(scope)
local stat = nil
local tokenList = {}
if tok:ConsumeKeyword('if', tokenList) then
--setup
local nodeIfStat = {}
nodeIfStat.AstType = 'IfStatement'
nodeIfStat.Clauses = {}
--clauses
repeat
local st, nodeCond = ParseExpr(scope)
if not st then return false, nodeCond end
local st, nodeBody = nil, nil
if not tok:ConsumeKeyword('then', tokenList) then
st, nodeBody = ParseSingleStatementList(scope)
if not st then return false, nodeBody end
nodeIfStat.SimpleIf = true
else
st, nodeBody = ParseStatementList(scope)
if not st then return false, nodeBody end
nodeIfStat.SimpleIf = false
end
nodeIfStat.Clauses[#nodeIfStat.Clauses+1] = {
Condition = nodeCond;
Body = nodeBody;
}
until not tok:ConsumeKeyword('elseif', tokenList)
--else clause
if tok:ConsumeKeyword('else', tokenList) then
local st, nodeBody = ParseStatementList(scope)
if not st then return false, nodeBody end
nodeIfStat.Clauses[#nodeIfStat.Clauses+1] = {
Body = nodeBody;
}
end
--end
if not nodeIfStat.SimpleIf and not tok:ConsumeKeyword('end', tokenList) then
return false, GenerateError("`end` expected.")
end
nodeIfStat.Tokens = tokenList
stat = nodeIfStat
elseif tok:ConsumeKeyword('while', tokenList) then
--setup
local nodeWhileStat = {}
nodeWhileStat.AstType = 'WhileStatement'
--condition
local st, nodeCond = ParseExpr(scope)
if not st then return false, nodeCond end
--do
if not tok:ConsumeKeyword('do', tokenList) then
return false, GenerateError("`do` expected.")
end
--body
local st, nodeBody = ParseStatementList(scope)
if not st then return false, nodeBody end
--end
if not tok:ConsumeKeyword('end', tokenList) then
return false, GenerateError("`end` expected.")
end
--return
nodeWhileStat.Condition = nodeCond
nodeWhileStat.Body = nodeBody
nodeWhileStat.Tokens = tokenList
stat = nodeWhileStat
elseif tok:ConsumeKeyword('do', tokenList) then
--do block
local st, nodeBlock = ParseStatementList(scope)
if not st then return false, nodeBlock end
if not tok:ConsumeKeyword('end', tokenList) then
return false, GenerateError("`end` expected.")
end
local nodeDoStat = {}
nodeDoStat.AstType = 'DoStatement'
nodeDoStat.Body = nodeBlock
nodeDoStat.Tokens = tokenList
stat = nodeDoStat
elseif tok:ConsumeKeyword('for', tokenList) then
--for block
if not tok:Is('Ident') then
return false, GenerateError("<ident> expected.")
end
local baseVarName = tok:Get(tokenList)
if tok:ConsumeSymbol('=', tokenList) then
--numeric for
local forScope = CreateScope(scope)
local forVar = forScope:CreateLocal(baseVarName.Data)
--
local st, startEx = ParseExpr(scope)
if not st then return false, startEx end
if not tok:ConsumeSymbol(',', tokenList) then
return false, GenerateError("`,` Expected")
end
local st, endEx = ParseExpr(scope)
if not st then return false, endEx end
local st, stepEx;
if tok:ConsumeSymbol(',', tokenList) then
st, stepEx = ParseExpr(scope)
if not st then return false, stepEx end
end
if not tok:ConsumeKeyword('do', tokenList) then
return false, GenerateError("`do` expected")
end
--
local st, body = ParseStatementList(forScope)
if not st then return false, body end
if not tok:ConsumeKeyword('end', tokenList) then
return false, GenerateError("`end` expected")
end
--
local nodeFor = {}
nodeFor.AstType = 'NumericForStatement'
nodeFor.Scope = forScope
nodeFor.Variable = forVar
nodeFor.Start = startEx
nodeFor.End = endEx
nodeFor.Step = stepEx
nodeFor.Body = body
nodeFor.Tokens = tokenList
stat = nodeFor
else
--generic for
local forScope = CreateScope(scope)
--
local varList = { forScope:CreateLocal(baseVarName.Data) }
while tok:ConsumeSymbol(',', tokenList) do
if not tok:Is('Ident') then
return false, GenerateError("for variable expected.")
end
varList[#varList+1] = forScope:CreateLocal(tok:Get(tokenList).Data)
end
if not tok:ConsumeKeyword('in', tokenList) then
return false, GenerateError("`in` expected.")
end
local generators = {}
local st, firstGenerator = ParseExpr(scope)
if not st then return false, firstGenerator end
generators[#generators+1] = firstGenerator
while tok:ConsumeSymbol(',', tokenList) do
local st, gen = ParseExpr(scope)
if not st then return false, gen end
generators[#generators+1] = gen
end
if not tok:ConsumeKeyword('do', tokenList) then
return false, GenerateError("`do` expected.")
end
local st, body = ParseStatementList(forScope)
if not st then return false, body end
if not tok:ConsumeKeyword('end', tokenList) then
return false, GenerateError("`end` expected.")
end
--
local nodeFor = {}
nodeFor.AstType = 'GenericForStatement'
nodeFor.Scope = forScope
nodeFor.VariableList = varList
nodeFor.Generators = generators
nodeFor.Body = body
nodeFor.Tokens = tokenList
stat = nodeFor
end
elseif tok:ConsumeKeyword('repeat', tokenList) then
local st, body = ParseStatementList(scope)
if not st then return false, body end
--
if not tok:ConsumeKeyword('until', tokenList) then
return false, GenerateError("`until` expected.")
end
-- FIX: Used to parse in parent scope
-- Now parses in repeat scope
local st, cond = ParseExpr(body.Scope)
if not st then return false, cond end
--
local nodeRepeat = {}
nodeRepeat.AstType = 'RepeatStatement'
nodeRepeat.Condition = cond
nodeRepeat.Body = body
nodeRepeat.Tokens = tokenList
stat = nodeRepeat
elseif tok:ConsumeKeyword('function', tokenList) then
if not tok:Is('Ident') then
return false, GenerateError("Function name expected")
end
local st, name = ParseSuffixedExpr(scope, true) --true => only dots and colons
if not st then return false, name end
--
local st, func = ParseFunctionArgsAndBody(scope, tokenList)
if not st then return false, func end
--
func.IsLocal = false
func.Name = name
stat = func
elseif tok:ConsumeKeyword('local', tokenList) then
if tok:Is('Ident') then
local varList = { tok:Get(tokenList).Data }
while tok:ConsumeSymbol(',', tokenList) do
if not tok:Is('Ident') then
return false, GenerateError("local var name expected")
end
varList[#varList+1] = tok:Get(tokenList).Data
end
local initList = {}
if tok:ConsumeSymbol('=', tokenList) then
repeat
local st, ex = ParseExpr(scope)
if not st then return false, ex end
initList[#initList+1] = ex
until not tok:ConsumeSymbol(',', tokenList)
end
--now patch var list
--we can't do this before getting the init list, because the init list does not
--have the locals themselves in scope.
for i, v in pairs(varList) do
varList[i] = scope:CreateLocal(v)
end
local nodeLocal = {}
nodeLocal.AstType = 'LocalStatement'
nodeLocal.LocalList = varList
nodeLocal.InitList = initList
nodeLocal.Tokens = tokenList
--
stat = nodeLocal
elseif tok:ConsumeKeyword('function', tokenList) then
if not tok:Is('Ident') then
return false, GenerateError("Function name expected")
end
local name = tok:Get(tokenList).Data
local localVar = scope:CreateLocal(name)
--
local st, func = ParseFunctionArgsAndBody(scope, tokenList)
if not st then return false, func end
--
func.Name = localVar
func.IsLocal = true
stat = func
else
return false, GenerateError("local var or function def expected")
end
elseif tok:ConsumeSymbol('::', tokenList) then
if not tok:Is('Ident') then
return false, GenerateError('Label name expected')
end
local label = tok:Get(tokenList).Data
if not tok:ConsumeSymbol('::', tokenList) then
return false, GenerateError("`::` expected")
end
local nodeLabel = {}
nodeLabel.AstType = 'LabelStatement'
nodeLabel.Label = label
nodeLabel.Tokens = tokenList
stat = nodeLabel
elseif tok:ConsumeKeyword('return', tokenList) then
local exList = {}
if not tok:IsKeyword('end') then
local st, firstEx = ParseExpr(scope)
if st then
exList[1] = firstEx
while tok:ConsumeSymbol(',', tokenList) do
local st, ex = ParseExpr(scope)
if not st then return false, ex end
exList[#exList+1] = ex
end
end
end
local nodeReturn = {}
nodeReturn.AstType = 'ReturnStatement'
nodeReturn.Arguments = exList
nodeReturn.Tokens = tokenList
stat = nodeReturn
elseif tok:ConsumeKeyword('break', tokenList) then
local nodeBreak = {}
nodeBreak.AstType = 'BreakStatement'
nodeBreak.Tokens = tokenList
stat = nodeBreak
elseif tok:ConsumeKeyword('goto', tokenList) then
if not tok:Is('Ident') then
return false, GenerateError("Label expected")
end
local label = tok:Get(tokenList).Data
local nodeGoto = {}
nodeGoto.AstType = 'GotoStatement'
nodeGoto.Label = label
nodeGoto.Tokens = tokenList
stat = nodeGoto
else
--statementParseExpr
local st, suffixed = ParseSuffixedExpr(scope)
if not st then return false, suffixed end
--assignment or call?
if tok:IsSymbol(',') or tok:IsSymbol('=') or tok:IsSymbol('+') or tok:IsSymbol('*') or tok:IsSymbol('/') or tok:IsSymbol('-') then
local nodeAssign = {}
nodeAssign.AstType = 'AssignmentStatement'
--check that it was not parenthesized, making it not an lvalue
if (suffixed.ParenCount or 0) > 0 then
return false, GenerateError("Can not assign to parenthesized expression, is not an lvalue")
end
--end operations
local compoundOperator = tok:Peek()
if tok:ConsumeSymbol('+') or tok:ConsumeSymbol('-') or tok:ConsumeSymbol('*') or tok:ConsumeSymbol('/')then
if tok:IsSymbol('=') then
nodeAssign.AstType = 'CompoundAssignmentStatement'
nodeAssign.CompoundType = compoundOperator.Data
end
end
--more processing needed
local lhs = { suffixed }
while tok:ConsumeSymbol(',', tokenList) do
local st, lhsPart = ParseSuffixedExpr(scope)
if not st then return false, lhsPart end
lhs[#lhs+1] = lhsPart
end
--equals
if not tok:ConsumeSymbol('=', tokenList) then
return false, GenerateError("`=` Expected.")
end
--rhs
local rhs = {}
local st, firstRhs = ParseExpr(scope)
if not st then return false, firstRhs end
rhs[1] = firstRhs
while tok:ConsumeSymbol(',', tokenList) do
local st, rhsPart = ParseExpr(scope)
if not st then return false, rhsPart end
rhs[#rhs+1] = rhsPart
end
--done
nodeAssign.Lhs = lhs
nodeAssign.Rhs = rhs
nodeAssign.Tokens = tokenList
stat = nodeAssign
elseif suffixed.AstType == 'CallExpr' or
suffixed.AstType == 'TableCallExpr' or
suffixed.AstType == 'StringCallExpr'
then
--it's a call statement
local nodeCall = {}
nodeCall.AstType = 'CallStatement'
nodeCall.Expression = suffixed
nodeCall.Tokens = tokenList
stat = nodeCall
else
return false, GenerateError("Assignment Statement Expected")
end
end
if tok:IsSymbol(';') then
stat.Semicolon = tok:Get( stat.Tokens )
end
return true, stat
end
local statListCloseKeywords = lookupify{'end', 'else', 'elseif', 'until'}
ParseStatementList = function(scope)
local nodeStatlist = {}
nodeStatlist.Scope = CreateScope(scope)
nodeStatlist.AstType = 'Statlist'
nodeStatlist.Body = { }
nodeStatlist.Tokens = { }
--
--local stats = {}
--
while not statListCloseKeywords[tok:Peek().Data] and not tok:IsEof() do
local st, nodeStatement = ParseStatement(nodeStatlist.Scope)
if not st then return false, nodeStatement end
--stats[#stats+1] = nodeStatement
nodeStatlist.Body[#nodeStatlist.Body + 1] = nodeStatement
end
if tok:IsEof() then
local nodeEof = {}
nodeEof.AstType = 'Eof'
nodeEof.Tokens = { tok:Get() }
nodeStatlist.Body[#nodeStatlist.Body + 1] = nodeEof
end
--
--nodeStatlist.Body = stats
return true, nodeStatlist
end
ParseSingleStatementList = function(scope)
local nodeStatlist = {}
nodeStatlist.Scope = CreateScope(scope)
nodeStatlist.AstType = 'Statlist'
nodeStatlist.Body = { }
nodeStatlist.Tokens = { }
--
--local stats = {}
--
local st, nodeStatement = ParseStatement(nodeStatlist.Scope)
if not st then return false, nodeStatement end
--stats[#stats+1] = nodeStatement
nodeStatlist.Body[#nodeStatlist.Body + 1] = nodeStatement
if tok:IsEof() then
local nodeEof = {}
nodeEof.AstType = 'Eof'
nodeEof.Tokens = { tok:Get() }
nodeStatlist.Body[#nodeStatlist.Body + 1] = nodeEof
end
--
--nodeStatlist.Body = stats
return true, nodeStatlist
end
local function mainfunc()
local topScope = CreateScope()
return ParseStatementList(topScope)
end
local st, main = mainfunc()
--print("Last Token: "..PrintTable(tok:Peek()))
return st, main
end
return { LexLua = LexLua, ParseLua = ParseLua }
|
padding = 2
mithralConstraints = {
InTileRange(
{padding, gir("GroundLine") + padding},
{gir("TileWidth") - padding, gir("TileHeight") - padding}
),
HasAllTags("ground"),
HasAttributes("open", Equal, 0),
}
mithralSolver = ConstraintSolver(mithralConstraints)
mithralSolver:Solve()
base = mithralSolver.pickedTile
base:AddTag("mithral")
reg = CreateRegion()
reg:AddTile(base)
local t1 = nil
local t2 = nil
if (base.hexPos.y > (gir("GroundHeight") / 2)) then
-- bottom part of the field; face down
reg:AddTag("mithralDOWN")
t1 = GetTileAtIndex(base.neighborNE)
t2 = GetTileAtIndex(base.neighborNW)
else
-- top part of the field; face up
reg:AddTag("mithralUP")
t1 = GetTileAtIndex(base.neighborSE)
t2 = GetTileAtIndex(base.neighborSW)
end
t1:AddTag("mithral")
t2:AddTag("mithral")
reg:AddTile(t1)
reg:AddTile(t2)
|
slot0 = class("PlayerSecondSummaryInfoScene", import("...base.BaseUI"))
slot0.getUIName = function (slot0)
return "PlayerSecondSummaryUI"
end
slot0.setActivity = function (slot0, slot1)
slot0.activityVO = slot1
end
slot0.setPlayer = function (slot0, slot1)
slot0.palyerVO = slot1
end
slot0.setSummaryInfo = function (slot0, slot1)
slot0.summaryInfoVO = slot1
end
slot0.init = function (slot0)
slot0.backBtn = slot0:findTF("bg/back_btn")
slot0.pageContainer = slot0:findTF("bg/main/pages")
slot0.pageFootContainer = slot0:findTF("bg/main/foots")
setActive(slot0.pageFootContainer, false)
end
slot0.didEnter = function (slot0)
if slot0.summaryInfoVO then
slot0:initSummaryInfo()
else
slot0:emit(PlayerSummaryInfoMediator.GET_PLAYER_SUMMARY_INFO)
end
onButton(slot0, slot0.backBtn, function ()
if slot0:inAnim() then
return
end
slot0:closeView()
end, SFX_CANCEL)
end
slot0.inAnim = function (slot0)
return slot0.inAniming or (slot0.currPage and slot0.pages[slot0.currPage]:inAnim())
end
slot0.initSummaryInfo = function (slot0)
slot0.loadingPage = SecondSummaryPage1.New(slot0:findTF("page1", slot0.pageContainer))
slot0.loadingPage:Init(slot0.summaryInfoVO)
slot0.pages = {}
slot1(slot0.pageContainer:Find("page2"), SecondSummaryPage2, slot0.summaryInfoVO)
slot1(slot0.pageContainer:Find("page3"), SecondSummaryPage3, slot0.summaryInfoVO)
setActive(slot2, false)
for slot7 = 1, math.floor((#slot0.activityVO:getConfig("config_data") - 1) / SecondSummaryPage4.PerPageCount) + 1, 1 do
slot1(cloneTplTo(slot2, slot0.pageContainer, "page4_1_" .. slot7), SecondSummaryPage4, setmetatable({
pageType = SecondSummaryPage4.PageTypeFurniture,
samePage = slot7,
activityVO = slot0.activityVO
}, {
__index = slot0.summaryInfoVO
}))
end
for slot7 = 1, math.floor((#slot0.activityVO:getConfig("config_client") - 1) / SecondSummaryPage4.PerPageCount) + 1, 1 do
slot1(cloneTplTo(slot2, slot0.pageContainer, "page4_2_" .. slot7), SecondSummaryPage4, setmetatable({
pageType = SecondSummaryPage4.PageTypeIconFrame,
samePage = slot7,
activityVO = slot0.activityVO
}, {
__index = slot0.summaryInfoVO
}))
end
slot1(slot0.pageContainer:Find("page5"), SecondSummaryPage5, slot0.summaryInfoVO)
onButton(slot0, slot0:findTF("page5/share", slot0.pageContainer), function ()
pg.ShareMgr.GetInstance():Share(pg.ShareMgr.TypeSecondSummary)
end, SFX_CONFIRM)
seriesAsync({
function (slot0)
slot0.inAniming = true
slot0.loadingPage:Show(slot0)
end,
function (slot0)
slot0.inAniming = false
slot0.loadingPage:Hide()
slot0:registerFootEvent()
slot0:registerDrag()
slot0()
end
}, function ()
setActive(slot0.pageFootContainer, true)
setActive:updatePageFoot(1)
end)
end
slot0.registerFootEvent = function (slot0)
slot1 = UIItemList.New(slot0.pageFootContainer, slot0.pageFootContainer:Find("dot"))
slot1:make(function (slot0, slot1, slot2)
slot3 = slot1 + 1
if slot0 == UIItemList.EventUpdate then
onToggle(slot0, slot2, function (slot0)
if slot0 then
slot0.pages[]:Show()
slot0.currPage = slot0
else
slot0.pages[slot0.currPage]:Hide()
end
end)
end
end)
slot1.align(slot1, #slot0.pages)
end
slot0.registerDrag = function (slot0)
slot0:addVerticalDrag(slot0:findTF("bg"), function ()
slot0:updatePageFoot(slot0.currPage - 1)
end, function ()
slot0:updatePageFoot(slot0.currPage + 1)
end)
end
slot0.updatePageFoot = function (slot0, slot1)
if slot0:inAnim() or not slot0.pages[slot1] then
return
end
triggerToggle(slot0.pageFootContainer:GetChild(slot1 - 1), true)
end
slot0.addVerticalDrag = function (slot0, slot1, slot2, slot3)
slot4 = GetOrAddComponent(slot1, "EventTriggerListener")
slot5 = nil
slot6 = 0
slot7 = 50
slot4:AddBeginDragFunc(function (slot0, slot1)
slot0 = 0
slot1 = slot1.position
end)
slot4.AddDragFunc(slot4, function (slot0, slot1)
slot0 = slot1.position.x - slot1.x
end)
slot4.AddDragEndFunc(slot4, function (slot0, slot1)
if slot0 < -slot1 then
if slot2 then
slot2()
end
elseif slot1 < slot0 and slot3 then
slot3()
end
end)
end
slot0.willExit = function (slot0)
for slot4, slot5 in pairs(slot0.pages) do
slot5:Dispose()
end
slot0.pages = nil
slot0.currPage = nil
end
return slot0
|
------------------------------------------------------------------------------
-- LuaSOAP support to WSDL semi-automatic generation.
-- See Copyright Notice in license.html
------------------------------------------------------------------------------
local assert, error, ipairs, pairs = assert, error, ipairs, pairs
local soap = require"soap"
local strformat = require"string".format
local tconcat = require"table".concat
local qname_patt = "^%w*%:%w*$"
local M = {
_COPYRIGHT = "Copyright (C) 2015-2020 Kepler Project",
_DESCRIPTION = "LuaSOAP provides a very simple API that convert Lua tables to and from XML documents",
_VERSION = "LuaSOAP 4.0 WSDL generation helping functions",
}
-- internal data structure details
-- self.name -- service name
-- self.encoding -- string with XML encoding
-- self.targetNamespace -- target namespace
-- self.otherNamespaces -- optional table with other namespaces
-- self.url
-- self.wsdl -- string with complete WSDL document
-- self.types[..] -- table indexed by numbers (to guarantee the order of type definitions)
-- self.methods[methodName] -- table indexed by strings (each method name)
-- request -- table
-- name -- string with message request name
-- [..] -- table with parameter definitions
-- name -- string with part name
-- element -- string with type element's name (optional)
-- type -- string with type (simple or complex) name (optional)
-- response -- idem
-- namespace -- string with qualifying namespace (optional)
-- portTypeName -- string with portType name attribute
-- bindingName -- string with binding name attribute
------------------------------------------------------------------------------
-- Produce WSDL definitions tag.
------------------------------------------------------------------------------
function M:gen_definitions ()
return strformat([[
<wsdl:definitions
xmlns:http="http://schemas.xmlsoap.org/wsdl/http/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:wsoap12="http://schemas.xmlsoap.org/wsdl/soap12/"
xmlns:s="http://www.w3.org/2001/XMLSchema"
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:tns="%s"
xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/"
targetNamespace="%s"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" %s>]],
self.targetNamespace, self.targetNamespace, soap.attrs (self.otherNamespaces))
end
------------------------------------------------------------------------------
-- Produce WSDL types tag.
------------------------------------------------------------------------------
function M:gen_types ()
if not self.types then
return ''
end
local all_types = {
tag = "wsdl:types",
{
tag = "s:schema",
attr = {
elementFormDefault = "qualified",
targetNamespace = self.targetNamespace,
},
}
}
for _ , elem in ipairs (self.types) do
all_types[1][ #all_types[1] + 1] = elem
end
return soap.serialize (all_types)
end
--=--------------------------------------------------------------------------
-- Produce a message tag.
-- generate one <wsdl:message> element with N <wsdl:part> elements inside it.
-- @param elem Table with message description.
-- @param method_name String with type of message ("request" or "response" or "fault").
-- @return String with a <wsdl:message>.
--=--------------------------------------------------------------------------
local function gen_message (elem, method_name)
local message = {
tag = "wsdl:message",
attr = {
name = assert (elem.name , method_name.." Message MUST have a name!"),
},
}
for i=1, #elem do
message[i] = {
tag = "wsdl:part",
attr = {
name = assert (elem[i].name , method_name.." Message part MUST have a name!"),
},
}
if elem[i].element then
message[i].attr.element = assert (elem[i].element:match(qname_patt), method_name.." Element must be qualified '"..elem[i].element.."'")
elseif elem[i].type then
message[i].attr.type = assert (elem[i].type:match(qname_patt), method_name.." Type must be qualified '"..elem[i].type.."'")
else
error ("Incomplete description: "..method_name.." in "..elem[i].name.." parameters MUST have an 'element' or a 'type' attribute")
end
end
return soap.serialize (message)
end
------------------------------------------------------------------------------
-- Produce the message tags for each method: request, response, fault.
-- generate two <wsdl:message> elements for each method.
-- @return String with all <wsdl:message>s.
------------------------------------------------------------------------------
function M:gen_messages ()
local m = {}
for method_name, desc in pairs (self.methods) do
if desc.request then
m[#m+1] = gen_message (desc.request, method_name )
end
if desc.response then
m[#m+1] = gen_message (desc.response, method_name )
end
if desc.fault then
m[#m+1] = gen_message (desc.fault, method_name )
end
end
return tconcat (m)
end
--=---------------------------------------------------------------------------
-- Produce portType tag.
-- @param desc Table describing a method.
-- @param method_name String with the method name.
--=---------------------------------------------------------------------------
local function gen_portType (desc, method_name)
local op = {
tag = "wsdl:operation",
attr = {
name = method_name,
--[parameterOrder], why would you need that in Lua?!
},
}
local portType = {
tag = "wsdl:portType",
attr = {
name = assert (desc.portTypeName , method_name.." You MUST have a portTypeName!"),
},
op,
}
local ns = desc.namespace or "tns:"
if desc.request then
op[ #op + 1] = {
tag = "wsdl:input",
attr = { message = ns..assert (desc.request.name, "The field 'name' is mandatory when there is a request") },
}
end
if desc.response then
op[ #op + 1] = {
tag = "wsdl:output",
attr = { message = ns..assert (desc.response.name, "The field 'name' is mandatory when there is a response") },
}
end
if desc.fault then
op[ #op + 1] = {
tag = "wsdl:fault",
attr = {
name = assert (desc.fault.name, "Fault name for '"..method_name.."' is mandatory when there is a fault element"),
message = ns..desc.fault.name,
},
}
end
return soap.serialize (portType)
end
------------------------------------------------------------------------------
-- Produce the portType tags for each method.
------------------------------------------------------------------------------
function M:gen_portTypes ()
local p = {}
for method_name, desc in pairs (self.methods) do
p[#p+1] = gen_portType (desc, method_name)
end
return tconcat (p)
end
--=---------------------------------------------------------------------------
local soap_attr = {
transport = "http://schemas.xmlsoap.org/soap/http", -- Other URI may be used
style = "document", --TODO "rpc"
}
local get_attr = {
verb = "GET",
}
local post_attr = {
verb = "POST",
}
local binding_tags = {
["1.1"] = { tag = "soap:binding", attr = soap_attr, },
["1.2"] = { tag = "wsoap12:binding", attr = soap_attr, },
--["GET"] = { tag = "http:binding", attr = get_attr, },
--["POST"] = { tag = "http:binding", attr = post_attr, },
}
binding_tags[1.1] = binding_tags["1.1"]
binding_tags[1.2] = binding_tags["1.2"]
local function gen_binding_mode (mode, desc)
return binding_tags[mode]
end
--=---------------------------------------------------------------------------
local operation_tags = {
["1.1"] = { tag = "soap:operation", attr = { soapAction = "To be filled", style = "document"}, }, --TODO "rpc"
["1.2"] = { tag = "wsoap12:operation", attr = { soapAction = "To be filled", style = "document"}, },
--["GET"] = { tag = "http:operation", attr = {}, },
--["POST"] = { tag = "http:operation", attr = {}, },
}
operation_tags[1.1] = operation_tags["1.1"]
operation_tags[1.2] = operation_tags["1.2"]
local function gen_binding_operation (mode, url)
operation_tags[mode].attr.soapAction = url
return operation_tags[mode]
end
--=---------------------------------------------------------------------------
local body_tags = {
[1.1] = { tag = "soap:body", attr = { use = "literal" }, },
[1.2] = { tag = "wsoap12:body", attr = { use = "literal" }, },
--["GET"] = { tag = "http:binding", attr = {}, },
--["POST"] = { tag = "http:binding", attr = {}, },
}
body_tags["1.1"] = body_tags[1.1]
body_tags["1.2"] = body_tags[1.2]
local function gen_binding_op_body (mode, desc)
return body_tags[mode]
end
--=---------------------------------------------------------------------------
local body_fault_tags = {
[1.1] = { tag = "soap:body", attr = { name = "To be filled", use = "literal" }, },
[1.2] = { tag = "wsoap12:body", attr = { name = "To be filled", use = "literal" }, },
--["GET"] = { tag = "http:binding", attr = {}, },
--["POST"] = { tag = "http:binding", attr = {}, },
}
body_fault_tags["1.1"] = body_fault_tags[1.1]
body_fault_tags["1.2"] = body_fault_tags[1.2]
local function gen_binding_op_body_fault (mode, desc)
body_fault_tags[mode].attr.name = desc.fault.name
return body_fault_tags[mode]
end
--=---------------------------------------------------------------------------
-- Generate binding
local function gen_binding (desc, method_name, url, mode)
local op = {
tag = "wsdl:operation",
attr = { name = method_name },
gen_binding_operation (mode, url)
}
local binding = {
tag = "wsdl:binding",
attr = {
name = assert (desc.bindingName..tostring(mode) , method_name.."You MUST have a bindingName!"),
type = ( desc.namespace or "tns:")..desc.portTypeName,
},
gen_binding_mode(mode, desc),
op,
}
if desc.request then
op[ #op +1] = {
tag = "wsdl:input",
gen_binding_op_body (mode, desc),
}
end
if desc.response then
op[ #op +1] = {
tag = "wsdl:output",
gen_binding_op_body (mode, desc),
}
end
if desc.fault then
op[ #op +1] = {
tag = "wsdl:fault",
gen_binding_op_body_fault (mode, desc),
}
end
return soap.serialize (binding)
end
------------------------------------------------------------------------------
-- Produce the bindings for each method according to each mode.
-- @return String.
------------------------------------------------------------------------------
function M:gen_bindings ()
local tm = type (self.mode)
assert (tm == "table", "Unexpected 'mode' type: "..tm.." (expecting a table)")
local b = {}
for _, mode in ipairs(self.mode) do
for method_name, desc in pairs (self.methods) do
b[#b+1] = gen_binding (desc, method_name, self.url, mode)
end
end
return tconcat (b)
end
--=---------------------------------------------------------------------------
-- Generate port
local address_tags = {
["1.1"] = "soap:address",
["1.2"] = "wsoap12:address",
--["GET"] = "http:address",
--["POST"] = "http:address",
}
address_tags[1.1] = address_tags["1.1"]
address_tags[1.2] = address_tags["1.2"]
local function gen_port (desc, url, mode)
local port = {
tag = "wsdl:port",
attr = {
name = desc.bindingName..tostring(mode),
binding = (desc.namespace or "tns:")..desc.bindingName..tostring(mode),
},
[1] = {
tag = address_tags[mode],
attr = { location = url },
},
}
return port
end
------------------------------------------------------------------------------
-- Produce the service tag.
------------------------------------------------------------------------------
function M:gen_service ()
local tm = type (self.mode)
assert (tm == "table", "Unexpected 'mode' type: "..tm.." (expecting a table)")
local service = {
tag = "wsdl:service",
attr = {
name = self.name,
},
}
for _, mode in ipairs(self.mode) do
for method_name, desc in pairs (self.methods) do
service[#service+1] = gen_port (desc, self.url, mode)
end
end
return soap.serialize (service)
end
------------------------------------------------------------------------------
-- Produce the WSDL document.
-- @return String with the WSDL definition.
------------------------------------------------------------------------------
function M:generate_wsdl ()
if self.wsdl then
return self.wsdl
end
local doc = {
self:gen_definitions (),
self:gen_types (),
self:gen_messages (),
self:gen_portTypes (),
self:gen_bindings (),
self:gen_service (),
"</wsdl:definitions>",
}
return tconcat (doc)
end
------------------------------------------------------------------------------
return M
|
-- =============================================================
-- Copyright Roaming Gamer, LLC. 2008-2018 (All Rights Reserved)
-- =============================================================
-- Collision Calculator
-- =============================================================
local function rpad(str, len, char)
if char == nil then char = ' ' end
return str .. string.rep(char, len - #str)
end
local ccmgr
ccmgr = {}
-- ==
-- ssk.ccmgr:newCalculator() - Creates a blank (unconfigured) collision calculator.
-- val - The value to round.
-- n - Number of decimal places to round to.
-- Returns a collision calculator instance (myCC).
-- ==
function ccmgr:newCalculator()
local collisionsCalculator = {}
collisionsCalculator._colliderNum = {}
collisionsCalculator._colliderCategoryBits = {}
collisionsCalculator._colliderMaskBits = {}
collisionsCalculator._knownCollidersCount = 0
-- ==
-- myCC:addName( colliderName ) - Add new 'named' collider type to known list of collider types, and
-- automatically assign a number to this collider type (16 Max).
--
-- colliderName - String containing name for new collider type.
--
-- Returns true if named type was successfully added to known colliders list, false otherwise.
-- ==
function collisionsCalculator:addName( colliderName )
colliderName = string.lower(colliderName)
if(not self._colliderNum[colliderName]) then
-- Be sure we don't create more than 16 named collider types
if( self._knownCollidersCount == 16 ) then
return false
end
local newColliderNum = self._knownCollidersCount + 1
self._knownCollidersCount = newColliderNum
self._colliderNum[colliderName] = newColliderNum
self._colliderCategoryBits[colliderName] = 2 ^ (newColliderNum - 1)
self._colliderMaskBits[colliderName] = 0
end
return true
end
function collisionsCalculator:addNames( ... )
for key, value in ipairs(arg) do
self:addName( string.lower(value) )
--print("Added name:", value)
end
end
-- PRIVATE - DO NOT USE IN YOUR GAME CODE
function collisionsCalculator:configureCollision( colliderNameA, colliderNameB )
colliderNameA = string.lower(colliderNameA)
colliderNameB = string.lower(colliderNameB)
--
-- Verify both colliders exist before attempting to configure them:
--
if( not self._colliderNum[colliderNameA] ) then
print("Error: collidesWith() - Unknown collider: " .. colliderNameA)
return false
end
if( not self._colliderNum[colliderNameB] ) then
print("Error: collidesWith() - Unknown collider: " .. colliderNameB)
return false
end
-- Add the CategoryBit for A to B's collider mask and vice versa
-- Note: The if() statements encapsulating this setup work ensure
-- that the faked bitwise operation is only done once
local colliderCategoryBitA = self._colliderCategoryBits[colliderNameA]
local colliderCategoryBitB = self._colliderCategoryBits[colliderNameB]
if( (self._colliderMaskBits[colliderNameA] % (2 * colliderCategoryBitB) ) < colliderCategoryBitB ) then
self._colliderMaskBits[colliderNameA] = self._colliderMaskBits[colliderNameA] + colliderCategoryBitB
end
if( (self._colliderMaskBits[colliderNameB] % (2 * colliderCategoryBitA) ) < colliderCategoryBitA ) then
self._colliderMaskBits[colliderNameB] = self._colliderMaskBits[colliderNameB] + colliderCategoryBitA
end
return true
end
-- ==
-- myCC:collidesWith( colliderNameA, ... ) - Automatically configure named collider A to collide with one or more
-- other named colliders.
--
-- Note: The algorithm used is fully associative, so configuring typeA to collide with typeB
-- automatically configures typeB too.
--
-- colliderNameA - A string containing the name of the collider that is being configured.
-- ... - One or more strings identifying previously added collider types that collide with colliderNameA.
--
-- Returns true if named type was successfully added to known colliders list, false otherwise.
-- ==
function collisionsCalculator:collidesWith_legacy( colliderNameA, ... )
for key, value in ipairs(arg) do
self:configureCollision( colliderNameA, value )
end
end
function collisionsCalculator:collidesWith( colliderName, otherColliders )
for key, value in ipairs(otherColliders) do
self:configureCollision( colliderName, value )
end
end
-- ==
-- myCC:getCategoryBits( colliderName ) - Get category bits for the named collider.
--
-- Note: Rarely used. Use the getCollisionFilter() function instead.
--
-- colliderName - A string containing the name of the collider you want the CategoryBits for.
--
-- Returns a number representing the CategoryBits for the named collider.
-- ==
function collisionsCalculator:getCategoryBits( colliderName )
colliderName = string.lower(colliderName)
return self._colliderMaskBits[colliderName]
end
-- ==
-- myCC:getMaskBits( colliderName ) - Get mask bits for the named collider.
--
-- Note: Rarely used. Use the getCollisionFilter() function instead.
-- colliderName - A string containing the name of the collider you want the MaskBits for.
--
-- Returns a number representing the MaskBits for the named collider.
-- ==
function collisionsCalculator:getMaskBits( colliderName )
colliderName = string.lower(colliderName)
return self._colliderCategoryBits[colliderName]
end
-- ==
-- myCC:getCollisionFilter( colliderName ) - Get collision filter for the named collider.
--
-- colliderName - A string containing the name of the collider you want the CollisionFilter for.
--
-- Returns CategoryBits and the MaskBits.
-- ==
function collisionsCalculator:getCollisionFilter( colliderName )
colliderName = string.lower(colliderName)
local collisionFilter =
{
categoryBits = self._colliderCategoryBits[colliderName],
maskBits = self._colliderMaskBits[colliderName],
}
return collisionFilter
end
-- ==
-- myCC:dump() - (Debug Feature) Prints collider names, numbers, category bits, and masks.
-- ==
function collisionsCalculator:dump()
print("*********************************************\n")
print("Dumping collision settings...")
print("name | num | cat bits | col mask")
print("-------------- | --- | -------- | --------")
for colliderName, colliderNum in pairs(self._colliderNum) do
print(rpad(colliderName,15,' ') .. "| "..
rpad(tostring(colliderNum),4,' ') .. "| "..
rpad(tostring(self._colliderCategoryBits[colliderName]),9,' ') .. "| "..
rpad(tostring(self._colliderMaskBits[colliderName]),8,' '))
end
print("\n*********************************************\n")
end
return collisionsCalculator
end
_G.ssk.cc = ccmgr
return ccmgr |
local dependencies = {
proptypes = {
git = "https://github.com/AmaranthineCodices/rbx-prop-types.git",
version = "master"
}
}
local lfs = require("lfs")
lfs.mkdir("lib")
assert(lfs.chdir("lib"))
for name, dependency in pairs(dependencies) do
os.execute(("git clone --depth=1 %s %s"):format(
dependency.git,
name
))
assert(lfs.chdir(name))
os.execute(("git checkout %s"):format(
dependency.version
))
assert(lfs.chdir(".."))
end |
local t = require( "taptest" )
local readlines = require( "readlines" )
local same = require( "same" )
f = io.open( "ReadLinesXmpl.txt", "w" )
f:write( "a ", "long ", "text\n\n", "is ", 1337 )
f:close()
strlst, err = readlines( "ReadLinesXmpl.txt" )
t( same( strlst, { "a long text", "", "is 1337" } ), true )
os.remove( "ReadLinesXmpl.txt" )
t()
|
---
-- PostProcessor.lua - Appearance modification post processor
--
local PostProcessor = {}
local kDialogueParts = {
Rika = "HeadNipah",
Sekibanki = "headFX",
}
function PostProcessor.optionChanged(app, option, prev, new)
if option == "Dialogue" then
local needsSave = false
-- Auto-detach
if kDialogueParts[prev] then
app:save(kDialogueParts[prev], false)
needsSave = true
end
-- Auto-attach
if kDialogueParts[new] then
app:save(kDialogueParts[new], true)
needsSave = true
end
if needsSave then
app:fireUpdate()
end
end
end
return PostProcessor
|
local chooseGoodsLayer=
{
name="chooseGoodsLayer",type=0,typeName="View",time=0,report=0,x=0,y=0,width=0,height=0,visible=1,fillParentWidth=1,fillParentHeight=1,nodeAlign=kAlignTopLeft,
{
name="bgImage",type=1,typeName="Image",time=65255603,report=0,x=-1,y=-109,width=1280,height=800,visible=1,fillParentWidth=1,fillParentHeight=1,nodeAlign=kAlignTopLeft,file="hall/common/bg_shiled.png"
},
{
name="contentBg",type=1,typeName="Image",time=65255641,report=0,x=0,y=0,width=925,height=565,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,file="hall/common/popupWindow/popupWindow_bg_55_55_55_55.png",gridLeft=55,gridRight=55,gridTop=55,gridBottom=55,
{
name="title",type=1,typeName="Image",time=65255854,report=0,x=0,y=-55,width=617,height=190,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTop,file="hall/common/popupWindow/popupWindow_redTitle.png",
{
name="title",type=4,typeName="Text",time=65255964,report=0,x=0,y=-5,width=0,height=0,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,fontSize=34,textAlign=kAlignCenter,colorRed=255,colorGreen=235,colorBlue=186,string=[[首次充值独享礼包]]
}
},
{
name="closeBtn",type=2,typeName="Button",time=65255743,report=0,x=-15,y=-15,width=60,height=60,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTopRight,file="hall/common/popupWindow/popupWindow_close.png"
},
{
name="topTipBg",type=1,typeName="Image",time=72001345,report=0,x=0,y=100,width=712,height=52,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTop,file="hall/common/bg_blank.png",
{
name="topTip",type=4,typeName="Text",time=65257267,report=0,x=0,y=0,width=203,height=33,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,fontSize=28,textAlign=kAlignLeft,colorRed=118,colorGreen=72,colorBlue=17
}
},
{
name="payListView",type=0,typeName="ListView",time=65268048,report=0,x=0,y=14,width=800,height=280,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter
},
{
name="bottomView",type=0,typeName="View",time=83989649,report=0,x=0,y=32,width=925,height=80,visible=1,fillParentWidth=1,fillParentHeight=0,nodeAlign=kAlignBottom,
{
name="Image1",type=1,typeName="Image",time=89894962,report=0,x=0,y=10,width=580,height=48,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,file="hall/common/popupWindow/popupWindow_describe_bg_25_25_25_25.png",gridLeft=25,gridRight=25,gridTop=25,gridBottom=25
},
{
name="bottomTip",type=4,typeName="Text",time=65259031,report=0,x=0,y=10,width=0,height=0,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,fontSize=32,textAlign=kAlignCenter,colorRed=167,colorGreen=142,colorBlue=96
}
}
}
}
return chooseGoodsLayer; |
local entergameWindow
local characterGroup
local outfitGroup
local protocol
local infoBox
local loadingBox
function init()
if not USE_NEW_ENERGAME then return end
entergameWindow = g_ui.displayUI('entergamev2')
entergameWindow.news:hide()
entergameWindow.quick:hide()
entergameWindow.registration:hide()
entergameWindow.characters:hide()
entergameWindow.createcharacter:hide()
entergameWindow.settings:hide()
-- entergame
entergameWindow.entergame.register.onClick = function()
entergameWindow.registration:show()
entergameWindow.entergame:hide()
end
entergameWindow.entergame.mainPanel.button.onClick = login
-- registration
entergameWindow.registration.back.onClick = function()
entergameWindow.registration:hide()
entergameWindow.entergame:show()
end
-- characters
--- outfits
entergameWindow.characters.mainPanel.showOutfits.onClick = function()
local status = not (entergameWindow.characters.mainPanel.showOutfits:isOn())
g_settings.set('showOutfits', status)
entergameWindow.characters.mainPanel.showOutfits:setOn(status)
if status then
entergameWindow.characters.mainPanel.outfitsPanel:show()
entergameWindow.characters.mainPanel.outfitsScroll:show()
entergameWindow.characters.mainPanel.charactersPanel:hide()
entergameWindow.characters.mainPanel.charactersScroll:hide()
else
entergameWindow.characters.mainPanel.outfitsPanel:hide()
entergameWindow.characters.mainPanel.outfitsScroll:hide()
entergameWindow.characters.mainPanel.charactersPanel:show()
entergameWindow.characters.mainPanel.charactersScroll:show()
end
end
local showOutfits = g_settings.getBoolean("showOutfits", false)
entergameWindow.characters.mainPanel.showOutfits:setOn(showOutfits)
if showOutfits then
entergameWindow.characters.mainPanel.charactersPanel:hide()
entergameWindow.characters.mainPanel.charactersScroll:hide()
else
entergameWindow.characters.mainPanel.outfitsPanel:hide()
entergameWindow.characters.mainPanel.outfitsScroll:hide()
end
--- auto reconnect
entergameWindow.characters.mainPanel.autoReconnect.onClick = function()
local status = (not entergameWindow.characters.mainPanel.autoReconnect:isOn())
g_settings.set('autoReconnect', status)
entergameWindow.characters.mainPanel.autoReconnect:setOn(status)
end
local autoReconnect = g_settings.getBoolean("autoReconnect", true)
entergameWindow.characters.mainPanel.autoReconnect:setOn(autoReconnect)
--- buttons
entergameWindow.characters.logout.onClick = function()
protocol:logout()
entergameWindow.characters:hide()
entergameWindow.entergame:show()
entergameWindow.entergame.mainPanel.account:setText("")
entergameWindow.entergame.mainPanel.password:setText("")
end
entergameWindow.characters.createcharacter.onClick = function()
entergameWindow.characters:hide()
entergameWindow.createcharacter:show()
entergameWindow.createcharacter.mainPanel.name:setText("")
end
entergameWindow.characters.settings.onClick = function()
entergameWindow.characters:hide()
entergameWindow.settings:show()
end
-- create character
entergameWindow.createcharacter.back.onClick = function()
entergameWindow.createcharacter:hide()
entergameWindow.characters:show()
end
entergameWindow.createcharacter.mainPanel.createButton.onClick = createcharacter
entergameWindow.settings.back.onClick = function()
entergameWindow.settings:hide()
entergameWindow.characters:show()
end
entergameWindow.settings.mainPanel.updateButton.onClick = updateSettings
-- pick server
local server = nil
if type(Servers) == "table" then
for name, url in pairs(Servers) do
server = url
end
elseif type(Servers) == "string" then
server = Servers
elseif type(Server) == "string" then
server = Server
end
if not server then
message("Configuration error", "You must set server url in init.lua!\nExample:\nServer = \"ws://otclient.ovh:8000\"")
return
end
-- init protocol
-- token is random string
local session = g_crypt.sha1Encode("" .. math.random() .. g_clock.realMicros() .. tostring(G.UUID) .. g_platform.getCPUName() .. g_platform.getProcessId())
protocol = EnterGameV2Protocol.new(session)
if not protocol:setUrl(server) then
return message("Configuration error", "Invalid url for entergamev2:\n" .. server)
end
protocol.onLogin = onLogin
protocol.onLogout = logout
protocol.onMessage = serverMessage
protocol.onLoading = showLoading
protocol.onQAuth = updateQAuth
protocol.onCharacters = updateCharacters
protocol.onNews = updateNews
protocol.onMotd = updateMotd
protocol.onCharacterCreate = onCharacterCreate
-- game stuff
connect(g_game, { onLoginError = onLoginError,
onLoginToken = onLoginToken ,
onUpdateNeeded = onUpdateNeeded,
onConnectionError = onConnectionError,
onGameStart = onGameStart,
onGameEnd = onGameEnd,
onLoginWait = onLoginWait,
onLogout = onLogout
})
if g_game.isOnline() then
onGameStart()
end
end
function terminate()
if not USE_NEW_ENERGAME then return end
if protocol then
protocol:destroy()
protocol = nil
end
if infoBox then
infoBox:destroy()
infoBox = nil
end
if loadingBox then
loadingBox:destroy()
loadingBox = nil
end
if characterGroup then
characterGroup:destroy()
characterGroup = nil
end
if outfitGroup then
outfitGroup:destroy()
outfitGroup = nil
end
entergameWindow:destroy()
entergameWindow = nil
disconnect(g_game, { onLoginError = onLoginError,
onLoginToken = onLoginToken ,
onUpdateNeeded = onUpdateNeeded,
onConnectionError = onConnectionError,
onGameStart = onGameStart,
onGameEnd = onGameEnd,
onLoginWait = onLoginWait,
onLogout = onLogout
})
end
function show()
end
function hide()
end
function message(title, text)
if infoBox then
infoBox:destroy()
end
infoBox = displayInfoBox(title, text)
infoBox.onDestroy = function(widget)
if widget == infoBox then
infoBox = nil
end
end
infoBox:show()
infoBox:raise()
infoBox:focus()
end
function showLoading(titie, text)
if loadingBox then
loadingBox:destroy()
end
local callback = function() end -- do nothing
loadingBox = displayGeneralBox(titie, text, {}, callback, callback)
loadingBox.onDestroy = function(widget)
if widget == loadingBox then
loadingBox = nil
end
end
loadingBox:show()
loadingBox:raise()
loadingBox:focus()
end
function serverMessage(title, text)
return message(title, text)
end
function updateCharacters(characters)
if outfitGroup then
outfitGroup:destroy()
end
if characterGroup then
characterGroup:destroy()
end
entergameWindow.characters.mainPanel.charactersPanel:destroyChildren()
entergameWindow.characters.mainPanel.outfitsPanel:destroyChildren()
outfitGroup = UIRadioGroup.create()
characterGroup = UIRadioGroup.create()
for i, character in ipairs(characters) do
local characterWidget = g_ui.createWidget('EntergameCharacter', entergameWindow.characters.mainPanel.charactersPanel)
characterGroup:addWidget(characterWidget)
local outfitWidget = g_ui.createWidget('EntergameBigCharacter', entergameWindow.characters.mainPanel.outfitsPanel)
outfitGroup:addWidget(outfitWidget)
for i, widget in ipairs({characterWidget, outfitWidget}) do
widget.character = character
widget.outfit:setOutfit(character["outfit"])
widget.line1:setText(character["line1"])
widget.line2:setText(character["line2"])
widget.line3:setText(character["line3"])
end
end
if #characters > 1 then
characterGroup:selectWidget(entergameWindow.characters.mainPanel.charactersPanel:getFirstChild())
outfitGroup:selectWidget(entergameWindow.characters.mainPanel.outfitsPanel:getFirstChild())
end
end
function updateQAuth(token)
if not token or token:len() == 0 then
return entergameWindow.quick:hide()
end
entergameWindow.quick:show()
entergameWindow.quick.qrcode:setQRCode(token, 1)
entergameWindow.quick.qrcode.onClick = function()
g_platform.openUrl(token)
end
entergameWindow.quick.quathlogo.onClick = entergameWindow.quick.qrcode.onClick
end
function updateNews(news)
if not news or #news == 0 then
return entergameWindow.news:hide()
end
entergameWindow.news:show()
entergameWindow.news.content:destroyChildren()
for i, entry in ipairs(news) do
local title = entry["title"]
local text = entry["text"]
local image = entry["image"]
if title then
local newsLabel = g_ui.createWidget('NewsLabel', entergameWindow.news.content)
newsLabel:setText(title)
end
if text ~= nil then
local newsText = g_ui.createWidget('NewsText', entergameWindow.news.content)
newsText:setText(text)
end
end
end
function updateMotd(text)
if not text or text:len() == 0 then
return entergameWindow.characters.mainPanel.motd:hide()
end
entergameWindow.characters.mainPanel.motd:show()
entergameWindow.characters.mainPanel.motd:setText(text)
end
function login()
local account = entergameWindow.entergame.mainPanel.account:getText()
local password = entergameWindow.entergame.mainPanel.password:getText()
entergameWindow.entergame:hide()
showLoading("Login", "Connecting to server...")
protocol:login(account, password, "")
end
function onLogin(data)
if loadingBox then
loadingBox:destroy()
loadingBox = nil
end
if data["error"] and data["error"]:len() > 0 then
entergameWindow.entergame:show()
return message("Login error", data["error"])
end
local incorrectThings = validateThings(data["things"])
if incorrectThings:len() > 0 then
entergameWindow.entergame:show()
return message("Login error - missing things", incorrectThings)
end
if infoBox then
infoBox:destroy()
end
local version = data["version"]
G.clientVersion = version
g_game.setClientVersion(version)
g_game.setProtocolVersion(g_game.getClientProtocolVersion(version))
g_game.setCustomOs(-1) -- disable custom os
local customProtocol = data["customProtocol"]
g_game.setCustomProtocolVersion(0)
if type(customProtocol) == 'number' then
g_game.setCustomProtocolVersion(customProtocol)
end
local email = data["email"]
local security = data["security"]
entergameWindow.settings.mainPanel.email:setText(email)
entergameWindow.settings.mainPanel.security:setCurrentIndex(math.max(1, security))
entergameWindow.characters:show()
entergameWindow.entergame:hide()
end
function logout()
if not entergameWindow.characters:isVisible() and not entergameWindow.createcharacter:isVisible() then
return
end
entergameWindow.characters:hide()
entergameWindow.createcharacter:hide()
entergameWindow.entergame:show()
message("Information", "Session expired, you has been logged out.")
end
function validateThings(things)
local incorrectThings = ""
local missingFiles = false
local versionForMissingFiles = 0
if things ~= nil then
local thingsNode = {}
for thingtype, thingdata in pairs(things) do
thingsNode[thingtype] = thingdata[1]
if not g_resources.fileExists("/things/" .. thingdata[1]) then
incorrectThings = incorrectThings .. "Missing file: " .. thingdata[1] .. "\n"
missingFiles = true
versionForMissingFiles = thingdata[1]:split("/")[1]
else
local localChecksum = g_resources.fileChecksum("/things/" .. thingdata[1]):lower()
if localChecksum ~= thingdata[2]:lower() and #thingdata[2] > 1 then
if g_resources.isLoadedFromArchive() then -- ignore checksum if it's test/debug version
incorrectThings = incorrectThings .. "Invalid checksum of file: " .. thingdata[1] .. " (is " .. localChecksum .. ", should be " .. thingdata[2]:lower() .. ")\n"
end
end
end
end
g_settings.setNode("things", thingsNode)
else
g_settings.setNode("things", {})
end
if missingFiles then
incorrectThings = incorrectThings .. "\nYou should open data/things and create directory " .. versionForMissingFiles ..
".\nIn this directory (data/things/" .. versionForMissingFiles .. ") you should put missing\nfiles (Tibia.dat and Tibia.spr) " ..
"from correct Tibia version."
end
return incorrectThings
end
function doGameLogin()
local selected = nil
if entergameWindow.characters.mainPanel.charactersPanel:isVisible() then
selected = characterGroup:getSelectedWidget()
else
selected = outfitGroup:getSelectedWidget()
end
if not selected then
return message("Entergame error", "Please select character")
end
local character = selected.character
if not g_game.getFeature(GameSessionKey) then
g_game.enableFeature(GameSessionKey)
end
g_game.loginWorld("", "", character.worldName, character.worldHost, character.worldPort, character.name, "", protocol.session)
end
function onLoginError(err)
message("Login error", err)
end
function onLoginToken()
end
function onUpdateNeeded(signature)
end
function onConnectionError(message, code)
end
function onGameStart()
entergameWindow:hide()
end
function onGameEnd()
entergameWindow:show()
end
function onLoginWait(message, time)
end
function onLogout()
end
function createcharacter()
local name = entergameWindow.createcharacter.mainPanel.name:getText()
local gender = entergameWindow.createcharacter.mainPanel.gender:getCurrentOption().text
local vocation = entergameWindow.createcharacter.mainPanel.vocation:getCurrentOption().text
local town = entergameWindow.createcharacter.mainPanel.town:getCurrentOption().text
if name:len() < 3 or name:len() > 20 then
return message("Error", "Invalid character name")
end
protocol:createCharacter(name, gender, vocation, town)
showLoading("Creating character", "Creating new character...")
end
function onCharacterCreate(err, msg)
if loadingBox then
loadingBox:destroy()
loadingBox = nil
end
if err then
return message("Error", err)
end
message("Success", msg)
entergameWindow.createcharacter:hide()
entergameWindow.characters:show()
end
function updateSettings()
local email = entergameWindow.settings.mainPanel.email:getText()
local security = entergameWindow.settings.mainPanel.security.currentIndex
protocol:updateSettings({
email=email,
security=security
})
entergameWindow.settings:hide()
entergameWindow.characters:show()
end |
-- Copyright (c) 2020 Trevor Redfern
--
-- This software is released under the MIT License.
-- https://opensource.org/licenses/MIT
describe("game.ui.screen_title", function()
require "game.ui"
it("uses the title property to set the name of the view", function()
local t = moonpie.ui.components.screen_title({ title = "Hello World!" })
local heading = t:find_by_id("screen_title_heading")
assert.equals("Hello World!", heading.text)
end)
end) |
object_tangible_loot_npc_loot_elect_module_simple_generic = object_tangible_loot_npc_loot_shared_elect_module_simple_generic:new {
}
ObjectTemplates:addTemplate(object_tangible_loot_npc_loot_elect_module_simple_generic, "object/tangible/loot/npc/loot/elect_module_simple_generic.iff")
|
Import("mod1.lua")
Import("mod2/mod2.lua")
|
print("Before the big 10 loop")
i = 0
--print everything
while i < 10 do
print("Inside: ", i+1)
i = i + 1
end
print("Afer the big 10 loop") |
local PLUGIN = PLUGIN
PLUGIN.name = "Stackable Items"
PLUGIN.author = "gm1003 ツ"
PLUGIN.description = "Adds stackable items."
ix.util.Include("sv_hooks.lua") |
slot0 = class("WeekTaskProgress", import("..BaseVO"))
slot0.Ctor = function (slot0)
return
end
slot0.Init = function (slot0, slot1)
slot0.targets = {}
slot0.dropData = {}
slot0.index = 0
slot0.target = 0
slot0.progress = 0
slot0.drops = {}
slot0.subTasks = {}
slot0.targets = pg.gameset.weekly_target.description
slot0.dropData = pg.gameset.weekly_drop_client.description
slot0.progress = slot1.pt or 0
for slot5, slot6 in ipairs(slot1.task) do
slot0.subTasks[WeekPtTask.New(slot6).id] = WeekPtTask.New(slot6)
end
slot0:UpdateTarget(table.indexof(slot0.targets, slot1.reward_lv) or 0)
end
slot0.IsMaximum = function (slot0)
return slot0.index >= #slot0.targets
end
slot0.UpdateTarget = function (slot0, slot1)
slot0.index = slot1
slot0.target = slot0.targets[slot1 + 1] or slot0.targets[#slot0.targets]
slot0.drops = slot0.dropData[slot1 + 1] or slot0.dropData[#slot0.dropData]
end
slot0.CanUpgrade = function (slot0)
return slot0.target <= slot0.progress and not slot0:IsMaximum()
end
slot0.Upgrade = function (slot0)
if slot0:CanUpgrade() then
slot0:UpdateTarget(slot0.index + 1)
end
end
slot0.GetDropList = function (slot0)
return slot0.drops
end
slot0.GetPhase = function (slot0)
return math.min(slot0.index + 1, #slot0.targets)
end
slot0.GetTotalPhase = function (slot0)
return #slot0.targets
end
slot0.GetProgress = function (slot0)
return slot0.progress
end
slot0.GetTarget = function (slot0)
return slot0.target
end
slot0.UpdateProgress = function (slot0, slot1)
slot0.progress = slot1
end
slot0.AddProgress = function (slot0, slot1)
slot0.progress = slot0.progress + slot1
end
slot0.GetAllPhaseDrops = function (slot0)
return {
resIcon = "Props/weekly_pt",
type = 1,
dropList = slot0.dropData,
targets = slot0.targets,
level = slot0.index,
count = slot0.progress,
resName = i18n("week_task_pt_name")
}
end
slot0.ReachMaxPt = function (slot0)
return slot0.targets[#slot0.targets] <= slot0.progress
end
slot0.GetSubTasks = function (slot0)
return slot0.subTasks
end
slot0.RemoveSubTasks = function (slot0, slot1)
for slot5, slot6 in ipairs(slot1) do
slot0:RemoveSubTask(slot6)
end
end
slot0.RemoveSubTask = function (slot0, slot1)
slot0.subTasks[slot1] = nil
end
slot0.AddSubTask = function (slot0, slot1)
slot0.subTasks[slot1.id] = slot1
end
slot0.UpdateSubTask = function (slot0, slot1)
slot0.subTasks[slot1.id] = slot1
end
slot0.GetSubTask = function (slot0, slot1)
return slot0.subTasks[slot1]
end
slot0.AnySubTaskCanSubmit = function (slot0)
if slot0:ReachMaxPt() then
return false
end
for slot4, slot5 in pairs(slot0.subTasks) do
if slot5:isFinish() then
return true
end
end
return false
end
slot0.GetCanSubmitSubTaskCnt = function (slot0)
if slot0:ReachMaxPt() then
return 0
end
slot1 = 0
for slot5, slot6 in pairs(slot0.subTasks) do
if slot6:isFinish() then
slot1 = slot1 + 1
end
end
return slot1
end
return slot0
|
jawa_beads = {
minimumLevel = 0,
maximumLevel = -1,
customObjectName = "",
directObjectTemplate = "object/tangible/loot/misc/jawa_beads.iff",
craftingValues = {
},
customizationStringNames = {},
customizationValues = {},
junkDealerTypeNeeded = JUNKJAWA,
junkMinValue = 35,
junkMaxValue = 70
}
addLootItemTemplate("jawa_beads", jawa_beads)
|
-- bitmasks
local struct = require "vstruct"
local io = require "vstruct.io"
local unpack = table.unpack or unpack
local m = {}
function m.read(_, buf, size)
local mask = {}
local e = io("endianness", "get")
local sof,eof,step
if e == "big" then
sof,eof,step = #buf,1,-1
else
sof,eof,step = 1,#buf,1
end
for i=sof,eof,step do
local byte = buf:byte(i)
for i=1,8 do
mask[#mask+1] = (byte % 2 == 1) and true or false
byte = math.floor(byte/2)
end
end
return mask
end
function m.readbits(bit, size)
local mask = {}
for i=1,size do
mask[i] = bit() == 1 and true or false
end
return mask
end
-- bitmask
-- we use a string here because using an unsigned will lose data on bitmasks
-- wider than lua's native number format
function m.write(fd, data, size)
local buf = ""
local e = io("endianness", "get")
for i=1,size*8,8 do
local bits = { unpack(data, i, i+7) }
local byte = string.char(struct.implode(bits, 8))
if e == "big" then
buf = byte..buf
else
buf = buf..byte
end
end
return io("s", "write", fd, buf, size)
end
function m.writebits(bit, data, size)
for i=1,size do
bit(data[i] and 1 or 0)
end
end
return m
|
modifier_vengefulspirit_command_aura_lua = class({})
--------------------------------------------------------------------------------
function modifier_vengefulspirit_command_aura_lua:IsHidden()
return true
end
--------------------------------------------------------------------------------
function modifier_vengefulspirit_command_aura_lua:IsAura()
return true
end
--------------------------------------------------------------------------------
function modifier_vengefulspirit_command_aura_lua:GetModifierAura()
return "modifier_vengefulspirit_command_aura_effect_lua"
end
--------------------------------------------------------------------------------
function modifier_vengefulspirit_command_aura_lua:GetAuraSearchTeam()
return DOTA_UNIT_TARGET_TEAM_FRIENDLY
end
--------------------------------------------------------------------------------
function modifier_vengefulspirit_command_aura_lua:GetAuraSearchType()
return DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_CREEP-- + DOTA_UNIT_TARGET_MECHANICAL
end
--------------------------------------------------------------------------------
function modifier_vengefulspirit_command_aura_lua:GetAuraSearchFlags()
return DOTA_UNIT_TARGET_FLAG_INVULNERABLE
end
--------------------------------------------------------------------------------
function modifier_vengefulspirit_command_aura_lua:GetAuraRadius()
return self.aura_radius
end
--------------------------------------------------------------------------------
function modifier_vengefulspirit_command_aura_lua:OnCreated( kv )
self.aura_radius = self:GetAbility():GetSpecialValueFor( "aura_radius" )
if IsServer() and self:GetParent() ~= self:GetCaster() then
self:StartIntervalThink( 0.5 )
end
end
--------------------------------------------------------------------------------
function modifier_vengefulspirit_command_aura_lua:OnRefresh( kv )
self.aura_radius = self:GetAbility():GetSpecialValueFor( "aura_radius" )
end
--------------------------------------------------------------------------------
function modifier_vengefulspirit_command_aura_lua:DeclareFunctions()
local funcs = {
MODIFIER_EVENT_ON_DEATH
}
return funcs
end
--------------------------------------------------------------------------------
function modifier_vengefulspirit_command_aura_lua:OnDeath( params )
if IsServer() then
if self:GetCaster() == nil then
return 0
end
if self:GetCaster():PassivesDisabled() then
return 0
end
if self:GetCaster() ~= self:GetParent() then
return 0
end
local hAttacker = params.attacker
local hVictim = params.unit
if hVictim ~= nil and hAttacker ~= nil and hVictim == self:GetCaster() and hAttacker:GetTeamNumber() ~= hVictim:GetTeamNumber() then
local hAuraHolder = nil
if hAttacker:IsHero() then
hAuraHolder = hAttacker
elseif hAttacker:GetOwnerEntity() ~= nil and hAttacker:GetOwnerEntity():IsHero() then
hAuraHolder = hAttacker:GetOwnerEntity()
end
if hAuraHolder ~= nil then
hAuraHolder:AddNewModifier( self:GetCaster(), self:GetAbility(), "modifier_vengefulspirit_command_aura_lua", { duration = -1 } )
local nFXIndex = ParticleManager:CreateParticle( "particles/units/heroes/hero_vengeful/vengeful_negative_aura.vpcf", PATTACH_ABSORIGIN_FOLLOW, hAuraHolder )
ParticleManager:SetParticleControlEnt( nFXIndex, 1, hVictim, PATTACH_ABSORIGIN_FOLLOW, nil, hVictim:GetOrigin(), false )
ParticleManager:ReleaseParticleIndex( nFXIndex )
end
end
end
return 0
end
--------------------------------------------------------------------------------
function modifier_vengefulspirit_command_aura_lua:OnIntervalThink()
if self:GetCaster() ~= self:GetParent() and self:GetCaster():IsAlive() then
self:Destroy()
end
end
--------------------------------------------------------------------------------
-------------------------------------------------------------------------------- |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.