content
stringlengths 5
1.05M
|
|---|
local screenW, screenH = guiGetScreenSize()
GTmodelsviewer = {
gridlist = {},
window = {},
button = {},
label = {}
}
GTmodelsviewer.window[1] = guiCreateWindow(10, (screenH - 421) / 2, 326, 421, "Real Estate - Property Viewer", false)
guiWindowSetSizable(GTmodelsviewer.window[1], false)
guiSetVisible( GTmodelsviewer.window[1], false)
--showCursor( true)
GTmodelsviewer.gridlist[1] = guiCreateGridList(10, 28, 306, 240, false, GTmodelsviewer.window[1])
guiGridListAddColumn(GTmodelsviewer.gridlist[1], "Objects", 0.9)
GTmodelsviewer.gridlist[2] = guiCreateGridList(10, 278, 171, 115, false, GTmodelsviewer.window[1])
guiGridListAddColumn(GTmodelsviewer.gridlist[2], "Textures", 0.8)
--GTmodelsviewer.button[1] = guiCreateButton(191, 303, 125, 40, "Preview Combination", false, GTmodelsviewer.window[1])
GTmodelsviewer.button[1] = guiCreateButton(191, 303, 125, 40, "Purchase Combination", false, GTmodelsviewer.window[1])
--guiSetFont(GTmodelsviewer.button[1], "clear-normal")
GTmodelsviewer.label[1] = guiCreateLabel(191, 278, 125, 15, "Cost: $0", false, GTmodelsviewer.window[1])
--guiSetFont(GTmodelsviewer.label[2], "clear-normal")
--GTmodelsviewer.button[2] = guiCreateButton(191, 353, 125, 40, "Purchase Combination", false, GTmodelsviewer.window[1])
--guiSetFont(GTmodelsviewer.button[2], "clear-normal")
GTmodelsviewer.label[2] = guiCreateLabel(9, 399, 307, 16, "Right Click on the GUI to Close it.", false, GTmodelsviewer.window[1])
local mcost = 0
local tcost = 0
local ocost = 0
--[[Types:
no: Materials Viewer
o: Object Viewer
--]]
local vType = "no"
addEventHandler( "onClientResourceStart", resourceRoot,
function()
-- Set Fonts
for i, label in pairs ( GTmodelsviewer.label) do
guiSetFont( label, "clear-normal")
end
for i, button in pairs ( GTmodelsviewer.button) do
guiSetFont( button, "clear-normal")
end
-- Load All Textures
for i, txdName in ipairs ( alltextures) do
local row = guiGridListAddRow( GTmodelsviewer.gridlist[2])
guiGridListSetItemText( GTmodelsviewer.gridlist[2], row, 1, "$"..txdName[3].." - "..txdName[1], false, false)
guiGridListSetItemData( GTmodelsviewer.gridlist[2], row, 1, txdName[2]..";"..txdName[3])
end
-- Load All Items
for name, category in pairs ( objectTable) do
local row = guiGridListAddRow( GTmodelsviewer.gridlist[1])
if #category > 1 then
guiGridListSetItemText( GTmodelsviewer.gridlist[1], row, 1, #category.." "..name.."s", true, false)
else
guiGridListSetItemText( GTmodelsviewer.gridlist[1], row, 1, #category.." "..name, true, false)
end
for i, object in pairs ( category) do
local row = guiGridListAddRow( GTmodelsviewer.gridlist[1])
local id = object[1]
local itemName = object[2]
local costr = object[3]
local cost = costr
guiGridListSetItemText( GTmodelsviewer.gridlist[1], row, 1, "$"..cost.." - "..itemName, false, false)
guiGridListSetItemData( GTmodelsviewer.gridlist[1], row, 1, id..";"..costr)
end
end
end
)
function setViewerVisible( state)
if state then
if not guiGetVisible( GTmodelsviewer.window[1]) then
guiSetVisible( GTmodelsviewer.window[1], true)
showCursor( true)
viewing = true
end
else
if guiGetVisible( GTmodelsviewer.window[1]) then
guiSetVisible( GTmodelsviewer.window[1], false)
showCursor( false)
viewing = false
end
end
end
addEventHandler( "onClientGUIClick", root,
function( button, state)
if source == GTmodelsviewer.window[1] then
if button == "right" then
setViewerVisible( false)
end
elseif source == GTmodelsviewer.gridlist[1] then
local row, col = guiGridListGetSelectedItem( source)
if row and col then
local text = guiGridListGetItemText( source, row, col)
if text ~= "" then
local mdata = split( guiGridListGetItemData( source, row, col), ";")
local objectID = mdata[1]
local cost = mdata[2]
if prevID ~= objectID then
setElementModel( prevObject, objectID)
prevID = objectID
mcost = cost
end
end
end
guiSetText( GTmodelsviewer.label[1], "Cost: $"..(mcost+tcost))
elseif source == GTmodelsviewer.gridlist[2] then
local row, col = guiGridListGetSelectedItem( source)
if row and col then
local text = guiGridListGetItemText( source, row, col)
if text ~= "" then
local tdata = split( guiGridListGetItemData( source, row, col), ";")
local texture = tdata[1]
local cost = tdata[2]
if texture == "none" then
if prevTXD ~= "none" then
prevTXD = "none"
removeCustomTexture( prevObject)
tcost = cost
end
else
if prevTXD ~= texture then
applyCustomTexture( prevObject, texture)
prevTXD = texture
tcost = cost
end
end
end
end
guiSetText( GTmodelsviewer.label[1], "Cost: $"..(mcost+tcost))
end
end
)
|
local AliasesModif = {}
local colors = require "colors"
local sides = require "sides"
local dmp = require "dump"
local aliasNode = require "AliasNode"
local client
local name
function AliasesModif:set(aname)
client = self; name = aname
end
local tree
local containerHEAD, containerCRUD, containerButtons
local nameField
local oldName
local typeField, doorField, blockField, sideField, colorField
local function cleanUp()
containerHEAD:removeChildren()
containerCRUD:removeChildren()
client.stopListeningToWindowWires(name)
end
local function offOnAlias(charge)
local selectedName = tree:getSelectedName()
client.offOnAlias(selectedName, charge)
end
local function upDownAlias(upDown)
local selectedName = tree:getSelectedName()
if selectedName == "Top" then return end
local selectedAlias = tree.getDataNode(tree.dataNode, selectedName)
local selectedParentAlias = tree.getParentDataNode(tree.dataNode, selectedName)
local i
local max
for k, v in ipairs(selectedParentAlias.children) do
if selectedAlias.name == v.name then
i = k
end
max = k
end
if upDown then
if i >= max then return end
else
if i <= 1 then return end
end
client.upDownAlias(selectedParentAlias.name, i, upDown)
end
local function updateAlias()
if oldName == "Top" then return end--
if oldName ~= nameField.text and not aliasNode.isNew(tree.dataNode, nameField.text) then return end
local origAlias = tree.getDataNode(tree.dataNode, tree:getSelectedName())
local alias = {}
alias.name = nameField.text
alias.node = origAlias.node
if alias.node then
alias.exp = origAlias.exp
alias.children = origAlias.children
else
if doorField.selectedItem == 1 then alias.door = false else alias.door = true end
alias.block = blockField:getItem(blockField.selectedItem).text
alias.side = sides[sideField:getItem(sideField.selectedItem).text]
alias.color = colors[colorField:getItem(colorField.selectedItem).text]
end
cleanUp()
client.updateAlias(oldName, alias.name, alias)
end
local function deleteAlias()
if oldName == "Top" then return end--
local alias = tree.getDataNode(tree.dataNode, tree:getSelectedName())
if alias.node and #alias.children > 0 then return end
cleanUp()
client.deleteAlias(alias.name)
end
local function insertAliasNode()
if oldName == nameField.text or not aliasNode.isNew(tree.dataNode, nameField.text) then return end
local parent
local selected = tree.getDataNode(tree.dataNode, tree:getSelectedName())
if selected.node then
parent = selected
else
parent = tree.getParentDataNode(tree.dataNode, tree:getSelectedName())
end
local alias = {}
alias.name = nameField.text
alias.node = true
alias.exp = true
alias.children = {}
cleanUp()
client.insertAlias(parent.name, alias.name, alias)
end
local function insertAliasLeaf()
if oldName == nameField.text or not aliasNode.isNew(tree.dataNode, nameField.text) then return end
local parent
local selected = tree.getDataNode(tree.dataNode, tree:getSelectedName())
if selected.node then
parent = selected
else
parent = tree.getParentDataNode(tree.dataNode, tree:getSelectedName())
end
local alias = {}
alias.name = nameField.text
alias.node = false
if blockField ~= nil then
if doorField.selectedItem == 1 then alias.door = false else alias.door = true end
alias.block = blockField:getItem(blockField.selectedItem).text
alias.side = sides[sideField:getItem(sideField.selectedItem).text]
alias.color = colors[colorField:getItem(colorField.selectedItem).text]
else
for k, v in pairs(client.data) do
alias.block = k; break
end
alias.side = 1
alias.color = 1
end
cleanUp()
client.insertAlias(parent.name, alias.name, alias)
end
local function displayHEAD(alias)
containerHEAD:addChild(client.GUI.text(2, 2, 0xFFFFFF, "Name:"))
nameField = containerHEAD:addChild(client.GUI.input(8, 2, 19, 1, 0xEEEEEE, 0x555555, 0x999999, 0xFFFFFF, 0x2D2D2D, "", ""))
oldName = alias.name
nameField.text = alias.name
local isNode; if alias.node then isNode = "yes" else isNode = "no" end
containerHEAD:addChild(client.GUI.text(30, 2, 0xFFFFFF, "Node: "..isNode))
local offButton = containerHEAD:addChild(client.GUI.button(2, 4, 8, 1, 0xFFEFFF, 0x555555, 0x880000, 0xFFFFFF, "Off"))
offButton.onTouch = function() offOnAlias(0) end
local onButton = containerHEAD:addChild(client.GUI.button(12, 4, 8, 1, 0xFFEFFF, 0x555555, 0x880000, 0xFFFFFF, "On"))
onButton.onTouch = function() offOnAlias(255) end
if alias.node == false then
local displayState = client.addSyncRectangle(alias.block, alias.side, alias.color, name)
displayState.x = 22; displayState.y = 4; displayState.width = 6
containerHEAD:addChild(displayState)
end
end
local function displayCRUD(alias)
if not alias.node then
containerCRUD:addChild(client.GUI.text(2, 2, 0xFFFFFF, "Type:"))
typeField = containerCRUD:addChild(client.GUI.comboBox(8, 2, 10, 1, 0xEEEEEE, 0x2D2D2D, 0xCCCCCC, 0x888888))
typeField:addItem("Output")
containerCRUD:addChild(client.GUI.text(20, 2, 0xFFFFFF, "IsDoor:"))
doorField = containerCRUD:addChild(client.GUI.comboBox(28, 2, 6, 1, 0xEEEEEE, 0x2D2D2D, 0xCCCCCC, 0x888888))
doorField:addItem("No");doorField:addItem("Yes")
if alias ~= nil and alias.door then doorField.selectedItem = 2 else doorField.selectedItem = 1 end
blockField = containerCRUD:addChild(client.GUI.comboBox(2, 4, 40, 1, 0xEEEEEE, 0x2D2D2D, 0xCCCCCC, 0x888888))
local ii = 1
local iiSelected
for k, v in pairs (client.data) do
blockField:addItem(k)
if alias ~= nil and k == alias.block then iiSelected = ii end
ii = ii + 1
end
if iiSelected == nil then iiSelected = 1 end
blockField.selectedItem = iiSelected
containerCRUD:addChild(client.GUI.text(2, 6, 0xFFFFFF, "Side:"))
sideField = containerCRUD:addChild(client.GUI.comboBox(8, 6, 10, 1, 0xEEEEEE, 0x2D2D2D, 0xCCCCCC, 0x888888))
for i = 0, 5 do
sideField:addItem(sides[i])
end
if alias ~= nil then sideField.selectedItem = alias.side + 1 end
containerCRUD:addChild(client.GUI.text(20, 6, 0xFFFFFF, "Color:"))
colorField = containerCRUD:addChild(client.GUI.comboBox(27, 6, 10, 1, 0xEEEEEE, 0x2D2D2D, 0xCCCCCC, 0x888888))
for i = 0, 15 do
colorField:addItem(colors[i])
end
if alias ~= nil then colorField.selectedItem = alias.color + 1 end
end
end
local function displayButtons()
local updateButton = containerButtons:addChild(client.GUI.button(2, 2, 5, 1, 0xFFEFFF, 0x555555, 0x880000, 0xFFFFFF, "Upd"))
updateButton.onTouch = function() updateAlias() end
local deleteButton = containerButtons:addChild(client.GUI.button(9, 2, 5, 1, 0xFFEFFF, 0x555555, 0x880000, 0xFFFFFF, "Del"))
deleteButton.onTouch = function() deleteAlias() end
local newNodeButton = containerButtons:addChild(client.GUI.button(16, 2, 8, 1, 0xFFEFFF, 0x555555, 0x880000, 0xFFFFFF, "New Node"))
newNodeButton.onTouch = function() insertAliasNode() end
local newLeafButton = containerButtons:addChild(client.GUI.button(26, 2, 8, 1, 0xFFEFFF, 0x555555, 0x880000, 0xFFFFFF, "New Leaf"))
newLeafButton.onTouch = function() insertAliasLeaf() end
local upButton = containerButtons:addChild(client.GUI.button(35, 2, 3, 1, 0xFFEFFF, 0x555555, 0x880000, 0xFFFFFF, "U"))
upButton.onTouch = function() upDownAlias(false) end
local downButton = containerButtons:addChild(client.GUI.button(39, 2, 3, 1, 0xFFEFFF, 0x555555, 0x880000, 0xFFFFFF, "D"))
downButton.onTouch = function() upDownAlias(true) end
end
local itemSelected = function(e1, e2, e3, e4, e5, e6, e7, e8, e9)
cleanUp()
local alias = tree.getDataNode(tree.dataNode, tree:getSelectedName())
displayHEAD(alias)
displayCRUD(alias)
end
local onItemExpanded = function(e1, e2, e3, e4, e5, e6, e7, e8, e9)
end
local refresh = function()
tree:refresh()
tree.selectedItem = 1
client.application:draw()
end
AliasesModif.display = function()
local window = client.application:addChild(client.GUI.titledWindow(50, 22, 74, 21, name, true))
window.actionButtons.close.onTouch = function() client.closeWindow(name) end
tree = client.GUI.aliasTree(client.dataAliases, 2, 2, 28, 19, 0x11E1E1, 0x3C3C3C, 0x3C3C3C, 0xA5A5A5, 0x3C3C3C, 0xE1E1E1,
0xB4B4B4, 0xA5A5A5, 0xC3C3C3, 0x4B4B4B)
window:addChild(tree); tree.onItemSelected = itemSelected; tree.onItemExpanded = onItemExpanded
tree.switch.refresh = refresh
client.listenToAliasesList(tree, name)
local panelHEAD = window:addChild(client.GUI.panel(32, 2, 42, 5, 0x880000))
containerHEAD = window:addChild(client.GUI.container(panelHEAD.x, panelHEAD.y, panelHEAD.width, panelHEAD.height))
local panelCRUD = window:addChild(client.GUI.panel(32, 8, 42, 9, 0x880000))
containerCRUD = window:addChild(client.GUI.container(panelCRUD.x, panelCRUD.y, panelCRUD.width, panelCRUD.height))
local panelBUTTONS = window:addChild(client.GUI.panel(32, 18, 42, 3, 0x880000))
containerButtons = window:addChild(client.GUI.container(panelBUTTONS.x, panelBUTTONS.y, panelBUTTONS.width, panelBUTTONS.height))
displayButtons()
return window
end
return AliasesModif
|
--------------------------------------------------------------------------------
-- Handler.......... : onApplicationWillQuit
-- Author........... :
-- Description...... :
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function SteamworksAI.onApplicationWillQuit ( )
--------------------------------------------------------------------------------
-- We'll shut down, stop running callbacks every frame
this.bInitialised ( false )
--------------------------------------------------------------------------------
end
--------------------------------------------------------------------------------
|
local util = require "util"
local create_configuration = require "create_configuration"
local create_tasks = require "create_tasks"
local create_environment = require "create_environment"
local args = { ... }
local fs_normalise = util.fs_normalise
local shared_print = util.shared_print
local run_with_stacktrace = util.run_with_stacktrace
--------------------------------------------------------------------------------
-- Show help if requested
if args[1] == "--help" or args[1] == "-h" then
local function opt(name, description)
term.setTextColour(colours.lightBlue)
term.write " "
term.write(name)
term.setTextColour(colours.grey)
term.write " - "
term.setTextColour(colours.lightGrey)
print(description)
end
term.setTextColour(colours.cyan)
term.write "mesh-build "
term.setTextColour(colours.lightGrey)
term.write "[<"
term.setTextColour(colours.white)
term.write "options"
term.setTextColour(colours.lightGrey)
term.write "...>] <"
term.setTextColour(colours.white)
term.write "task"
term.setTextColour(colours.lightGrey)
term.write "> [<"
term.setTextColour(colours.white)
term.write "args"
term.setTextColour(colours.lightGrey)
print "...>]"
print "> Run a task from a build file."
opt("--root-dir, -r", "Set build root directory")
opt("--build-file, -b", "Specify path to build file")
opt("--verbose, -v", "Show debug output")
opt("--no-remotes", "Block using remote scripts")
opt("--unsafe-parent-environment, -u", "Allow access to all variables")
return result
end
--------------------------------------------------------------------------------
-- Main script
local build_file = "build.mesh.lua"
local root_dir = "."
local allow_unsafe = false
local allow_remote = true
local verbose = false
local task = "build"
while #args > 0 do
if not args[1]:find "^%-" then
break
end
local argument = table.remove(args, 1)
if argument == "--unsafe-parent-environment" or argument == "-u" then
allow_unsafe = true
elseif argument == "--no-remotes" then
allow_remote = false
elseif argument == "--verbose" or argument == "-v" then
verbose = true
elseif argument == "--build-file" or argument == "-b" then
build_file = table.remove(args, 1) or error("No build file given", 0)
elseif argument == "--root-dir" or argument == "--root-directory" or argument == "-r" then
root_dir = table.remove(args, 1) or error("No root directory given", 0)
elseif argument == "--" then
break
else
printError("Unknown option '" .. argument .. "'\n > Hint: Pass '--' to stop passing options")
return
end
end
task = table.remove(args, 1) or "build"
build_file = fs_normalise(shell.resolve(build_file))
root_dir = fs_normalise(shell.resolve(root_dir))
if verbose and task ~= "tasks" then
local function option(name, value)
term.setTextColour(colours.lightGrey)
term.write(name)
term.setTextColour(colours.grey)
term.write(": ")
term.setTextColour(colours.cyan)
print(value)
end
local function path_option(name, value)
local cwd = shell.dir()
if value:sub(1, #cwd + 1) == cwd .. "/" then
value = "./" .. value:sub(#cwd + 2)
elseif value == cwd then
value = "."
elseif cwd ~= "" then
value = "/" .. value
end
return option(name, value)
end
option("Task", task)
path_option("Build file", build_file)
path_option("Root directory", root_dir)
option("Allow unsafe environment", allow_unsafe)
option("Allow remote scripts", allow_remote)
end
local env = create_environment(allow_unsafe, allow_remote, verbose, root_dir, args)
local h = io.open(build_file)
if not h then h = io.open(build_file .. ".lua") end
local content = h and h:read "*a"
or error("Failed to open build file '" .. build_file .. "'", 0)
h:close()
local fsrc = fs.getName(build_file)
local f, err = load(content, fsrc, nil, env.environment)
if not f then error("Syntax error in build file '" .. build_file .. "': " .. tostring(err), 0) end
term.setTextColour(colours.white)
if not run_with_stacktrace(f, args, nil, 0, function(err)
printError("Error loading build file: " .. tostring(err))
end) then error() end
if task == "tasks" then
for i = 1, #env.tasks do
print(env.tasks[i].name)
end
return
end
if env.cancel_build then
printError("Build canceled")
return
end
local tasks_to_run = {}
local queue = { task }
-- TODO: this doesn't work
-- A: B, C ; C: B
-- order: A, B, C not A, C, B
while #queue > 0 do
local t = table.remove(queue, 1)
if not tasks_to_run[t] then
local td = env.tasks[t]
if not td then
error("No such task '" .. t .. "'", 0)
end
for i = 1, #td.depends_on do
table.insert(queue, td.depends_on[i])
end
table.insert(tasks_to_run, td)
tasks_to_run[t] = true
end
end
for i = 1, #tasks_to_run do
env.tasks_length = math.max(env.tasks_length, #tasks_to_run[i].name)
if not tasks_to_run[i].runnable then
error("Cannot run task '" .. tasks_to_run[i].name .. "'", 0)
end
end
for i = #tasks_to_run, 1, -1 do
local t = tasks_to_run[i]
local ctx = {
config = t.configuration
}
env.current_task = t.name
for j = 1, #t.on_run do
term.setBackgroundColour(colours.black)
term.setTextColour(colours.white)
if not run_with_stacktrace(t.on_run[j], { ctx }, t.name, env.tasks_length, function(err)
shared_print(t.name, env.tasks_length, colours.red, tostring(err))
end) then error() end
if env.cancel_build then
shared_print(t.name, env.tasks_length, colours.red, "Build canceled")
return
end
end
end
|
local toolbar = require"hs.webview.toolbar"
local console = require"hs.console"
local image = require"hs.image"
local fnutils = require"hs.fnutils"
local listener = require"utils.speech"
local application = require"hs.application"
local styledtext = require"hs.styledtext"
local doc = require"hs.doc"
local watchable = require"hs.watchable"
local canvas = require"hs.canvas"
local module = {}
local imageBasePath = hs.configdir .. "/_localAssets/images/"
local autoHideImage = function()
return imageBasePath .. (module.watchConsoleAutoClose:value() and "unpinned.png" or "pinned.png")
end
local listenerImage = function()
return imageBasePath .. (module.watchListenerStatus:value() and "microphone_on.png" or "microphone_off.png")
end
module.watchConsoleAutoClose = watchable.watch("hammerspoonMenu.status", function(...)
module.toolbar:modifyItem{ id = "autoHide", image = image.imageFromPath(autoHideImage()) }
end)
module.watchListenerStatus = watchable.watch("utils.speech.isListening", function(...)
module.toolbar:modifyItem{ id = "listener", image = image.imageFromPath(listenerImage()) }
end)
module.watchInternetStatus = watchable.watch("generalStatus.internet", function(w, p, i, oldValue, value)
module.toolbar:modifyItem{ id = "internet", image = image.imageFromName(value and "NSToolbarBookmarks" or "NSStopProgressFreestandingTemplate") }
end)
module.watchVPNStatus = watchable.watch("generalStatus.privateVPN", function(w, p, i, oldValue, value)
module.toolbar:modifyItem{ id = "privateVPN", image = image.imageFromName(value and "NSLockLockedTemplate" or "NSLockUnlockedTemplate") }
end)
local imageHolder = canvas.new{x = 10, y = 10, h = 50, w = 50}
imageHolder[1] = {
frame = { h = 50, w = 50, x = 0, y = -6 },
text = styledtext.new("⌘", {
font = { name = ".AppleSystemUIFont", size = 50 },
paragraphStyle = { alignment = "center" }
}),
type = "text",
}
local cheatSheetOn = imageHolder:imageFromCanvas():template(true)
imageHolder[2] = {
action = "stroke",
closed = false,
coordinates = { { x = 0, y = 0 }, { x = 50, y = 50 } },
strokeColor = { red = 1.0 },
strokeWidth = 3,
type = "segments",
}
imageHolder[3] = {
action = "stroke",
closed = false,
coordinates = { { x = 50, y = 0 }, { x = 0, y = 50 } },
strokeColor = { red = 1.0 },
strokeWidth = 3,
type = "segments",
}
local cheatSheetOff = imageHolder:imageFromCanvas():template(true)
imageHolder = imageHolder:delete()
module.watchCheatSheetStatus = watchable.watch("cheatsheet.enabled", function(w, p, i, oldValue, value)
module.toolbar:modifyItem{ id = "cheatsheet", image = value and cheatSheetOn or cheatSheetOff }
end)
imageHolder = canvas.new{x = 10, y = 10, h = 50, w = 50}
imageHolder[1] = {
frame = { h = 50, w = 50, x = 0, y = 0 },
text = styledtext.new("🖥", {
font = { name = ".AppleSystemUIFont", size = 50 },
paragraphStyle = { alignment = "center" }
}),
type = "text",
}
local popConsoleOn = imageHolder:imageFromCanvas()--:template(true)
imageHolder[2] = {
action = "stroke",
closed = false,
coordinates = { { x = 0, y = 0 }, { x = 50, y = 50 } },
strokeColor = { red = 1.0 },
strokeWidth = 3,
type = "segments",
}
imageHolder[3] = {
action = "stroke",
closed = false,
coordinates = { { x = 50, y = 0 }, { x = 0, y = 50 } },
strokeColor = { red = 1.0 },
strokeWidth = 3,
type = "segments",
}
local popConsoleOff = imageHolder:imageFromCanvas()--:template(true)
imageHolder = imageHolder:delete()
module.watchPopConsoleStatus = watchable.watch("popConsole.enabled", function(w, p, i, oldValue, value)
module.toolbar:modifyItem{ id = "popConsole", image = value and popConsoleOn or popConsoleOff }
end)
imageHolder = canvas.new{x = 10, y = 10, h = 50, w = 50}
imageHolder[1] = {
frame = { h = 50, w = 50, x = 0, y = -6 },
text = styledtext.new("ⅵ", {
font = { name = ".AppleSystemUIFont", size = 50 },
paragraphStyle = { alignment = "center" }
}),
type = "text",
}
local viKeysOn = imageHolder:imageFromCanvas():template(true)
imageHolder[2] = {
action = "stroke",
closed = false,
coordinates = { { x = 0, y = 0 }, { x = 50, y = 50 } },
strokeColor = { red = 1.0 },
strokeWidth = 3,
type = "segments",
}
imageHolder[3] = {
action = "stroke",
closed = false,
coordinates = { { x = 50, y = 0 }, { x = 0, y = 50 } },
strokeColor = { red = 1.0 },
strokeWidth = 3,
type = "segments",
}
local viKeysOff = imageHolder:imageFromCanvas():template(true)
imageHolder = imageHolder:delete()
module.watchViKeysStatus = watchable.watch("viKeys.enabled", function(w, p, i, oldValue, value)
module.toolbar:modifyItem{ id = "viKeys", image = value and viKeysOn or viKeysOff }
end)
local consoleToolbar = {
{
id = "autoHide",
label = "Auto Hide Console",
image = image.imageFromPath(autoHideImage()),
tooltip = "Hide the Hammerspoon Console when focus changes?",
fn = function(bar, attachedTo, item)
module.watchConsoleAutoClose:change(not module.watchConsoleAutoClose:value())
end,
},
{
id = "listener",
label = "HS Listener",
image = image.imageFromPath(listenerImage()),
tooltip = "Toggle the Hammerspoon Speech Recognition Listener",
fn = function(bar, attachedTo, item)
if listener.recognizer then
if listener:isListening() then
listener:disableCompletely()
else
listener:start()
end
else
listener.init():start()
end
end,
},
{ id = "NSToolbarFlexibleSpaceItem" },
{
id = "cust",
label = "customize",
tooltip = "Modify Toolbar",
fn = function(t, w, i)
t:customizePanel()
end,
image = image.imageFromName("NSToolbarCustomizeToolbarItemImage")
}
}
fnutils.each({
{ "SmartGit", "com.syntevo.smartgit", },
{ "XCode", "com.apple.dt.Xcode" },
{ "Console", "com.apple.Console", },
{ "Terminal", "com.apple.Terminal" },
{ "BBEdit", "com.barebones.bbedit" },
{ "Safari", "com.apple.Safari" },
{ "Activity Monitor", "com.apple.ActivityMonitor"},
{ "AXUI Inspector", "com.apple.AccessibilityInspector"},
}, function(entry)
local app, bundleID = table.unpack(entry)
table.insert(consoleToolbar, {
id = bundleID,
label = app,
tooltip = app,
image = image.imageFromAppBundle(bundleID),
fn = function(bar, attachedTo, item)
application.launchOrFocusByBundleID(bundleID)
end,
default = false,
})
end)
table.insert(consoleToolbar, {
id = "internet",
label = "Internet",
tooltip = "Internet Status",
image = image.imageFromName(module.watchInternetStatus:value() and "NSToolbarBookmarks" or "NSStopProgressFreestandingTemplate"),
fn = function(bar, attachedTo, item)
end,
default = false,
})
table.insert(consoleToolbar, {
id = "privateVPN",
label = "Private VPN",
tooltip = "Private VPN State",
image = image.imageFromName(module.watchVPNStatus:value() and "NSLockLockedTemplate" or "NSLockUnlockedTemplate"),
fn = function(bar, attachedTo, item)
end,
default = false,
})
table.insert(consoleToolbar, {
id = "hammerspoonDocumentation",
label = "HS Documentation",
tooltip = "Show HS Documentation Browser",
image = image.imageFromName("NXHelpIndex"),
fn = function(bar, attachedTo, item)
local base = require"hs.doc.hsdocs"
if not base._browser then
base.help()
else
base._browser:show()
end
end,
default = false,
})
table.insert(consoleToolbar, {
id = "cheatsheet",
label = "CheatSheet Status",
tooltip = "Toggle CheatSheet Functionality",
image = module.watchCheatSheetStatus:value() and cheatSheetOn or cheatSheetOff,
fn = function(t, a, i)
module.watchCheatSheetStatus:change(not module.watchCheatSheetStatus:value())
end,
default = false,
})
table.insert(consoleToolbar, {
id = "popConsole",
label = "popConsole Status",
tooltip = "Toggle popConsole Functionality",
image = module.watchPopConsoleStatus:value() and popConsoleOn or popConsoleOff,
fn = function(t, a, i)
module.watchPopConsoleStatus:change(not module.watchPopConsoleStatus:value())
end,
default = false,
})
table.insert(consoleToolbar, {
id = "viKeys",
label = "viKeys Status",
tooltip = "Toggle viKeys Functionality",
image = module.watchViKeysStatus:value() and viKeysOn or viKeysOff,
fn = function(t, a, i)
module.watchViKeysStatus:change(not module.watchViKeysStatus:value())
end,
default = false,
})
local makeModuleListForMenu = function()
local searchList = {}
for i,v in ipairs(doc._jsonForModules) do
table.insert(searchList, v.name)
end
for i,v in ipairs(doc._jsonForSpoons) do
table.insert(searchList, "spoon." .. v.name)
end
table.sort(searchList, function(a, b) return a:lower() < b:lower() end)
return searchList
end
table.insert(consoleToolbar, {
id = "searchID",
label = "HS Doc Search",
tooltip = "Search for a HS function or method",
fn = function(t, w, i, text)
if text ~= "" then require"hs.doc.hsdocs".help(text) end
end,
default = false,
searchfield = true,
searchPredefinedMenuTitle = false,
searchPredefinedSearches = makeModuleListForMenu(),
searchWidth = 250,
})
module._moduleListChanges = watchable.watch("hs.doc", "changeCount", function(w, p, k, o, n)
if module.toolbar then
module.toolbar:modifyItem{
id = "searchID",
searchPredefinedSearches = makeModuleListForMenu(),
}
end
end)
module.toolbar = toolbar.new("_asmConsole_001")
:addItems(consoleToolbar)
:canCustomize(true)
:autosaves(true)
:separator(false)
:setCallback(function(...)
print("+++ Oops! You better assign me something to do!")
end)
console.toolbar(module.toolbar)
-- not in core yet
if console.titleVisibility then console.titleVisibility("hidden") end
return setmetatable(module, {
__gc = function(self)
hs.openConsole() --trying to figure out what's causing console growth creep when a toolbar is attached
console.toolbar(nil)
end,
})
|
--[[
--=====================================================================================================--
Script Name: Console Logo, for SAPP (PC & CE)
Description: Custom ascii console logo
NOTES:
USE THIS WEBSITE TO GENERATE YOUR LOGO:
https://patorjk.com/software/taag/#p=display&f=Graffiti&t=Type%20Something%20
Some fonts will NOT work due to something called character escaping.
I recommend using the font "KBAN"
Copyright (c) 2021, Jericho Crosby <jericho.crosby227@gmail.com>
* Notice: You can use this document subject to the following conditions:
https://github.com/Chalwk77/HALO-SCRIPT-PROJECTS/blob/master/LICENSE
--=====================================================================================================--
]]--
-- config starts --
-- See this page for instructions on tweaking the time stamp format:
-- https://www.lua.org/pil/22.1.html
local time_stamp_format = "%A, %d %B %Y - %X"
local logo = {
-- format: {"text", text color code}
-- See SAPP documentation for color codes:
-- http://halo.isimaginary.com/SAPP%20Documentation%20Revision%202.5.pdf
-- Make sure logo text is encapsulated in "quotes".
-- Custom Variables: "%time_stamp%" & "%server_name%"
-- Use anywhere to output their values
{ "================================================================================", 10 },
{ "%time_stamp%", 6 },
{ "" },
{ " '||' '||' | '||' ..|''|| ..|'''.| '||''''| ", 12, },
{ " || || ||| || .|' || .|' ' || . ", 12, },
{ " ||''''|| | || || || || || ||''| ", 12, },
{ " || || .''''|. || '|. || '|. . || ", 12, },
{ " .||. .||. .|. .||. .||.....| ''|...|' ''|....' .||.....| ", 12, },
{ " ->-<->-<->-<->-<->-<->-<->-<->-<->-<->-<->-<->-<->-", 7 },
{ " %server_name%", 10 },
{ " ->-<->-<->-<->-<->-<->-<->-<->-<->-<->-<->-<->-<->-", 7 },
{ "" },
{ "================================================================================", 10 }
}
-- config ends --
api_version = "1.12.0.0"
function OnScriptLoad()
timer(50, "PrintLogo")
end
local function read_widestring(a, l)
local count = 0
local byte_table = {}
for i = 1, l do
if (read_byte(a + count) ~= 0) then
byte_table[i] = string.char(read_byte(a + count))
end
count = count + 2
end
return table.concat(byte_table)
end
function PrintLogo()
if (get_var(0, "$gt") ~= "n/a") then
local time_stamp = os.date(time_stamp_format)
local network_struct = read_dword(sig_scan("F3ABA1????????BA????????C740??????????E8????????668B0D") + 3)
local server_name = read_widestring(network_struct + 0x8, 0x42)
for _, v in pairs(logo) do
local text = v[1]
local color = v[2] or 0
cprint(text:gsub("%%time_stamp%%", time_stamp):gsub("%%server_name%%", server_name), color)
end
end
end
function OnScriptUnload()
-- N/A
end
|
local win = am.window{
title = "tunnel",
}
-- constants
local num_edges = 7
local num_rings = 50
local ring_gap = 2
local forward = vec3(0, 0, -1)
local up = vec3(0, 1, 0)
-- state
local player_pos = vec3(0)
local player_speed = vec3(0, 0, -50)
local ring_color = vec4(1)
local radius = 10
-- tunnel shader
local t_vert_shader = [[
precision highp float;
attribute vec3 vert;
attribute vec4 color;
uniform mat4 MV;
uniform mat4 P;
varying vec4 v_color;
void main() {
v_color = color;
gl_Position = P * MV * vec4(vert, 1.0);
}
]]
local t_frag_shader = [[
precision mediump float;
varying vec4 v_color;
void main() {
gl_FragColor = v_color;
}
]]
-- postprocess shader
local pp_vert_shader = [[
precision highp float;
attribute vec2 vert;
attribute vec2 uv;
varying vec2 v_uv;
uniform mat4 MV;
uniform mat4 P;
void main() {
v_uv = uv;
gl_Position = P * MV * vec4(vert, 0.0, 1.0);
}
]]
local pp_frag_shader = [[
precision mediump float;
uniform sampler2D tex;
varying vec2 v_uv;
void main() {
vec2 coord = gl_FragCoord.xy;
float noise1 = fract(sin(dot(coord, vec2(12.9898,78.233))) * 43.5453);
gl_FragColor = fract(texture2D(tex, v_uv + vec2(noise1 * 0.01, 0.0)));
}
]]
-- create tunnel vertices
local verts = am.buffer(num_edges * num_rings * 12):view"vec3"
local colors = am.buffer(num_edges * num_rings * 16):view"vec4"
function add_ring(i, pos)
local v = (i - 1) * num_edges + 1
local r = math.random()
for j = 1, num_edges do
local angle = (j - 1) / num_edges * 2 * math.pi + r
local x = math.cos(angle) * radius
local y = math.sin(angle) * radius
verts[v] = vec3(x, y, 0) + pos
if math.random() > 0.1 then
colors[v] = ring_color
else
colors[v] = vec4(math.randvec3(), 1)
end
local delta_color = am.delta_time * (math.randvec3() - 0.5) * 3
ring_color = math.clamp(ring_color + vec4(delta_color, 1), vec4(0), vec4(1))
v = v + 1
end
radius = (math.sin(am.frame_time / 10) + 1) * 0.5 * 60
end
for i = 1, num_rings do
add_ring(i, vec3(0, 0, -i * ring_gap + 10))
end
local lines = {}
local l = 1
local v = 1
for i = 1, num_rings do
for j = 1, num_edges do
if j > 1 then
lines[l] = v - 1
lines[l + 1] = v
else
lines[l] = v + num_edges - 1
lines[l + 1] = v
end
v = v + 1
l = l + 2
end
end
-- create tunnel node
local tunnel_node =
am.use_program(am.program(t_vert_shader, t_frag_shader))
^ am.bind{
vert = verts,
color = colors,
}
^ am.draw("lines", am.uint_elem_array(lines))
-- create main scene node
local main_scene =
am.postprocess{
auto_clear = false,
width = 320,
height = 240,
program = am.program(pp_vert_shader, pp_frag_shader)
}
^ am.bind{P = math.perspective(math.rad(70), win.width/win.height, 1, 1000)}
^ am.lookat(player_pos, player_pos + forward, up):tag"camera"
^ tunnel_node
-- main action (run once per frame)
local next_ring = 1
local t = 0
function main_action()
forward = math.normalize(vec3(-win:mouse_norm_position(), -1))
local cam = main_scene"camera"
cam.eye = player_pos
cam.center = player_pos + forward
player_pos = player_pos + player_speed * am.delta_time
t = t + am.delta_time
while -player_speed.z / t >= ring_gap do
local ring_pos = player_pos - vec3(0, 0, num_rings * ring_gap - 10)
add_ring(next_ring, ring_pos)
t = t + ring_gap / player_speed.z
next_ring = next_ring % num_rings + 1
end
end
-- attach main_action to main_scene
main_scene:action(main_action)
-- attach main scene to window
win.scene = main_scene
|
local m = require 'lpeglabel'
local matcher = require 'glob.matcher'
local function prop(name, pat)
return m.Cg(m.Cc(true), name) * pat
end
local function object(type, pat)
return m.Ct(
m.Cg(m.Cc(type), 'type') *
m.Cg(pat, 'value')
)
end
local function expect(p, err)
return p + m.T(err)
end
local parser = m.P {
'Main',
['Sp'] = m.S(' \t')^0,
['Slash'] = m.P('/')^1,
['Main'] = m.Ct(m.V'Sp' * m.P'{' * m.V'Pattern' * (',' * expect(m.V'Pattern', 'Miss exp after ","'))^0 * m.P'}')
+ m.Ct(m.V'Pattern')
+ m.T'Main Failed'
,
['Pattern'] = m.Ct(m.V'Sp' * prop('neg', m.P'!') * expect(m.V'Unit', 'Miss exp after "!"'))
+ m.Ct(m.V'Unit')
,
['NeedRoot'] = prop('root', (m.P'.' * m.V'Slash' + m.V'Slash')),
['Unit'] = m.V'Sp' * m.V'NeedRoot'^-1 * expect(m.V'Exp', 'Miss exp') * m.V'Sp',
['Exp'] = m.V'Sp' * (m.V'FSymbol' + object('/', m.V'Slash') + m.V'Word')^0 * m.V'Sp',
['Word'] = object('word', m.Ct((m.V'CSymbol' + m.V'Char' - m.V'FSymbol')^1)),
['CSymbol'] = object('*', m.P'*')
+ object('?', m.P'?')
+ object('[]', m.V'Range')
,
['SimpleChar'] = m.P(1) - m.S',{}[]*?/',
['EscChar'] = m.P'\\' / '' * m.P(1),
['Char'] = object('char', m.Cs((m.V'EscChar' + m.V'SimpleChar')^1)),
['FSymbol'] = object('**', m.P'**'),
['RangeWord'] = 1 - m.P']',
['Range'] = m.P'[' * m.Ct(m.V'RangeUnit'^0) * m.P']'^-1,
['RangeUnit'] = m.Ct(m.C(m.V'RangeWord') * m.P'-' * m.C(m.V'RangeWord'))
+ m.V'RangeWord',
}
local mt = {}
mt.__index = mt
mt.__name = 'glob'
function mt:addPattern(pat)
if type(pat) ~= 'string' then
return
end
self.pattern[#self.pattern+1] = pat
if self.options.ignoreCase then
pat = pat:lower()
end
local states, err = parser:match(pat)
if not states then
self.errors[#self.errors+1] = {
pattern = pat,
message = err
}
return
end
for _, state in ipairs(states) do
if state.neg then
self.refused[#self.refused+1] = matcher(state)
else
self.passed[#self.passed+1] = matcher(state)
end
end
end
function mt:setOption(op, val)
if val == nil then
val = true
end
self.options[op] = val
end
function mt:__call(path)
if self.options.ignoreCase then
path = path:lower()
end
for _, refused in ipairs(self.refused) do
if refused(path) then
return false
end
end
for _, passed in ipairs(self.passed) do
if passed(path) then
return true
end
end
return false
end
return function (pattern, options)
local self = setmetatable({
pattern = {},
options = {},
passed = {},
refused = {},
errors = {},
}, mt)
if type(pattern) == 'table' then
for _, pat in ipairs(pattern) do
self:addPattern(pat)
end
else
self:addPattern(pattern)
end
if type(options) == 'table' then
for op, val in pairs(options) do
self:setOption(op, val)
end
end
return self
end
|
minetest.register_craftitem("snowball:ball", {
description = "Throwable Snowball",
range = 0,
stack_max= 16,
inventory_image = "snowball.png",
on_use = function(itemstack, user, pointed_thing)
if not minetest.setting_getbool("creative_mode") then itemstack:take_item()
end
if pointed_thing.type ~= "nothing" then
local pointed = minetest.get_pointed_thing_position(pointed_thing)
if vector.distance(user:getpos(), pointed) < 8 then
return itemstack
end
end
local pos = user:getpos()
local dir = user:get_look_dir()
local yaw = user:get_look_yaw()
if pos and dir then
pos.y = pos.y + 1.5
local obj = minetest.add_entity(pos, "snowball:snow")
if obj then
obj:setvelocity({x=dir.x * 35, y=dir.y * 35, z=dir.z * 35})
obj:setacceleration({x=dir.x * -3, y=-10, z=dir.z * -3})
obj:setyaw(yaw + math.pi)
local ent = obj:get_luaentity()
if ent then
ent.player = ent.player or user
end
end
end
return itemstack
end,
})
local SNOWBALL = {
physical = false,
timer = 0,
visual = "cube",
visual_size = {x=0.5, y=0.0,},
textures = {'snowball.png','snowball.png','snowball.png','snowball.png','snowball.png','snowball.png'},
lastpos= {},
collisionbox = {0, 0, 0, 0, 0, 0},
}
SNOWBALL.on_step = function(self, dtime)
self.timer = self.timer + dtime
local pos = self.object:getpos()
local node = minetest.get_node(pos)
if self.timer > 0.07 then
local objs = minetest.get_objects_inside_radius({x = pos.x, y = pos.y, z = pos.z}, 1)
for k, obj in pairs(objs) do
if obj:get_luaentity() ~= nil then
if obj:get_luaentity().name ~= "snowball:snow" and obj:get_luaentity().name ~= "__builtin:item" then
local damage = 6
obj:punch(self.object, 1.0, {
full_punch_interval = 1.0,
damage_groups= {fleshy = damage},
}, nil)
minetest.sound_play("default_dig_cracky", {pos = self.lastpos, gain = 0.8})
self.object:remove()
end
else
local damage = 6
obj:punch(self.object, 1.0, {
full_punch_interval = 1.0,
damage_groups= {fleshy = damage},
}, nil)
minetest.sound_play("default_dig_cracky", {pos = self.lastpos, gain = 0.8})
self.object:remove()
end
end
end
if self.lastpos.x ~= nil then
if minetest.registered_nodes[node.name].walkable then
if not minetest.setting_getbool("creative_mode") then
minetest.add_item(self.lastpos, "")
end
minetest.sound_play("default_dig_cracky", {pos = self.lastpos, gain = 0.8})
self.object:remove()
end
end
self.lastpos= {x = pos.x, y = pos.y, z = pos.z}
end
minetest.register_entity("snowball:snow", SNOWBALL)
minetest.register_craft({
type = "cooking",
output = 'snowball:ball',
recipe = 'default:snow',
})
minetest.register_craft({
output = 'snowball:ball 3',
recipe = {
{'default:snow', '', ''},
{'', '', ''},
{'', '', ''},
}
})
|
require 'socket'
local c = socket.connect('localhost',3335)
local log = io.open('log.txt','a')
function readfile(file)
local f,err = io.open(file)
if not f then return nil,err end
local contents = f:read '*a':gsub('\n','\001')
f:close()
return contents
end
function eval(line)
c:send(line..'\n')
local res = c:receive()
return res:gsub('\001','\n')
end
local init,err = readfile 'init.lua'
if init then
print 'loading init.lua'
io.write(eval(init)..'\n')
end
io.write '> '
local line = io.read()
while line do
log:write(line,'\n')
local cmd,file = line:match '^%.(.)%s+(.+)$'
if file then
local mod
if cmd == 'm' then
mod = file
file = mod:gsub('%.','/')..'.lua'
end
line,err = readfile(file)
if mod and line then
line = '--mod:'..mod..'\001'..line
end
else
local expr = line:match '^%s*=%s*(.+)$'
if expr then
line = 'print('..expr..')'
end
end
if line then
local res = eval(line)
log:write(res,'\n')
io.write(res)
else
print(err)
end
io.write '> '
line = io.read()
end
log:close()
c:close()
|
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ==========
PlaceObj('XTemplate', {
group = "Infopanel Sections",
id = "ipAlienDigger",
PlaceObj('XTemplateTemplate', {
'__context_of_kind', "AlienDigger",
'__template', "Infopanel",
}, {
PlaceObj('XTemplateTemplate', {
'comment', "salvage",
'__condition', function (parent, context) return UICity.mystery.can_destroy_diggers end,
'__template', "InfopanelButton",
'OnContextUpdate', function (self, context, ...)
if context.is_being_destroyed then
self:SetIcon("UI/Icons/IPButtons/cancel.tga")
self:SetRolloverTitle(T(1176, "Cancel Destroy"))
self:SetRolloverText(T(1178, "Cancel the order to destroy the alien Dredger."))
else
self:SetIcon("UI/Icons/IPButtons/demolition.tga")
self:SetRolloverTitle(T(1175, "Destroy"))
self:SetRolloverText(T(1177, "Destroy this Dredger by sending a Drone to overload the fuel ignition systems."))
end
end,
'OnPressParam', "ToggleDestroyFromUI",
}),
}),
})
|
----------------------------------------------
-- Sample of SlibRGB57wTM1640.lua for W4.00.03
-- Copyright (c) 2019, AoiSaya
-- All rights reserved.
-- 2019/09/01 rev.0.03
-----------------------------------------------
function chkBreak(n)
sleep(n or 0)
if fa.sharedmemory("read", 0x00, 0x01, "") == "!" then
error("Break!",2)
end
end
fa.sharedmemory("write", 0x00, 0x01, "-")
local script_path = function()
local str = debug.getinfo(2, "S").source:sub(2)
return str:match("(.*/)")
end
--main
local myDir = script_path()
local libDir = myDir.."lib/"
local fontDir= myDir.."font/"
local led = require(libDir.."SlibRGB57wTM1640")
local jfont = require(libDir.."SlibJfont")
local a3x8 = jfont:open("3x8.sef")
local k6x8 = jfont:open("k6x8.sef")
local bright = 1 -- 0..8
local d, r, g, b
local str= {
"そらまめ34号から",
"たいせつな",
"お知らせ ",
"FlashAir Developers",
"は",
"2019/9/17",
"正午に",
"ヘイサ",
"されます "
}
led:setup(bright)
jfont:setFont(a3x8,k6x8)
local color = 1
rgb = {}
for i=1,15 do
rgb[i] = 0
end
while 1 do
chkBreak(5000)
for _,strUTF8 in ipairs(str) do
strEUC, euc_length = jfont:utf82euc(strUTF8)
p=1
b = bit32.btest(color,1)
r = bit32.btest(color,2)
g = bit32.btest(color,4)
color = color % 7 + 1
while p<=#strEUC do
bitmap,fh,fw,p = jfont:getFont(strEUC, p)
for i=1,fw==3 and 4 or fw do
rgb = {table.unpack(rgb,4)}
d = i<=fw and bitmap[i] or 0
rgb[13] = r and d or 0
rgb[14] = g and d or 0
rgb[15] = b and d or 0
led:write(rgb)
chkBreak(80)
end
collectgarbage()
end
end
chkBreak(2000)
end
|
-- MODULE CONFIG.LUA
-- by Garran Plum
--
-- GP Configuration for this individual mod.
-- IMPORT GP OBJECT
local myMod, GP = ...
GP:log("config.lua", GP:version())
-- MY CONFIG Mod Name
local modName = "DETAILER"
-- MY CONFIG Remix
local remix = {
-- Pine Trees
-- Fancy Nature Pack
PINES = {"JK_PINE_A_PART", "JK_PINE_B_PART", "JK_PINE_C_PART"},
-- Maple Trees
-- Fancy Nature Pack
MAPLES = {"JK_MAPLE_A_PART", "JK_MAPLE_B_PART"},
-- Oak Trees
-- Fancy Nature Pack
OAKS = {"JK_OAK_A_PART", "JK_OAK_B_PART", "JK_OAK_C_PART"},
-- Beech Trees
-- Fancy Nature Pack
BEECHES = {
"JK_BEECH_A_PART", "JK_BEECH_B_PART", "JK_BEECH_C_PART",
"JK_BEECH_D_PART", "JK_BEECH_SAPLING_A_PART"
},
-- Birch Trees
-- Fancy Nature Pack
BIRCHES = {"JK_BIRCH_A_PART", "JK_BIRCH_B_PART", "JK_BIRCH_C_PART"},
-- Misc. Trees
-- Nature Deco
TREES = {
"TREE_SWAMP", "TREE_SWAMP2", "TREE_SWAMP3", "TREE_DEAD", "TREE_DEAD2",
"TREE_DEAD3"
},
-- Shrubs & Bushes
-- Nature Deco
SHRUBS = {
"FERN", -- Fancy Nature Pack
"JK_SHRUB_FERN_PART", "JK_SHRUB_A_PART", "JK_SHRUB_FORSYTHIA_PART",
"JK_SHRUB_STEPHANANDRA_PART", "JK_SHRUB_LAVENDER_PART"
},
-- Flowers
-- Fancy Nature Pack
FLOWERS = {
"JK_FLOWER_CORNFLOWER_PART", "JK_FLOWER_POPPIES_PART",
"JK_FLOWER_CHAMOMILE_PART", "JK_MUSHROOM_PART"
},
-- Grass
-- Shrubbery
GRASS = {
"GRASS01SMALL", "GRASS01MED", "GRASS01LARGE", -- Nature Deco
"GRASS1", "GRASS2"
},
-- Large Rocks (Boulders)
-- Nature Deco
LGROCKS = {
"BOULDER1", "BOULDER2", "BOULDER3", "BOULDER4", "BOULDER5", "BOULDER6"
},
-- Medium Rocks (Stones)
-- Nature Deco
MEDROCKS = {
"STONE_TALL1", "STONE_TALL2", "STONE_TALL3", "STONE_FLAT1",
"STONE_FLAT2", "STONE_FLAT3"
},
-- Small Rocks (Rocks!)
-- Nature Deco
SMROCKS = {
"STONE1", "STONE2", "STONE3", "STONE4", "STONE5", "STONE6", "STONE7",
"STONE8", "STONE9"
},
-- Logs
-- Nature Deco
LOGS = {"MUSHROOM_LOG", "TREE_FALLEN", "TREE_FALLEN2", "TREE_STUMP"},
-- Aquatic Plants
WATER = {"LILYPAD1", "LILYPAD2", "LILYPAD3", "REED1", "REED2"},
-- Animals
-- Fantasy Deco
FAUNA = {
"CAT_PART", "DOG_PART", "RABBIT_PART", "CHICKEN1_PART", "CHICKEN2_PART",
"GOOSE1_PART"
}
}
-- MY CONFIG Categories
local categories = {
PINES = {
JK_PINE_A_PART = {Order = 1}, JK_PINE_B_PART = {Order = 2}, JK_PINE_C_PART = {Order = 3}
},
MAPLES = {
JK_MAPLE_A_PART = {Order = 1}, JK_MAPLE_B_PART = {Order = 2}
},
OAKS = {
JK_OAK_A_PART = {Order = 1}, JK_OAK_B_PART = {Order = 2}, JK_OAK_C_PART = {Order = 3}
},
BEECHES = {
JK_BEECH_A_PART = {Order = 1}, JK_BEECH_B_PART = {Order = 2}, JK_BEECH_C_PART = {Order = 3},
JK_BEECH_D_PART = {Order = 4}, JK_BEECH_SAPLING_A_PART = {Order = 5}
},
BIRCHES = {
JK_BIRCH_A_PART = {Order = 1}, JK_BIRCH_B_PART = {Order = 2}, JK_BIRCH_C_PART = {Order = 3}
},
TREES = {
TREE_SWAMP = {Order = 1}, TREE_SWAMP2 = {Order = 2}, TREE_SWAMP3 = {Order = 3},
TREE_DEAD = {Order = 4}, TREE_DEAD2 = {Order = 5}, TREE_DEAD3 = {Order = 6}
},
SHRUBS = {
FERN = {Order = 1}, JK_SHRUB_FERN_PART = {Order = 2}, JK_SHRUB_A_PART = {Order = 3},
JK_SHRUB_FORSYTHIA_PART = {Order = 4}, JK_SHRUB_STEPHANANDRA_PART = {Order = 5}, JK_SHRUB_LAVENDER_PART = {Order = 6}
},
FLOWERS = {
JK_FLOWER_CORNFLOWER_PART = {Order = 1}, JK_FLOWER_POPPIES_PART = {Order = 2},
JK_FLOWER_CHAMOMILE_PART = {Order = 3}, JK_MUSHROOM_PART = {Order = 4}
},
GRASS = {
GRASS01SMALL = {Order = 1}, GRASS01MED = {Order = 2}, GRASS01LARGE = {Order = 3},
GRASS1 = {Order = 4}, GRASS2 = {Order = 5}
},
LGROCKS = {
BOULDER1 = {Order = 1}, BOULDER2 = {Order = 2}, BOULDER3 = {Order = 3},
BOULDER4 = {Order = 4}, BOULDER5 = {Order = 5}, BOULDER6 = {Order = 6}
},
MEDROCKS = {
STONE_TALL1 = {Order = 1}, STONE_TALL2 = {Order = 2}, STONE_TALL3 = {Order = 3},
STONE_FLAT1 = {Order = 4}, STONE_FLAT2 = {Order = 5}, STONE_FLAT3 = {Order = 6}
},
SMROCKS = {
STONE1 = {Order = 1}, STONE2 = {Order = 2}, STONE3 = {Order = 3},
STONE4 = {Order = 4}, STONE5 = {Order = 5}, STONE6 = {Order = 6},
STONE7 = {Order = 7}, STONE8 = {Order = 8}, STONE9 = {Order = 9}
},
LOGS = {
MUSHROOM_LOG = {Order = 1}, TREE_FALLEN = {Order = 3}, TREE_FALLEN2 = {Order = 4}, TREE_STUMP = {Order = 2}
},
WATER = {
LILYPAD1 = {Order = 1}, LILYPAD2 = {Order = 2}, LILYPAD3 = {Order = 3}, REED1 = {Order = 4}, REED2 = {Order = 5}
},
FAUNA = {
DOG_PART = {Order = 2}, CAT_PART = {Order = 1}, RABBIT_PART = {Order = 3},
CHICKEN1_PART = {Order = 4}, CHICKEN2_PART = {Order = 5}, GOOSE1_PART = {Order = 6}
}
}
-- MY CONFIG Monuments
local monuments = {
[modName] = {
Categories = {
PINES = {Order = 1},
MAPLES = {Order = 2},
OAKS = {Order = 3},
BEECHES = {Order = 4},
BIRCHES = {Order = 5},
TREES = {Order = 6},
SHRUBS = {Order = 7},
FLOWERS = {Order = 8},
GRASS = {Order = 9},
LGROCKS = {Order = 10},
MEDROCKS = {Order = 11},
SMROCKS = {Order = 12},
LOGS = {Order = 13},
WATER = {Order = 14},
FAUNA = {Order = 15}
},
Type = "DECORATION"
}
}
--
--
--
--
--
-- WARNING!
--
-- MY CONFIG Ends Here. Changing code below this line will change *GPS*, not just your mod!
-- As an alternative to the code above, you may supply your own config table to GP.loaded.
--
--
-- Create the config table.
local config = {
version = GP:version(),
remix = remix or {},
modName = modName,
modelFiles = modelFiles or {},
categories = categories or {},
nodeTypes = nodeTypes or {},
jobs = jobs or {},
workplaces = workplaces or {},
monuments = monuments or {}
}
-- Use global to return config to loader :-(.
GP.loaded = config
|
--settings.lua
data:extend(
{
{
type = "bool-setting",
name = "debug-messages",
order = "aa",
setting_type = "runtime-global",
localised_name = "Debug messages?",
localised_description = "[facDump] Should we turn on debug messages?",
default_value = false,
per_user = true
}
}
)
|
slot0 = class("BattleGateTest")
ys.Battle.BattleGateTest = slot0
slot0.__name = "BattleGateTest"
slot0.Entrance = function (slot0, slot1)
if not slot1.LegalFleet(slot0.mainFleetId) then
return
end
slot4 = {}
for slot10, slot11 in ipairs(slot6) do
slot4[#slot4 + 1] = slot11.id
end
slot7 = slot0.mainFleetId
slot9 = pg.expedition_data_template[slot0.stageId].dungeon_id
BeginStageCommand.SendRequest(SYSTEM_TEST, slot4, {
slot0.stageId
}, function (slot0)
slot0.key:sendNotification(GAME.BEGIN_STAGE_DONE, {
mainFleetId = slot0,
prefabFleet = {},
stageId = slot1,
system = SYSTEM_TEST,
token = slot0.key
})
end, function (slot0)
slot0:RequestFailStandardProcess(slot0)
end)
end
slot0.Exit = function (slot0, slot1)
slot2 = pg.battle_cost_template[SYSTEM_TEST]
slot5 = slot0.statistics._battleScore
slot6 = 0
slot7 = {}
slot1.SendRequest(slot1, slot1.GeneralPackage(slot0, slot7), function (slot0)
slot0.statistics.mvpShipID = -1
{}:sendNotification(GAME.FINISH_STAGE_DONE, {
system = SYSTEM_TEST,
statistics = slot0.statistics,
score = slot1,
drops = {},
commanderExps = {},
result = slot0.result,
extraDrops =
})
end)
end
return slot0
|
--[[
This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:25' using the latest game version.
NOTE: This file should only be used as IDE support; it should NOT be distributed with addons!
****************************************************************************
CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC.
****************************************************************************
]]
-- Piece --
ZO_ItemSetCollectionPieceData = ZO_InitializingObject:Subclass()
function ZO_ItemSetCollectionPieceData:Initialize(pieceId, itemSetCollectionSlot)
self.pieceId = pieceId
self.itemSetCollectionSlot = itemSetCollectionSlot
self:RefreshItemLink() -- Update it the first time immediately during the load screen
end
function ZO_ItemSetCollectionPieceData:GetId()
return self.pieceId
end
function ZO_ItemSetCollectionPieceData:GetItemSetCollectionSlot()
return self.itemSetCollectionSlot
end
function ZO_ItemSetCollectionPieceData:GetSetId()
return self.itemSetCollectionData:GetId()
end
function ZO_ItemSetCollectionPieceData:SetItemSetCollectionData(itemSetCollectionData)
self.itemSetCollectionData = itemSetCollectionData
end
function ZO_ItemSetCollectionPieceData:GetItemSetCollectionData()
return self.itemSetCollectionData
end
function ZO_ItemSetCollectionPieceData:MarkItemLinkDirty()
self.isItemLinkDirty = true
end
function ZO_ItemSetCollectionPieceData:InternalCreateItemLink()
return GetItemSetCollectionPieceItemLink(self.pieceId, LINK_STYLE_DEFAULT, ITEM_TRAIT_TYPE_NONE)
end
function ZO_ItemSetCollectionPieceData:RefreshItemLink()
-- As these are often accessed from entry instance data, make sure that the refreshed info actually gets applied to the source data and not the entry instance data
-- In order to keep this hefty system more lightweight, let the garbage collector clean up isItemLinkDirty. It shouldn't dirty often, so no reason to keep the memory around
local itemLink = self:InternalCreateItemLink()
if self.dataSource then
self.dataSource.itemLink = itemLink
self.dataSource.isItemLinkDirty = nil
else
self.itemLink = itemLink
self.isItemLinkDirty = nil
end
end
function ZO_ItemSetCollectionPieceData:GetItemLink()
if self.isItemLinkDirty then
self:RefreshItemLink()
end
return self.itemLink
end
function ZO_ItemSetCollectionPieceData:GetRawName()
return GetItemLinkName(self:GetItemLink())
end
function ZO_ItemSetCollectionPieceData:GetRawColorizedName()
local colorDef = GetItemQualityColor(self:GetDisplayQuality())
return colorDef:Colorize(self:GetName())
end
function ZO_ItemSetCollectionPieceData:GetFormattedName()
return zo_strformat(SI_LINK_FORMAT_ITEM_NAME, self:GetRawName())
end
function ZO_ItemSetCollectionPieceData:GetFormattedColorizedName()
local colorDef = GetItemQualityColor(self:GetDisplayQuality())
return colorDef:Colorize(self:GetFormattedName())
end
function ZO_ItemSetCollectionPieceData:GetFunctionalQuality()
return GetItemLinkFunctionalQuality(self:GetItemLink())
end
function ZO_ItemSetCollectionPieceData:GetDisplayQuality()
return GetItemLinkDisplayQuality(self:GetItemLink())
end
function ZO_ItemSetCollectionPieceData:GetArmorType()
return GetItemLinkArmorType(self:GetItemLink())
end
function ZO_ItemSetCollectionPieceData:GetEquipmentFilterType()
return GetEquipmentFilterTypeForItemSetCollectionSlot(self:GetItemSetCollectionSlot())
end
function ZO_ItemSetCollectionPieceData:MatchesEquipmentFilterTypes(equipmentFilterTypes)
return ZO_IsElementInNumericallyIndexedTable(equipmentFilterTypes, self:GetEquipmentFilterType())
end
function ZO_ItemSetCollectionPieceData:GetIcon()
return GetItemLinkIcon(self:GetItemLink())
end
function ZO_ItemSetCollectionPieceData:GetTraitType()
return GetItemLinkTraitType(self:GetItemLink())
end
function ZO_ItemSetCollectionPieceData:GetTraitCategory()
return GetItemLinkTraitCategory(self:GetItemLink())
end
function ZO_ItemSetCollectionPieceData:GetTradeskillType()
return GetItemLinkCraftingSkillType(self:GetItemLink())
end
function ZO_ItemSetCollectionPieceData:IsUnlocked()
-- There's a piece id function, but using the slot, if it's already known, is more effecient
return IsItemSetCollectionSlotUnlocked(self:GetSetId(), self:GetItemSetCollectionSlot())
end
function ZO_ItemSetCollectionPieceData:IsLocked()
return not self:IsUnlocked()
end
function ZO_ItemSetCollectionPieceData:IsNew()
return IsItemSetCollectionSlotNew(self:GetSetId(), self:GetItemSetCollectionSlot())
end
function ZO_ItemSetCollectionPieceData:ClearNew(dontBroadcast)
ClearItemSetCollectionSlotNew(self:GetSetId(), self:GetItemSetCollectionSlot(), not dontBroadcast)
end
function ZO_ItemSetCollectionPieceData:IsSearchResult()
-- Text search filters on sets, not individual pieces
return self.itemSetCollectionData:IsSearchResult()
end
-- Reconstruction Piece --
ZO_ItemSetCollectionReconstructionPieceData = ZO_ItemSetCollectionPieceData:Subclass()
function ZO_ItemSetCollectionReconstructionPieceData:Initialize()
-- Info will be set post initialize
end
function ZO_ItemSetCollectionReconstructionPieceData:Copy(itemSetCollectionPieceData)
self.pieceId = itemSetCollectionPieceData:GetId()
self.itemSetCollectionSlot = itemSetCollectionPieceData:GetItemSetCollectionSlot()
self.itemSetCollectionData = itemSetCollectionPieceData:GetItemSetCollectionData()
self:MarkItemLinkDirty()
self.overrideTraitType = ITEM_TRAIT_TYPE_NONE
self.upgradeFunctionalQuality = nil
end
function ZO_ItemSetCollectionReconstructionPieceData:GetOverrideTraitType()
return self.overrideTraitType
end
function ZO_ItemSetCollectionReconstructionPieceData:SetOverrideTraitType(overrideTraitType)
if self.overrideTraitType ~= overrideTraitType then
self.overrideTraitType = overrideTraitType
self:MarkItemLinkDirty()
end
end
function ZO_ItemSetCollectionReconstructionPieceData:GetMinimumFunctionalQuality()
return GetItemLinkFunctionalQuality(GetItemSetCollectionPieceItemLink(self.pieceId, LINK_STYLE_DEFAULT, ITEM_TRAIT_TYPE_NONE))
end
function ZO_ItemSetCollectionReconstructionPieceData:GetUpgradeFunctionalQuality()
return self.upgradeFunctionalQuality or self:GetFunctionalQuality()
end
function ZO_ItemSetCollectionReconstructionPieceData:SetUpgradeFunctionalQuality(upgradeFunctionalQuality)
if self.upgradeFunctionalQuality ~= upgradeFunctionalQuality then
self.upgradeFunctionalQuality = upgradeFunctionalQuality
self:MarkItemLinkDirty()
end
end
function ZO_ItemSetCollectionReconstructionPieceData:InternalCreateItemLink()
return GetItemSetCollectionPieceItemLink(self.pieceId, LINK_STYLE_DEFAULT, self.overrideTraitType, self.upgradeFunctionalQuality)
end
function ZO_ItemSetCollectionReconstructionPieceData:GetCostInfo(overrideFunctionalQuality)
local itemSetCollectionData = self:GetItemSetCollectionData()
local currencyOptionTypes = ITEM_SET_COLLECTIONS_DATA_MANAGER:GetReconstructionCurrencyOptionTypes()
local currencyOptions = {}
for _, currencyType in ipairs(currencyOptionTypes) do
local currencyCost = itemSetCollectionData:GetReconstructionCurrencyOptionCost(currencyType)
local currencyLocation = GetCurrencyPlayerStoredLocation(currencyType)
table.insert(currencyOptions,
{
currencyAvailable = GetCurrencyAmount(currencyType, currencyLocation),
currencyIcon = ZO_Currency_GetPlatformCurrencyIcon(currencyType),
currencyLocation = currencyLocation,
currencyName = GetCurrencyName(currencyType),
currencyRequired = currencyCost,
currencyType = currencyType,
})
end
local tradeskillType = self:GetTradeskillType()
local minimumQuality = self:GetMinimumFunctionalQuality()
-- Calculate the costs from the default quality through the requested upgrade quality.
local upgradeQuality = overrideFunctionalQuality or (self:GetUpgradeFunctionalQuality() - 1)
local materialCosts = {}
for quality = minimumQuality, upgradeQuality do
local reagentItemLink = GetSmithingImprovementItemLink(tradeskillType, quality)
local _, reagentIcon, reagentsAvailable = GetSmithingImprovementItemInfo(tradeskillType, quality)
local reagentsRequired = GetSmithingGuaranteedImprovementItemAmount(tradeskillType, quality)
local materialCost =
{
fromFunctionalQuality = quality,
toFunctionalQuality = quality + 1,
reagentIcon = reagentIcon,
reagentItemLink = reagentItemLink,
reagentsRequired = reagentsRequired,
reagentsAvailable = reagentsAvailable,
}
table.insert(materialCosts, materialCost)
end
return currencyOptions, materialCosts
end
-- Collection --
ZO_ItemSetCollectionData = ZO_InitializingObject:Subclass()
function ZO_ItemSetCollectionData:Initialize(itemSetId)
self.itemSetId = itemSetId
self.pieces = {}
-- Get Item Set Collection Category information
local itemSetCollectionCategoryId = GetItemSetCollectionCategoryId(itemSetId)
if itemSetCollectionCategoryId ~= 0 then
local itemSetCollectionCategoryData = ITEM_SET_COLLECTIONS_DATA_MANAGER:GetOrCreateItemSetCollectionCategoryData(itemSetCollectionCategoryId)
self.itemSetCollectionCategoryData = itemSetCollectionCategoryData
itemSetCollectionCategoryData:AddItemSetCollectionData(self)
end
for i = 1, GetNumItemSetCollectionPieces(itemSetId) do
local pieceId, slot = GetItemSetCollectionPieceInfo(itemSetId, i)
local itemSetCollectionPieceData = ITEM_SET_COLLECTIONS_DATA_MANAGER:GetOrCreateItemSetCollectionPieceData(pieceId, slot)
table.insert(self.pieces, itemSetCollectionPieceData)
itemSetCollectionPieceData:SetItemSetCollectionData(self)
end
end
function ZO_ItemSetCollectionData:GetId()
return self.itemSetId
end
function ZO_ItemSetCollectionData:GetRawName()
return GetItemSetName(self.itemSetId)
end
function ZO_ItemSetCollectionData:GetFormattedName()
return zo_strformat(SI_ITEM_SET_NAME_FORMATTER, self:GetRawName())
end
function ZO_ItemSetCollectionData:GetSetType()
return GetItemSetType(self.itemSetId)
end
function ZO_ItemSetCollectionData:GetUnperfectedSetId()
return GetItemSetUnperfectedSetId(self.itemSetId)
end
function ZO_ItemSetCollectionData:GetUnperfectedSetCollectionData()
return ITEM_SET_COLLECTIONS_DATA_MANAGER:GetItemSetCollectionData(self:GetUnperfectedSetId())
end
function ZO_ItemSetCollectionData:GetNumPieces()
return #self.pieces
end
function ZO_ItemSetCollectionData:GetNumUnlockedPieces()
return GetNumItemSetCollectionSlotsUnlocked(self.itemSetId)
end
function ZO_ItemSetCollectionData:HasAnyUnlockedPieces()
return self:GetNumUnlockedPieces() > 0
end
function ZO_ItemSetCollectionData:HasAnyNewPieces()
return ItemSetCollectionHasNewPieces(self.itemSetId)
end
function ZO_ItemSetCollectionData:ClearNew(dontBroadcast)
local DONT_BROADCAST = true
for _, itemSetCollectionPieceData in self:PieceIterator() do
itemSetCollectionPieceData:ClearNew(DONT_BROADCAST)
end
if not dontBroadcast then
ITEM_SET_COLLECTIONS_DATA_MANAGER:OnCollectionNewStatusCleared(self)
end
end
function ZO_ItemSetCollectionData:GetReconstructionCurrencyOptionCost(currencyType)
return GetItemReconstructionCurrencyOptionCost(self.itemSetId, currencyType)
end
function ZO_ItemSetCollectionData:GetReconstructionCurrencyOptionInfo(currencyOptionIndex)
local currencyType = ITEM_SET_COLLECTIONS_DATA_MANAGER:GetReconstructionCurrencyOptionType(currencyOptionIndex)
return currencyType, self:GetReconstructionCurrencyOptionCost(currencyType)
end
function ZO_ItemSetCollectionData:GetCategoryData()
return self.itemSetCollectionCategoryData
end
function ZO_ItemSetCollectionData:GetPieceDataBySlot(itemSetCollectionSlot)
for i, itemSetCollectionPieceData in self:PieceIterator() do
if CompareId64s(itemSetCollectionPieceData:GetItemSetCollectionSlot(), itemSetCollectionSlot) == 0 then
return itemSetCollectionPieceData
end
end
return nil
end
function ZO_ItemSetCollectionData:SetSearchResultsVersion(searchResultsVersion)
self.searchResultsVersion = searchResultsVersion
self.itemSetCollectionCategoryData:SetSearchResultsVersion(searchResultsVersion)
end
function ZO_ItemSetCollectionData:IsSearchResult()
if self.searchResultsVersion then
if self.searchResultsVersion == ITEM_SET_COLLECTIONS_DATA_MANAGER:GetSearchResultsVersion() then
return true
else
-- Old search result, might as well clean it up while we're here
self.searchResultsVersion = nil
end
end
return false
end
do
-- if this triggers, need to add set type to this arbitrary sort order
internalassert(ITEM_SET_TYPE_MAX_VALUE == 5)
local SET_TYPE_SORT_ORDER =
{
[ITEM_SET_TYPE_MONSTER] = 1,
[ITEM_SET_TYPE_WEAPON] = 2,
[ITEM_SET_TYPE_DUNGEON] = 3,
[ITEM_SET_TYPE_WORLD] = 4,
[ITEM_SET_TYPE_CRAFTED] = 99, -- Technically invalid for item set collections
[ITEM_SET_TYPE_NONE] = 99, -- Technically invalid for item set collections
}
function ZO_ItemSetCollectionData:CompareTo(otherItemSetCollectionData)
if self:GetId() == otherItemSetCollectionData:GetId() then
-- table.sort compares an entry to itself, no good answer, just always return false
return false
end
local setTypeSortOrder = SET_TYPE_SORT_ORDER[self:GetSetType()]
local otherSetTypeSortOrder = SET_TYPE_SORT_ORDER[otherItemSetCollectionData:GetSetType()]
if setTypeSortOrder ~= otherSetTypeSortOrder then
return setTypeSortOrder < otherSetTypeSortOrder
end
-- Check for perfected versions of sets and group them after their unperfected counterpart
local unperfectedSetCollectionData = self:GetUnperfectedSetCollectionData()
local otherUnperfectedSetCollectionData = otherItemSetCollectionData:GetUnperfectedSetCollectionData()
local isSetPerfected = unperfectedSetCollectionData ~= nil
local isOtherSetPerfected = otherUnperfectedSetCollectionData ~= nil
local sortName = isSetPerfected and unperfectedSetCollectionData:GetRawName() or self:GetRawName()
local otherSortName = isOtherSetPerfected and otherUnperfectedSetCollectionData:GetRawName() or otherItemSetCollectionData:GetRawName()
if sortName == otherSortName then
-- Names in theory should only match if one is the perfected version of the other, or when table.sort compares an entry to itself
if isSetPerfected ~= isOtherSetPerfected then
-- Unperfected comes first
return isOtherSetPerfected
else
return self:GetId() < otherItemSetCollectionData:GetId()
end
else
return sortName < otherSortName
end
end
end
function ZO_ItemSetCollectionData:PieceIterator(filterFunctions)
return ZO_FilteredNumericallyIndexedTableIterator(self.pieces, filterFunctions)
end
function ZO_ItemSetCollectionData:AnyChildPassesFilters(pieceFilterFunctions)
for _, pieceData in self:PieceIterator(pieceFilterFunctions) do
return true
end
return false
end
-- Category --
ZO_ItemSetCollectionCategoryData = ZO_InitializingObject:Subclass()
function ZO_ItemSetCollectionCategoryData:Initialize(categoryId)
self.categoryId = categoryId
self.collections = {}
self.subcategories = {}
-- Get parent category information
local parentCategoryId = GetItemSetCollectionCategoryParentId(categoryId)
if parentCategoryId ~= 0 then
self.parentCategoryData = ITEM_SET_COLLECTIONS_DATA_MANAGER:GetOrCreateItemSetCollectionCategoryData(parentCategoryId)
self.parentCategoryData:AddSubcategoryData(self)
end
end
function ZO_ItemSetCollectionCategoryData:AddSubcategoryData(subcategoryData)
table.insert(self.subcategories, subcategoryData)
end
function ZO_ItemSetCollectionCategoryData:AddItemSetCollectionData(itemSetCollectionData)
table.insert(self.collections, itemSetCollectionData)
end
function ZO_ItemSetCollectionCategoryData:GetId()
return self.categoryId
end
function ZO_ItemSetCollectionCategoryData:GetName()
return GetItemSetCollectionCategoryName(self.categoryId)
end
function ZO_ItemSetCollectionCategoryData:GetFormattedName()
return zo_strformat(SI_ITEM_SET_CATEGORY_NAME_FORMATTER, self:GetName())
end
function ZO_ItemSetCollectionCategoryData:GetKeyboardIcons()
return GetItemSetCollectionCategoryKeyboardIcons(self.categoryId)
end
function ZO_ItemSetCollectionCategoryData:GetGamepadIcon()
return GetItemSetCollectionCategoryGamepadIcon(self.categoryId)
end
function ZO_ItemSetCollectionCategoryData:GetOrder()
return GetItemSetCollectionCategoryOrder(self.categoryId)
end
function ZO_ItemSetCollectionCategoryData:GetParentCategoryData()
return self.parentCategoryData
end
function ZO_ItemSetCollectionCategoryData:IsTopLevel()
return self.parentCategoryData == nil
end
function ZO_ItemSetCollectionCategoryData:IsSubcategory()
return self.parentCategoryData ~= nil
end
function ZO_ItemSetCollectionCategoryData:GetNumSubcategories()
return #self.subcategories
end
function ZO_ItemSetCollectionCategoryData:HasSubcategories()
return #self.subcategories > 0
end
function ZO_ItemSetCollectionCategoryData:GetNumCollections()
return #self.collections
end
function ZO_ItemSetCollectionCategoryData:HasCollections()
return #self.collections > 0
end
function ZO_ItemSetCollectionCategoryData:GetNumPieces()
local numPieces = 0
if self:HasSubcategories() then
for _, subcategoryData in self:SubcategoryIterator() do
numPieces = numPieces + subcategoryData:GetNumPieces()
end
else
for _, collectionData in self:CollectionIterator() do
numPieces = numPieces + collectionData:GetNumPieces()
end
end
return numPieces
end
function ZO_ItemSetCollectionCategoryData:GetNumUnlockedPieces()
local numUnlockedPieces = 0
if self:HasSubcategories() then
for _, subcategoryData in self:SubcategoryIterator() do
numUnlockedPieces = numUnlockedPieces + subcategoryData:GetNumUnlockedPieces()
end
else
for _, collectionData in self:CollectionIterator() do
numUnlockedPieces = numUnlockedPieces + collectionData:GetNumUnlockedPieces()
end
end
return numUnlockedPieces
end
-- Minor optimization over calling the two functions independently
function ZO_ItemSetCollectionCategoryData:GetNumUnlockedAndTotalPieces()
local numUnlockedPieces = 0
local numTotalPieces = 0
if self:HasSubcategories() then
for _, subcategoryData in self:SubcategoryIterator() do
local numUnlockedSubcategoryPieces, numTotalSubcategoryPieces = subcategoryData:GetNumUnlockedAndTotalPieces()
numUnlockedPieces = numUnlockedPieces + numUnlockedSubcategoryPieces
numTotalPieces = numTotalPieces + numTotalSubcategoryPieces
end
else
for _, collectionData in self:CollectionIterator() do
numUnlockedPieces = numUnlockedPieces + collectionData:GetNumUnlockedPieces()
numTotalPieces = numTotalPieces + collectionData:GetNumPieces()
end
end
return numUnlockedPieces, numTotalPieces
end
do
local COLLECTION_FILTERS = { ZO_ItemSetCollectionData.HasAnyUnlockedPieces }
function ZO_ItemSetCollectionCategoryData:HasAnyUnlockedPieces()
if self:HasSubcategories() then
for _, subcategoryData in self:SubcategoryIterator({ ZO_ItemSetCollectionCategoryData.HasAnyUnlockedPieces }) do
return true
end
else
for _, collectionData in self:CollectionIterator(COLLECTION_FILTERS) do
return true
end
end
return false
end
end
function ZO_ItemSetCollectionCategoryData:HasAnyNewPieces()
if self:HasSubcategories() then
for _, subcategoryData in self:SubcategoryIterator({ ZO_ItemSetCollectionCategoryData.HasAnyNewPieces }) do
return true
end
else
for _, collectionData in self:CollectionIterator({ ZO_ItemSetCollectionData.HasAnyNewPieces }) do
return true
end
end
end
function ZO_ItemSetCollectionCategoryData:ClearNew(dontBroadcast)
local DONT_BROADCAST = true
if self:HasSubcategories() then
for _, subcategoryData in self:SubcategoryIterator() do
subcategoryData:ClearNew(DONT_BROADCAST)
end
else
for _, collectionData in self:CollectionIterator() do
collectionData:ClearNew(DONT_BROADCAST)
end
end
if not dontBroadcast then
ITEM_SET_COLLECTIONS_DATA_MANAGER:OnCollectionCategoryNewStatusCleared(self)
end
end
function ZO_ItemSetCollectionCategoryData:SetSearchResultsVersion(searchResultsVersion)
self.searchResultsVersion = searchResultsVersion
if self.parentCategoryData then
self.parentCategoryData:SetSearchResultsVersion(searchResultsVersion)
end
end
function ZO_ItemSetCollectionCategoryData:IsSearchResult()
if self.searchResultsVersion then
if self.searchResultsVersion == ITEM_SET_COLLECTIONS_DATA_MANAGER:GetSearchResultsVersion() then
return true
else
-- Old search result, might as well clean it up while we're here
self.searchResultsVersion = nil
end
end
return false
end
function ZO_ItemSetCollectionCategoryData:Equals(otherItemSetCollectionCategoryData)
return self:GetId() == otherItemSetCollectionCategoryData:GetId()
end
function ZO_ItemSetCollectionCategoryData:CompareTo(otherItemSetCollectionCategoryData)
local order = self:GetOrder()
local otherOrder = otherItemSetCollectionCategoryData:GetOrder()
return order < otherOrder or (order == otherOrder and self:GetName() < otherItemSetCollectionCategoryData:GetName())
end
function ZO_ItemSetCollectionCategoryData:SortChildren()
self:SortSubcategories()
self:SortCollections()
end
function ZO_ItemSetCollectionCategoryData:SortSubcategories()
table.sort(self.subcategories, ZO_ItemSetCollectionCategoryData.CompareTo)
for _, subcategory in ipairs(self.subcategories) do
subcategory:SortChildren()
end
end
function ZO_ItemSetCollectionCategoryData:SortCollections()
table.sort(self.collections, ZO_ItemSetCollectionData.CompareTo)
end
function ZO_ItemSetCollectionCategoryData:SubcategoryIterator(filterFunctions)
return ZO_FilteredNumericallyIndexedTableIterator(self.subcategories, filterFunctions)
end
function ZO_ItemSetCollectionCategoryData:CollectionIterator(filterFunctions)
return ZO_FilteredNumericallyIndexedTableIterator(self.collections, filterFunctions)
end
function ZO_ItemSetCollectionCategoryData:AnyChildPassesFilters(pieceFilterFunctions)
if self:HasSubcategories() then
for _, subcategoryData in self:SubcategoryIterator() do
if subcategoryData:AnyChildPassesFilters(pieceFilterFunctions) then
return true
end
end
else
for _, collectionData in self:CollectionIterator() do
if collectionData:AnyChildPassesFilters(pieceFilterFunctions) then
return true
end
end
end
return false
end
|
function class_new(name)
local new_class = {}
function new_class.newObject(...)
local sup = new_class:superClass()
local newinst = {}
local meta = {}
if sup == nil then
meta.__index = new_class
else
newinst.super = sup.new(...)
function meta.__index(table,key)
local classGet = rawget(new_class,key)
local superGet = rawget(newinst.super,key)
return (superGet or classGet or newinst.super[key])
end
function meta.__newindex(table, key, value)
if newinst.super[key] == nil then
rawset(table,key,value)
else
newinst.super[key] = value
end
end
end
setmetatable(newinst, meta)
return newinst
end
new_class.new = new_class.newObject
function new_class:class()
return new_class
end
function new_class:name()
return (name == nil and "unknown" or name)
end
function new_class:superClass()
return nil
end
function new_class:superClasses()
local classes = {}
local curr_class = new_class:superClass()
while curr_class ~= nil do
table.insert(classes,curr_class)
curr_class = curr_class:superClass()
end
return classes
end
function new_class:is_a(someClass)
local cur_class = new_class
while cur_class ~= nil do
if cur_class == someClass then return true
else cur_class = cur_class:superClass() end
end
return false
end
return new_class
end
function class_extends(baseClass,name)
local new_class = class_new(name)
if baseClass~=nil then
setmetatable(new_class,{__index=baseClass})
function new_class:superClass()
return baseClass
end
end
return new_class
end
|
-- -*- coding: utf-8 -*-
------------------------------------------------------------------------
-- Copyright © 2011-2015, RedJack, LLC.
-- All rights reserved.
--
-- Please see the COPYING file in this distribution for license details.
------------------------------------------------------------------------
-- Loads either avro.legacy.avro or avro.ffi.avro, depending on whether
-- the LuaJIT FFI module is available.
local avro = require "avro.module"
local ffi_present = pcall(require, "ffi")
if ffi_present then
-- print("Loading ffi version")
avro.c = require("avro.ffi.avro")
else
-- print("Loading legacy version")
avro.c = require("avro.legacy.avro")
end
avro.c.ffi_present = ffi_present
return avro.c
|
--
-- Chartboost Corona SDK
-- Created by: Chris
--
local cmd = (...)
local mod_name
if cmd then mod_name = cmd:match( "^(.*)%..-$" ) end
local __chartboost__modules = {}
local function __chartboost__require__(name)
local mod = __chartboost__modules[name]
if mod then
return __chartboost__modules[name]()
else
return require(name)
end
end
-- these methods will be replaced in the build script - they don't actually do anything as is
__chartboost__declare("chartboost.libraries.lib.class")
__chartboost__declare("chartboost.libraries.CBUtility")
__chartboost__declare("chartboost.networking.CBWebImageCache")
__chartboost__declare("chartboost.networking.CBURLOpener")
__chartboost__declare("chartboost.model.CBImpressionType")
__chartboost__declare("chartboost.model.CBImpressionState")
__chartboost__declare("chartboost.model.CBOrientation")
__chartboost__declare("chartboost.model.CBAnimationType")
__chartboost__declare("chartboost.view.CBAnimations")
__chartboost__declare("chartboost.view.CBAnimationManager")
__chartboost__declare("chartboost.view.CBUnderfinedProgressBar")
__chartboost__declare("chartboost.view.CBLoadingView")
__chartboost__declare("chartboost.view.CBBackgroundView")
__chartboost__declare("chartboost.view.CBPopupImpressionView")
__chartboost__declare("chartboost.nativeviews.CBRoundRectImageView")
__chartboost__declare("chartboost.nativeviews.CBActionButton")
__chartboost__declare("chartboost.nativeviews.CBMoreAppsCell")
__chartboost__declare("chartboost.nativeviews.CBMoreAppsRegularCell")
__chartboost__declare("chartboost.nativeviews.CBMoreAppsFeaturedCell")
__chartboost__declare("chartboost.nativeviews.CBMoreAppsWebViewCell")
__chartboost__declare("chartboost.CBViewProtocol")
__chartboost__declare("chartboost.CBViewController")
__chartboost__declare("chartboost.nativeviews.CBNativeInterstitialViewProtocol")
__chartboost__declare("chartboost.nativeviews.CBMoreAppsViewProtocol")
__chartboost__declare("chartboost.view.CBWebViewProtocol")
__chartboost__declare("chartboost.model.CBImpression")
local exposed_modules = {}
-- these four classes are the mandatory interface for the public chartbooost corona code
-- everything else can be modified freely, but the methods in these three classes must remain functional
exposed_modules["chartboost.model.CBImpression"] = __chartboost__modules["chartboost.model.CBImpression"]
exposed_modules["chartboost.CBViewController"] = __chartboost__modules["chartboost.CBViewController"]
exposed_modules["chartboost.networking.CBWebImageCache"] = __chartboost__modules["chartboost.networking.CBWebImageCache"]
exposed_modules["chartboost.networking.CBURLOpener"] = __chartboost__modules["chartboost.networking.CBURLOpener"]
-- get internal library
local success, cb = pcall(require, mod_name .. ".chartboost_internal")
if (not success) then
print "Chartboost requires the additional library file 'chartboost_internal.lua' to be found in the same directory as 'chartboost.lua'."
end
return cb(exposed_modules)
|
--- Telegram dice object.
-- This object represents a dice with random value from 1 to 6. (Yes, we're aware of the “proper” singular of die. But it's awkward, and we decided to help it change. One dice at a time!).
-- @classmod Dice
local class = require("middleclass")
local Dice = class("telegram.structures.Dice")
--- Create a new dice object using data returned by Telegram Bot API.
-- @tparam table data The dice data returned by Telegram Bot API.
-- @treturn Chat The new created dice object.
function Dice:initialize(data)
--- Emoji on which the dice throw animation is based (string).
self.emoji = data.emoji
--- Emoji on which the dice throw animation is based (number).
self.value = data.value
end
--- Operators overrides.
-- @section operators_overrides
--- Test if the 2 dice objects are equal (same emoji, and same value).
-- @tparam Dice dice The dice to compare with.
-- @treturn boolean `true` if they're the same.
function Dice:__eq(dice)
return (self.emoji == dice.emoji) and (self.value == dice.emoji)
end
return Dice
|
ITEM.name = "Titanium"
ITEM.description = "A small beam of titanium, which is used to craft most weapons."
ITEM.model = "models/props_c17/TrapPropeller_Lever.mdl"
ITEM.price = 45
ITEM.exRender = true
|
require("prototype.entity")
require("prototype.fluid")
require("prototype.item")
require("prototype.tile")
require("prototype.recipe")
|
local stat_overrides = {
_NpcDaggers = {
Talents = "ViolentMagic;Ambidextrous"
},
_NpcUnarmed = {
Talents = "ViolentMagic;Ambidextrous"
},
_NpcWands_Water = {
Talents = "ViolentMagic;Ambidextrous"
},
_NpcSwords = {
Talents = "ViolentMagic;Ambidextrous"
},
_NpcAxes = {
Talents = "ViolentMagic;Ambidextrous"
},
_NpcClubs = {
Talents = "ViolentMagic;Ambidextrous"
},
_NpcTwoHandedSwords = {
Talents = "ViolentMagic"
},
_NpcTwoHandedAxes = {
Talents = "ViolentMagic"
},
_NpcTwoHandedMaces = {
Talents = "ViolentMagic"
},
_NpcSpears = {
Talents = "ViolentMagic"
},
_NpcStaffs = {
Talents = "ViolentMagic;FaroutDude"
},
_NpcStaffs_Fire = {
Talents = "ViolentMagic;FaroutDude"
},
_NpcStaffs_Water = {
Talents = "ViolentMagic;FaroutDude"
},
_NpcStaffs_Poison = {
Talents = "ViolentMagic;FaroutDude"
},
_NpcStaffs_Earth = {
Talents = "ViolentMagic;FaroutDude"
},
_NpcStaffs_Air = {
Talents = "ViolentMagic;FaroutDude"
},
_NpcBows = {
Talents = "ViolentMagic;ElementalRanger"
},
_NpcCrossbows = {
Talents = "ViolentMagic;ElementalRanger"
},
_NpcWands_Fire = {
Talents = "ViolentMagic;Ambidextrous"
},
_NpcWands_Air = {
Talents = "ViolentMagic;Ambidextrous"
},
_NpcWands_Poison = {
Talents = "ViolentMagic;Ambidextrous"
},
LLENEMY_TALENT_COUNTER = {
Description = "LLENEMY_TALENT_COUNTER_EXTENDER_Description",
DescriptionParams = "CounterChance"
},
LLENEMY_ACTIVATE_FLAMING_TONGUES = {
LeaveAction = "" -- NRD_ApplyActiveDefense instead
},
LLENEMY_ACTIVATE_HEALING_TEARS = {
LeaveAction = "" -- NRD_ApplyActiveDefense instead
},
Stats_Herbmix_Courage = {
StatusIcon = ""--"Item_QUEST_Herbmix_Courage"
},
Stats_Herbmix_Ferocity = {
StatusIcon = ""--"Item_QUEST_Herbmix_Ferocity"
},
DEATH_RESIST = {
StackId = "Stack_Death_Resist"
},
-- So Madness can be cast on allies with Empowered by Madness
Target_MaddeningSong = {
TargetConditions = "Character"
},
-- So Piercing Immunity doesn't make you immune to deathfog
DamageSurface_Deathfog = {
["Damage Type"] = "None"
},
}
-- v40 and up introduced a way to add talents to NPCs
local talent_belt_overrides = {
--LLENEMY_TALENT_LONEWOLF = { Items = "", StackId = "Stack_LLENEMY_Talent_LoneWolf"},
LLENEMY_TALENT_TORTURER = { Items = "", StackId = "Stack_LLENEMY_Talent_Torturer"},
--LLENEMY_TALENT_UNSTABLE = { Items = "", StackId = "Stack_LLENEMY_Talent_Unstable"},
LLENEMY_TALENT_WHATARUSH = { Items = "", StackId = "Stack_LLENEMY_Talent_WhatARush"},
LLENEMY_TALENT_LEECH = { Items = "", StackId = "Stack_LLENEMY_Talent_Leech"},
LLENEMY_TALENT_QUICKSTEP = { Items = "", StackId = "Stack_LLENEMY_Talent_Quickstep"},
LLENEMY_TALENT_SADIST = { Items = "", StackId = "Stack_LLENEMY_Talent_Sadist"},
LLENEMY_TALENT_GLADIATOR = { Items = "", StackId = "Stack_LLENEMY_Talent_Gladiator"},
LLENEMY_TALENT_HAYMAKER = { Items = "", StackId = "Stack_LLENEMY_Talent_Haymaker"},
LLENEMY_TALENT_INDOMITABLE = { Items = "", StackId = "Stack_LLENEMY_Talent_Indomitable"},
LLENEMY_TALENT_SOULCATCHER = { Items = "", StackId = "Stack_LLENEMY_Talent_SoulCatcher"},
LLENEMY_TALENT_MAGICCYCLES = { Items = "", StackId = "Stack_LLENEMY_Talent_MagicCycles"},
LLENEMY_TALENT_GREEDYVESSEL = { Items = "", StackId = "Stack_LLENEMY_Talent_GreedyVessel"},
LLENEMY_TALENT_BACKSTAB = { Items = "", StackId = "Stack_LLENEMY_Talent_Backstab"},
}
-- Statuses displayed in LLENEMY_UPGRADE_INFO
local upgrade_info_statuses = {
"LLENEMY_TALENT_BACKSTAB",
"LLENEMY_TALENT_LEECH",
"LLENEMY_TALENT_LONEWOLF",
"LLENEMY_TALENT_QUICKSTEP",
"LLENEMY_TALENT_RANGERRANGE",
"LLENEMY_TALENT_WHATARUSH",
"LLENEMY_TALENT_TORTURER",
"LLENEMY_TALENT_SADIST",
"LLENEMY_TALENT_HAYMAKER",
"LLENEMY_TALENT_GLADIATOR",
"LLENEMY_TALENT_INDOMITABLE",
"LLENEMY_TALENT_SOULCATCHER",
--"LLENEMY_TALENT_MASTERTHIEF",
--"LLENEMY_TALENT_GREEDYVESSEL",
--"LLENEMY_TALENT_MAGICCYCLES",
"LLENEMY_INF_NECROFIRE",
"LLENEMY_INF_NECROFIRE_G",
"LLENEMY_INF_WATER",
"LLENEMY_INF_WATER_G",
"LLENEMY_INF_BLESSED_ICE",
"LLENEMY_INF_BLESSED_ICE_G",
"LLENEMY_INF_POISON",
"LLENEMY_INF_POISON_G",
"LLENEMY_INF_ACID",
"LLENEMY_INF_ACID_G",
"LLENEMY_INF_ELECTRIC",
"LLENEMY_INF_ELECTRIC_G",
"LLENEMY_INF_CURSED_ELECTRIC",
"LLENEMY_INF_CURSED_ELECTRIC_G",
"LLENEMY_INF_BLOOD",
"LLENEMY_INF_BLOOD_G",
"LLENEMY_INF_OIL",
"LLENEMY_INF_OIL_G",
"LLENEMY_INF_FIRE",
"LLENEMY_INF_FIRE_G",
"LLENEMY_BONUS_TREASURE_ROLL",
--"LLENEMY_IMMUNITY_LOSECONTROL",
"LLENEMY_DOUBLE_DIP",
"LLENEMY_PERSEVERANCE_MASTERY",
"LLENEMY_BONUSSKILLS_SINGLE",
"LLENEMY_BONUSSKILLS_SET_NORMAL",
"LLENEMY_BONUSSKILLS_SOURCE",
"LLENEMY_BONUSSKILLS_SET_ELITE",
}
local function OverrideStats()
local total_changes = 0
local total_stats = 0
--LeaderLib_7e737d2f-31d2-4751-963f-be6ccc59cd0c
-- if _G["LeaderLib"] ~= nil or Ext.IsModLoaded("7e737d2f-31d2-4751-963f-be6ccc59cd0c") then
-- if _G["LeaderLib_Lua_PrintEnabled"] == true then
-- end
-- end
for statname,overrides in pairs(stat_overrides) do
for property,value in pairs(overrides) do
--LeaderLib.PrintDebug("LLENEMY_StatOverrides.lua] Overriding stat: " .. statname .. " (".. property ..") = \"".. value .."\"")
Ext.StatSetAttribute(statname, property, value)
total_changes = total_changes + 1
end
total_stats = total_stats + 1
end
for statname,overrides in pairs(talent_belt_overrides) do
for property,value in pairs(overrides) do
--LeaderLib.PrintDebug("LLENEMY_StatOverrides.lua] Overriding stat: " .. statname .. " (".. property ..") = \"".. value .."\"")
Ext.StatSetAttribute(statname, property, value)
total_changes = total_changes + 1
end
total_stats = total_stats + 1
end
--LeaderLib.PrintDebug("LLENEMY_StatOverrides.lua] Enabling v42+ enhancements.")
--LeaderLib.PrintDebug("==============================================================")
--LeaderLib.PrintDebug("LLENEMY_StatOverrides.lua] (Upgrade Info) enabled. Hiding statuses used for info.")
for _,statname in pairs(upgrade_info_statuses) do
Ext.StatSetAttribute(statname, "Icon", "")
total_changes = total_changes + 1
total_stats = total_stats + 1
end
--LeaderLib.PrintDebug("==============================================================")
-- Gravedigger_be822931-e829-4555-b50f-3b80b6f17d86
if Ext.IsModLoaded("be822931-e829-4555-b50f-3b80b6f17d86") then
Ext.StatSetAttribute("WPN_LLENEMY_ShadowTreasure_Shovel_2H", "Skills", "Target_HeavyAttack;Target_LLGRAVE_Dig")
end
LeaderLib.PrintDebug("LLENEMY_StatOverrides.lua] Changed ("..tostring(total_changes)..") properties in ("..tostring(total_stats)..") stats (added talents to enemy weapons).")
end
return {
Init = OverrideStats
}
|
require("util/static")
Util = {}
--[[--
keyup fallback
]]
function Util.KeyUp(key)
if key == KEY_ESCAPE then
static.quit()
end
end
--[[--
keydown fallback
]]
function Util.KeyDown(key)
end
--[[--
resize fallback
@param w
@param h
]]
function Util.Resize(w, h)
SCREEN_WIDTH = w
SCREEN_HEIGHT = h
end
--[[--
mousewheel fallback
@param x
@param y
]]
function Util.MouseWheel(x, y, dx, dy)
end
--[[--
mousedown fallback
@param x
@param y
]]
function Util.MouseDown(x,y)
end
--[[--
mousemove fallback
@param x
@param y
]]
function Util.MouseMove(x,y)
end
--[[--
fallback
@param x
@param y
]]
function Util.MouseUp(x,y)
end
--[[--
Take a class and make global the methods that are expected by C++
@param controller
]]
function Util.setController(controller)
local f = {"Start", "Update", "End", "Resize", "KeyDown", "KeyUp", "MouseWheel", "MouseDown", "MouseMove", "MouseUp"}
for i, v in ipairs(f) do
if controller[v] then
rawset(_G, v, controller[v])
else
rawset(_G, v, Util[v])
end
end
end
--[[--
First class to call this becomes main.
Hence there is a pattern of the first import being `require("util")` followed by local `isMain = Util.isMain()` - this guarentees the first loaded class will be main. Other require calls should follow this pattern.
@return if caller is main
]]
function Util.isMain()
if Util.main then
return false
end
Util.main = true
return true
end
--[[--
Make a controller the current controller if it says it's main
@param isMain usually returned from Util.isMain()
@param controller Controller to make current
]]
function Util.try(isMain, controller)
if isMain then
Util.setController(controller)
end
end
|
local awful = require("awful")
local gears = require("gears")
local utils = require("utils")
local icons = require("icons")
local BaseWidget = require("widgets.base").BaseWidget
local WiredWidget = BaseWidget.derive()
function WiredWidget:update()
local connected = utils.read_number("/sys/class/net/" .. self.interface .. "/carrier") == 1
if connected ~= self.connected then
self.connected = connected
self:updateIcon()
end
if not connected then
return
end
self.ip = "N/A"
utils.async_lines("ip addr show " .. self.interface, function(line)
self.ip = string.match(line, "inet (%d+%.%d+%.%d+%.%d+)") or self.ip
end)
end
function WiredWidget:create(args)
args = args or {}
self.autohide = args.autohide
self.interface = args.interface or "eth0"
self.connected = false
self.mac = utils.read("/sys/class/net/" .. self.interface .. "/address", "N/A")
self.ip = "N/A"
local box = self:init(nil, icons.net_wired_na)
self:attach(box)
self:updateIcon()
self.timer = gears.timer({ timeout = args.timeout or 30 })
self.timer:connect_signal("timeout", function() self:update() end)
self.timer:start()
self:update()
end
function WiredWidget:updateIcon()
self:get_container():set_visible(true)
if self.connected then
self:set_icon(icons.net_wired)
elseif not self.autohide then
self:set_icon(icons.net_wired_na)
else
self:get_container():set_visible(false)
end
end
function WiredWidget:attach(box)
box:buttons(awful.util.table.join(
awful.button({}, 1, function() utils.toggle_run_term("nmtui") end)
))
utils.registerPopupNotify(box, "Wired network", function(w)
if self.connected then
return "IP:\t\t" .. self.ip .. "\nMAC:\t\t" .. self.mac
else
return "Disconnected"
end
end)
end
return WiredWidget
|
--[[
pbInfo - Locales/lang.DE.lua
v0.49
by p.b. a.k.a. novayuna
released under the Creative Commons License By-Nc-Sa: http://creativecommons.org/licenses/by-nc-sa/3.0/
]]
pbInfo.QuestTracker.CompleteText = '%(Fertig%)';
pbInfo.QuestTracker.DailyQuestPatterns = {'"(%d+) Tages%-Quest"', "heute nicht noch einmal", "benutzt Tagesquest%-Karte"};
pbInfo.ChatFrame.XPTP = {'^%+%d+ Erfahrungspunkte', '^%+%d+ Talentpunkte'};
pbInfo.ChatFrame.XPTPDebt = {'^Erfahrungsschulden sind um %d+ gesunken', '^TP%-Schulden wurden um %d+ reduziert'};
pbInfo.ChatFrame.Progress = {'^(.+)%-Lernfortschritt: [%d.]+%%'}; -- do not translate %s and PERCENTAGE
pbInfo.Locale = {
["Messages"] = {
["DESCRIPTION"] = "pbInfo shows a tooltip with several information about the mob, player or NPC you are hovering, a tooltip with information about gathering materials and it modifies the target blood bars to show a mob's real healthpoints.\n\nBy now, pbInfo includes a ThreatMeter, a QuestTracker and a ChatLog.",
["LOADED"] = "AddOn geladen",
["NVT"] = "Kein g\195\188ltiges Ziel ausgew\195\164hlt!",
["TOGGLEtrue"] = " wurde erfolgreich |cff00FF00aktiviert|r.",
["TOGGLEfalse"] = " wurde erfolgreich |cffFF0000deaktiviert|r.",
["TOGGLEerror"] = " existiert nicht in der Konfiguration.",
["ONLOAD"] = "Um Optionen umzuschalten, benutze den Minimap-Button oder /pbic.",
["ATTENTIONENABLE"] = "Achtung, das AddOn wurde in der Vergangenheit |cffFF0000deaktiviert|r. Benutze /pbic zum Aktivieren."
},
["Tooltip"] = {
["HP"] = "Lebenspunkte",
["LVL"] = "Stufe",
["PROGRESS"] = "Fortschritt",
["TITLE"] = "Titel",
["GUILD"] = "Gilde",
["DISTANCE"] = "Entfernung",
["TARGET"] = "Ziel",
["MANATYPE1"] = "Mana",
["MANATYPE2"] = "Wut",
["MANATYPE3"] = "Fokus",
["MANATYPE4"] = "Energie",
["MATINBAG"] = "Im Rucksack",
["MATONBANK"] = "Auf der Bank"
},
["ClockTooltip"] = {
["CNDTIME"] = "Candara-Zeit",
["ONLINE"] = "Online",
["TIMEFORMAT"] = "%H:%M" -- http://www.lua.org/pil/22.1.html
},
["QuestTracker"] = {
["DAILY"] = "Tagesquest",
["REWARD"] = "Belohnung",
["QUESTNPC"] = "Quest-NPC",
["XP"] = "XP",
["TP"] = "TP",
["GOLD"] = "Gold",
["DQITEMS"] = "Tagesquest-Items",
["COMPLQUESTS"] = "fertige Quests",
["INFOTOOLTIP"] = "Linke Maustaste zum Ein-/Ausblenden dr\195\188cken.\n\nUmschalttaste und rechte Maustaste gedr\195\188ckt halten, um den QuestTracker zu bewegen."
},
["Config"] = {
["Title"] = "pbInfo-Einstellungen",
["TabGeneral"] = "Allgemein",
["TabTooltip"] = "Tooltip",
["TabTargetFrame"] = "TargetFrame",
["TabBloodBars"] = "BloodBars",
["TabThreatMeter"] = "Aggr-O-Meter",
["TabQuestTracker"] = "QuestTracker",
["TabChatLog"] = "ChatLog",
["TabCastingBar"] = "CastingBar",
["TabChatFrame"] = "ChatFrame",
["SettingEnable"] = "pbInfo aktivieren",
["SettingThousandsSeparatorFormat"] = "Tsd.-Trennzeichen:",
["SettingTimeStampFormat"] = "Uhrzeit Format:",
["SettingExtraLanguage"] = "Sprache:",
["SettingModifyTooltip"] = "Infos zu Monstern/Spielern anzeigen",
["SettingModifyHealthbar"] = "Lebenspunkte im Targetframe anzeigen",
["SettingHealthbarShowPercentage"] = "Prozentwerte auch anzeigen",
["SettingHealthColorFade"] = "Weiches Lebenspunkte-F\195\164rben",
["SettingShowMana"] = "Mana, Wut, Energie und Fokus anzeigen",
["SettingShowDistance"] = "Entfernung anzeigen",
["SettingTooltipShowRace"] = "Rasse anzeigen",
["SettingTooltipShowPlayerInfo"] = "Spieler-Titel anzeigen (experimentell)",
["SettingShowMouseoverTarget"] = "Target des Ziels anzeigen",
["SettingAllNPC"] = "Auch f\195\188r NPCs anzeigen",
["SettingStickyTooltip"] = "Tooltip fixieren",
["SettingStickyAllTooltips"] = "alle Tooltips (Zauber, Items, etc.)",
["SettingStickyTooltipButton"] = "Position setzen",
["SettingShowMaterialInfo"] = "Infos zu Abbau-Materialien anzeigen",
["SettingShowMatInfoItemCount"] = "Anzahl der Items anzeigen",
["SettingShowMatInfoItemCountBank"] = "+ Bankitems",
["SettingShowMatInfoItemCountIV"] = "+ InventoryViewer Support",
["SettingShowClockTooltip"] = "ClockTooltip im Tageslichticon anzeigen",
["SettingHealthBarColorFade"] = "Lebenspunktebalken f\195\164rben",
["SettingModifyBloodBars"] = "Lebenspunkte in BloodBars anzeigen",
["SettingBloodBarsColorFade"] = "BloodBars f\195\164rben",
["SettingBloodBarsDelay"] = "Update-Verz\195\182gerung in Sekunden:",
["SettingThreatMeter"] = "Aggr-O-Meter",
["SettingThreatMeterShowTitle"] = "Titel anzeigen",
["SettingThreatMeterLock"] = "Position fixieren",
["SettingThreatMeterPlayerOnTop"] = "Platziere den Spieler immer oben",
["SettingThreatMeterWarnTargetTargetTarget"]= 'Warnen, wenn "TargetTargetTarget = Ich"',
["TooltipThreatMeterWarnTargetTargetTarget"]= "Zeigt eine Warnmeldung, falls das Ziel deines Ziels dich ansvisiert.\nBsp.: Tank -> Mob -> Du",
["SettingThreatMeterHideOnNoTarget"] = "Ausblenden bei fehlendem Ziel",
["SettingThreatMeterHideOnNoParty"] = "Ausblenden, wenn nicht in Gruppe",
["SettingThreatMeterRelativeToMaxThreat"] = "Aggro relativ zur Max-Aggro anzeigen",
["SettingThreatMeterShowRealThreat"] = "Zeige Realwerte statt Prozente",
["SettingThreatMeterDisplayLimit"] = "% min. Aggro f\195\188r Listeneintrag",
["SettingGameTooltipAlpha"] = "% Tooltip-Transparenz",
["SettingThreatMeterAlpha"] = "% Aggr-O-Meter-Transparenz",
["SettingThreatMeterDelay"] = "Update-Verz\195\182gerung in Sekunden:",
["SettingQuestTracker"] = "QuestTracker",
["SettingQuestTrackerShowTitle"] = "Titel anzeigen",
["SettingQuestTrackerSortAsc"] = "Aufsteigend sortieren",
["SettingQuestTrackerProgressColorFade"] = "Fortschritt weich f\195\164rben",
["SettingQuestTrackerTooltip"] = "Tooltip anzeigen",
["SettingQuestTrackerTooltipRight"] = "Tooltip rechts anzeigen",
["SettingQuestTrackerTooltipDescription"] = "Zusammenfassung anzeigen",
["SettingQuestTrackerHighlightDailies"] = "Tagesquests hervorheben",
["SettingQuestTrackerOpenQuestbook"] = "Questbuch bei Linksklick \195\182ffnen",
["SettingQuestTrackerShowDailiesCounter"] = "Tagesquest-Z\195\164hler anzeigen (experimentell)",
["SettingQuestTrackerFontSizesTitle"] = "Schriftgr\195\182\195\159e des Titels:",
["SettingQuestTrackerFontSizesQuestTitle"] = "Schriftgr\195\182\195\159e der Questnamen:",
["SettingQuestTrackerFontSizesQuestItems"] = "Schriftgr\195\182\195\159e der Questitems:",
["SettingQuestTrackerColorsDailyQuest"] = "Tagesquest-Farbe",
["SettingChatLog"] = "ChatLog",
["SettingChatLogMaxLinesPerChat"] = "Chatzeilen in History speichern",
["SettingChatFrameFilterTitles"] = "Chat-Titel ([Zone], [Party], ...) entfernen",
["SettingChatFrameFilterXPTP"] = "XP-/TP-Meldungen entfernen",
["SettingChatFrameFilterXPTPDebt"] = "Debt-Meldungen entfernen",
["SettingChatFrameFilterProgress"] = "Fortschritt-Meldungen entfernen", -- changed: remove all progress messages
["SettingChatFrameFilterProgressGather"] = "Nur Sammel-Meldungen", -- added: remove gathering progress messages only (mining, woodcutting, harbalism)
["SettingChatFrameShowPlayerInfo"] = "Zeige Klassen- & Level-Infos",
["SettingTimeStamp"] = "TimeStamp im Chat anzeigen",
["SettingTimeStampNotInCombatLog"] = "Nicht im Kampfprotokoll anzeigen",
["SettingAutoRepairAll"] = "Beim Handeln autom. reparieren",
["SettingCastingBarShowCastTime"] = "Cast-Zeit anzeigen",
["SettingCastingBarButton"] = "CastingBar verschieben",
["TooltipBorderTitle"] = "GameTooltip-Position",
["TooltipBorderText"] = "Ziehen und loslassen",
["ResetButton"] = "! Reset pbInfo !",
["SaveButton"] = "Speichern",
["CloseButton"] = "Schlie\195\159en"
}
};
|
function Server_StartGame(game,standing)
print("Test1");
local playerGameData = Mod.PlayerGameData;
for _,pid in pairs(game.ServerGame.Game.Players)do
if(pid.IsAI == false)then
playerGameData[pid.ID] = {};
playerGameData[pid.ID].Capturedterritories = 0;
playerGameData[pid.ID].Lostterritories = 0;
playerGameData[pid.ID].Ownedterritories = 0;
playerGameData[pid.ID].Capturedbonuses = 0;
playerGameData[pid.ID].Lostbonuses = 0;
playerGameData[pid.ID].Ownedbonuses = 0;
playerGameData[pid.ID].Killedarmies = 0;
playerGameData[pid.ID].Lostarmies = 0;
playerGameData[pid.ID].Ownedarmies = 0;
playerGameData[pid.ID].Eleminateais = 0;
playerGameData[pid.ID].Eleminateplayers = 0;
playerGameData[pid.ID].Eleminateaisandplayers = 0;
print("Test2");
end
end
for _,terr in pairs(standing.Territories)do
if(terr.OwnerPlayerID ~= WL.PlayerID.Neutral)then
if(game.ServerGame.Game.PlayingPlayers[terr.OwnerPlayerID].IsAI == false)then
playerGameData[terr.OwnerPlayerID].Ownedterritories = playerGameData[terr.OwnerPlayerID].Ownedterritories+1;
playerGameData[terr.OwnerPlayerID].Ownedarmies = playerGameData[terr.OwnerPlayerID].Ownedarmies+terr.NumArmies.NumArmies;
end
end
end
for _,boni in pairs(game.Map.Bonuses)do
local Match = true;
for _,terrid in pairs(boni.Territories)do
if(pid == nil)then
pid = standing.Territories[terrid].OwnerPlayerID;
end
if(pid ~= standing.Territories[terrid].OwnerPlayerID)then
Match = false;
end
end
if(Match == true)then
if(pid ~= WL.PlayerID.Neutral and game.ServerGame.Game.PlayingPlayers[pid].IsAI == false)then
playerGameData[pid].Ownedbonuses = playerGameData[pid].Ownedbonuses+1;
end
end
pid = nil;
end
print("Test3");
Mod.PlayerGameData = playerGameData;
end
|
--This script converts an excel file in a txt file by using LuaCOM
--1 previously delete temporary test data
os.execute('del "C:\\Temp\\test_*.txt"')
--1.1 library
require("luacom") --require treatment of office files
--2.1 read excel file names of the directory in a Lua table
excelFileTable={}
p=io.popen('dir C:\\Temp\\*xlsx /o')
for file in p:lines() do
local DayText,MonthText,YearText,HourText,MinuteText,FileText=file:match("(%d%d).(%d%d).(%d%d%d%d).*(%d%d):(%d%d).*%d+ (.*)")
if DayText then
excelFileTable[FileText]=YearText .. MonthText .. DayText .. HourText .. MinuteText
end --if DayText then
end --for file in p:lines() do
--2.2 read names of excel file exports as txt in a Lua table
secureFileTable={}
p=io.popen('dir C:\\Temp\\Archiv\\*xlsx2.txt /o')
for file in p:lines() do
local DayText,MonthText,YearText,HourText,MinuteText,FileText=file:match("(%d%d).(%d%d).(%d%d%d%d).*(%d%d):(%d%d).*%d+ (.*)")
if DayText then
secureFileTable[FileText]=YearText .. MonthText .. DayText .. HourText .. MinuteText
end --if DayText then
end --for file in p:lines() do
--test with: for k,v in pairs(excelFileTable) do print(secureFileTable[k:gsub(".xlsx","_xlsx2") .. ".txt"], v) end
--2.3 collect file names from tree
dofile("C:\\Tree\\documentation_tree.lua")
function treeCollectFileNamesRecursive(TreeTable)
collectFileNamesTable[TreeTable.branchname]=true
for k,v in pairs(TreeTable) do
if type(v)=="table" then
treeCollectFileNamesRecursive(v)
else
collectFileNamesTable[v]=true
end --if type(v)=="table" then
end --for k,v in pairs(TreeTable) do
end --function treeCollectFileNamesRecursive(TreeTable)
collectFileNamesTable={}
treeCollectFileNamesRecursive(lua_tree_output)
for k,v in pairs(collectFileNamesTable) do
if k:match("\\.*%.xlsx$") then
--test with: print(k,v)
p=io.popen('dir "' .. k .. '" /o')
for file in p:lines() do
local DayText,MonthText,YearText,HourText,MinuteText,FileText=file:match("(%d%d).(%d%d).(%d%d%d%d).*(%d%d):(%d%d).*%d+ (.*)")
if DayText then
excelFileTable[FileText]=YearText .. MonthText .. DayText .. HourText .. MinuteText
end --if DayText then
end --for file in p:lines() do
--test with: print(k:gsub("\\([^\\]+)%.xlsx","\\Archiv\\%1_xlsx2.txt"))
p=io.popen('dir "' .. k:gsub("\\([^\\]+)%.xlsx","\\Archiv\\%1_xlsx2.txt") .. '" /o')
for file in p:lines() do
local DayText,MonthText,YearText,HourText,MinuteText,FileText=file:match("(%d%d).(%d%d).(%d%d%d%d).*(%d%d):(%d%d).*%d+ (.*)")
if DayText then
secureFileTable[FileText]=YearText .. MonthText .. DayText .. HourText .. MinuteText
end --if DayText then
end --for file in p:lines() do
end --if k:match("\\.*%.xlsx$") then
end --for k,v in pairs(collectFileNamesTable) do
--test with: for k,v in pairs(excelFileTable) do print(secureFileTable[k:gsub(".xlsx","_xlsx2") .. ".txt"], v) end
--3. export excel files to txt if there is no export or if the date of the export to txt is older than the date of the excel file
--and make a copy of the previous version of the text file
fileTable={}
p=io.popen('dir C:\\Temp\\*.xlsx /b/o/s')
for ExcelFile in p:lines() do
fileTable[ExcelFile]=true
end --for ExcelFile in p:lines() do
for k,v in pairs(collectFileNamesTable) do
if k:match("\\.*%.xlsx$") then
fileTable[k]=true
end --if k:match("\\.*%.xlsx$") then
end --for k,v in pairs(collectFileNamesTable) do
for k,v in pairs(fileTable) do
local ExcelFile=k
filePath=ExcelFile:match("(.*)\\([^\\]+)$")
ActiveDocumentText=ExcelFile:match("\\([^\\]+)$")
if secureFileTable[ActiveDocumentText:gsub(".xlsx","_xlsx2") .. ".txt"]==nil or
excelFileTable[ActiveDocumentText]>secureFileTable[ActiveDocumentText:gsub(".xlsx","_xlsx2") .. ".txt"] then
print("Securisation of " .. filePath .. "\\" .. ActiveDocumentText)
os.execute('copy "' .. filePath .. '\\Archiv\\' .. ActiveDocumentText:gsub(".xlsx","_xlsx2") .. '.txt" "' .. filePath .. '\\Archiv\\' .. ActiveDocumentText:gsub(".xlsx","_xlsx1") .. '.txt"')
excel=luacom.CreateObject("Excel.Application")
excel.Workbooks:Open(ExcelFile)
outputfile1=io.output(filePath .. "\\Archiv\\" .. ActiveDocumentText:gsub(".xlsx","_xlsx2") .. ".txt")
for i = 1, excel.Worksheets.Count do
local WorksheetName=excel.Worksheets(i).Name
excel.Worksheets(i):SaveAs("C:\\Temp\\test_" .. ActiveDocumentText .. "_" .. i .. ".txt", 20)
inputfile1=io.open("C:\\Temp\\test_" .. ActiveDocumentText .. "_" .. i .. ".txt","r")
CTempText=inputfile1:read("*a")
inputfile1:close()
--test with: print(WorksheetName,excel.Worksheets(i).Name)
outputfile1:write("Tabelle " .. WorksheetName .. ":\n" .. CTempText)
end --for i = 1, excel.Worksheets.Count do
excel:Quit()
outputfile1:close()
end --if excelFileTable[ActiveDocumentText]>secureFileTable[ActiveDocumentText .. ".txt"] then
end --for k,v in pairs(fileTable) do
|
mappings = {
{ name = "value", device="Audio", control="Volume Envelope"},
}
|
local beautiful = require 'beautiful'
local gears = require 'gears'
screen.connect_signal('request::wallpaper', function(s)
if beautiful.wallpaper then
local wallpaper = beautiful.wallpaper
if type(wallpaper) == 'function' then
wallpaper = wallpaper(s)
end
gears.wallpaper.maximized(wallpaper, s, true)
end
end)
|
jester.help_map.event = {}
jester.help_map.event.description_short = [[Interact with the FreeSWITCH event system.]]
jester.help_map.event.description_long = [[This module provides actions for interacting with the FreeSWITCH event system.]]
jester.help_map.event.actions = {}
jester.help_map.event.actions.fire_event = {}
jester.help_map.event.actions.fire_event.description_short = [[Fires a custom event.]]
jester.help_map.event.actions.fire_event.description_long = [[Fires a custom event. Event-Name will be 'CUSTOM', and Event-Subclass will be '[subclass]::[event_type]'.
The body will automatically have two newline characters appended to it.]]
jester.help_map.event.actions.fire_event.params = {
subclass = [[(Optional) The first portion of the Event-Subclass header (before the double colons). Default is 'jester'.]],
event_type = [[The second portion of the Event-Subclass header (after the double colons).]],
headers = [[(Optional) A table of event headers, key = header name, value = header description. Note that some headers will need to use the full table key syntax, eg. 'headers = {["Custom-Value"] = "foo"}'.]],
header_prefix = [[(Optional) Prefix all header keys with this string. Defaults to 'Jester-'.]],
body = [[(Optional) The event body.]],
}
|
-- handles all music and soundeffects
local loop = nil -- the default background loop
function soundHandler_init()
loop = love.audio.newSource( "res/sound/ambient.ogg")
loop:setLooping(true)
--loop:play()
end
|
--[[
This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:25' using the latest game version.
NOTE: This file should only be used as IDE support; it should NOT be distributed with addons!
****************************************************************************
CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC.
****************************************************************************
]]
local GamepadInteractiveSortFilterFocus_ParametricList = ZO_GamepadMultiFocusArea_Base:Subclass()
function GamepadInteractiveSortFilterFocus_ParametricList:HandleMovement(horizontalResult, verticalResult)
if verticalResult == MOVEMENT_CONTROLLER_MOVE_NEXT then
self.manager:MoveNext()
return true
elseif verticalResult == MOVEMENT_CONTROLLER_MOVE_PREVIOUS then
self.manager:MovePrevious()
return true
end
return false
end
function GamepadInteractiveSortFilterFocus_ParametricList:HandleMovePrevious()
local consumed = false
if self.manager:AtTopOfList() then
consumed = ZO_GamepadMultiFocusArea_Base.HandleMovePrevious(self)
end
return consumed
end
function GamepadInteractiveSortFilterFocus_ParametricList:HandleMoveNext()
local consumed = false
if self.manager:AtBottomOfList() then
consumed = ZO_GamepadMultiFocusArea_Base.HandleMoveNext(self)
end
return consumed
end
ZO_Gamepad_MultiFocus_ParametricList_Screen = ZO_Object:MultiSubclass(ZO_GamepadMultiFocusArea_Manager, ZO_Gamepad_ParametricList_Screen)
function ZO_Gamepad_MultiFocus_ParametricList_Screen:New(...)
return ZO_Gamepad_ParametricList_Screen.New(self, ...)
end
function ZO_Gamepad_MultiFocus_ParametricList_Screen:Initialize(control, createTabBar, activateOnShow, scene)
ZO_Gamepad_ParametricList_Screen.Initialize(self, control, createTabBar, activateOnShow, scene)
ZO_GamepadMultiFocusArea_Manager.Initialize(self)
self:InitializeMultiFocusArea()
end
-- Multi Focus Area functions --
function ZO_Gamepad_MultiFocus_ParametricList_Screen:InitializeMultiFocusArea()
local function ActivateCallback()
self._currentList:Activate()
self:OnListAreaActivate()
end
local function DeactivateCallback()
self._currentList:Deactivate()
self:OnListAreaDeactivate()
end
self.parametricListArea = GamepadInteractiveSortFilterFocus_ParametricList:New(self, ActivateCallback, DeactivateCallback)
self.parametricListArea:SetKeybindDescriptor(self.keybindStripDescriptor)
self:AddNextFocusArea(self.parametricListArea)
self.currentFocalArea = self.parametricListArea
end
function ZO_Gamepad_MultiFocus_ParametricList_Screen:ResetFocusArea()
self:SelectFocusArea(self.parametricListArea)
end
function ZO_Gamepad_MultiFocus_ParametricList_Screen:OnListAreaActivate()
-- override in derived functions for desired behaviour
end
function ZO_Gamepad_MultiFocus_ParametricList_Screen:OnListAreaDeactivate()
-- override in derived functions for desired behaviour
end
function ZO_Gamepad_ParametricList_Screen:MoveNext()
self._currentList:MoveNext()
end
function ZO_Gamepad_ParametricList_Screen:MovePrevious()
self._currentList:MovePrevious()
end
function ZO_Gamepad_ParametricList_Screen:AtTopOfList()
return self._currentList:GetSelectedIndex() == 1
end
function ZO_Gamepad_ParametricList_Screen:AtBottomOfList()
return self._currentList:GetSelectedIndex() == self._currentList:GetNumItems()
end
-- Header functions --
function ZO_Gamepad_MultiFocus_ParametricList_Screen:SetupHeaderFocus(headerFocus)
assert(false) -- Cannot use this function in this class
end
function ZO_Gamepad_MultiFocus_ParametricList_Screen:UpdateDirectionalInput()
ZO_GamepadMultiFocusArea_Manager.UpdateDirectionalInput(self) -- explicitly state which base class function we want to use
end
-- Scene functions --
-- A function which should be called as the StateChanged callback for the scene.
function ZO_Gamepad_MultiFocus_ParametricList_Screen:OnStateChanged(oldState, newState)
if newState == SCENE_SHOWING or newState == SCENE_GROUP_SHOWING then
self:PerformDeferredInitialize()
if self.activateOnShow then
self:SetCurrentList(self:GetMainList())
end
SCENE_MANAGER:AddFragment(self.headerFragment)
self:OnShowing()
elseif newState == SCENE_HIDING then
self:OnHiding()
elseif newState == SCENE_HIDDEN or newState == SCENE_GROUP_HIDDEN then
self:OnHide()
self:Deactivate()
elseif newState == SCENE_SHOWN or newState == SCENE_GROUP_SHOWN then
self:OnShow()
end
end
function ZO_Gamepad_MultiFocus_ParametricList_Screen:RefreshKeybinds()
self:UpdateActiveFocusKeybinds()
end
-- A function called when the screen is being shown. This should call self:PerformUpdate() if self.dirty.
function ZO_Gamepad_MultiFocus_ParametricList_Screen:OnShowing()
if self.dirty then
self:PerformUpdate()
end
if not DIRECTIONAL_INPUT:IsListening(self) then
self._currentList:SetDirectionalInputEnabled(false)
DIRECTIONAL_INPUT:Activate(self, self.control)
end
self:ActivateCurrentFocus()
end
-- A function called when the screen is fully hidden. This may be overridden in a sub-class.
function ZO_Gamepad_MultiFocus_ParametricList_Screen:OnHide()
if DIRECTIONAL_INPUT:IsListening(self) then
DIRECTIONAL_INPUT:Deactivate(self)
end
self:DeactivateCurrentFocus()
end
|
include("shared.lua")
local hsvToColor = HSVToColor
local curTime = CurTime
function ENT:Draw()
self:DrawModel()
local ang = LocalPlayer():EyeAngles()
ang:RotateAroundAxis( ang:Forward(), 90 )
ang:RotateAroundAxis( ang:Right(), 90 )
local centerx, centery = 0, -150
cam.Start3D2D(self:GetPos(), Angle( 0, ang.y, ang.z ), 0.07)
draw.SimpleText("Candy Cane", "xyz_font_60_static", centerx, centery, Color(255,255,255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
draw.SimpleText("One time use", "xyz_font_40_static", centerx, centery+35, hsvToColor((curTime()*50)%360, 1, 1), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
cam.End3D2D()
end
|
local String = require("string");
local Lockbox = require("lockbox");
Lockbox.ALLOW_INSECURE = true;
local tests = {
"Base64Tests",
"MD2Tests",
"MD4Tests",
"MD5Tests",
"RIPEMD128Tests",
"RIPEMD160Tests",
"SHA1Tests",
"SHA2_224Tests",
"SHA2_256Tests",
"HMACTests",
"HKDFTests",
"PBKDF2Tests",
"DESCipherTests",
"DES3CipherTests",
"AES128CipherTests",
"AES192CipherTests",
"AES256CipherTests",
"TEACipherTests",
"XTEACipherTests",
};
local status = 0
for k,v in pairs(tests) do
print(String.format("Running %s...",v));
local ok, err = pcall(
function()
require("test."..v)
end
);
if not ok then
print(String.format("FAIL: %s failed with error:\n%s\n", v, err));
status = 1
else
print(String.format("%s passed!\n",v));
end
end
os.exit(status)
|
local ITEM = Clockwork.item:New("weapon_base");
ITEM.name = "M92 Beretta";
ITEM.cost = 0;
ITEM.model = "models/weapons/w_beretta_m92.mdl";
ITEM.weight = 0.95;
ITEM.uniqueID = "m9k_m92beretta";
ITEM.business = false;
ITEM.description = "A fairly new looking handgun and is very light, chambers 9x19mm Parabellum";
ITEM.isAttachment = false;
ITEM.hasFlashlight = true;
ITEM.loweredOrigin = Vector(3, 0, -4);
ITEM.loweredAngles = Angle(0, 45, 0);
ITEM.attachmentBone = "ValveBiped.Bip01_Pelvis";
ITEM.attachmentOffsetAngles = Angle(90, 0, 0);
ITEM.attachmentOffsetVector = Vector(0, 6.55, 8.72);
ITEM:Register();
|
-- Based off of the Duplicator GUI
PANEL.VoteName = "none"
PANEL.MaterialName = "exclamation"
function PANEL:Init()
self.RefreshBtn = vgui.Create("DImageButton", self)
self.RefreshBtn:SetMaterial("gui/silkicons/arrow_refresh")
self.RefreshBtn:SetTooltip("Refresh List")
self.RefreshBtn.DoClick = function() return self:Populate() end
self.SaveBtn = vgui.Create("DImageButton", self)
self.SaveBtn:SetMaterial("gui/silkicons/camera_add")
self.SaveBtn:SetTooltip("Save Track")
self.SaveBtn.DoClick = function() self:Save() end
self.SaveFileName = vgui.Create("DTextEntry", self)
self.SaveFileName:SetKeyboardInputEnabled(true)
self.SaveFileName:SetEnabled(true)
self.List = vgui.Create("PanelList", self)
self.List:SetSpacing(1)
self.SaveList = {}
end
function PANEL:Save()
--RunConsoleCommand("tool_duplicator_store", self.SaveFileName:GetValue())
end
function PANEL:PerformLayout()
self:SetTall(500)
self.RefreshBtn:SizeToContents()
self.RefreshBtn:AlignRight(5)
self.RefreshBtn:AlignBottom()
self.SaveBtn:SizeToContents()
self.SaveBtn:AlignRight(self.RefreshBtn:GetWide() + 9)
self.SaveBtn:AlignBottom()
self.SaveFileName:SetTall(self.SaveBtn:GetTall())
self.SaveFileName:AlignLeft(5)
self.SaveFileName:AlignBottom()
self.SaveFileName:StretchRightTo(self.SaveBtn, 4)
self.List:StretchToParent(0, 0, 0, 0)
self.List:StretchBottomTo(self.SaveBtn, 4)
end
function PANEL:Clear()
self.SaveList = {}
return self.List:Clear()
end
function PANEL:Add(id, name)
self.SaveList[id] = name
end
function PANEL:Populate()
self.List:Clear()
self.SaveList = file.Find(CatmullRomCams.FilePath .. "*.txt")
for k, v in pairs(self.SaveList) do
local btn = vgui.Create("DCatmullCamTrackSaveLoadButton", self)
btn:SetFile(v)
btn:SetID(k)
self.List:AddItem(btn)
end
end
derma.DefineControl("DCatmullCamTrackSaveLoadMenu", "Its time to kick ass and chew bubble-gum, and I'm all outa' gum...", PANEL, "DPanel")
|
slot0 = class("GuildDonateTask", import("..BaseVO"))
slot0.Ctor = function (slot0, slot1)
slot0.id = slot1.id
slot0.configId = slot0.id
end
slot0.bindConfigTable = function (slot0)
return pg.guild_contribution_template
end
slot0.getCommitItem = function (slot0)
return {
slot0:getConfig("type"),
slot0:getConfig("type_id"),
slot0:getConfig("consume")
}
end
slot0.getCapital = function (slot0)
return slot0:getConfig("award_capital")
end
slot0.GetLivenessAddition = function (slot0)
return slot0:getConfig("guild_active")
end
slot0.canCommit = function (slot0)
if slot0:getCommitItem()[1] == DROP_TYPE_RESOURCE then
if getProxy(PlayerProxy):getData()[id2res(slot1[2])] < slot1[3] then
return false
end
elseif slot1[1] == DROP_TYPE_ITEM and getProxy(BagProxy):getItemCountById(slot1[2]) < slot1[3] then
return false
end
return true
end
return slot0
|
--MCmobs v0.4
--maikerumine
--made for MC like Survival game
--License for code WTFPL and otherwise stated in readmes
--dofile(minetest.get_modpath("mobs").."/api.lua")
--###################
--################### ZOMBIE
--###################
--[[
mobs:register_mob("mobs_mc:22zombie", {
type = "animal",
passive = true,
runaway = true,
stepheight = 1.2,
hp_min = 30,
hp_max = 60,
armor = 150,
collisionbox = {-0.35, -0.01, -0.35, 0.35, 2, 0.35},
rotate = -180,
visual = "mesh",
mesh = "zombie.b3d",
textures = {
{"zombie.png"},
},
visual_size = {x=3.5, y=3.5},
walk_velocity = 0.6,
run_velocity = 2,
jump = true,
animation = {
speed_normal = 25, speed_run = 50,
stand_start = 40, stand_end = 80,
walk_start = 0, walk_end = 40,
run_start = 0, run_end = 40,
},
})
mobs:register_egg("mobs_mc:22zombie", "Zombie", "zombie_inv.png", 0)
]]
local zombie = {
type = "monster",
hp_min = 20,
hp_max = 20,
collisionbox = {-0.35, -0.01, -0.35, 0.35, 2, 0.35},
--collisionbox = {-0.5, -0.01, -0.5, 0.5, 1.9, 0.5},
--rotate = -180,
visual = "mesh",
--mesh = "zombie.b3d", new
mesh = "mobs_zombie.x",
textures = {
--{"zombie.png"},
{"mobs_zombie.png"},
},
visual_size = {x=1, y=1},
makes_footstep_sound = true,
sounds = {
random = "zombie1",
death = "zombiedeath",
damage = "zombiehurt1",
attack = "default_punch3",
},
walk_velocity = .8,
run_velocity = 1.6,
damage = 3,
fear_height = 8,
pathfinding = 1,
jump = true,
--jump_height = 3,
group_attack = true,
drops = {
{name = "mobs:rotten_flesh",
chance = 1,
min = 0,
max = 2,},
{name = "default:iron_ingot",
-- approximation to 8.5%
chance = 11,
min = 1,
max = 1,},
{name = "farming:carrot",
-- approximation to 8.5%
chance = 11,
min = 1,
max = 1,},
{name = "farming:potato",
-- approximation to 8.5%
chance = 11,
min = 1,
max = 1,},
},
animation = {
speed_normal = 24,
speed_run = 48,
stand_start = 0,
stand_end = 23,
walk_start = 24,
walk_end = 47,
run_start = 48,
run_end = 62,
hurt_start = 64,
hurt_end = 86,
death_start = 88,
death_end = 118,
},
drawtype = "front",
lava_damage = 5,
-- TODO: Burn mob only when in direct sunlight
light_damage = 2,
view_range = 17,
attack_type = "dogfight",
}
mobs:register_mob("mobs_mc:zombie", zombie)
-- Baby zombie.
-- A smaller and more dangerous variant of the zombie
local baby_zombie = table.copy(zombie)
baby_zombie.collisionbox = {-0.25, -0.01, -0.25, 0.25, 0.94, 0.25}
baby_zombie.visual_size = {x=0.5, y=0.5}
baby_zombie.walk_velocity = 1.2
baby_zombie.run_velocity = 2.4
baby_zombie.light_damage = 0
mobs:register_mob("mobs_mc:baby_zombie", baby_zombie)
-- Husk.
-- Desert variant of the zombie
local husk = table.copy(zombie)
husk.textures = {{"mobs_mc_husk.png"}}
husk.light_damage = 0
husk.water_damage = 3
-- TODO: Husks avoid water
mobs:register_mob("mobs_mc:husk", husk)
-- Baby husk.
-- A smaller and more dangerous variant of the husk
local baby_husk = table.copy(husk)
baby_husk.collisionbox = {-0.25, -0.01, -0.25, 0.25, 0.94, 0.25}
baby_husk.visual_size = {x=0.5, y=0.5}
baby_husk.walk_velocity = 1.2
baby_husk.run_velocity = 2.4
mobs:register_mob("mobs_mc:baby_husk", baby_husk)
-- Spawning
mobs:register_spawn("mobs_mc:zombie", {"default:dirt_with_grass", "default:dirt_with_dry_grass","default:stone","default:dirt","default:coarse_dirt", "default:sand"}, 7, -1, 8000, 4, 31000)
-- Baby zombie is 20 times less likely than regular zombies
mobs:register_spawn("mobs_mc:baby_zombie", {"default:dirt_with_grass", "default:dirt_with_dry_grass","default:stone","default:dirt","default:coarse_dirt", "default:sand"}, 7, -1, 100000, 4, 31000)
mobs:register_spawn("mobs_mc:husk", {"default:sand", "default:redsand", "default:sandstone", "default:redsandstone"}, 7, -1, 8090, 4, 31000)
mobs:register_spawn("mobs_mc:baby_husk", {"default:sand", "default:redsand", "default:sandstone", "default:redsandstone"}, 7, -1, 100000, 4, 31000)
-- Compatibility
mobs:alias_mob("mobs:zombie", "mobs_mc:zombie")
-- Spawn eggs
mobs:register_egg("mobs_mc:zombie", "Spawn Zombie", "spawn_egg_zombie.png")
mobs:register_egg("mobs_mc:baby_zombie", "Spawn Baby Zombie", "spawn_egg_baby_zombie.png") -- TODO: To be removed
mobs:register_egg("mobs_mc:husk", "Spawn Husk", "spawn_egg_husk.png") -- TODO: To be removed
mobs:register_egg("mobs_mc:baby_husk", "Spawn Baby Husk", "spawn_egg_baby_husk.png") -- TODO: To be removed
mobs:register_egg("mobs_mc:zombie", "Zombie", "zombie_inv.png", 0)
if minetest.settings:get_bool("log_mods") then
minetest.log("action", "MC Zombie loaded")
end
|
-- `--::-.`
-- ./shddddddddhs+.
-- :yddddddddddddddddy:
-- `sdddddddddddddddddddds`
-- ydddh+sdddddddddy+ydddds M-Like:Box
-- /ddddy:oddddddddds:sddddd/ By adebray - adebray
-- sdddddddddddddddddddddddds
-- sdddddddddddddddddddddddds Created: 2015-12-01 03:38:03
-- :ddddddddddhyyddddddddddd: Modified: 2015-12-01 08:57:21
-- odddddddd/`:-`sdddddddds
-- +ddddddh`+dh +dddddddo
-- -sdddddh///sdddddds-
-- .+ydddddddddhs/.
-- .-::::-`
local Box = {}
function Box.FromCenter(point, size)
return {
center = point,
A = Point.new(point.x - size.x, point.y - size.y),
B = Point.new(point.x + size.x, point.y - size.y),
C = Point.new(point.x + size.x, point.y + size.y),
D = Point.new(point.x - size.x, point.y + size.y)
}
end
function Box.FromCorner(point, size)
return {
center = Point.new(point.x + size.x / 2, point.y + size.y / 2),
A = Point.new(point.x, point.y),
B = Point.new(point.x + size.x, point.y),
C = Point.new(point.x + size.x, point.y + size.y),
D = Point.new(point.x, point.y + size.y)
}
end
function Box.get_collision(corner, values)
return Point.new(
values.x - corner.x,
values.y - corner.y
)
end
function Box.collides(EntityBox, MeshBox)
if EntityBox.center.x - MeshBox.center.x < 0 and
EntityBox.center.y - MeshBox.center.y < 0 then
return Box.get_collision(MeshBox.A, EntityBox.C)
elseif EntityBox.center.x - MeshBox.center.x > 0 and
EntityBox.center.y - MeshBox.center.y < 0 then
return Box.get_collision(Point.new(EntityBox.D.x, MeshBox.B.y), Point.new(MeshBox.B.x, EntityBox.D.y))
elseif EntityBox.center.x - MeshBox.center.x < 0 and
EntityBox.center.y - MeshBox.center.y > 0 then
return Box.get_collision(Point.new(MeshBox.D.x, EntityBox.B.y), Point.new(EntityBox.B.x, MeshBox.D.y))
elseif EntityBox.center.x - MeshBox.center.x > 0 and
EntityBox.center.y - MeshBox.center.y > 0 then
return Box.get_collision(EntityBox.A, MeshBox.C)
else
return Point.new(0, 0)
end
end
return Box
|
require("functions")
require("prototypes.categories")
require("prototypes.styles")
require("prototypes.research-reports")
require("prototypes.particles")
require("prototypes.elements")
require("prototypes.deep-space-accelerator")
require("prototypes.building.research-center")
require("prototypes.building.analysis-center")
require("prototypes.building.accelerator")
require("prototypes.building.facility")
require("prototypes.technology")
|
-- stateful.lua - v1.0.3 (2014-10)
-- requires middleclass >2.0
-- Copyright (c) 2011 Enrique García Cota
-- 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.
-- Based on YaciCode, from Julien Patte and LuaObject, from Sebastien Rocca-Serra
local Stateful = { static = {} }
local _callbacks = {
enteredState = 1,
exitedState = 1,
pushedState = 1,
poppedState = 1,
pausedState = 1,
continuedState = 1
}
local _BaseState = {}
local function _addStatesToClass(klass, superStates)
klass.static.states = {}
for stateName, state in pairs(superStates or {}) do
klass:addState(stateName,state)
end
end
local function _getStatefulMethod(instance, name)
if not _callbacks[name] then
local stack = rawget(instance, '__stateStack')
if not stack then return end
for i = #stack, 1, -1 do
if stack[i][name] then return stack[i][name] end
end
end
end
local function _getNewInstanceIndex(prevIndex)
if type(prevIndex) == 'function' then
return function(instance, name) return _getStatefulMethod(instance, name) or prevIndex(instance, name) end
end
return function(instance, name) return _getStatefulMethod(instance, name) or prevIndex[name] end
end
local function _getNewAllocateMethod(oldAllocateMethod)
return function(klass, ...)
local instance = oldAllocateMethod(klass, ...)
instance.__stateStack = {}
return instance
end
end
local function _modifyInstanceIndex(klass)
klass.__instanceDict.__index = _getNewInstanceIndex(klass.__instanceDict.__index)
end
local function _getNewSubclassMethod(prevSubclass)
return function(klass, name)
local subclass = prevSubclass(klass, name)
_addStatesToClass(subclass, klass.states)
_modifyInstanceIndex(subclass)
return subclass
end
end
local function _modifySubclassMethod(klass)
klass.static.subclass = _getNewSubclassMethod(klass.static.subclass)
end
local function _modifyAllocateMethod(klass)
klass.static.allocate = _getNewAllocateMethod(klass.static.allocate)
end
local function _assertType(val, name, expected_type, type_to_s)
assert(type(val) == expected_type, "Expected " .. name .. " to be of type " .. (type_to_s or expected_type) .. ". Was " .. tostring(val) .. "(" .. type(val) .. ")")
end
local function _assertInexistingState(klass, stateName)
assert(klass.states[stateName] == nil, "State " .. tostring(stateName) .. " already exists on " .. tostring(klass) )
end
local function _assertExistingState(self, state, stateName)
assert(state, "The state " .. stateName .. " was not found in " .. tostring(self.class) )
end
local function _invokeCallback(self, state, callbackName, ...)
if state and state[callbackName] then state[callbackName](self, ...) end
end
local function _getCurrentState(self)
return self.__stateStack[#self.__stateStack]
end
local function _getStateFromClassByName(self, stateName)
local state = self.class.static.states[stateName]
_assertExistingState(self, state, stateName)
return state
end
local function _getStateIndexFromStackByName(self, stateName)
if stateName == nil then return #self.__stateStack end
local target = _getStateFromClassByName(self, stateName)
for i = #self.__stateStack, 1, -1 do
if self.__stateStack[i] == target then return i end
end
end
local function _getStateName(self, target)
for name,state in pairs(self.class.static.states) do
if state == target then return name end
end
end
function Stateful:included(klass)
_addStatesToClass(klass)
_modifyInstanceIndex(klass)
_modifySubclassMethod(klass)
_modifyAllocateMethod(klass)
end
function Stateful.static:addState(stateName, superState)
superState = superState or _BaseState
_assertType(stateName, 'stateName', 'string')
_assertInexistingState(self, stateName)
self.static.states[stateName] = setmetatable({}, { __index = superState })
return self.static.states[stateName]
end
function Stateful:gotoState(stateName, ...)
if self.nextStateName ~= nil then
print(debug.traceback())
end
self.nextStateName = stateName
self.nextStateArgs = {...}
--[[
self:popAllStates()
if stateName == nil then
self.__stateStack = { }
else
_assertType(stateName, 'stateName', 'string', 'string or nil')
local newState = _getStateFromClassByName(self, stateName)
self.__stateStack = { newState }
_invokeCallback(self, newState, 'enteredState', ...)
end]]
end
function Stateful:checkState()
if (self.nextStateName ~= nil) then
self:popAllStates()
self.curStateName = self.nextStateName
self.nextStateName = nil
if self.curStateName == nil then
self.__stateStack = { }
else
_assertType(self.curStateName, 'stateName', 'string', 'string or nil')
local newState = _getStateFromClassByName(self, self.curStateName)
self.__stateStack = { newState }
_invokeCallback(self, newState, 'enteredState', unpack(self.nextStateArgs))
end
end
end
function Stateful:pushState(stateName)
local oldState = _getCurrentState(self)
_invokeCallback(self, oldState, 'pausedState')
local newState = _getStateFromClassByName(self, stateName)
table.insert(self.__stateStack, newState)
_invokeCallback(self, newState, 'pushedState')
_invokeCallback(self, newState, 'enteredState')
end
function Stateful:popState(stateName)
local oldStateIndex = _getStateIndexFromStackByName(self, stateName)
local oldState
if oldStateIndex then
oldState = self.__stateStack[oldStateIndex]
_invokeCallback(self, oldState, 'poppedState')
_invokeCallback(self, oldState, 'exitedState')
table.remove(self.__stateStack, oldStateIndex)
end
local newState = _getCurrentState(self)
if oldState ~= newState then
_invokeCallback(self, newState, 'continuedState')
end
end
function Stateful:popAllStates()
local size = #self.__stateStack
for i=1,size do self:popState() end
end
function Stateful:getStateStackDebugInfo()
local info, state = {}, nil
for i=#self.__stateStack,1,-1 do
state = self.__stateStack[i]
table.insert(info, _getStateName(self, state))
end
return info
end
return Stateful
|
local ROOT = script:GetCustomProperty("Root"):WaitForObject()
local LIQUID = ROOT:GetCustomProperty("Liquid"):WaitForObject()
local TRIGGER = ROOT:GetCustomProperty("Trigger"):WaitForObject()
local SPLASH = ROOT:GetCustomProperty("Splash"):WaitForObject()
local GLOW = ROOT:GetCustomProperty("Glow"):WaitForObject()
-- local FLOW = ROOT:GetCustomProperty("Flow"):WaitForObject()
local MAX_WELL_CAPACITY = ROOT:GetCustomProperty("MaxWellCapacity")
local HEALING_RATE = ROOT:GetCustomProperty("HealingRate")
local HEALING_AMOUNT = ROOT:GetCustomProperty("HealingAmount")
local REPLENISH_RATE = ROOT:GetCustomProperty("ReplenishRate")
local REPLENISH_AMOUNT = ROOT:GetCustomProperty("ReplenishAmount")
local lastHeal = time()
local lastReplenish = time()
local fullWell = LIQUID:GetPosition().z
function GetOverlappingPlayers(trigger)
local objects = trigger:GetOverlappingObjects()
local players = {}
for _, object in pairs(objects) do
if object:IsA("Player") then
table.insert(players, object)
end
end
return players
end
function GetWellCapacity()
return ROOT:GetCustomProperty("WellCapacity")
end
function HealPlayers()
if math.abs(lastHeal - time()) > HEALING_RATE and #GetOverlappingPlayers(TRIGGER) > 0 then
print("Draining..")
-- Get all player in the trigger.
local players = GetOverlappingPlayers(TRIGGER)
for _, player in pairs(players) do
-- Current well capacity remaining
if player:IsA("Player") then
-- Heal the player if their health is less than max.
if player.hitPoints < player.maxHitPoints and GetWellCapacity() >= HEALING_AMOUNT then
player.hitPoints = player.hitPoints + HEALING_AMOUNT
ROOT:SetNetworkedCustomProperty("WellCapacity", GetWellCapacity() - HEALING_AMOUNT)
elseif GetWellCapacity() < 0 and player.hitPoints < player.maxHitPoints then
player.hitPoints = player.hitPoints + GetWellCapacity()
ROOT:SetNetworkedCustomProperty("WellCapacity", GetWellCapacity() - GetWellCapacity())
end
-- Clamp the player health to max hitpoints
if player.hitPoints > player.maxHitPoints then
player.hitPoints = player.maxHitPoints
end
end
end
UpdateWell()
lastHeal = time()
end
end
function ReplenishWell()
if math.abs(lastReplenish - time()) > REPLENISH_RATE and #GetOverlappingPlayers(TRIGGER) < 1 and GetWellCapacity() < MAX_WELL_CAPACITY then
print("Replenishing..")
ROOT:SetNetworkedCustomProperty("WellCapacity", GetWellCapacity() + REPLENISH_AMOUNT)
if GetWellCapacity() > MAX_WELL_CAPACITY then
ROOT:SetNetworkedCustomProperty("WellCapacity", MAX_WELL_CAPACITY)
end
UpdateWell()
lastReplenish = time()
end
end
function UpdateWell()
local liquidPosition = LIQUID:GetPosition()
local wellDepth = CalculateWellLevel()
LIQUID:MoveTo(Vector3.New(liquidPosition.x, liquidPosition.y, wellDepth), 0.5, true)
end
function CalculateWellLevel()
local wellPercentage = GetWellCapacity() / MAX_WELL_CAPACITY * 100
GLOW.intensity = wellPercentage
if FLOW then
if wellPercentage < 0.1 and FLOW.isEnabled == true then
FLOW.isEnabled = false
elseif wellPercentage > 0.1 and FLOW.isEnabled == false then
FLOW.isEnabled = true
end
end
local wellDepth = (wellPercentage / 100) * fullWell
return wellDepth
end
function Tick()
HealPlayers()
ReplenishWell()
CalculateWellLevel()
Task.Wait()
end
function OnEnterWell(trigger, other)
if other:IsA("Player") then
SPLASH:Play()
end
end
TRIGGER.beginOverlapEvent:Connect(OnEnterWell)
function OnPlayerJoined(player)
player.maxHitPoints = 2000
end
Game.playerJoinedEvent:Connect(OnPlayerJoined)
|
local oBody = require("oBody")
local oEffect = require("oEffect")
local tolua = require("tolua")
local oModel = require("oModel")
local CCScheduler = require("CCScheduler")
local oWorld = require("oWorld")
local oPlatformWorld = require("oPlatformWorld")
local CCSprite = require("CCSprite")
local oData = require("oData")
local oVec2 = require("oVec2")
local CCDirector = require("CCDirector")
local function Simulation(level)
if 1 == level then return 1, 1
elseif 2 == level then return 4, 2
elseif 3 == level then return 8, 3
end
end
local function Children(parent, data, items, sceneData)
local children = data.children
if children then
for i, child in ipairs(children) do
child = child(parent, i, items, sceneData)
if child then
parent:addChild(child)
end
end
end
end
local function Contact(world, data)
local groups = data.groups
local contacts = data.contacts
if groups and contacts then
for i = 1, #contacts do
local contact = contacts[i]
world:setShouldContact(unpack(contact))
end
end
end
local function Groups(data)
local default = {
[0] = "Hide",
"P1","P2","P3","P4",
"P5","P6","P7","P8",
"P9","P10","P11","P12",
"DetectPlayer",
"Terrain",
"Detect"
}
return setmetatable(data, {__index = default})
end
local function AlignGet(pos,align)
if align == 1 then -- Center
return pos
else
local winSize = CCDirector.winSize
if align == 2 then -- LeftBottom
return pos-oVec2(winSize.width/2,winSize.height/2)
elseif align == 3 then -- LeftTop
return oVec2(pos.x-winSize.width/2,winSize.height/2-pos.y)
elseif align == 4 then -- RightTop
return oVec2(winSize.width/2,winSize.height/2)-pos
elseif align == 5 then -- RightBottom
return oVec2(winSize.width/2-pos.x,pos.y-winSize.height/2)
else
return pos
end
end
end
local Types = {
PlatformWorld = 1, UILayer = 2,
Camera = 3, Layer = 4,
World = 5, Body = 6,
Model = 7, Sprite = 8,
Effect = 9, SubCam = 10
}
local TypeNames = {}
for k, v in pairs(Types) do
TypeNames[v] = k
end
local function DataCreater(dataDef)
local create = dataDef.create
dataDef.create = nil
local dataMt = {
__call = create,
__index = function(self, k)
local index = dataDef[k]
if index then
return self[index]
else
return nil
end
end
}
return function(data)
return setmetatable(data, dataMt)
end
end
local GameItems = {
PlatformWorld = DataCreater {
itemType = 1, gravity = 2,
contacts = 3, groups = 4,
simulation = 5, camera = 6,
ui = 7, children = 8,
outline = 9,
create = function(self)
local world = oPlatformWorld()
world.gravity = oVec2(0, self.gravity)
world:setIterations(Simulation(self.simulation))
world.scheduler = CCScheduler()
world:slot("Cleanup", function()
CCDirector.scheduler:unschedule(world.scheduler)
end)
CCDirector.scheduler:schedule(world.scheduler)
local items = {Scene = world}
if self.camera then
self.camera(world,nil,items)
end
if self.ui then
self.ui(world,nil,items)
end
Contact(world, self)
Children(world, self, items, self)
return world,items
end
},
UILayer = DataCreater {
itemType = 1, visible = 2,
children = 3, display = 4,
fold = 5,
create = function(self, scene, _, items, sceneData)
local layer = scene.UILayer
items.UI = layer
layer.visible = self.visible
Children(layer, self, items, sceneData)
return nil
end
},
Camera = DataCreater {
itemType = 1, boundary = 2,
area = 3, subCams = 4,
create = function(self, scene, _, items)
local camera = scene.camera
items.Camera = camera
return nil
end
},
SubCam = DataCreater {
itemType = 1, name = 2,
position = 3, zoom = 4,
angle = 5,
create = function(self)
return nil
end
},
Layer = DataCreater {
itemType = 1, name = 2,
ratioX = 3, ratioY = 4,
offset = 5, zoom = 6,
visible = 7, children = 8,
display = 9, fold = 10,
create = function(self, scene, index, items, sceneData)
scene:setLayerOffset(index, self.offset)
local layer = scene:getLayer(index)
layer.scaleX = self.zoom
layer.scaleY = self.zoom
layer.visible = self.visible
items[self.name] = layer
Children(layer, self, items, sceneData)
return nil
end
},
World = DataCreater {
itemType = 1, name = 2,
gravity = 3, simulation = 4,
ratioX = 5, ratioY = 6,
offset = 7, zoom = 8,
visible = 9, children = 10,
outline = 11, display = 12,
fold = 13,
create = function(self, scene, index, items, sceneData)
scene:setLayerOffset(index, self.offset)
local layer = scene:getLayer(index)
layer.scaleX = self.zoom
layer.scaleY = self.zoom
local world = oWorld()
world.gravity = self.gravity
world.visible = self.visible
world:setIterations(Simulation(self.simulation))
layer:addChild(world)
world.scheduler = CCScheduler()
CCDirector.scheduler:schedule(world.scheduler)
world:slot("Cleanup", function()
CCDirector.scheduler:unschedule(world.scheduler)
end)
oData:apply(world)
Contact(world, sceneData)
items[self.name] = world
Contact(world, self)
Children(world, self, items, sceneData)
return nil
end
},
Body = DataCreater {
itemType = 1, name = 2,
file = 3, group = 4,
position = 5, angle = 6,
visible = 7, display = 8,
create = function(self, parent, _, items)
local world = items.Scene
if "oWorld" == tolua.type(parent) then
world = parent
end
local body = oBody(self.file, world, self.position, self.angle)
body.data:each(function(_, v)
if "oBody" == tolua.type(v) then
v.group = self.group
end
end)
body.visible = self.visible
items[self.name] = body
return body
end
},
Model = DataCreater {
itemType = 1, name = 2,
file = 3, position = 4,
angle = 5, scale = 6,
skew = 7, opacity = 8,
look = 9, animation = 10,
speed = 11, loop = 12,
faceRight = 13, visible = 14,
display = 15, align = 16,
create = function(self, _, _, items)
local model = oModel(self.file)
model.position = AlignGet(self.position,self.align)
model.angle = self.angle
model.scaleX = self.scale.x
model.scaleY = self.scale.y
model.skewX = self.skew.x
model.skewY = self.skew.y
model.opacity = self.opacity
model.look = self.look
model.speed = self.speed
model.loop = self.loop
model.faceRight = self.faceRight
model.visible = self.visible
model:play(self.animation)
items[self.name] = model
return model
end
},
Sprite = DataCreater {
itemType = 1, name = 2,
file = 3, position = 4,
angle = 5, scale = 6,
skew = 7, opacity = 8,
visible = 9, display = 10,
align = 11,
create = function(self, _, _, items)
local sprite = CCSprite(self.file)
sprite.position = AlignGet(self.position,self.align)
sprite.angle = self.angle
sprite.scaleX = self.scale.x
sprite.scaleY = self.scale.y
sprite.skewX = self.skew.x
sprite.skewY = self.skew.y
sprite.opacity = self.opacity
sprite.visible = self.visible
items[self.name] = sprite
return sprite
end
},
Effect = DataCreater {
itemType = 1, name = 2,
effect = 3, position = 4,
play = 5, visible = 6,
display = 7, align = 8,
create = function(self, parent, _, items)
local effect = oEffect(self.effect)
effect.visible = self.visible
effect:addTo(parent)
effect.position = AlignGet(self.position,self.align)
if self.play then
effect:start()
end
items[self.name] = effect
return nil
end
}
}
local function loader(filename)
local function setupData(data)
GameItems[TypeNames[data[1]]](data)
if data.children then
local children = data.children
for i = 1, #children do
local child = children[i]
setupData(child)
end
end
end
local data = dofile(filename)
setupData(data)
if data.groups then
Groups(data.groups)
end
if data.camera then
local camera = data.camera
GameItems.Camera(camera)
if camera.subCams then
local subCams = camera.subCams
for i = 1, #subCams do
local cam = subCams[i]
GameItems.SubCam(cam)
end
end
end
return data
end
return loader
|
local math = require 'math'
local storage_dict = require 'nginx-metrix.storage.dict'
math.randomseed(ngx and ngx.now() or os.time())
-- Window Item --
local WindowItem = {}
WindowItem.__index = WindowItem
---
--
function WindowItem.create_key()
return ngx.md5(string.format('%.3f %.12f', ngx.now(), math.random()))
end
---
-- @param payload
--
function WindowItem.new(payload)
local windowItem = setmetatable({ _key = WindowItem.create_key(), _payload = payload, _next = nil }, WindowItem)
windowItem:store()
return windowItem
end
---
-- @param self WindowItem
--
function WindowItem.store(self)
return storage_dict.set('WindowItem^' .. self._key, self)
end
---
-- @param key
--
function WindowItem.restore(key)
local data = storage_dict.get('WindowItem^' .. key)
if data ~= nil then
return setmetatable(data, WindowItem)
end
return nil
end
---
-- @param self
--
function WindowItem.key(self)
return self._key
end
function WindowItem.payload(self)
return self._payload
end
---
-- @param self
-- @param next
--
function WindowItem.next(self, next)
if next ~= nil then
self._next = next:key()
self:store()
elseif self._next == nil then
return nil
else
next = WindowItem.restore(self._next)
if next == nil then
self._next = nil
self:store()
end
return next
end
end
-- /Window Item --
-- Window --
local Window = {}
Window.__index = Window
---
-- @param name
-- @param limit
--
function Window.open(name, limit)
local window = (storage_dict.get('Window^' .. name)) or { _name = name, _limit = limit, _size = 0, _head = nil, _tail = nil }
return setmetatable(window, Window)
end
---
-- @param self
--
function Window.store(self)
return storage_dict.set('Window^' .. self._name, self)
end
function Window.size(self)
return self._size
end
Window.len = Window.size
---
-- @param self
-- @param payload
--
function Window.push(self, payload)
if self._limit == self._size then
self:pop()
end
local item = WindowItem.new(payload)
if self._tail ~= nil then
WindowItem.restore(self._tail):next(item)
end
self._tail = item:key()
if self._head == nil then
self._head = self._tail
end
self._size = self._size + 1
self:store()
end
---
-- @param self
--
function Window.pop(self)
if self._head == nil then
return nil
end
local head = WindowItem.restore(self._head)
self._head = head._next
if self._head == nil then
self._tail = nil
end
self._size = self._size - 1
self:store()
return head:payload()
end
---
-- @param self
--
function Window.totable(self)
local list = {}
local item = self._head and WindowItem.restore(self._head)
while item ~= nil do
table.insert(list, item:payload())
item = item:next()
end
return list;
end
-- /Window --
--------------------------------------------------------------------------------
-- EXPORTS
--------------------------------------------------------------------------------
local exports = Window
if __TEST__ then
exports.__private__ = {
WindowItem = WindowItem,
}
end
return exports
|
local l_sys = require("l_sys")
local sh = l_sys.sh
local x86_64_driver = {}
-- 加载驱动
x86_64_driver.load = function()
end
-- 卸载驱动
x86_64_driver.unload = function()
end
return x86_64_driver
|
hook.Add("TTS.PlayerInitialSpawn", "TTS::CheckFamilySharing", function(ply)
if ply:IsBot() then return end
-- print(ply:GetPData("notfamilysharing"))
-- if ply:GetPData("notfamilysharing") == "true" then return end
local ply64 = ply:SteamID64()
local RadioUrlStreams = "https://api.steampowered.com/IPlayerService/IsPlayingSharedGame/v1?key=70449E6E69DAA578D83622AA05A8CD29&steamid="..ply64.."&appid_playing=4000"
http.Fetch(RadioUrlStreams,
function( body, len, headers, code )
if IsValid(ply) then
local listofskyp = util.JSONToTable(body)
local owner = listofskyp["response"]["lender_steamid"]
-- print(owner)
if owner ~= '0' then
-- TTS.Fetch("bans.ImportQuoteData", {
-- sid = ply:SteamID(),
-- type = '1',
-- data = util.TableToJSON({[owner] = true}),
-- })
ply.IsFamilySharing = true
return
end
ply:SetPData("notfamilysharing","true")
end
end)
end)
netstream.Hook("TTS::SendQuoteTime", function(ply, data)
-- TTS.Fetch("bans.ImportQuoteData", {
-- sid = ply:SteamID(),
-- type = '2',
-- data = util.TableToJSON(array),
-- })
if ply.IsFamilySharing then
local text =[[Доступ к серверу аккаунтам с не купленным Garry`s mod ограничен]]
ply:Kick(text)
end
-- //end
-- //print("------------------")
-- //print(ply)
-- //PrintTable(data)
end)
|
--!The Make-like install Utility based on Lua
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you 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.
--
-- Copyright (C) 2015 - 2018, TBOOX Open Source Group.
--
-- @author ruki
-- @file uninstall.lua
--
-- uninstall package from the prefix directory
function main(package)
-- remove the previous installed files
local prefixdir = package:prefixdir()
for _, relativefile in ipairs(package:prefixinfo().installed) do
-- trace
vprint("removing %s ..", relativefile)
-- remove file
local prefixfile = path.absolute(relativefile, prefixdir)
os.tryrm(prefixfile)
-- remove it if the parent directory is empty
local parentdir = path.directory(prefixfile)
while parentdir and os.isdir(parentdir) and os.emptydir(parentdir) do
os.tryrm(parentdir)
parentdir = path.directory(parentdir)
end
end
-- unregister this package
package:unregister()
-- remove the prefix file
os.tryrm(package:prefixfile())
end
|
admins = {
{ name = "KaliBwoy", title = "Owner", accountName = "KaliBwoy" },
{ name = "Cena", title = "Co-owner", accountName = "Cena" },
{ name = "Kreator", title = "Server Manager", accountName = "Goldberg" },
{ name = "Mihoje", title = "Developer", accountName = "Mihoje" },
{ name = "Haxardous", title = "Developer", accountName = "Axa" },
{ name = "Nick_026", title = "Gayloper", accountName = "Nick_026" },
{ name = "MoshPit", title = "Map Manager", accountName = "MoshMosh" },
{ name = "Dubby", title = "Map Manager", accountName = "dubby" },
{ name = "Koolaid", title = "Map Manager", accountName = "koolaidkarlis" },
{ name = "Stig", title = "Old Admin", accountName = "Stig" },
{ name = "AbueloEbrio", title = "Alcoholic Admin", accountName = "santiii733" },
{ name = "Jap", title = "Admin", accountName = "jap3" },
{ name = "Mekuar", title = "Admin", accountName = "Mekuar1" },
{ name = "Military", title ="Admin", accountName = "mili"},
{ name = "Mateoryt", title="Admin", accountName = "mateoryt"},
{ name = "Semert", title="Admin", accountName = "semert"}
}
|
if aaa then end
if aaa+bbb+ccc == 123 then end
if aaa+bbb and
ccc or eee then
local t = 123
if aaa then
end
if ddd then
else --hahh
end
end
if a then
elseif aa then
elseif ccc then
else
end
if a then return a --end
end
if a --
then
end
|
local common = require("common")
local s1 = common.getApprox(7,14,50)
local s2 = common.getApprox(14,7,50)
local s3 = common.getApprox(14,6,50)
local s4 = common.getApprox(355,113,50)
local s5 = common.getApprox(307,113,50)
print(s1:len(), s1)
print(s2:len(), s2)
print(s3:len(), s3)
print(s4:len(), s4)
print(s5:len(), s5)
|
--[[
add stealth detection via W
add peel for most AD teammate
]]--
if myHero.charName ~= "Warwick" then return end
local qrange = 400
local wrange = 1250
local rrange = 700
local smiterange = 760
local SmiteSlot = nil
local ts
local QREADY, WREADY, EREADY, RREADY = false, false, false, false
local BRKSlot, DFGSlot, HXGSlot, BWCSlot, TMTSlot, RAHSlot, RNDSlot, YGBSlot = nil, nil, nil, nil, nil, nil, nil, nil
local BRKREADY, DFGREADY, HXGREADY, BWCREADY, TMTREADY, RAHREADY, RNDREADY, YGBREADY = false, false, false, false, false, false, false, false
local QREADY, WREADY, EREADY, RREADY = false, false, false, false
--myHero:GetSpellData(_E).level == 1 then erange = 1500
function OnLoad()
PrintChat(">> Loaded Smitewick V3 by Silent Man.")
ww = scriptConfig("Smitewick", "IfYouReadThisBuyMeAPizza")
ww:addSubMenu("ComboSettings" , "comboConfig")
ww.comboConfig:addParam("combo", "Combo", SCRIPT_PARAM_ONKEYDOWN, false, 32)
ww.comboConfig:addParam("useQ", "Use Q in combo", SCRIPT_PARAM_ONOFF, true)
ww.comboConfig:addParam("useQ2", "Auto Harass with Q", SCRIPT_PARAM_ONOFF, true)
ww.comboConfig:addParam("useW", "Use W when ally near", SCRIPT_PARAM_ONOFF, false)
ww.comboConfig:addParam("useR", "Use R in combo", SCRIPT_PARAM_ONOFF, true)
ww.comboConfig:addParam("autoitem", "Auto use items", SCRIPT_PARAM_ONOFF, true)
ww:addSubMenu("SmiteSettings" , "smitesettings")
--ww.smitesettings:addParam("disablesmite", "Toggle Smite Players", SCRIPT_PARAM_ONKEYTOGGLE, true, GetKey("L"))
ww.smitesettings:addParam("smiteks", "Smite to Killsteal", SCRIPT_PARAM_ONOFF, true)
ww.smitesettings:addParam("smiteult", "Smite+Ult Combo", SCRIPT_PARAM_ONOFF, true)
ww:addSubMenu("UltSettings" , "ultsettings")
ww.ultsettings:addParam("ksR", "Ks with R", SCRIPT_PARAM_ONOFF, true)
ww.ultsettings:addParam("ccR", "Use R on CC'd", SCRIPT_PARAM_ONOFF, true)
--[[ww:addSubMenu("Draw Circles", "draw")
ww.draw:addParam("drawq", "Draw Q", SCRIPT_PARAM_ONOFF, true)
ww.draw:addParam("drawr", "Draw R", SCRIPT_PARAM_ONOFF, true)
ww.draw:addParam("drawsmite", "Draw Smite Range", SCRIPT_PARAM_ONOFF, false)]]--
ww:addSubMenu("Orbwalker Settings", "Orbwalking")
ww.smitesettings:permaShow("smiteult")
--ww:addParam("savelife", "Safe Life with Q", SCRIPT_PARAM_ONOFF, false)
ts = TargetSelector(TARGET_LOW_HP, 760, DAMAGE_PHYSICAL)
ts.name = "Warwick"
ww:addTS(ts)
if myHero:GetSpellData(SUMMONER_1).name:lower():find("smite") then SmiteSlot = SUMMONER_1
elseif myHero:GetSpellData(SUMMONER_2).name:lower():find("smite") then SmiteSlot = SUMMONER_2
else SmiteSlot = nil
end
DelayAction(CheckOrbwalk, 8)
end
function CheckOrbwalk()
if _G.Reborn_Loaded and not _G.Reborn_Initialised then
DelayAction(CheckOrbwalk, 1)
elseif _G.Reborn_Initialised then
sacused = true
ww.Orbwalking:addParam("info11","SAC Detected", SCRIPT_PARAM_INFO, "")
elseif _G.MMA_Loaded then
ww.Orbwalking:addParam("info11","MMA Detected", SCRIPT_PARAM_INFO, "")
mmaused = true
else
require "SxOrbWalk"
SxOrb:LoadToMenu(ww.Orbwalking, false)
sxorbused = true
SxOrb:RegisterAfterAttackCallback(MyAfterAttack)
DelayAction(function()
if SxOrb.Version < 2.3 then
Print("Your SxOrbWalk library is outdated, please get the latest version!")
end
end, 5)
end
end
function Checks()
QREADY = (myHero:CanUseSpell(_Q) == READY)
WREADY = (myHero:CanUseSpell(_W) == READY)
EREADY = (myHero:CanUseSpell(_E) == READY)
RREADY = (myHero:CanUseSpell(_R) == READY)
IGNITEREADY = (IGNITESlot ~= nil and myHero:CanUseSpell(IGNITESlot) == READY)
BRKSlot, DFGSlot, HXGSlot, BWCSlot, TMTSlot, RAHSlot, RNDSlot, YGBSlot = GetInventorySlotItem(3153), GetInventorySlotItem(3128), GetInventorySlotItem(3146), GetInventorySlotItem(3144), GetInventorySlotItem(3077), GetInventorySlotItem(3074), GetInventorySlotItem(3143), GetInventorySlotItem(3142)
QREADY = (myHero:CanUseSpell(_Q) == READY)
WREADY = (myHero:CanUseSpell(_W) == READY)
EREADY = (myHero:CanUseSpell(_E) == READY)
RREADY = (myHero:CanUseSpell(_R) == READY)
DFGREADY = (DFGSlot ~= nil and myHero:CanUseSpell(DFGSlot) == READY)
HXGREADY = (HXGSlot ~= nil and myHero:CanUseSpell(HXGSlot) == READY)
BWCREADY = (BWCSlot ~= nil and myHero:CanUseSpell(BWCSlot) == READY)
BRKREADY = (BRKSlot ~= nil and myHero:CanUseSpell(BRKSlot) == READY)
TMTREADY = (TMTSlot ~= nil and myHero:CanUseSpell(TMTSlot) == READY)
RAHREADY = (RAHSlot ~= nil and myHero:CanUseSpell(RAHSlot) == READY)
RNDREADY = (RNDSlot ~= nil and myHero:CanUseSpell(RNDSlot) == READY)
YGBREADY = (YGBSlot ~= nil and myHero:CanUseSpell(YGBSlot) == READY)
IREADY = (ignite ~= nil and myHero:CanUseSpell(ignite) == READY)
ts:update()
end
function OnTick()
Checks()
if ww.comboConfig.useQ2 then
QHarass()
end
if ww.comboConfig.combo then
Combo()
end
autoW()
if ww.ultsettings.ksR then
autoult()
end
if ww.ultsettings.ccR then
ccR()
end
if ww.smitesettings.smiteks then
SmiteKS()
end
end
--[[unction UseUlt()
local erange = GetERange()
if EREADY and GetDistance(ts.target) <= erange and not ts.target.visable then
CastSpell(_E)
function GetERange()
if myHero:GetSpellData(_E).level == 1 then
return 1500
elseif myHero:GetSpellData(_E).level == 2 then
return 2300
elseif myHero:GetSpellData(_E).level == 3 then
return 3100
elseif myHero:GetSpellData(_E).level == 4 then
return 3900
elseif myHero:GetSpellData(_E).level == 5 then
return 4700
end
end
end
end ]]--
function ccR()
if ValidTarget(ts.target, 700) and ww.ultsettings.ccR then
if RREADY and (ts.target.canMove == false) then
CastSpell(_R, ts.target)
end
end
end
function Combo()
if ww.comboConfig.useQ then
QHarass()
end
if ww.comboConfig.autoitem then
useitems()
end
if ww.smitesettings.smiteult then
smiteChamp()
end
if ww.comboConfig.useR then
Ult()
end
end
function Ult()
if ValidTarget(ts.target, 700) and ww.comboConfig.useR then
if RREADY then
CastSpell(_R, ts.target)
end
end
end
function autoW()
if ww.comboConfig.useW then
for k, ally in pairs(GetAllyHeroes()) do
if GetDistance(ally) <= 1250 then
CastSpell(_W)
end
end
end
end
function QHarass()
Checks()
if ValidTarget(ts.target, qrange) then
if QREADY then
CastSpell(_Q, ts.target)
end
end
end
function autoult()
if RREADY then
local rDmg = 0
for i = 1, heroManager.iCount, 1 do
local enemyhero = heroManager:getHero(i)
if ValidTarget(enemyhero, (rrange+50)) then
rDmg = getDmg("R", enemyhero, myHero)
if enemyhero.health <= rDmg then
CastSpell(_R, enemyhero)
end
end
end
end
end
function smiteChamp()
local smiteDmg = 0
if SmiteSlot ~= nil and myHero:CanUseSpell(SmiteSlot) == READY then
for i = 1, heroManager.iCount, 1 do
local target = heroManager:getHero(i)
if ValidTarget(target) then
smiteDmg = 15 + 3 * myHero.level
if target ~= nil and target.team ~= myHero.team and not target.dead and target.visible and GetDistance(target) < 760 then
CastSpell(SmiteSlot, target)
end
end
end
end
end
function SmiteKS()
if ww.smitesettings.smiteks then
local smiteDmg = 0
if SmiteSlot ~= nil and myHero:CanUseSpell(SmiteSlot) == READY then
for i = 1, heroManager.iCount, 1 do
local target = heroManager:getHero(i)
if ValidTarget(target) then
smiteDmg = 15 + 3 * myHero.level
if target ~= nil and target.team ~= myHero.team and not target.dead and target.visible and GetDistance(target) < 700 and target.health < smiteDmg then CastSpell(SmiteSlot, target)
end
end
end
end
end
end
function useitems()
if ts.target ~= nil and ww.comboConfig.autoitem then
--[[ Items ]]--
if GetDistance(ts.target) < 450 then
if DFGREADY then CastSpell(DFGSlot, ts.target) end
if HXGREADY then CastSpell(HXGSlot, ts.target) end
if BWCREADY then CastSpell(BWCSlot, ts.target) end
if BRKREADY then CastSpell(BRKSlot, ts.target) end
if YGBREADY then CastSpell(YGBSlot, ts.target) end
if TMTREADY and GetDistance(ts.target) < 275 then CastSpell(TMTSlot) end
if RAHREADY and GetDistance(ts.target) < 275 then CastSpell(RAHSlot) end
if RNDREADY and GetDistance(ts.target) < 275 then CastSpell(RNDSlot) end
end
end
end
function OnDraw()
Checks()
if myHero.dead then return end
if QREADY then DrawCircle(myHero.x, myHero.y, myHero.z, qrange, 0x19A712)
else DrawCircle(myHero.x, myHero.y, myHero.z, qrange, 0x992D3D)
end
if RREADY then DrawCircle(myHero.x, myHero.y, myHero.z, rrange, 0x19A712)
else DrawCircle(myHero.x, myHero.y, myHero.z, rrange, 0x992D3D)
end
if (myHero:CanUseSpell(SmiteSlot) == READY) then DrawCircle(myHero.x, myHero.y, myHero.z, smiterange, 0x19A712)
else DrawCircle(myHero.x, myHero.y, myHero.z, smiterange, 0x992D3D)
end
end
--[[
smite+bork+ultdmg
function doDraw(enemy)
local smiteDmg = 0
if SmiteSlot ~= nil and myHero:CanUseSpell(SmiteSlot) == READY then
smiteDmg = 15 + 3 * myHero.level
end
local BoRKDmg = 0
if BoRKREADY and ValidTarget(target) then
BoRKDmg = target.maxHealth*.10
end
--local bwcDmg = 100
totaldamage = BoRKDmg + smiteDmg
PrintFloatText(myHero, 0, "..BoRKDmg)
--PrintAlert(""..enemy.charName.." is killable",
end
end
]]--
--[[savelifewithQfunction]
function savelife()
if myhero.Health < blahblah and no enemy in qrange then
CastSpell(_Q, enemyminion)
end]]--
--[[
function ClosestAllyMostAD()
local attackdamage = 0
local closest = nil
for i=1, heroManager.iCount do
currentAlly = heroManager:GetHero(i)
if currentAlly.team == myHero.team and currentAlly.charName ~= myHero.charName then
if not currentAlly.dead and currentAlly.totalDamage >= attackdamage and myHero:GetDistance(currentAlly) <= rrange then
attackdamage = currentAlly.totalDamage
closest = currentAlly
end
end
end
return closest
end
function FindClosestEnemy(person)
local distance = 25000
local closest = nil
for i=1, heroManager.iCount do
currentEnemy = heroManager:GetHero(i)
if currentEnemy.team ~= myHero.team and not currentEnemy.dead and person:GetDistance(currentEnemy) < distance then
distance = person:GetDistance(currentEnemy)
closest = currentEnemy
end
end
return closest
end]]--
|
--[[
* Label : Module for hover module base functionality
* Author : DVD ( dvd_video )
* E-mail : dvd_video@abv.bg
* Date : 19-01-2017
* Location : lua/hovermodule/hovermodlib.lua
* Defines : A list of functions for initializing a hover module
]]--
local type = type
local next = next
local pcall = pcall
local print = print
local pairs = pairs
local unpack = unpack
local tobool = tobool
local tostring = tostring
local tonumber = tonumber
local CreateConVar = CreateConVar
local PrintTable = PrintTable
local Vector = Vector
local Angle = Angle
local Color = Color
local SysTime = SysTime
local IsValid = IsValid
local CompileString = CompileString
local CompileFile = CompileFile
local setmetatable = setmetatable
local getmetatable = getmetatable
local collectgarbage = collectgarbage
local LocalPlayer = LocalPlayer
local os = os
local ents = ents
local math = math
local file = file
local vgui = vgui
local table = table
local input = input
local numpad = numpad
local string = string
local language = language
local duplicator = duplicator
local FILL = FILL
local KEY_E = KEY_E
local CLIENT = CLIENT
local SERVER = SERVER
local KEY_LSHIFT = KEY_LSHIFT
local COLLISION_GROUP_NONE = COLLISION_GROUP_NONE
local RENDERMODE_TRANSALPHA = RENDERMODE_TRANSALPHA
local libOpVars = {}
module("hovermodlib")
function GetOpVar(anyKey)
return (anyKey and libOpVars[anyKey])
end
function IsNil(anyVal)
return (anyVal == nil)
end
function IsString(sVal)
return (getmetatable(sVal) == GetOpVar("TYPE_METASTRING"))
end
function IsEmptyTable(tData)
return IsNil(next(tData))
end
function IsEmptyString(sData)
return (sData == GetOpVar("STRING_ZERO"))
end
function IsNumber(sVal)
return (tonumber(sVal) and IsNil(getmetatable(sVal)))
end
function GetPick(bIf, vTru, vFls)
if(bIf) then return vTru else return vFls end
end
-- Function that calculates a sign
function GetSign(anyVal)
local nVal = (tonumber(anyVal) or 0)
return ((nVal > 0 and 1) or (nVal < 0 and -1) or 0) end
function GetDate()
return (os.date(GetOpVar("DATE_FORMAT"))
.." "..os.date(GetOpVar("TIME_FORMAT")))
end
function GetXY(xyPnt,nX,nY)
local xyOut = {x = tonumber(xyPnt and xyPnt.x or 0), y = tonumber(xyPnt and xyPnt.y or 0)}
xyOut.x, xyOut.y = (xyOut.x + (tonumber(nX) or 0)), (xyOut.y + (tonumber(nY) or 0))
return xyOut -- Get a new point without overwriting the old one
end
-- Golden retriever. Retrieves file line as string
-- But seriously returns the sting line and EOF flag
local function GetStringFile(pFile)
if(not pFile) then return StatusLog("", "GetStringFile: No file"), true end
local sCh, sLine = "X", "" -- Use a value to start cycle with
while(sCh) do sCh = pFile:Read(1); if(not sCh) then break end
if(sCh == "\n") then return sLine:Trim(), false else sLine = sLine..sCh end
end; return sLine:Trim(), true -- EOF has been reached. Return the last data
end
-- Project a vector without making a copy
function ProjectAngle(vVec, aAng)
local F, R, U = aAng:Forward(), aAng:Right(), aAng:Up()
local X, Y, Z = vVec:Dot(F), vVec:Dot(R), vVec:Dot(U)
vVec.x, vVec.y, vVec.z = X, Y, Z; return vVec
end
-- Create vector from a component list
function GetVectorString(sVec)
local symComp = GetOpVar("OPSYM_COMPONENT") -- Handle also [0,0,0]
local arVec = symComp:Explode(sVec:gsub("%[",""):gsub("%]",""))
return Vector(tonumber(arVec[1]) or 0,
tonumber(arVec[2]) or 0,
tonumber(arVec[3]) or 0)
end
-- Fixes a value to the nearest fraction
local function FixValue(nVal, nFrc)
local nVal = tonumber(nVal) or 0
local nFrc = tonumber(nFrc) or 0.01 -- Default the second digit
local q, f = math.modf(nVal / nFrc)
return nFrc * (q + (f > 0.5 and 1 or 0))
end
-- Converts vector to string with a given fraction
function GetStringVector(vVec, nFrc)
local symComp = GetOpVar("OPSYM_COMPONENT")
local x = FixValue(vVec.x, nFrc)
local y = FixValue(vVec.y, nFrc)
local z = FixValue(vVec.z, nFrc)
return tostring(x)..symComp..tostring(y)..symComp..tostring(z)
end
function LogStatus(anyMsg, ...)
local tSet = GetOpVar("LOG_SETTINGS")
if(tSet["ENAB"]:GetBool()) then
local tSkip, tOnly = tSet["SKIP"], tSet["ONLY"]
local fLog, sMsg = GetOpVar("DIRPATH_BASE"), tostring(anyMsg)
if(tSkip and tSkip[1]) then for id = 1, #tSkip do
if(sMsg:find(tostring(tSkip[id]))) then return ... end end end
if(tOnly and tOnly[1]) then for id = 1, #tOnly do
if(not sMsg:find(tostring(tOnly[id]))) then return ... end end end
if(tSet["LAST"] and tSet["LAST"] == sMsg) then return ... else tSet["LAST"] = sMsg end
local bFile, sLib = tSet["FILE"]:GetBool(), GetOpVar("LIBRARY_NAME")
local sLogo = GetPick(bFile, "", tostring(tSet.Info)..": ")
local sTime = "["..GetDate()..":"..("%f"):format(SysTime()).."] "
local sInst = (CLIENT and "CLIENT") or (SERVER and "SERVER") or "NOINST"
local sLogs = sInst.." > "..sTime..sLogo..sMsg
if(bFile) then file.Append(fLog..sLib.."_log.txt", sLogs.."\n")
else print(sLogs) end
end; return ...
end
function InitDataMapping()
local tMap = GetOpVar("MAPPING_ENTDATA")
local tGen = GetOpVar("MAPPING_GENERAL")
for key, rec in pairs(tMap) do
local var, id = tostring(rec[3] or ""), (tonumber(rec[5]) or 0)
local foo = ((type(rec[6]) == "function") and rec[6] or nil)
if(var and (type(var) == "string") and not IsEmptyString(var)) then tGen[var] = {key, id, foo}
if(id <= 0) then LogStatus("InitDataMapping: Invalid ID #"..id.." for <"..key.."/"..var..">") end
end
end -- All generals must be defined using the global hover unit data[item][3]
end
local function ckControlTar(tab)
local cn, mx, mt = #tab, table.getn(tab)
if(cn ~= mx) then
return LogStatus("ckControlTar: Array vacancies "..cn.." of "..mx, false) end
if(cn == 0) then return LogStatus("ckControlTar: Array empty", false) end
for id = 1, cn do if(type(tab[id]) ~= "string") then
return LogStatus("ckControlTar: Array value #"..tostring(tab[id]).." not string", false) end end
return true
end
local function ckControlTun(tab, dep)
local cn, mx, mt = #tab, table.getn(tab), getmetatable("string")
if(cn ~= mx) then
return LogStatus("ckControlTun: Array vacancies "..cn.." of "..mx, false) end
if(cn == 0) then return LogStatus("ckControlTun: Array empty", false) end
if(cn > 3) then return LogStatus("ckControlTun: Array too long #"..cn, false) end
for id = 1, cn do if(type(tab[id]) ~= "string") then
return LogStatus("ckControlTun: Array value #"..tostring(tab[id]).." not string", false) end end
return true
end
local function ckControlRef(tab, dep)
local cn, mx = #tab, table.getn(tab)
if(cn ~= mx) then
return LogStatus("ckControlRef: Array vacancies "..cn.." of "..mx, false) end
if(cn == 0) then return LogStatus("ckControlRef: Array empty", false) end
if(cn > 2) then return LogStatus("ckControlRef: Array too long", false) end
if(type(tab[1]) ~= "number") then return LogStatus("ckControlRef: Base value NaN", false) end
if(tab[2]) then
if(type(tab[2]) ~= "string") then
return LogStatus("ckControlRef: Wire input not string but {"..
type(tab[2]).."}<"..tostring(tab[2])..">", false) end
local wRef = GetOpVar("WIRE_REFERENCES").Name
for i = 1, #wRef do if(wRef[i] == tab[2]) then return true end
end; return LogStatus("ckControlRef: Wire input mismatch <"..tab[2]..">", false)
end; return true
end
local function ckVecOrigin(vec, dep) return true end
local function ckVecDirect(vec, dep)
if(vec:Length() == 0) then
return LogStatus("ckVecLength: Vector zero", false) end
return true
end
local function ckTargetTable(tab, dep)
for k, v in pairs(tab) do
if(type(k) ~= "string") then -- All classes are strings so this is OK
return LogStatus("ckTargetTable: Class not string but {"..type(k).."}<"..tostring(k)..">", false) end
if(type(v) ~= "boolean") then -- Did intentionally for troubleshooting target list converter
return LogStatus("ckTargetTable: Class state {"..type(v).."}<"..tostring(v)..">", false) end
if(not v) then LogStatus("ckTargetTable: Class disabled <"..k..">") end
end; return true
end
local function ckEmptyString(str)
if(IsEmptyString(str)) then
return LogStatus("ckEmptyString: Value empty", false) end; return true
end
function InitDependancies(vEnab, vFile)
libOpVars["STRING_ZERO" ] = ""
libOpVars["NUMBER_ZERO" ] = 10e-5
libOpVars["VECTOR_ZERO" ] = Vector()
libOpVars["ANGLE_ZERO" ] = Angle ()
-- More meaningful name to the one above used for labels
libOpVars["DATE_FORMAT" ] = "%d-%m-%y"
libOpVars["TIME_FORMAT" ] = "%H:%M:%S"
libOpVars["LOCALIFY_TABLE" ] = GetPick(CLIENT,{},nil)
libOpVars["TRANSLATE_KEYTAB"] = {[2]="nam",[4]="cat",[7]="tip"}
libOpVars["FILE_ENTITY" ] = "sent_"..GetOpVar("NAME_ENTITY") -- How is the entity controlled class called
-- Base directory for all the data written. Defines there the library data is stored
libOpVars["NAME_LIMIT" ] = GetOpVar("NAME_ENTITY").."s"
libOpVars["DIRPATH_BASE" ] = GetOpVar("NAME_TOOL").."/"
libOpVars["DIRPATH_SAVE" ] = GetOpVar("NAME_ENTITY").."/"
libOpVars["DIRPATH_PRESET" ] = "presets/"
libOpVars["DIRPATH_AUSAVE" ] = "autosave/"
libOpVars["FORM_LANGPATH" ] = "%s"..GetOpVar("NAME_ENTITY").."/lang/%s"
libOpVars["LOG_SETTINGS" ] = {
["SKIP"] = {}, ["ONLY"] = {}, ["LAST"] = "",
["INFO"] = GetOpVar("NAME_TOOL"):gsub("^%l", string.upper),
["ENAB"] = vEnab, -- Enable logging in general
["FILE"] = vFile -- Enable logging file
} -- Make a list with the log settings
libOpVars["CLASS_TARGETS" ] = {
["prop_physics"] = true,
["prop_dynamic"] = true,
["prop_static"] = true,
["prop_ragdoll"] = true
}
libOpVars["WIRE_REFERENCES" ] = {
Name = {"RefGap", "RefSide", "RefPitch", "RefYaw", "RefRoll"},
Type = {"NORMAL", "NORMAL" , "NORMAL" , "NORMAL", "NORMAL" },
Note = {"Refer gap spacing" ,
"Refer side symmetry",
"Refer pitch bias" ,
"Refer yaw turn" ,
"Refer roll lean" }
}
libOpVars["CLASS_REGUPHYS" ] = "prop_physics" -- Regular physics enabled prop
libOpVars["TYPE_DEFCOLUMN" ] = {} -- Columns that are enabled for processing
libOpVars["UNIT_DESCRIPTION"] = {__size = 0} -- The hover unit description
libOpVars["WIRE_PORTNAMES" ] = {} -- Wire ports validation status storage
libOpVars["TYPE_METASTRING" ] = getmetatable("") -- Store string meta-table
--[[
* This is used for data mapping
* [1] > Data type and return value of `type()`
* [2] > The value to be different from
* [3] > Console variable mapping name
* [4] > Validation function
* [5] > Export ID the smaller the first
* [6] > Function used to convert the string to the value needed
* Keys are stored in square brackets. If the key name
* is bordered with {} this means is must be applied on a
* list of such values
]]--
-- Legend for the mapping parameters
-- If the convar name is defined, the general type is used
libOpVars["MAPPING_GENERAL"] = {} -- Mapping Convar name to column name and ID
libOpVars["MAPPING_ENTDATA"] = {
["Name"] = {"string" , nil, "name" , nil, 1, tostring},
["Prop"] = {"string" , nil, "model" , ckEmptyString, 2, tostring},
["FwLoc"] = {"Vector" , nil, "fwloc" , ckVecDirect, 3, GetVectorString},
["UpLoc"] = {"Vector" , nil, "uploc" , ckVecDirect, 4, GetVectorString},
["CnLoc"] = {"Vector" , nil, "cnloc" , ckVecOrigin, 5, GetVectorString},
["Mass"] = {"number" , "+", "mass" , nil, 6 , tonumber},
["MasPrt"] = {"boolean", nil, "enmassp", nil, 7, tobool},
["Tick"] = {"number" , "+", "tick" , nil, 8 , tonumber},
["KeyOn"] = {"number" , "+", "keyon" , nil, 9 , tonumber},
["KeyF"] = {"number" , "+", "keyf" , nil, 10, tonumber},
["KeyR"] = {"number" , "+", "keyr" , nil, 11, tonumber},
["Target"] = {"string" , nil, "target" , nil, 12, tostring},
["NumFor"] = {"number" , nil, "numfor" , nil, 13, tonumber},
["NumTog"] = {"boolean", nil, "numtog" , nil, 14, tobool},
["FrcDep"] = {"number" , nil, "forcedp", nil, 15, tonumber},
["FrcDpC"] = {"boolean", nil, "encfdp" , nil, 16, tobool},
["{Control}"] = { -- List of control structures
["Tar"] = {"table" , nil, nil, ckControlTar},
["Tun"] = {"table" , nil, nil, ckControlTun},
["Ref"] = {"table" , nil, nil, ckControlRef},
["Prs"] = {"string" , nil, nil, ckEmptyString},
["Cmb"] = {"boolean" , nil},
["Neg"] = {"boolean" , nil},
["Dev"] = {"function", nil},
["ID"] = {"number" , nil}
},
["{Sensors}"] = { -- List of sensor structures
["Hit"] = {"table" , nil, nil, ckTargetTable},
["Org"] = {"Vector", nil, nil, ckVecOrigin},
["Dir"] = {"Vector", nil, nil, ckVecDirect},
["Len"] = {"number", "~0"}, -- Length
["ID"] = {"number", nil}, -- Export ID
["Val"] = {"number", nil} -- Where the sensor sample is stored
},
["{Forcers}"] = { -- List of forcer structures
["Org"] = {"Vector", nil, nil, ckVecOrigin},
["Dir"] = {"Vector", nil, nil, ckVecDirect},
["ID"] = {"number", nil}
}
}
end
--[[
* This defines the initialization columns.
* It tells the program which column name is valid
]]--
function InitColumnNames()
local tCol = GetOpVar("TYPE_DEFCOLUMN") -- Columns that are enabled for processing
tCol[GetOpVar("TYPE_GENERAL")] = {["Val"] = true}
tCol[GetOpVar("TYPE_FORCER") ] = {["Org"] = true, ["Dir"] = true}
tCol[GetOpVar("TYPE_SENSOR") ] = {["Len"] = true, ["Org"] = true ,
["Dir"] = true, ["Hit"] = true}
tCol[GetOpVar("TYPE_CONTROL")] = {["Ref"] = true, ["Tun"] = true ,
["Cmb"] = true, ["Neg"] = true ,
["Prs"] = true, ["Tar"] = true}
end
function LogTable(tT,sS,tP)
local vS, vT, vK, sS = type(sS), type(tT), "", tostring(sS or "Data")
if(vT ~= "table") then
return LogStatus("{"..vT.."}["..tostring(sS or "Data").."] = <"..tostring(tT)..">") end
if(IsEmptyTable(tT)) then
return LogStatus(sS.." = {}") end; LogStatus(sS.." = {}")
for k,v in pairs(tT) do
if(type(k) == "string") then vK = sS.."[\""..k.."\"]"
else sK = tostring(k)
if(tP and tP[k]) then sK = tostring(tP[k]) end
vK = sS.."["..sK.."]"
end
if(type(v) ~= "table") then
if(type(v) == "string") then LogStatus(vK.." = \""..v.."\"")
else sK = tostring(v)
if(tP and tP[v]) then sK = tostring(tP[v]) end
LogStatus(vK.." = "..sK)
end
else
if(v == tT) then LogStatus(vK.." = "..sS)
else LogTable(v,vK,tP) end
end
end
end
--[[
* This function defines a margin for when a number
* is in certain borders the process is considered a fail
]]--
local function DecodeMargin(vNum, sMar)
local nNum = (tonumber(vNum) or 0)
local sMar = tostring(sMar or "")
if(sMar == "~0") then return (nNum ~= 0)
elseif(sMar == "=0") then return (nNum == 0)
elseif(sMar == "0+") then return (nNum >= 0)
elseif(sMar == "0-") then return (nNum <= 0)
elseif(sMar == "+") then return (nNum > 0)
elseif(sMar == "-") then return (nNum < 0)
else LogStatus("DecodeMargin("..tostring(vNum)..","..sMar.."): Not supported") end
end
--[[
* ValidateTable: Validates a stricture based
* on the parameters given
* aName > Any name to identify the validation
* tData > The data to validate
* tPara > Validation parameters
* iStg > Initial recursion stage. Managed internally
]]--
function ValidateTable(aName, tData, tPara, oPly, iStg)
local suc, nam, stg = true, tostring(aName), ((tonumber(iStg) or 0)+1)
for key, val in pairs(tData) do -- Output success
local par, dep = tPara[key], nam.."["..key.."]"
if(suc and not par and tPara["{"..key.."}"]) then -- Process item list of the same type
local par = tPara["{"..key.."}"]
if(not par) then
return NotifyUser(oPly, "ValidateTable["..stg.."]: Hash item "..dep.." <"..type(val).."> fail", "ERROR", false) end
for ki, vi in pairs(val) do
local li = dep.."["..ki.."]"
if(not ValidateTable(li, vi, par, oPly, stg)) then
suc = NotifyUser(oPly, "ValidateTable["..stg.."]: Recursive item "
..dep.." <"..type(val).."> fail", "ERROR", false) end
end
elseif(suc and (type(par) ~= "table")) then -- It is not item list and parameters are invalid
return NotifyUser(oPly, "ValidateTable["..stg.."]: Parameter "..dep.." <"..type(par).."> fail", "ERROR", false)
elseif(suc and par[4] and type(par[4]) == "function") then -- Use the validation function for the value
if(type(val) ~= par[1]) then -- Not having the experted type
suc = NotifyUser(oPly, "ValidateTable["..stg.."]: Function type "
..dep.." is <"..type(val).."> expects <"..par[1]..">", "ERROR", false) end
suc = par[4](val, dep); if(not suc) then
NotifyUser(oPly, "Validated via function "..dep.." fail !", "ERROR") end
LogStatus("Validated via function "..dep.." "..(suc and "OK" or "fail"))
elseif(suc and type(val) == "table") then -- All the table parameters
if(not ValidateTable(dep, val, par, oPly, stg)) then
suc = NotifyUser(oPly, "ValidateTable["..stg.."]: Recursive type "..dep.." <"..type(val).."> fail", "ERROR", false) end
else -- Process all the generals
if(suc) then -- Make sure validating only successful records for faster recursion
if(type(val) ~= par[1]) then -- Not having the experted type
suc = NotifyUser(oPly, "ValidateTable["..stg.."]: Value type "..dep.." <"..type(val).."> fail", "ERROR", false) end
if(type(val) == "Vector") then
if(par[2] and not DecodeMargin(val:Length(), par[2])) then -- Vectors having zero length
suc = NotifyUser(oPly, "ValidateTable["..stg.."]: Vector length "..dep.." <"..type(val).."> fail", "ERROR", false) end
else
if(par[2] and not DecodeMargin(val, par[2])) then -- The value is defined as invalid
suc = NotifyUser(oPly, "ValidateTable["..stg.."]: Value "..dep.." <"..type(val).."> fail", "ERROR", false) end
end
end
end
end; return LogStatus("ValidateTable["..stg.."]: Validated > "..tostring(aName).." "..(suc and "OK" or "fail"), suc)
end
--[[
* WireMixSetPoint: This function mixes the names types and
* notes for the inputs given with the data provided by the
* library variable /WIRE_REFERENCES/
* tName > Wire inputs names list
* tType > Wire inputs types list
* tNote > Wire inputs notes list
]]--
function WireMixSetPoint(tName, tType, tNote)
local tPorts = GetOpVar("WIRE_REFERENCES")
local syItem = GetOpVar("OPSYM_ITEMSPLIT")
local syInde = GetOpVar("OPSYM_GENINDENT")
for ID = 1, #tName do
local nm = tostring(tName[ID] or ""):Trim()
local tp = tostring(tType[ID] or ""):Trim()
local nt = tostring(tNote[ID] or ""):Trim()
if(not IsEmptyString(nm) and not IsEmptyString(tp)) then
tName[ID], tType[ID] = nm, tp
if(not IsEmptyString(nt)) then tNote[ID] = (syInde..nt..syInde) else tNote[ID] = ""
LogStatus("WireMixSetPoint: Skip processing notes <"..nm..">") end
else return LogStatus("WireMixSetPoint: Failed processing output <"
..nm.."/"..tp.."/"..nt..">", false) end
end
for ID = 1, #tPorts.Name do
local nm = tostring(tPorts.Name[ID] or ""):Trim()
local tp = tostring(tPorts.Type[ID] or ""):Trim()
local nt = tostring(tPorts.Note[ID] or ""):Trim()
if(not IsEmptyString(nm) and not IsEmptyString(tp)) then
table.insert(tName, nm); table.insert(tType, tp)
if(not IsEmptyString(nt)) then table.insert(tNote, syInde..nt..syInde) else table.insert(tNote, "")
LogStatus("WireMixSetPoint: Skip adding notes <"..nm..">") end
else return LogStatus("WireMixSetPoint: Failed adding output <"
..nm.."/"..tp..">", false) end
end; return LogStatus("WireMixSetPoint: Done", true)
end
--[[
* NewConvarArray: Class long strings manager. Implements a convar array manager
* A long string can be stored in beams with a given length
* Names are stored using the convar name concatenated with the ID
* I may be long, but I'm sure that you're gonna beam me up Scotty
* sNam > The convar array base name
* nCnt > Defines the length of the array
* nLen > How many characters are gonna be stored in one cvar member
* sInf > Convar information as what is the object used for
* nFlg > Flags for the convars: http://wiki.garrysmod.com/page/Enums/FCVAR
]]--
function NewConvarArray(sNam, nCnt, nLen, sInf, nFlg)
local mNam, mInf = (tostring(sNam or ""):lower()), tostring(sInf or "")
local mCnt, mLen = (tonumber(nCnt) or 0), (tonumber(nLen) or 0)
if(IsEmptyString(mNam)) then return LogStatus("NewConvarArray: Name empty. "..mInf, nil) end
if(mCnt <= 0) then return LogStatus("NewConvarArray: Beam count invalid <"..mNam.."> #"..mCnt, nil) end
if(mLen <= 0) then return LogStatus("NewConvarArray: Bean length invalid <"..mNam..">"..mSiz, nil) end
local mTab = {}
if(nFlg ~= 0) then -- For custom behaviour
for id = 1, mCnt do mTab[id] = CreateConVar(mNam.."_"..id, "", nFlg, mInf) end
else -- This must behave like a client convar with user data enabled
for id = 1, mCnt do mTab[id] = CreateClientConVar(mNam.."_"..id, mVal, true, true, mInf) end
end
local self = {}
function self:GetValue(vD)
local sD, sO = tostring(vD or ""), ""
for id = 1, mCnt do sO = sO..sD..mTab[id]:GetString() end return sO
end
function self:GetName() return mNam end
function self:GetInfo() return mInf end
function self:GetCount() return mCnt end
function self:GetLength() return mLen end
function self:SetValue(sIn, vD)
local sI, cE = tostring(sIn or ""), nil
local sD, tE = tostring(vD or ""), nil
if(not IsEmptyString(sD)) then tE = sD:Explode(sI); cE = #tE else
tE = {}
local iS, iE = 1, mLen
local sS, id = sIn:sub(iS, iE), 1
while(sS and not IsEmptyString(sS)) do
tE[id] = sS;
iS, iE, id = (iS + mLen), (iE + mLen), (id + 1)
sS = sIn:sub(iS, iE)
end; cE = #tE
end
if(cE > mCnt) then return LogStatus("NewConvarArray: Array <"..mNam
.."> shorter ["..sD.."] {"..cE.." > "..mCnt.."} for <"..sI..">", nil) end
for id = 1, mCnt do
local sB = tE[id]
if(sB:len() > mLen) then
return LogStatus("NewConvarArray: Array ["..id.."] <"..mNam.."> shorter {"
..sB:len().." > "..mLen.."} for <"..sB..">", nil) end
mTab[id]:SetString(sB)
end
end; return self
end
--[[
* NewSensor: Class sensors manager. Implements a sensor attachment
* Ent > Entity the sensor is attached to
* Len > Length of the sensor
* Pos > Local position of the sensor
* Dir > Local direction of the sensor
]]--
local mtSensor = {}
mtSensor.__index = mtSensor
mtSensor.__tostring = function(oSen) return "["..mtSensor.__type.."]"..
" {E="..tostring(oSen:getEntity())..", L="..tostring(oSen:getLength())..
", O="..tostring(oSen:getOrigin())..", D="..tostring(oSen:getDirect()).."}" end
function NewSensor(sNam)
local mNam = tostring(sNam or "") -- Name used to identify the thing
if(IsEmptyString(mNam)) then return LogStatus("NewSensor: Name invalid", nil) end
local mOrg = Vector() -- Local position relative to mEnt
local mDir = Vector() -- Local direction relative to mEnt
local mLen, mEnt = 0 -- Length and base attachment entity
local mtTrC, mfTrace = {} -- The tracer function to be used
local self, mtTrO = {}, {} -- Define the member parameters
local mtTrI = { -- This table stores the trace input information
start = Vector(), -- Start position of the trace
endpos = Vector(), -- End position of the trace
mask = MASK_SOLID, -- Mask telling it what to hit ( currently solid )
output = mtTrO, -- Trace result for avoiding table creation in real time
filter = function(oEnt) -- Only valid props which are not the main entity or world or mtTrC
if(oEnt and oEnt:IsValid() and oEnt ~= mEnt and -- The trace is not attachment and is valid
(IsEmptyTable(mtTrC) or mtTrC[oEnt:GetClass()])) then return true end end }
setmetatable(self, mtSensor)
function self:getEntity() return mEnt end
function self:getLength() return mLen end
function self:getTrace() return mtTrI end
function self:isHit() return mtTrO.Hit end
function self:getFraction() return mtTrO.Fraction end
function self:Sample() mfTrace(mtTrI); return self end
function self:getOrigin() v = Vector(); v:Set(mOrg) return v end
function self:getDirect() v = Vector(); v:Set(mDir) return v end
function self:setTarget(sCls, bEn)
mtTrC[tostring(sCls or ""):Trim()] = tobool(bEn); return self end
function self:setTracer(fTrs)
mfTrace = fTrs; if(type(mfTrace) ~= "function") then
return LogStatus("NewSensor.setTracer: Tracer not function", nil) end; return self
end
function self:setEntity(oEnt) -- Load the base entity
if(not (oEnt and oEnt:IsValid())) then
return LogStatus("NewSensor.setEntity: Entity invalid <"..tostring(oEnt)..">", nil) end
mEnt = oEnt; return LogStatus("NewSensor.setEntity("..tostring(mEnt)..") OK", self)
end
function self:setOrigin(vOrg) -- Load the local origin
if(type(vOrg) ~= "Vector") then
return LogStatus("NewSensor.setOrigin: Origin "..type(vOrg).." invalid <"..tostring(vOrg)..">", nil) end
mOrg:Set(vOrg); return LogStatus("NewSensor.setOrigin("..tostring(mOrg)..") OK", self)
end
function self:setLength(nLen) -- Load the maximum length
local nLen = (tonumber(nLen) or 0); if(nLen <= 0) then
return LogStatus("NewSensor.setLength: Length invalid <"..tostring(nLen)..">", nil) end
mLen = nLen; mDir:Normalize(); mDir:Mul(mLen); return LogStatus("NewSensor.setLength("..tostring(mLen)..") OK", self)
end
function self:setDirect(vDir) -- Load the direction
if(type(vDir) ~= "Vector") then
return LogStatus("NewSensor.setDirect: Direct "..type(vDir).." invalid <"..tostring(vDir)..">", nil) end
if(not (mLen and mLen >= 0)) then
return LogStatus("NewSensor.setDirect: Length invalid <"..tostring(mLen)..">", nil) end
mDir:Set(vDir); mDir:Normalize(); mDir:Mul(mLen)
return LogStatus("NewSensor.setDirect("..tostring(mDir)..") OK", self)
end -- Uses custom ePos, eAng according to forward and up locals given
function self:Update(cPos, cAng) -- Updates the trace parameters and gets ready to sample
local oPos = GetPick(IsNil(cPos), mEnt:GetPos() , cPos) -- Custom center (pos)
local oAng = GetPick(IsNil(cAng), mEnt:GetAngles(), cAng) -- Custom angle (ucs)
local vstr, vend = mtTrI.start, mtTrI.endpos
vstr:Set(mOrg); vstr:Rotate(oAng); vstr:Add(oPos)
vend:Set(mDir); vend:Rotate(oAng); vend:Add(vstr); return self
end -- Executed in real-time. Performs a trace sensor update
function self:Dump() -- The same as the setup method
LogStatus("["..mtSensor.__type.."] Properties:")
LogStatus(" Name : "..tostring(mNam))
LogStatus(" Entity: "..tostring(mEnt))
LogStatus(" Origin: "..tostring(mOrg))
LogStatus(" Direct: "..tostring(mDir))
LogStatus(" Length: "..tostring(mLen))
return self
end
function self:Validate()
local oSta = self; if(mLen <= 0) then -- Start validation as valid status
oSta = LogStatus("NewSensor.Validate: Length invalid <"..tostring(mLen)..">", nil) end
if(mDir:Length() == 0) then -- Vector magnitude cannot be negative
oSta = LogStatus("NewSensor.Validate: Direct invalid <"..tostring(mDir)..">", nil) end
if(not (mEnt and mEnt:IsValid())) then
oSta = LogStatus("NewSensor.Validate: Entity invalid <"..tostring(mEnt)..">", nil) end
if(type(mtTrI) ~= "table") then
oSta = LogStatus("NewSensor.Validate: Trace input invalid <"..type(mtTrI)..">", nil) end
if(type(mtTrO) ~= "table") then
oSta = LogStatus("NewSensor.Validate: Trace out invalid <"..type(mtTrO)..">", nil) end
if(type(mfTrace) ~= "function") then
oSta = LogStatus("NewSensor.Validate: Tracer invalid <"..type(mfTrace)..">", nil) end
if(not oSta) then self:Dump() end -- Try to validate the object return it validated
return LogStatus("NewSensor.Validate: Sensor <"..mNam.."> "..(oSta and "OK" or "fail"), oSta)
end; return LogStatus("NewSensor: Create ["..mNam.."]", self) -- The sensor object
end
--[[
* NewForcer: Class forcer manager. Implements a forcer attachment
* Ent > Entity the forcer is attached to
* Pos > Local position of the forcer
* Dir > Local direction of the forcer
]]--
local mtForcer = {}
mtForcer.__index = mtForcer
mtForcer.__tostring = function(oSen) return "["..mtForcer.__type.."]"..
" {E="..tostring(oSen:getEntity())..", O="..tostring(oSen:getOrigin())..", D="..tostring(oSen:getDirect()).."}" end
function NewForcer(sNam)
local mNam = tostring(sNam or "") -- Name used to identify the thing
if(IsEmptyString(mNam)) then return LogStatus("NewForcer: Name invalid", nil) end
local mOrg = Vector() -- Local position of the forcer
local mDir = Vector() -- Local direction of the force applied
local fOrg = Vector() -- Force world-space origin position relative to custom center
local fDir = Vector() -- Force world-space direction vector of the force applied
local self, mEnt, mPhy = {} -- Define the member parameters and the local physics
setmetatable(self, mtForcer)
function self:getEntity() return mEnt end
function self:getPhysics() return mPhy end
function self:getOrigin() v = Vector(); v:Set(mOrg) return v end
function self:getDirect() v = Vector(); v:Set(mDir) return v end
function self:setEntity(oEnt) -- Load the base entity
if(not (oEnt and oEnt:IsValid())) then
return LogStatus("NewForcer.setEntity: Entity invalid <"..tostring(oEnt)..">", nil) end
mEnt, mPhy = oEnt, oEnt:GetPhysicsObject()
if(not (mPhy and mPhy:IsValid())) then
return LogStatus("NewForcer.setEntity: Physics invalid <"..tostring(oEnt)..">", nil) end
return LogStatus("NewForcer.setEntity("..tostring(mEnt)..") OK", self)
end
function self:setOrigin(vOrg) -- Load the local origin
if(type(vOrg) ~= "Vector") then
return LogStatus("NewForcer.setOrigin: Origin "..type(vOrg).." invalid <"..tostring(vOrg)..">", nil) end
mOrg:Set(vOrg); return LogStatus("NewForcer.setOrigin("..tostring(mOrg)..") OK", self)
end
function self:setDirect(vDir) -- Load the direction
if(type(vDir) ~= "Vector") then
return LogStatus("NewForcer.setDirect: Direct "..type(vDir).." invalid <"..tostring(vDir)..">", nil) end
mDir:Set(vDir); mDir:Normalize(); return LogStatus("NewForcer.setDirect("..tostring(mDir)..") OK", self)
end -- Uses custom ePos, eAng according to forward and up locals given
function self:Update(cPos, cAng) -- Updates the trace parameters and gets ready to sample
local oPos = GetPick(IsNil(cPos), mEnt:GetPos() , cPos) -- Custom center (pos)
local oAng = GetPick(IsNil(cAng), mEnt:GetAngles(), cAng) -- Custom angle (ucs)
fOrg:Set(mOrg); fOrg:Rotate(oAng); fOrg:Add(oPos)
fDir:Set(mDir); fDir:Rotate(oAng); return self
end -- Executed in real-time. Performs position and direction update
function self:Force(nAmt) fDir:Mul(tonumber(nAmt) or 0)
mPhy:ApplyForceOffset(fDir, fOrg); return self
end -- This method applies the offset force after update is performed on the forcer
function self:Dump() -- The same as the setup method
LogStatus("["..mtForcer.__type.."] Properties:")
LogStatus(" Name : "..tostring(mNam))
LogStatus(" Entity: "..tostring(mEnt))
LogStatus(" Origin: "..tostring(mOrg))
LogStatus(" Direct: "..tostring(mDir))
return self
end
function self:Validate()
local oSta = self
if(not (mEnt and mEnt:IsValid())) then
oSta = LogStatus("NewForcer.Validate: Entity invalid <"..tostring(mEnt)..">", nil) end
if(not (mPhy and mPhy:IsValid())) then
oSta = LogStatus("NewForcer.Validate: Physics invalid <"..tostring(mEnt)..">", nil) end
if(mDir:Length() == 0) then -- Vector magnitude cannot be negative
oSta = LogStatus("NewForcer.Validate: Direct invalid <"..tostring(mDir)..">", nil) end
if(not oSta) then self:Dump() end -- Try to validate the object return it validated
return LogStatus("NewForcer.Validate: Forcer <"..mNam.."> "..(oSta and "OK" or "fail"), oSta)
end; return LogStatus("NewForcer: Create ["..mNam.."]", self) -- The forcer object
end
--[[
* NewControl: Class hovering state processing manager. Implements a controller unit
* nTo > Controller sampling time in seconds
* sName > Controller hash name differentiation
]]--
local mtControl = {}
mtControl.__index = mtControl
mtControl.__tostring = function(oCon)
return oCon:getType().."["..mtControl.__type.."] ["..tostring(oCon:getPeriod()).."]"..
"{T="..oCon:getTune()..",W="..oCon:getWindup()..",P="..oCon:getPower().."}"
end
function NewControl(nTo, sName)
local mTo = (tonumber(nTo) or 0); if(mTo <= 0) then -- Sampling time [s]
return LogStatus("NewControl: Sampling time <"..tostring(nTo).."> invalid",nil) end
local self = {} -- Place to store the methods
local mfAbs = math.abs -- Function used for error absolute
local mfSgn = GetSign -- Function used for error sign
local mErrO, mErrN = 0, 0 -- Error state values
local mvCon, meInt = 0, true -- Control value and integral enabled
local mvP, mvI, mvD = 0, 0, 0 -- Term values
local mkP, mkI, mkD = 0, 0, 0 -- P, I and D term gains
local mpP, mpI, mpD = 1, 1, 1 -- Raise the error to power of that much
local mbCmb, mbInv, mbOn, mSatD, mSatU = true, false, true -- Saturation limits and settings
local mName, mType, mTune, mWind, mPow = tostring(sName or "N/A"), "", "", "", ""
setmetatable(self, mtControl) -- Save the settings internally
function self:getValue(kV,eV,pV) return (kV*mfSgn(eV)*mfAbs(eV)^pV) end
function self:getGains() return mkP, mkI, mkD end
function self:setEnInt(bSt) meInt = tobool(bSt); return self end
function self:getEnInt() return meInt end
function self:getError() return mErrO, mErrN end
function self:getControl() return mvCon end
function self:getTune() return mTune end
function self:getWindup() return mWind end
function self:getPower() return mPow end
function self:getType() return mType end
function self:getPeriod() return mTo end
function self:setTune(sTune)
local symComp = GetOpVar("OPSYM_COMPONENT")
local sTune = tostring(sTune or ""):Trim()
local arTune = symComp:Explode(sTune)
if(arTune[1] and (tonumber(arTune[1] or 0) > 0)) then
mkP = (tonumber(arTune[1] or 0)) -- Proportional term
else return LogStatus("NewControl.setTune: P-gain <"..tostring(arTune[1]).."> invalid",nil) end
if(arTune[2] and (tonumber(arTune[2] or 0) > 0)) then
mkI = (mTo / (2 * (tonumber(arTune[2] or 0)))) -- Discrete integral term approximation
if(mbCmb) then mkI = mkI * mkP end
else LogStatus("NewControl.setTune: I-gain <"..tostring(arTune[2]).."> skip") end
if(arTune[3] and (tonumber(arTune[3] or 0) > 0)) then
mkD = (tonumber(arTune[3] or 0) * mTo) -- Discrete derivative term approximation
if(mbCmb) then mkD = mkD * mkP end
else LogStatus("NewControl.setTune: D-gain <"..tostring(arTune[3]).."> skip") end
mType = ((mkP > 0) and "P" or "")..((mkI > 0) and "I" or "")..((mkD > 0) and "D" or "")
-- Init multiple states using the table, so on duplication can be created easily
mTune = tostring(sTune or ""); return LogStatus("NewControl.setTune: <"..tostring(sTune or "")..">", self)
end
function self:setWindup(sWind)
local symComp = GetOpVar("OPSYM_COMPONENT")
local sWind = tostring(sWind or ""):Trim()
local arSat = symComp:Explode(sWind)
if(arSat and tonumber(arSat[1]) and tonumber(arSat[2])) then
arSat[1], arSat[2] = tonumber(arSat[1]), tonumber(arSat[2]) -- Saturation windup
if(arSat[1] < arSat[2]) then
mSatD, mSatU = arSat[1], arSat[2]
LogStatus("NewControl.setWindup: Bounds {"..tostring(mSatD).."<"..tostring(mSatU).."} load")
else LogStatus("NewControl.setWindup: Bounds {"..tostring(arSat[1]).."<"..tostring(arSat[2]).."} skip") end
else LogStatus("NewControl.setWindup: Windup <"..tostring(sWind or "").."> skip") end
mWind = tostring(sWind or ""); return LogStatus("NewControl.setWindup: OK", self)
end
function self:setPower(sPow)
local symComp = GetOpVar("OPSYM_COMPONENT")
local sPow = tostring(sPow or ""):Trim()
local arPow = symComp:Explode(sPow) -- Power ignored when missing
if(arPow and tonumber(arPow[1]) and tonumber(arPow[2]) and tonumber(arPow[3])) then
mpP = (tonumber(arPow[1]) or 1) -- Proportional power
mpI = (tonumber(arPow[2]) or 1) -- Integral power
mpD = (tonumber(arPow[3]) or 1) -- Derivative power
LogStatus("NewControl.setPower: Power <"..tostring(mpP)..symComp..tostring(mpI)..symComp..tostring(mpD).."> load")
else LogStatus("NewControl.setPower: Power <"..tostring(sPow or "").."> skip") end
mPow = tostring(sPow or ""); return LogStatus("NewControl.setPower: OK", self)
end
function self:setFlags(bCmb, bInv)
mbCmb, mbInv = tobool(bCmb), tobool(bInv)
return LogStatus("NewControl.setFlags: OK", self) end
function self:Toggle(bOn) -- Executed in realtime
mbOn = tobool(bOn); return self end
function self:Reset() -- Executed in realtime
mErrO, mErrN, mvP, mvI, mvD, mvCon, meInt = 0, 0, 0, 0, 0, 0, true; return self end
function self:Process(vRef,vOut) -- Executed in realtime
if(not mbOn) then return self:Reset() end
mErrO = mErrN -- Refresh error state sample
mErrN = (mbInv and (vOut-vRef) or (vRef-vOut))
if(mkP > 0) then -- P-Term
mvP = self:getValue(mkP, mErrN, mpP) end
if((mkI > 0) and (mErrN ~= 0) and meInt) then -- I-Term
mvI = self:getValue(mkI, mErrN + mErrO, mpI) + mvI end
if((mkD > 0) and (mErrN ~= mErrO)) then -- D-Term
mvD = self:getValue(mkD, mErrN - mErrO, mpD) end
mvCon = mvP + mvI + mvD -- Calculate the control signal
if(mSatD and mSatU) then -- Apply anti-windup effect
if (mvCon < mSatD) then mvCon, meInt = mSatD, false
elseif(mvCon > mSatU) then mvCon, meInt = mSatU, false
else meInt = true end
end; return self
end
function self:Dump()
local sLabel = GetPick(not IsEmptyString(mType), mType.."-", mType)
LogStatus("["..sLabel..mtControl.__type.."] Properties:")
LogStatus(" Name : "..mName.." ["..tostring(mTo).."]s")
LogStatus(" Param: {"..mTune.."}")
LogStatus(" Gains: {P="..tostring(mkP)..", I="..tostring(mkI)..", D="..tostring(mkD).."}")
LogStatus(" Power: {P="..tostring(mpP)..", I="..tostring(mpI)..", D="..tostring(mpD).."}\n")
LogStatus(" Limit: {D="..tostring(mSatD)..",U="..tostring(mSatU).."}")
LogStatus(" Error: {"..tostring(mErrO)..", "..tostring(mErrN).."}")
LogStatus(" Value: ["..tostring(mvCon).."] {P="..tostring(mvP)..", I="..tostring(mvI)..", D="..tostring(mvD).."}")
return self -- The dump method
end; return LogStatus("NewControl: Create ["..mName.."]", self) -- The control object
end
-- Checks if the record has a sensor object
function IsSensorRec(oRec)
if(tonumber(oRec)) then return false end
if(not (oRec and oRec.Obj)) then return false end
return (getmetatable(oRec.Obj) == mtSensor)
end
-- Checks if the record has a sensor object
function IsForcerRec(oRec)
if(tonumber(oRec)) then return false end
if(not (oRec and oRec.Obj)) then return false end
return (getmetatable(oRec.Obj) == mtForcer)
end
-- Checks if the record has a control object
function IsControlRec(oRec)
if(tonumber(oRec)) then return false end
if(not (oRec and oRec.Obj)) then return false end
return (getmetatable(oRec.Obj) == mtControl)
end
--[[
* Is the type enabled for an object
* sTyp > Either general, sensor, forcer or control hash
]]--
function IsType(sTyp)
local tCol = GetOpVar("TYPE_DEFCOLUMN")
return ((tCol and sTyp) and tCol[sTyp])
end
--[[
* Is the column name enabled for an object
* sTyp > Either general, sensor, forcer or control hash
* sCol > The name of the column to be checked
]]--
function IsHash(sTyp, sCol)
local tTyp = IsType(sTyp)
return ((tTyp and sCol) and tTyp[sCol])
end
function GetDescriptionID(vID)
local tDes = GetOpVar("UNIT_DESCRIPTION")
local nID = (tonumber(vID) or 0)
return (tDes and tDes[nID] or nil)
end
function GetDescriptionSize()
local tDes = GetOpVar("UNIT_DESCRIPTION")
return (tDes and tDes.__size or 0)
end
function SetDescription(tData)
local tDes = GetOpVar("UNIT_DESCRIPTION")
local nSiz, nTot = tDes.__size, #tDes; if(nSiz ~= nTot) then
return LogStatus("SetDescription: Stack mismatch <"..nSiz.."#"..nTot..">", false) end
nSiz = nSiz + 1; tDes[nSiz] = tData; tDes.__size = nSiz
return LogStatus("SetDescription: ["..nSiz.."]<"..tostring(tData.Name or "")..">"..tostring(tData.Prop or ""), false)
end
function InitConstants()
libOpVars["LIBRARY_NAME" ] = "hovermodlib" -- Name of the library
libOpVars["LIBRARY_VERSION" ] = "1.0" -- General version of the whole thing
libOpVars["GOLDEN_RATIO" ] = 1.61803398875 -- Golden ration for panel resolution be more appealing
libOpVars["OPSYM_GENINDENT" ] = " " -- What symbol is used for indent spacing readability
libOpVars["OPSYM_ITEMSPLIT" ] = "/" -- Primary delimiter to split multiple string items by
libOpVars["OPSYM_COMPONENT" ] = "," -- Secondary delimiter to split individual item components
libOpVars["OPSYM_INITSTRING"] = "@" -- Trigger symbol for string source initialization ( including general settings )
libOpVars["OPSYM_INITFILE" ] = "$" -- Trigger symbol for file source initialization ( including general settings )
libOpVars["OPSYM_COMMENT" ] = "#" -- Trigger symbol for file source initialization ( including general settings )
libOpVars["NAME_ENTITY" ] = "hovermodule" -- The entity name used for limits and stuff
libOpVars["NAME_TOOL" ] = "hovermoduletool" -- The tool mode which operates the entity
libOpVars["TYPE_GENERAL" ] = "general" -- General storage type for hover unit properties
libOpVars["TYPE_SENSOR" ] = "sensor" -- The internal sensor type as string
mtSensor.__type = GetOpVar("TYPE_SENSOR") -- Define local type for usage inside OOP sensors
libOpVars["TYPE_FORCER" ] = "forcer" -- The internal forcer type as string
mtForcer.__type = GetOpVar("TYPE_FORCER") -- Define local type for usage inside OOP forcers
libOpVars["TYPE_CONTROL" ] = "control" -- The internal control type as string
mtControl.__type = GetOpVar("TYPE_CONTROL") -- Define local type for usage inside OOP control
libOpVars["HASH_ENTITY" ] = "HoverDataMD" -- Where in the entity the data is stored
libOpVars["LOCALIFY_AUTO" ] = "en" -- Default translation if a phrase is now found
libOpVars["MISS_NOID" ] = "N" -- No ID selected
libOpVars["MISS_NOAV" ] = "N/A" -- Not Available
libOpVars["MISS_NOMD" ] = "X" -- No model
libOpVars["MISS_NOTR" ] = "Oops, missing ?" -- No translation found
end
--[[
* Compiles a user-defined state deviation from a string
* sErr > The error deviation given as a sensor hash formula
* sCon > The state name that its error will be defined this way
* stSen > The sensor structure used to compile the error function
]]--
function GetDeviation(sErr, sCon, stSen)
local sCo = tostring(sCon):rep(1):Trim() -- Copy a temporary error selection
local sDv = tostring(sErr):rep(1):Trim()
for key, sen in pairs(stSen) do
if(type(sen) == "table" and IsString(key)) then
sDv = sDv:gsub(key, "oSens[\""..tostring(key).."\"].Val") end end
local sFc = "return (function(oSens) "..sDv.." end)"
local suc1, out1 = pcall(CompileString, sFc, GetOpVar("FILE_ENTITY").."_"..sCo); if(not suc1) then
return LogStatus("GetDeviation("..sCo.."): Failed primary <"..sFc.."> @"..tostring(out1), nil) end
local suc2, out2 = pcall(out1); if(not suc2) then
return LogStatus("GetDeviation("..sCo.."): Failed secondary <"..sFc.."> @"..tostring(out2), nil) end
return LogStatus("GetDeviation("..sCo.."): <"..sFc..">", out2)
end
--[[
* Updates the target hit list with additional classes if the file is provided
* Automatically loads <library_name>_hit.txt into the class target list
* bRep > Whenever to replace the internal class targets with the file or not
]]--
function InitTargetsHit(bRep)
local tTrgs, lbNam = GetOpVar("CLASS_TARGETS"), GetOpVar("LIBRARY_NAME")
local fName = GetOpVar("DIRPATH_BASE")..lbNam.."_hit.txt"
local S = file.Open(fName, "rb", "DATA")
if(S) then local isEOF, sLine = false, ""
if(bRep) then for key, _ in pairs(tTrgs) do tTrgs[key] = nil end end
while(not isEOF) do sLine, isEOF = GetStringFile(S)
if(not IsEmptyString(sLine)) then tTrgs[sLine] = true end end
S:Close(); return LogStatus("InitTargetsHit: OK <"..fName..">", true)
else return LogStatus("InitTargetsHit: Missing <"..fName..">", true) end
end
--[[
* Tells the library which log outputs must be skipped
* Automatically loads <library_name>(_slskip/_slonly).txt into the log skip settings
* bRep > Whenever to replace the internal class targets with the file or not
]]--
function SettingsLogs(sHash)
local sKey = tostring(sHash or ""):upper():Trim()
if(not (sKey == "SKIP" or sKey == "ONLY")) then
return LogStatus("SettingsLogs("..sKey.."): Invalid hash", false) end
local tLogs, lbNam = GetOpVar("LOG_SETTINGS")[sKey], GetOpVar("LIBRARY_NAME")
if(not tLogs) then return LogStatus("SettingsLogs("..sKey.."): Skip table", true) end
local fName = GetOpVar("DIRPATH_BASE")..lbNam.."_sl"..sKey:lower()..".txt"
local S = file.Open(fName, "rb", "DATA"); table.Empty(tLogs)
if(S) then local sLine, isEOF = "", false
while(not isEOF) do sLine, isEOF = GetStringFile(S)
if(not IsEmptyString(sLine)) then table.insert(tLogs, sLine) end
end; S:Close(); return LogStatus("SettingsLogs("..sKey.."): Success <"..fName..">", true)
else return LogStatus("SettingsLogs("..sKey.."): Missing <"..fName..">", true) end
end
--[[
* ConvertTraceTargets: Prepares a list of targets for a wet job
* Retrieves the table hash hit list and hires the hit-man :D
* You must be very careful when using this function as SO can get hurt !
* But seriously: Converts "prop/ test " to {["prop"] = true, ["test"] = true}
* If no arguments are provided or an empty string, uses CLASS_TARGETS
* sCls > The string to convert to a hash format
* tHit > Hit targets table to use if provided
* bHit > Whenever or not to use the global hit targets
]]--
function ConvertTraceTargets(sCls, bHit, tHit)
local sCls = tostring(sCls or "")
local tArg = GetPick(type(tHit)=="table",tHit,GetOpVar("CLASS_TARGETS"))
local tSrc = GetPick(bHit,tArg,{})
if(not IsEmptyString(sCls)) then
tSrc = GetOpVar("OPSYM_ITEMSPLIT"):Explode(tostring(sCls))
for ID = 1, #tSrc do -- Kill targets sequentially in order
tSrc[tSrc[ID]:Trim()] = true; tSrc[ID] = nil end
end -- Hire the hit-man to do the wet job
local tHit = {} -- How many targets are there
for key, val in pairs(tSrc) do tHit[key] = tSrc[key] end
return tHit -- Report to the agency
end
--[[
* Transforms a setup line to initialization table
* sLine > The line to transform
* tBase > Base table to store the stuff
* tSeq > A place where the sequential type ID is stored
]]--
function TransformSettings(sLine, tBase, tSeq) -- Mecha henshin !
local sBase, cnt, tab, typ, key = sLine:Trim(), 1, 0
if(sBase:sub(1,1) == GetOpVar("OPSYM_COMMENT")) then return true end
for v in sBase:gmatch("{(.-)}") do -- All the items in curly brackets
local exp = (":"):Explode(v) -- Explode on : to get key-value pairs
local fld = tostring(exp[1] or ""):Trim(); if(IsEmptyString(fld)) then
return LogStatus("TransformSettings: Key missing <["..tostring(cnt).."],"..sBase..">", false) end
local val = tostring(exp[2] or ""):Trim(); if(IsEmptyString(val)) then
return LogStatus("TransformSettings: Value missing <["..tostring(cnt).."]["..fld.."],"..sBase..">", false) end
if(cnt == 1) then
typ, key = fld, val; if(not IsType(typ)) then
return LogStatus("TransformSettings: Type ["..tostring(cnt).."] <"..fld.."> missing", false) end
if(not tBase[typ]) then tBase[typ] = {} end
if(not tSeq[typ]) then tSeq[typ] = 0 end; tSeq[typ] = tSeq[typ] + 1
tBase[typ][key] = {}; tab = tBase[typ][key]; tab["ID"] = tSeq[typ]
else -- Register the data in the column provided
if(IsHash(typ, fld)) then tab[fld] = val:Trim()
else LogStatus("TransformSettings: Column <"..fld.."> ["..typ.."]"..key.." skipped") end
end; cnt = cnt + 1
end; return true
end
--[[
* Does a post-processing of an initialization parametrization
* tSet > A value set table to be processed
* tgHit > If the hit list is not available for the sensor use the global one
* bgHit > Flag for using the global table or not
]]--
function PostProcessInit(oPly, tSet, tgHit, bgHit)
if(CLIENT) then
return LogStatus("PostProcessInit: Working on client", false) end
if(not (tSet and type(tSet) == "table")) then
return LogStatus("PostProcessInit: Set missing", false) end
local syItem = GetOpVar("OPSYM_ITEMSPLIT")
local tSen = tSet[GetOpVar("TYPE_SENSOR")]
tSen = ((type(tSen) == "table") and (next(tSen) and tSen or nil) or nil)
local tFrc = tSet[GetOpVar("TYPE_FORCER")]
tFrc = ((type(tFrc) == "table") and (next(tFrc) and tFrc or nil) or nil)
local tCon = tSet[GetOpVar("TYPE_CONTROL")]
tCon = ((type(tCon) == "table") and (next(tCon) and tCon or nil) or nil)
if(tSen) then
for key, rec in pairs(tSen) do -- Process sensors
if(not tonumber(rec)) then
rec["ID"] = (tonumber(rec["ID"]) or 0); if(rec["ID"] < 1) then
return LogStatus("PostProcessInit: Sensor <"..key.."> invalid ID", false) end
rec["Len"] = (tonumber(rec["Len"]) or 0)
if(not (rec["Len"] and math.abs(rec["Len"]) ~= 0)) then
return LogStatus("PostProcessInit: Sensor <"..key.."> invalid length", false) end
rec["Org"], rec["Val"] = GetVectorString(rec["Org"]), 0
rec["Dir"] = GetVectorString(rec["Dir"])
if(rec["Dir"] and rec["Dir"]:Length() == 0) then
return NotifyUser(oPly, "PostProcessInit: Sensor <"..key.."> invalid direct", "ERROR", false) end
rec["Hit"] = ConvertTraceTargets(rec["Hit"],bgHit,tgHit)
end
end
else LogStatus("PostProcessInit: Sensors skip") end
if(tFrc) then
for key, rec in pairs(tFrc) do -- Process forcers
if(not tonumber(rec)) then
rec["ID"] = (tonumber(rec["ID"]) or 0); if(rec["ID"] < 1) then
return LogStatus("PostProcessInit: Forcer <"..key.."> invalid ID", false) end
rec["Dir"] = GetVectorString(rec["Dir"])
if(rec["Dir"] and rec["Dir"]:Length() == 0) then
return NotifyUser(oPly, "PostProcessInit: Forcer <"..key.."> invalid direct", "ERROR", false) end
rec["Org"] = GetVectorString(rec["Org"])
end
end
else LogStatus("PostProcessInit: Forcers skip")end
if(tSen and tFrc and tCon) then
for key, rec in pairs(tCon) do -- Process controllers
if(not tonumber(rec)) then
rec["Tun"] = syItem:Explode(rec["Tun"])
for k, v in pairs(rec["Tun"]) do rec["Tun"][k] = tostring(v or ""):Trim() end
rec["Cmb"], rec["Neg"] = tobool(rec["Cmb"]), tobool(rec["Neg"])
rec["ID"] = (tonumber(rec["ID"]) or 0); if(rec["ID"] < 1) then
return LogStatus("PostProcessInit: Controller <"..key.."> invalid ID", false) end
rec["Ref"] = syItem:Explode(rec["Ref"])
rec["Ref"][1] = tonumber((rec["Ref"][1]):Trim()) or 0
rec["Ref"][2] = tostring(rec["Ref"][2] or ""):Trim()
rec["Ref"][2] = GetPick(not IsEmptyString(rec["Ref"][2]),rec["Ref"][2],nil)
rec["Dev"] = GetDeviation(rec["Prs"], key, tSen) -- Define the deviation function for the error
rec["Tar"] = syItem:Explode(tostring(rec["Tar"])) -- Forcer mapping for every control
for k, v in pairs(rec["Tar"]) do rec["Tar"][k] = tostring(v or ""):Trim() end
end
end
else return LogStatus("PostProcessInit: Control missing", false) end
return LogStatus("PostProcessInit: OK", true)
end
--[[
* Creates an initialization structure from three sources
* srSet > A source set to be used either $file or @string
* sgHit > A trace targets list string to be used if a sensor has none
* bgHit > Whenever to use the global hit list or not
]]--
function InitializeUnitSource(oPly, srSet, sgHit, bgHit)
local sHit = tostring(sgHit or ""):Trim()
local sSet, tSet = tostring(srSet or ""):Trim(), {}
local tHit, sMod = ConvertTraceTargets(sHit,bgHit), sSet:sub(1,1)
local mdFil, mdStr = GetOpVar("OPSYM_INITFILE"), GetOpVar("OPSYM_INITSTRING")
if(sMod == mdFil) then -- Use a file
local sNm = sSet:sub(2,-1); if(IsEmptyString(sNm)) then
return LogStatus("InitializeUnitSource(F): File name empty",nil) end
if(not sNm:find(".txt", 1, true)) then sNm = sNm..".txt" end
if(not file.Exists(sNm, "DATA")) then
return LogStatus("InitializeUnitSource(F): File missing: "..sNm,nil) end
local ioF = file.Open(sNm, "rb", "DATA"); if(not ioF) then
return LogStatus("InitializeUnitSource(F): File failed <"..tostring(sNm)..">",nil) end
local ln, eof, seq = "", false, {}
while(not eof) do ln, eof = GetStringFile(ioF)
if(not IsEmptyString(ln)) then
if(not TransformSettings(ln, tSet, seq)) then
return LogStatus("InitializeUnitSource(F): Transform failed <"..ln..">",nil) end
end
end; ioF:Close()
if(not PostProcessInit(oPly, tSet, tHit, bgHit)) then
return LogStatus("InitializeUnitSource(F): Post-process fail", nil) end
collectgarbage(); return LogStatus("InitializeUnitSource(F): OK", tSet)
elseif(sMod == mdStr) then
local ini, seq = mdStr:Explode(sSet:sub(2,-1)), {}
for cnt = 1, #ini, 1 do local ln = ini[cnt]:Trim()
if(not IsEmptyString(ln)) then
if(not TransformSettings(ln, tSet, seq)) then
return LogStatus("InitializeUnitSource(S): Transform failed <"..ln..">",nil) end
end
end
if(not PostProcessInit(oPly, tSet, tHit, bgHit)) then
return LogStatus("InitializeUnitSource(S): Post-process fail", nil) end
collectgarbage(); return LogStatus("InitializeUnitSource(S): OK", tSet)
else return LogStatus("InitializeUnitSource: Mode missed <"..sMod..">", nil) end
end
--[[
* Exports a set of hover module controls
* into array of initialization strings
* sKey > The sensor name/key to export
* stCon > The sensor structure to be exported
* tData > Where is the data stored
]]--
local function ExportSensor(sKey, stSen, tData)
local tyArg = type(stSen); if(tyArg ~= "table") then
return LogStatus("ExportSensor: Argument <"..tyArg.."> mismatch", false) end
local symCp = GetOpVar("OPSYM_COMPONENT")
local org, dir, len = stSen["Org"], stSen["Dir"], stSen["Len"]
local sLin , ID = "{"..GetOpVar("TYPE_SENSOR")..":"..sKey.."}", (#tData + 1)
sLin = sLin.."{Len:"..tostring(len).."}"
sLin = sLin.."{Org:"..tostring(org.x)..symCp..tostring(org.y)..symCp..tostring(org.z).."}"
sLin = sLin.."{Dir:"..tostring(dir.x)..symCp..tostring(dir.y)..symCp..tostring(dir.z).."}"
local lst = ""; for hit, _ in pairs(stSen["Hit"]) do lst = lst.."/"..tostring(hit) end
lst = lst:sub(2,-1); sLin = sLin..GetPick(IsEmptyString(lst), "", "{Hit:"..lst.."}")
tData[ID] = sLin; ID = ID + 1; sLin = ""; return true
end
--[[
* Exports a set of hover module controls
* into array of initialization strings
* sKey > The control name/key to export
* stCon > The control structure to be exported
* tData > Where is the data stored
]]--
local function ExportControl(sKey, stCon, tData)
local tyArg = type(stCon); if(tyArg ~= "table") then
return LogStatus("ExportControl: Argument <"..tyArg.."> mismatch", false) end
local symItem = GetOpVar("OPSYM_ITEMSPLIT")
local cmb, neg, ref = stCon["Cmb"], stCon["Neg"], stCon["Ref"]
local tun, prs, tar = stCon["Tun"], stCon["Prs"], stCon["Tar"]
local sLin, ID = "{"..GetOpVar("TYPE_CONTROL")..":"..sKey.."}", (#tData + 1)
sLin = sLin.."{Cmb:"..tostring(cmb):Trim().."}"
sLin = sLin.."{Neg:"..tostring(neg):Trim().."}"
sLin = sLin.."{Tar:"; for i = 1, #tar do
sLin = sLin..tostring(tar[i]):Trim()..symItem end; sLin = sLin:sub(1,-2).."}"
sLin = sLin.."{Ref:"..tostring(ref[1] or ""):Trim()
..symItem..GetPick(ref[2], tostring(ref[2]), ""):Trim().."}"
sLin = sLin.."{Tun:"..tostring(tun[1] or ""):Trim()..
symItem..tostring(tun[2] or ""):Trim()..
symItem..tostring(tun[3] or ""):Trim().."}"
sLin = sLin.."{Prs:"..tostring(prs):Trim().."}"
tData[ID] = sLin; ID = ID + 1; sLin = ""; return true
end
--[[
* Exports a set of hover module general settings ( properties )
* into array of initialization strings
* sKey > The property name/key to export
* stGen > The property structure to be exported
* tData > Where is the data stored
]]--
local function ExportGeneral(sKey, stGen, tData)
local tyArg = type(stGen); if(tyArg ~= "table") then
return LogStatus("ExportGeneral: Argument <"..tyArg.."> mismatch", false) end
local sLin, ID = "{"..GetOpVar("TYPE_GENERAL")..":"..sKey.."}", (#tData + 1)
if(type(stGen.Val) == "Vector") then local vVal = stGen.Val
sLin = sLin.."{Val:"..tostring(vVal.x)..","..tostring(vVal.y)..","..tostring(vVal.z).."}"
else sLin = sLin.."{Val:"..tostring(stGen.Val).."}" end
tData[ID] = sLin; return true
end
--[[
* Exports a set of hover module forcer settings
* into array of initialization strings
* sKey > The force name/key to export
* stFor > The force structure to be exported
* tData > Where is the data stored
]]--
local function ExportForcer(sKey, stFor, tData)
local tyArg = type(stFor)
if(tyArg ~= "table") then return LogStatus("ExportForcer: Argument <"..tyArg.."> mismatch", false) end
local org, dir, symCp = stFor["Org"], stFor["Dir"], GetOpVar("OPSYM_COMPONENT")
local sLin, ID = "{"..GetOpVar("TYPE_FORCER")..":"..sKey.."}", (#tData + 1)
sLin = sLin.."{Org:"..tostring(org.x)..symCp..tostring(org.y)..symCp..tostring(org.z).."}"
sLin = sLin.."{Dir:"..tostring(dir.x)..symCp..tostring(dir.y)..symCp..tostring(dir.z).."}"
tData[ID] = sLin; return true
end
--[[
* Orders structure hash keys by item /ID/ containment
* Returns a table of ordered sequential keys
* stSet > The source table for the report
* tRep.All > The number of all keys existing
* tRep.Int > The number of integer keys existing
* tRep.Cnt > The number of keys without holes
* tRep.Key > The list of keys (ordered)
* tRep.Ord > The list of IDs (ordered) (not needed)
]]--
local function GetKeyReportID(stSet)
local tRep, cnt = {Cnt = #stSet, Int = 0, All = 0, Key = {}, Ord = {}}, 1
for k, v in pairs(stSet) do
tRep.All = tRep.All + 1
if(type(v) == "table") then
local id = (tonumber(v.ID) or 0)
if(id and id > 0) then
tRep.Key[cnt], tRep.Ord[cnt] = k, id; cnt = cnt + 1
else return LogStatus("GetKeyReportID: Unsortable <"..tostring(k)..","..tostring(v.ID)..">", nil) end
elseif(type(k) == "number") then tRep.Int = tRep.Int + 1 end
end; cnt = 1 -- Direct selection sort
while(tRep.Key[cnt]) do
for ind = cnt+1, #tRep.Ord, 1 do
local ord, key = tRep.Ord, tRep.Key
if(ord[ind] < ord[cnt]) then
key[cnt], key[ind] = key[ind], key[cnt]
ord[cnt], ord[ind] = ord[ind], ord[cnt]
end
end; cnt = cnt + 1
end; tRep.Ord = nil; return tRep
end
--[[
* Exports a set of hover module settings
* into array of initialization strings
* stSet > A table set to export
* sType > The set type either /sensor/, /forcer/, /control/ or /general/
]]--
function ExportInitString(stSet, sType)
if(not (stSet and type(stSet) == "table")) then
return LogStatus("ExportInitString: Set definition missing", nil) end
local tRep, tSet, cnt, typ = GetKeyReportID(stSet), {}, 1, tostring(sType)
if(not tRep) then return LogStatus("ExportInitString: Sort by ID fail", nil) end
local tExp = {[GetOpVar("TYPE_GENERAL")] = ExportGeneral,
[GetOpVar("TYPE_SENSOR")] = ExportSensor ,
[GetOpVar("TYPE_FORCER")] = ExportForcer ,
[GetOpVar("TYPE_CONTROL")] = ExportControl}
if(not IsType(sType)) then return LogStatus("ExportInitString: Invalid type <"..typ..">", nil) end
while(tRep.Key[cnt]) do
local key = tRep.Key[cnt]
local val = stSet[key]
tExp[sType](key, val, tSet); cnt = cnt + 1
end; return tSet
end
--[[
* This function updates the general settings to the specifies fields.
* When they are read from the file they are strings and must be converted
* stHoverData > The hover module initialization data to be updated
* tGen > The general setting we need to update the structure with
]]--
function SetGeneralTable(stHoverData, tGen, bReplace)
local tMap = GetOpVar("MAPPING_GENERAL")
for key, rec in pairs(tGen) do
local map = tMap[key]
local col, foo = map[1], map[3]
if(bReplace and type(col) == "string") then
if(type(foo) == "function") then
stHoverData[col] = foo(rec.Val)
else stHoverData[col] = rec.Val end
end
end
end
--[[
* Creates a general purpose table based on non-list entity fields
* This table is later used for exporting the general setting into a file
* eHov > The hover entity to be extracted
]]--
function GetGeneralTable(eHov)
local sCls = GetOpVar("FILE_ENTITY")
local tGen = GetOpVar("MAPPING_GENERAL")
local sHas = GetOpVar("HASH_ENTITY")
if(not (eHov and eHov:IsValid() and eHov:GetClass() == sCls)) then
return LogStatus("GetGeneralTable: Entity invalid <"..tostring(eHov)..">") end
local hovData = eHov[sHas]
local tExp = {}; for key, val in pairs(tGen) do
tExp[key] = {Val = hovData[val[1]], ID = val[2]} end
return tExp
end
--[[
* Exports a hover module unit setting into a file
* eHov > The hover module entity
* sFile > The file to export the settings to
]]--
function ExportUnitSource(eHov, sFile)
if(not (eHov and eHov:IsValid())) then
return LogStatus("ExportUnitSource: Hover module invalid", nil) end
local sMag, sEnt = eHov:GetClass(), GetOpVar("FILE_ENTITY")
if(sMag ~= sEnt) then -- If another entity is given
return LogStatus("ExportUnitSource: Hover class <"..sMag.."> invalid", nil) end
local sNm = tostring(sFile or "default"); if(IsEmptyString(sNm)) then
return LogStatus("ExportUnitSource: File name empty", nil) end
if(not sNm:find(".txt", 1, true)) then sNm = sNm..".txt" end
local ioF = file.Open(sNm, "wb", "DATA"); if(not ioF) then
return LogStatus("ExportUnitSource: Failed to open file <"..sNm..">", nil) end
local sKey, ID = GetOpVar("HASH_ENTITY"), 1
local tData = {ExportInitString(GetGeneralTable(eHov), GetOpVar("TYPE_GENERAL")),
ExportInitString(eHov[sKey].Sensors , GetOpVar("TYPE_SENSOR")) ,
ExportInitString(eHov[sKey].Forcers , GetOpVar("TYPE_FORCER")) ,
ExportInitString(eHov[sKey].Control , GetOpVar("TYPE_CONTROL"))}
while(tData[ID]) do
local tSet, ST = tData[ID], 1
while(tSet[ST]) do
ioF:Write(tostring(tSet[ST]).."\n"); ST = ST + 1
end; ioF:Write("\n"); ID = ID + 1
end; ioF:Flush() ioF:Close()
end
function NotifyUser(pPly,sMsg,sTyp,...)
if(SERVER) then -- Send notification to client that something happened
pPly:SendLua("GAMEMODE:AddNotify(\""..tostring(sMsg).."\", NOTIFY_"..tostring(sTyp)..", 6)")
pPly:SendLua("surface.PlaySound(\"ambient/water/drip"..math.random(1, 4)..".wav\")")
end; return ...
end
local function onHoverModuleRemove(ent, ...)
local remID = {...}; for k, v in pairs(remID) do numpad.Remove(v) end
LogStatus("onHoverModuleRemove: Numpad removed <"..tostring(ent)..">")
end
function NewHoverModule(oPly, vPos, aAng, stHoverData)
local sLimit = GetOpVar("NAME_ENTITY"); if(not oPly:CheckLimit(sLimit)) then
return LogStatus("NewHoverModule: Hover module limit <"..sLimit.."> reached", nil) end
local eDye = GetPick(stHoverData.Dye,stHoverData.Dye,Color(255, 255, 255, 255))
local sNam = GetOpVar("NAME_TOOL") -- Get the creator tool
local eHov = ents.Create(GetOpVar("FILE_ENTITY")) -- Create the thing
if(eHov and eHov:IsValid()) then -- Setup the module entity if valid
eHov:SetPos(vPos) -- Set position
eHov:SetAngles(aAng) -- Set orientation
eHov:SetModel(stHoverData.Prop) -- Use the model given
eHov:Spawn() -- Make the ENT:Initialize run once
eHov:SetPlayer(oPly) -- Set the player who has spawned it
eHov:SetColor(eDye) -- Apply the color if given
eHov:SetRenderMode(RENDERMODE_TRANSALPHA) -- Use the alpha of the color given
eHov:SetCollisionGroup(COLLISION_GROUP_NONE) -- Normal collision: https://wiki.garrysmod.com/page/Enums/COLLISION
eHov:SetNotSolid(false) -- Make it collide like a solid
eHov:CallOnRemove("HoverModuleNumpadCleanup", onHoverModuleRemove,
numpad.OnDown(oPly, stHoverData.KeyOn, sNam.."_Power_On" , eHov ),
numpad.OnDown(oPly, stHoverData.KeyF , sNam.."_ForceForward_On" , eHov ),
numpad.OnUp (oPly, stHoverData.KeyF , sNam.."_ForceForward_Off", eHov ),
numpad.OnDown(oPly, stHoverData.KeyR , sNam.."_ForceReverse_On" , eHov ),
numpad.OnUp (oPly, stHoverData.KeyR , sNam.."_ForceReverse_Off", eHov ))
if(not eHov:Setup(stHoverData)) then eHov:Remove() -- Setup the data and controllers
return LogStatus("NewHoverModule: Setup module invalid", nil) end
eHov:Activate() -- Start ENT:Think method run in real-time
oPly:AddCount (sLimit, eHov) -- Register entity to the max count
oPly:AddCleanup(sLimit, eHov) -- Register entity to the clean-up list
return LogStatus("NewHoverModule: OK <"..tostring(eHov)..">", eHov);
end; return LogStatus("NewHoverModule: Entity invalid", nil)
end
function GetPhrase(sKey)
local sDef = GetOpVar("MISS_NOTR")
local tSet = GetOpVar("LOCALIFY_TABLE")
local sKey = tostring(sKey) if(IsNil(tSet[sKey])) then
LogStatus("Miss <"..sKey..">"); return GetOpVar("MISS_NOTR") end
return (tSet[sKey] or GetOpVar("MISS_NOTR")) -- Translation fail safe
end
local function GetLocalify(sCode)
local sCode = tostring(sCode or GetOpVar("MISS_NOAV"))
if(not CLIENT) then return LogStatus("("..sCode..") Not client", nil) end
local sTool, sLimit = GetOpVar("NAME_TOOL"), GetOpVar("NAME_LIMIT")
local sPath = GetOpVar("FORM_LANGPATH"):format("", sCode..".lua") -- Translation file path
if(not file.Exists("lua/"..sPath, "GAME")) then
return LogStatus("("..sCode..") Missing", nil) end
local fCode = CompileFile(sPath); if(not fCode) then
return LogStatus("("..sCode..") No function", nil) end
local bFunc, fFunc = pcall(fCode); if(not bFunc) then
return LogStatus("("..sCode..")[1] "..fFunc, nil) end
local bCode, tCode = pcall(fFunc, sTool, sLimit); if(not bCode) then
return LogStatus("("..sCode..")[2] "..tCode, nil) end
return tCode -- The successfully extracted translations
end
function InitLocalify(sCode)
local cuCod = tostring(sCode or GetOpVar("MISS_NOAV"))
if(not CLIENT) then return LogStatus("("..cuCod..") Not client", nil) end
local thSet = GetOpVar("LOCALIFY_TABLE"); table.Empty(thSet)
local auCod = GetOpVar("LOCALIFY_AUTO") -- Automatic translation code
local auSet = GetLocalify(auCod); if(not auSet) then
return LogStatus("Base mismatch <"..auCod..">", nil) end
if(cuCod ~= auCod) then local cuSet = GetLocalify(cuCod)
if(cuSet) then -- When the language infornation is extracted apply on success
for key, val in pairs(auSet) do auSet[key] = (cuSet[key] or auSet[key]) end
else LogStatus("Custom skipped <"..cuCod..">") end -- Apply auto code
end; for key, val in pairs(auSet) do thSet[key] = auSet[key]; language.Add(key, val) end
end
|
require('abilities/overlord_interface')
require('abilities/creature_powers')
require('dire_events')
function summon_melee_spawner(keys)
return create_spawner(keys,"npc_melee_spawner",spawners.melee_spawn_string)
end
function summon_ranged_spawner(keys)
return create_spawner(keys,"npc_ranged_spawner",spawners.ranged_spawn_string)
end
function summon_zombie_spawner(keys)
return create_spawner(keys,"npc_zombie_spawner",spawners.zombie_spawn_string)
end
function summon_ghoul_spawner(keys)
return create_spawner(keys,"npc_ghoul_spawner",spawners.ghoul_spawn_string)
end
function summon_orc_spawner(keys)
return create_spawner(keys,"npc_orc_spawner",spawners.warcamp_spawn_string)
end
function create_spawner_start(keys)
local caster = keys.caster
local point = keys.target_points[1]
local ability = keys.ability
if vision:fow_check(caster, point) == false then
EmitSoundOn("General.CastFail_InvalidTarget_Hero", caster)
caster:Stop()
return
end
end
function create_spawner(keys,spawner_name,unit_string)
local point = keys.target_points[1]
local caster = keys.caster
local casterPos = caster:GetAbsOrigin()
local difference = point - casterPos
local ability = keys.ability
--set up a check to make sure there isn't already a building there
if vision:fow_check(caster, point) == false and ability ~= nil then
caster:ModifyGold(keys.GoldCost, false, 0)
EmitSoundOn("General.CastFail_InvalidTarget_Hero", caster)
ability:EndCooldown()
return
end
GridNav:DestroyTreesAroundPoint(point, 200, true)
spawner = CreateUnitByName(spawner_name, point, true, caster, caster, caster:GetTeam())
if PlayerResource:GetPlayerCountForTeam(caster:GetTeam()) > 0 then
spawner:SetControllableByPlayer(caster:GetPlayerID(), false)
end
spawners:new_spawner(spawner,unit_string)
local particle = ParticleManager:CreateParticle("particles/units/heroes/hero_slark/slark_dark_pact_pulses.vpcf", PATTACH_ABSORIGIN_FOLLOW, spawner)
ParticleManager:SetParticleControl(particle, 1, spawner:GetAbsOrigin())
ParticleManager:SetParticleControl(particle, 3, spawner:GetAbsOrigin())
ParticleManager:SetParticleControl(particle, 4, spawner:GetAbsOrigin())
ParticleManager:SetParticleControl(particle, 5, spawner:GetAbsOrigin())
EmitSoundOn("Portal.Hero_Appear", spawner)
if caster:GetOwner() ~= nil then
spawner:SetForwardVector(caster:GetForwardVector())
spawner:SetBaseMaxHealth(spawner:GetMaxHealth() * (ability:GetLevel() + 1)/2)
spawner:SetMaxHealth(spawner:GetMaxHealth() * (ability:GetLevel() + 1)/2)
spawner:SetBaseHealthRegen(spawner:GetBaseHealthRegen() * (ability:GetLevel() + 1)/2)
spawner:SetHealth(spawner:GetMaxHealth())
make_building_dummy(spawner)
overlord_interface:set_default_state(caster)
end
return spawner
end
function summon_monster_start(keys)
local caster = keys.caster
local point = keys.target_points[1]
EmitSoundOn("Hero_Warlock.RainOfChaos",caster)
Timers:CreateTimer(0, function()
if caster:IsChanneling() then
StartAnimation(caster, {duration=10, activity=ACT_DOTA_CAST_ABILITY_2, rate=.1})
return 12
else
return
end
end)
GridNav:DestroyTreesAroundPoint(point, 200, true)
local targets = FindUnitsInRadius( caster:GetTeam(),point, nil, 300, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_BASIC + DOTA_UNIT_TARGET_HERO, 0, FIND_ANY_ORDER, false )
for _,target in pairs(targets) do
target:AddNewModifier(caster, keys.ability, "modifier_stunned", {duration = 1})
end
keys.ability:ApplyDataDrivenModifier(caster, caster, "modifier_disable_actions", {})
local monster = CreateUnitByName(keys.MonsterString , point, true, caster, caster, caster:GetTeam()) -- ( szUnitName, vLocation, bFindClearSpace, hNPCOwner, hUnitOwner, iTeamNumber )
monster_effects(keys,monster)
monster:SetControllableByPlayer(caster:GetPlayerID(), false)
monster.summoner = caster
caster.monster = monster
Timers:CreateTimer(0,function()
if caster:IsChanneling() == false then
summon_monster_end(keys)
return
end
return .1
end)
end
function summon_monster_end(keys)
local caster = keys.caster
local monster = caster.monster
caster:RemoveModifierByName("modifier_disable_actions")
ParticleManager:DestroyParticle(caster.summon_monster_particle,false)
ParticleManager:CreateParticle("particles/econ/items/abaddon/abaddon_alliance/abaddon_aphotic_shield_explosion_alliance_wave.vpcf",PATTACH_ABSORIGIN, monster)
if monster:IsNull() == false then
if monster:IsAlive() == true then
monster:SetControllableByPlayer(-1, false)
monster:SetOwner(nil)
monster:SetTeam(DOTA_TEAM_CUSTOM_1)
monster:Stop()
local unit_script_string = spawners.ai[monster:GetUnitName()]
spawners:assign_neutral_ai(monster,unit_script_string)
spawners:unit_order(monster, unit_script_string)
end
end
PlayerResource:IncrementAssists(caster:GetPlayerOwnerID(), -1)
overlord_interface:set_default_state(caster)
local ability = caster:FindAbilityByName("summon_monster_ability")-- Reset the Overlord's summon monster cooldown
ability:EndCooldown()
ability:StartCooldown(ability:GetCooldown(ability:GetLevel() - 1)) --for some reason GetLevel is offset by 1
end
function upgrade_spawner_ability(keys)
local ability = keys.ability
local spawner = keys.caster
ability:SetHidden(true)
spawners:upgrade(spawner)
spawner:SetBaseMaxHealth(spawner:GetMaxHealth() * 1.3)
spawner:SetMaxHealth(spawner:GetMaxHealth() * 1.3)
spawner:SetHealth(spawner:GetMaxHealth())
local x = spawner:GetModelScale()
spawner:SetModelScale(1.3*x)
end
function attack_command(keys)
local caster = keys.caster
local target = keys.target
local point = keys.target_points[1]
local range = keys.Range
EmitSoundOn("abaddon_abad_attack_02",caster)
spawners:command_in_radius("attack_move", point, caster:GetTeam(), point, range)
overlord_interface:set_default_state(caster)
end
function global_attack_command(keys)
local caster = keys.caster
local target = keys.target
local point = caster:GetOrigin()
EmitSoundOn("abaddon_abad_lasthit_10",caster)
spawners:command_in_radius("global_attack", caster:GetOrigin(),caster:GetTeam(), point)
overlord_interface:set_default_state(caster)
end
function defend_command(keys)
local caster = keys.caster
local target = keys.target
local point = caster:GetOrigin()
local range = keys.Range
if RandomInt(1,10) > 8 then
EmitSoundOn("abaddon_abad_laugh_0".. RandomInt(1,4),caster)
end
spawners:command_in_radius("defend", caster:GetOrigin(),caster:GetTeam(), point, range)
overlord_interface:set_default_state(caster)
end
function move_command(keys)
local caster = keys.caster
local point = keys.target_points[1]
local range = keys.Range
EmitSoundOn("abaddon_abad_attack_06",caster)
spawners:command_in_radius("move", caster:GetOrigin(),caster:GetTeam(), point, range)
overlord_interface:set_default_state(caster)
end
function kill_command(keys)
local caster = keys.caster
local range = keys.Range
local target = keys.target
EmitSoundOn("abaddon_abad_kill_08",caster)
spawners:command_in_radius("attack_target", caster:GetOrigin(),caster:GetTeam(), target, range)
overlord_interface:set_default_state(caster)
end
function deactivate_toggle_off(keys)
spawner = keys.caster
spawner.deactivated = false
end
function deactivate_toggle_on(keys)
local spawner = keys.caster
spawner.deactivated = true
end
function blinding_mist_start(keys)
local caster = keys.caster
local point = keys.target_points[1]
local radius = keys.radius
local targets = keys.target_entities
local duration = keys.duration
local mesh = 50
EmitSoundOnLocationWithCaster(caster:GetOrigin(),"Hero_Warlock.Upheaval", caster)
EmitSoundOn("abaddon_abad_rival_15",caster)
for i=0,duration do
Timers:CreateTimer(i, function()
for i = 1, mesh do
local smoke = ParticleManager:CreateParticle("particles/rain_of_chaos/riki_smokebomb_b_no_cull.vpcf", PATTACH_ABSORIGIN, GameMode.ancient)
smoke_point = point + RandomVector(i*radius/mesh)
ParticleManager:SetParticleControl(smoke, 0,smoke_point + Vector(0,0,400))
ParticleManager:SetParticleControl(smoke, 1,Vector(100000,1000,1))
--ParticleManager:SetParticleControl(smoke, 2,point)
Timers:CreateTimer(6, function()
ParticleManager:DestroyParticle(smoke, false)
end)
end
end)
end
overlord_interface:set_default_state(caster)
end
function blinding_mists(keys)
local target = keys.target
if target:GetClassname() == "npc_dota_building" or target:GetClassname() == "npc_dota_tower" then
AddFOWViewer(target:GetTeam(),target:GetOrigin(),400,1,true)
elseif target.FogFlag == nil then
AddFOWViewer(target:GetTeam(),target:GetOrigin(),400,1,true)
target.FogFlag = true
Timers:CreateTimer(50, function()
target.FogFlag = nil
end)
end
end
function create_building_start(keys)
local caster = keys.caster
local point = keys.target_points[1]
local ability = keys.ability
StartSoundEvent("Portal.Loop_Appear",caster)
Timers:CreateTimer(0, function()
if caster:IsChanneling() then
StartAnimation(caster, {duration=2, activity=ACT_DOTA_CAST_ABILITY_1, rate=.5})
local portal_particles = ParticleManager:CreateParticle("particles/econ/events/fall_major_2015/teleport_end_fallmjr_2015_lvl2_black_b.vpcf", PATTACH_ABSORIGIN, caster)
ParticleManager:SetParticleControl(portal_particles,0,point + Vector(0,0,100))
Timers:CreateTimer(4, function()
ParticleManager:DestroyParticle(portal_particles,false)
end)
return 2
else
StopSoundEvent("Portal.Loop_Appear",caster)
return
end
end)
end
function create_building(keys)
local building_name = keys.building
local point = keys.target_points[1]
local caster = keys.caster
local casterPos = caster:GetAbsOrigin()
local difference = point - casterPos
local ability = keys.ability
StopSoundEvent("Portal.Loop_Appear",caster)
EmitSoundOn("Portal.Hero_Appear", caster)
GridNav:DestroyTreesAroundPoint(point, 150, true)
building = CreateUnitByName(building_name, point, true, caster, caster, caster:GetTeam())
if building_name == "npc_flame_turret" then
building:SetForwardVector(-1 * caster:GetForwardVector()) --wtf it faces backwards
else
building:SetForwardVector(caster:GetForwardVector())
end
building:SetControllableByPlayer(caster:GetPlayerID(), false)
make_building_dummy(building)
caster:Stop()
StartAnimation(caster,{duration=.1, activity=ACT_DOTA_IDLE, rate=1})
StartAnimation(building, {duration=24*60, activity=ACT_DOTA_IDLE, rate=.3})
local particle = ParticleManager:CreateParticle("particles/units/heroes/hero_slark/slark_dark_pact_pulses.vpcf", PATTACH_ABSORIGIN, building)
--ParticleManager:SetParticleControl(particle, 0, spawner:GetAbsOrigin())
EmitSoundOn("Portal.Hero_Appear", spawner)
overlord_interface:set_default_state(caster)
end
function betray(keys)
local caster = keys.caster
local target = keys.target
local duration = keys.duration
EmitSoundOnLocationWithCaster(target:GetOrigin(),"Hero_Abaddon.BorrowedTime",target)
if target:IsIllusion() then
target:ForceKill(false)
end
if target:IsHero() then
keys.ability:ApplyDataDrivenModifier(caster, target, "betrayal_hero_modifier", {})
target:AddNoDraw()
local outgoingDamage = 200
local incomingDamage = 100
local origin = target:GetOrigin()
local unit_name = target:GetUnitName()
local targetAngles = target:GetAngles()
-- handle_UnitOwner needs to be nil, else it will crash the game.
local illusion = CreateUnitByName(unit_name, origin, true, caster, nil, caster:GetTeamNumber())
illusion:SetModelScale(target:GetModelScale() * 1.2)
illusion:SetOwner(caster)
illusion:SetAngles( targetAngles.x, targetAngles.y, targetAngles.z )
illusion:SetControllableByPlayer(caster:GetPlayerID(), false)
-- Level Up the unit to the casters level
local targetLevel = target:GetLevel()
for i=1,targetLevel-1 do
illusion:HeroLevelUp(false)
end
-- Set the skill points to 0 and learn the skills of the caster
illusion:SetAbilityPoints(0)
for abilitySlot=0,15 do
local ability = target:GetAbilityByIndex(abilitySlot)
if ability ~= nil then
local abilityLevel = ability:GetLevel()
local abilityName = ability:GetAbilityName()
local illusionAbility = illusion:FindAbilityByName(abilityName)
illusionAbility:SetLevel(abilityLevel)
end
end
-- Recreate the items of the caster
for itemSlot=0,5 do
local item = target:GetItemInSlot(itemSlot)
if item ~= nil then
local itemName = item:GetName()
local newItem = CreateItem(itemName, illusion, illusion)
illusion:AddItem(newItem)
end
end
-- Set the unit as an illusion
-- modifier_illusion controls many illusion properties like +Green damage not adding to the unit damage, not being able to cast spells and the team-only blue particle
illusion:AddNewModifier(target, ability, "modifier_illusion", { duration = duration, outgoing_damage = outgoingDamage, incoming_damage = incomingDamage})
-- illusion:AddNewModifier(target, ability, "modifier_kill", { duration = duration})
-- Without MakeIllusion the unit counts as a hero, e.g. if it dies to neutrals it says killed by neutrals, it respawns, etc.
illusion:MakeIllusion()
-- Set the illusion hp to be the same as the caster
illusion:SetHealth(target:GetHealth())
local particles = ParticleManager:CreateParticle("particles/units/heroes/hero_abaddon/abaddon_borrowed_time.vpcf", PATTACH_ABSORIGIN_FOLLOW,illusion)
keys.ability:ApplyDataDrivenModifier(caster, illusion, "betrayal_modifier", {})
Timers:CreateTimer(0, function()
if IsValidEntity(illusion) then
if illusion:IsAlive() then
angles = illusion:GetAngles()
target:SetAngles(angles.x, angles.y, angles.z)
target:SetOrigin(illusion:GetOrigin())
return .1
else
target:RemoveNoDraw()
end
end
end)
Timers:CreateTimer(duration, function()
ParticleManager:DestroyParticle(particles,false)
end)
elseif target:GetUnitName() == "npc_dota_roshan" then
target:SetOwner(caster)
target:SetControllableByPlayer(caster:GetPlayerID(), false)
target:SetTeam(caster:GetTeam())
local start_scale = target:GetModelScale()
target:SetModelScale(start_scale * 1.3)
keys.ability:ApplyDataDrivenModifier(caster, target, "betrayal_modifier", {})
local particles = ParticleManager:CreateParticle("particles/units/heroes/hero_abaddon/abaddon_borrowed_time.vpcf", PATTACH_ABSORIGIN_FOLLOW,target)
Timers:CreateTimer(duration, function()
ParticleManager:DestroyParticle(particles,false)
target:SetOwner(nil)
target:SetControllableByPlayer(-1, false)
target:SetModelScale(start_scale)
target:SetTeam(DOTA_TEAM_NEUTRALS)
end)
else
keys.ability:ApplyDataDrivenModifier(caster, target, "betrayal_hero_modifier", {})
local unit_name = target:GetUnitName()
local origin = target:GetOrigin()
local angles = target:GetAngles()
target:ForceKill(false)
UTIL_Remove(target)
local traitor = CreateUnitByName(unit_name, origin, false, caster, nil, caster:GetTeamNumber())
traitor:SetOwner(caster)
traitor:SetControllableByPlayer(caster:GetPlayerID(), false)
traitor:SetAngles(angles.x, angles.y, angles.z)
traitor:SetModelScale(traitor:GetModelScale() * 1.2)
traitor:SetBaseMaxHealth(traitor:GetBaseMaxHealth()*2)
traitor:SetHealth(traitor:GetMaxHealth())
traitor:SetBaseDamageMax(traitor:GetBaseDamageMax()*2)
traitor:SetBaseDamageMin(traitor:GetBaseDamageMin()*2)
keys.ability:ApplyDataDrivenModifier(caster, traitor, "betrayal_modifier", {})
local particles = ParticleManager:CreateParticle("particles/units/heroes/hero_abaddon/abaddon_borrowed_time.vpcf", PATTACH_ABSORIGIN_FOLLOW,traitor)
Timers:CreateTimer(duration, function()
keys.ability:ApplyDataDrivenModifier(caster, traitor, "traitor_modifier", {})
ParticleManager:DestroyParticle(particles,false)
end)
end
end
function final_death_animation(caster)
for i=1,6 do
item = caster:GetItemInSlot(i)
if item~=nil then
if item:GetName() == "item_aegis" then
caster:RemoveItem(item)
end
end
end
caster:RemoveNoDraw()
caster:AddNewModifier(caster, nil, "modifier_invulnerable", {})
caster:Stop()
caster:SetControllableByPlayer(-1, false)
GameMode.ancient:AddNewModifier(caster, nil, "modifier_invulnerable", {})
facing = caster:GetForwardVector()
left = facing:Cross(Vector(0,0,1))
local location = caster:GetOrigin()
local sky = location + Vector(0,0,1000)
StartAnimation(caster, {duration=6, activity=ACT_DOTA_DISABLED, rate=1})
local roll = RandomInt(1,15)
if roll < 10 then
death_cry_roll = "0"..roll
else
death_cry_roll = roll
end
EmitSoundOn("abaddon_abad_death_"..death_cry_roll, caster)
for i=1,100 do
Timers:CreateTimer(RandomFloat(0,5), function()
local shockparticle = ParticleManager:CreateParticle("particles/econ/items/zeus/lightning_weapon_fx/zuus_base_attack_explosion_core_b_immortal_lightning_immortal_lightning.vpcf",PATTACH_ABSORIGIN,caster)
if RandomInt(1,5) > 4 then
EmitSoundOnLocationWithCaster(caster:GetOrigin(), "Hero_Zuus.ArcLightning.Target", caster)
end
ParticleManager:SetParticleControl(shockparticle,3,location + RandomVector(50) + Vector(0,0,RandomInt(0,300)))
end)
end
beams = {}
for i=1,5 do
Timers:CreateTimer(RandomFloat(2,4), function()
EmitSoundOnLocationWithCaster(caster:GetOrigin(), "Hero_Pugna.LifeDrain.Cast", caster)
local beamparticle = ParticleManager:CreateParticle("particles/units/heroes/hero_pugna/pugna_life_drain_beam_2b_disabled.vpcf",PATTACH_ABSORIGIN,caster)
ParticleManager:SetParticleControl(beamparticle,1,location+Vector(0,0,RandomInt(100,250)))
ParticleManager:SetParticleControl(beamparticle,0,sky + RandomVector(300))
ParticleManager:SetParticleControl(beamparticle,11,Vector(.1,0,0))
table.insert(beams,beamparticle)
end)
end
Timers:CreateTimer(6, function()
EmitSoundOnLocationWithCaster(caster:GetOrigin(), "Hero_Abaddon.AphoticShield.Destroy", caster)
for _,beamparticle in pairs(beams) do
ParticleManager:DestroyParticle(beamparticle,false)
local explosion = ParticleManager:CreateParticle("particles/econ/items/abaddon/abaddon_alliance/abaddon_aphotic_shield_alliance_explosion.vpcf",PATTACH_ABSORIGIN,caster)
ParticleManager:SetParticleControl(explosion,0,location + Vector(0,0,300))
StartAnimation(caster, {duration=60, activity=ACT_DOTA_DIE, rate=.4})
end
end)
Timers:CreateTimer(8, function()
EmitSoundOnLocationWithCaster(caster:GetOrigin(),"Hero_Warlock.Upheaval", caster)
for i=1,15 do
local grasp = ParticleManager:CreateParticle("particles/econ/items/warlock/warlock_staff_glory/warlock_upheaval_hellborn_debuff.vpcf", PATTACH_ABSORIGIN, caster)
ParticleManager:SetParticleControl(grasp,0,location + RandomVector(RandomInt(1,150)) - 100 * facing + 100 * left)
Timers:CreateTimer(5, function()
ParticleManager:DestroyParticle(grasp,false)
end)
end
end)
Timers:CreateTimer(12, function()
caster:AddNoDraw()
caster:ForceKill(true)
end)
end
function make_building_dummy(unit)
local dummy = CreateUnitByName("npc_particle_dummy_unit", unit:GetOrigin(), false, unit:GetOwner(), unit:GetOwner(), unit:GetTeam())
Timers:CreateTimer(0,function()
if unit:IsAlive() == false then
UTIL_Remove(dummy)
return
else
return .1
end
end)
end
|
local Size = require "util.Size"
describe("util.size", function()
it("should construct as Size(int, int)", function()
local s = Size(5,10)
assert.are.equal(5,s.width)
assert.are.equal(10,s.height)
end)
it("should construct as Size{int, int}", function()
local s = Size{5,10}
assert.are.equal(5,s.width)
assert.are.equal(10,s.height)
end)
it("should construct as Size{x=int, y=int}", function()
local s = Size{x=5,y=10}
assert.are.equal(5,s.width)
assert.are.equal(10,s.height)
end)
it("should construct as Size{w=int, h=int}", function()
local s = Size{w=5,h=10}
assert.are.equal(5,s.width)
assert.are.equal(10,s.height)
end)
it("should construct as Size{width=int, height=int}", function()
local s = Size{width=5,height=10}
assert.are.equal(5,s.width)
assert.are.equal(10,s.height)
end)
it("should fail construction for any other input", function()
assert.has.error(function() Size() end)
assert.has.error(function() Size{} end)
assert.has.error(function() Size(1) end)
assert.has.error(function() Size{1} end)
assert.has.error(function() Size("1", "3") end)
end)
it("should be able to add two sizes together", function()
local s = Size(1,2) + Size(3,4)
assert.are.equal(4,s.width)
assert.are.equal(6,s.height)
end)
it("should be able to subtract two sizes together", function()
local s = Size(1,2) - Size(3,4)
assert.are.equal(-2,s.width)
assert.are.equal(-2,s.height)
end)
it("should be able to compare two sizes", function()
assert.is_true(Size(1,2) == Size(1,2))
assert.is_false(Size(1,2) == Size(3,4))
end)
it("should unpack when called", function()
local x,y = Size(5,10)()
assert.are.equal(5, x)
assert.are.equal(10, y)
end)
it("should be able to resolve (int, int)", function()
local s = Size.resolveFunctionArgs(5,10)
assert.are.equal(5, s.width)
assert.are.equal(10, s.height)
end)
it("should be able to resolve {int, int}", function()
local s = Size.resolveFunctionArgs{5,10}
assert.are.equal(5, s.width)
assert.are.equal(10, s.height)
end)
it("should be able to resolve {x=int, y=int}", function()
local s = Size.resolveFunctionArgs{x=5,y=10}
assert.are.equal(5, s.width)
assert.are.equal(10, s.height)
end)
it("should be able to resolve {w=int, h=int}", function()
local s = Size.resolveFunctionArgs{w=5,h=10}
assert.are.equal(5, s.width)
assert.are.equal(10, s.height)
end)
it("should be able to resolve {width=int, height=int}", function()
local s = Size.resolveFunctionArgs{width=5,height=10}
assert.are.equal(5, s.width)
assert.are.equal(10, s.height)
end)
it("should reuse itself when resolving instance of Size", function()
local s = Size(1,2)
assert.are.equal(s, Size.resolveFunctionArgs(s))
end)
end)
|
require('quest')
-- A quest to clear Stonewall of the goblin sea-captain.
local function kirin_goblin_start_fn()
add_message_with_pause("KIRIN_GOBLIN_QUEST_START_SID")
add_message_with_pause("KIRIN_GOBLIN_QUEST_START2_SID")
clear_and_add_message("KIRIN_GOBLIN_QUEST_START3_SID")
add_object_to_player_tile("goblincrusher")
end
local function kirin_goblin_completion_condition_fn()
return (get_num_creature_killed_global("akojo") > 0)
end
local function kirin_goblin_completion_fn()
add_message_with_pause("KIRIN_GOBLIN_QUEST_COMPLETE_SID")
add_message_with_pause("KIRIN_GOBLIN_QUEST_COMPLETE2_SID")
clear_and_add_message("KIRIN_GOBLIN_QUEST_COMPLETE3_SID")
add_object_to_player_tile("silari")
return true
end
kirin_goblin_quest = Quest:new("kirin_goblin",
"KIRIN_GOBLIN_QUEST_TITLE_SID",
"KIRIN_DESCRIPTION_SID",
"KIRIN_GOBLIN_DESCRIPTION_SID",
"KIRIN_GOBLIN_QUEST_COMPLETE_SID",
"KIRIN_GOBLIN_QUEST_REMINDER_SID",
truefn,
kirin_goblin_start_fn,
kirin_goblin_completion_condition_fn,
kirin_goblin_completion_fn)
if kirin_goblin_quest:execute() == false then
add_message("KIRIN_SPEECH_TEXT_SID")
end
|
return {
["skull"] = "💀",
["exploding_head"] = "🤯",
["camping"] = "🏕️",
["mortar_board"] = "🎓",
["gem"] = "💎",
["scream"] = "😱",
["control_knobs"] = "🎛️",
["woman_guard"] = "💂♀️",
["man_lifting_weights"] = "🏋️♂️",
["family_mmgg"] = "👨👨👧👧",
["raised_hand"] = "✋",
["family_wwb"] = "👩👩👦",
["princess"] = "👸",
["woozy_face"] = "🥴",
["shrug"] = "🤷",
["donut"] = "🍩",
["key2"] = "🗝️",
["clock4"] = "🕓",
["woman_bowing"] = "🙇♀️",
["slot_machine"] = "🎰",
["musical_keyboard"] = "🎹",
["custard"] = "🍮",
["pig"] = "🐷",
["man_farmer"] = "👨🌾",
["small_airplane"] = "🛩️",
["clock730"] = "🕢",
["star_of_david"] = "🔯",
["melon"] = "🍈",
["u6708"] = "🈷️",
["hatching_chick"] = "🐣",
["flag_gu"] = "🇬🇺",
["loudspeaker"] = "📢",
["family_wgb"] = "👩👧👦",
["bullettrain_front"] = "🚅",
["flag_fk"] = "🇫🇰",
["person_climbing"] = "🧗",
["white_circle"] = "⚪",
["saxophone"] = "🎷",
["flag_pl"] = "🇵🇱",
["snowflake"] = "❄️",
["paella"] = "🥘",
["aquarius"] = "♒",
["shower"] = "🚿",
["dash"] = "💨",
["atom"] = "⚛️",
["large_black_square"] = "⬛",
["shell"] = "🐚",
["minibus"] = "🚐",
["baseball_cap"] = "🧢",
["medium_small_white_square"] = "◽",
["family_mmb"] = "👨👨👦",
["sunglasses"] = "😎",
["medium_white_square"] = "◻️",
["chains"] = "⛓️",
["fishing_pole_and_fish"] = "🎣",
["clown"] = "🤡",
["biohazard_sign"] = "☣️",
["flag_scot"] = "🏴",
["ice_cream"] = "🍨",
["sunny"] = "☀️",
["flag_ax"] = "🇦🇽",
["moyai"] = "🗿",
["seat"] = "💺",
["chicken"] = "🐔",
["fortune_cookie"] = "🥠",
["giraffe"] = "🦒",
["man_scientist"] = "👨🔬",
["woman_lifting_weights"] = "🏋️♀️",
["bronze_medal"] = "🥉",
["symbols"] = "🔣",
["biohazard"] = "☣️",
["flag_mp"] = "🇲🇵",
["muslce"] = "💪",
["scream_cat"] = "🙀",
["rotating_light"] = "🚨",
["play_button"] = "▶️",
["piano"] = "🎹",
["octopus"] = "🐙",
["cartwheel"] = "🤸",
["birthday"] = "🎂",
["woman_construction_worker"] = "👷♀️",
["flag_sr"] = "🇸🇷",
["white_sun_small_cloud"] = "🌤️",
["mountain_cableway"] = "🚠",
["dog2"] = "🐕",
["seedling"] = "🌱",
["first_place"] = "🥇",
["fish"] = "🐟",
["flag_vu"] = "🇻🇺",
["flag_tj"] = "🇹🇯",
["woman_vampire"] = "🧛♀️",
["guitar"] = "🎸",
["paperclips"] = "🖇️",
["dizzy"] = "💫",
["womans_clothes"] = "👚",
["open_file_folder"] = "📂",
["slight_smile"] = "🙂",
["sweat"] = "😓",
["sled"] = "🛷",
["cactus"] = "🌵",
["hotdog"] = "🌭",
["musical_note"] = "🎵",
["broccoli"] = "🥦",
["pie"] = "🥧",
["grinning"] = "😀",
["goal_net"] = "🥅",
["wilted_flower"] = "🥀",
["dancer"] = "💃",
["clock330"] = "🕞",
["white_sun_behind_cloud"] = "🌥️",
["cityscape"] = "🏙️",
["flan"] = "🍮",
["flag_eh"] = "🇪🇭",
["film_projector"] = "📽️",
["racing_car"] = "🏎️",
["paperclip"] = "📎",
["party_popper"] = "🎉",
["speech_bubble_eye"] = "👁️🗨️",
["mosque"] = "🕌",
["video_camera"] = "📹",
["smiley"] = "😃",
["family_mbb"] = "👨👦👦",
["trophy"] = "🏆",
["women_bunny_ears"] = "👯♀️",
["japanese_service_charge_button"] = "🈂️",
["information_desk_person"] = "💁",
["shopping_trolley"] = "🛒",
["thought_bubble"] = "💭",
["maple_leaf"] = "🍁",
["zzz"] = "💤",
["studio_microphone"] = "🎙️",
["crocodile"] = "🐊",
["flag_mr"] = "🇲🇷",
["school_satchel"] = "🎒",
["arrow_down_left"] = "↙️",
["flag_ua"] = "🇺🇦",
["inbox_tray"] = "📥",
["call_me_hand"] = "🤙",
["arrow_up"] = "⬆️",
["skeleton"] = "💀",
["bug"] = "🐛",
["musical_score"] = "🎼",
["ferry"] = "⛴️",
["anchor"] = "⚓",
["oil"] = "🛢️",
["vulcan"] = "🖖",
["angry"] = "😠",
["salad"] = "🥗",
["flag_ps"] = "🇵🇸",
["honey_pot"] = "🍯",
["anger"] = "💢",
["massage"] = "💆",
["paw_prints"] = "🐾",
["tokyo_tower"] = "🗼",
["church"] = "⛪",
["oncoming_taxi"] = "🚖",
["beginner"] = "🔰",
["roller_coaster"] = "🎢",
["atom_symbol"] = "⚛️",
["flag_ga"] = "🇬🇦",
["last_quarter_moon"] = "🌗",
["atm"] = "🏧",
["national_park"] = "🏞️",
["projector"] = "📽️",
["point_up"] = "☝️",
["sound"] = "🔉",
["spider"] = "🕷️",
["japan"] = "🗾",
["four_leaf_clover"] = "🍀",
["taco"] = "🌮",
["shopping_cart"] = "🛒",
["water_buffalo"] = "🐃",
["flag_ly"] = "🇱🇾",
["mask"] = "😷",
["see_no_evil"] = "🙈",
["flag_gh"] = "🇬🇭",
["flag_ph"] = "🇵🇭",
["dango"] = "🍡",
["slightly_smiling_face"] = "🙂",
["bin"] = "🗑️",
["flag_lk"] = "🇱🇰",
["snowman"] = "⛄",
["chocolate_bar"] = "🍫",
["shallow_pan_of_food"] = "🥘",
["radioactive_sign"] = "☢️",
["chopsticks"] = "🥢",
["arrow_curve_down"] = "⤵️",
["pensive"] = "😔",
["wave"] = "👋",
["flag_gt"] = "🇬🇹",
["face_with_cowboy_hat"] = "🤠",
["flag_ls"] = "🇱🇸",
["woman_student"] = "👩🎓",
["mountain_snow"] = "🏔️",
["doughnut"] = "🍩",
["jack_o_lantern"] = "🎃",
["racecar"] = "🏎️",
["circus_tent"] = "🎪",
["flag_eng"] = "🏴",
["flag_sj"] = "🇸🇯",
["tea"] = "🍵",
["drool"] = "🤤",
["woman_singer"] = "👩🎤",
["airplane"] = "✈️",
["poultry_leg"] = "🍗",
["purple_heart"] = "💜",
["pizza"] = "🍕",
["clock11"] = "🕚",
["boxing_gloves"] = "🥊",
["second_place_medal"] = "🥈",
["woman_running"] = "🏃♀️",
["flag_kr"] = "🇰🇷",
["sneezing_face"] = "🤧",
["desktop_computer"] = "🖥️",
["flag_ng"] = "🇳🇬",
["flag_xk"] = "🇽🇰",
["scroll"] = "📜",
["fountain"] = "⛲",
["expressionless"] = "😑",
["stopwatch"] = "⏱️",
["pound"] = "💷",
["reminder_ribbon"] = "🎗️",
["framed_picture"] = "🖼️",
["weary"] = "😩",
["point_down"] = "👇",
["flag_pf"] = "🇵🇫",
["sushi"] = "🍣",
["zombie"] = "🧟",
["o"] = "⭕",
["hammer_and_pick"] = "⚒️",
["night_with_stars"] = "🌃",
["person_in_lotus_position"] = "🧘",
["flag_kp"] = "🇰🇵",
["person_doing_cartwheel"] = "🤸",
["woman_zombie"] = "🧟♀️",
["bridge_at_night"] = "🌉",
["new_moon_with_face"] = "🌚",
["back_of_hand"] = "🤚",
["rhinoceros"] = "🦏",
["magnifying_glass_left"] = "🔍",
["flag_et"] = "🇪🇹",
["island"] = "🏝️",
["man_mountain_biking"] = "🚵♂️",
["bow"] = "🙇",
["dart"] = "🎯",
["leopard"] = "🐆",
["pineapple"] = "🍍",
["flag_ge"] = "🇬🇪",
["peace_symbol"] = "☮️",
["volleyball"] = "🏐",
["unicorn"] = "🦄",
["rainbow_flag"] = "🏳️🌈",
["star_struck"] = "🤩",
["drum"] = "🥁",
["flag_ht"] = "🇭🇹",
["raised_hand_with_part_between_middle_and_ring_fingers"] = "🖖",
["astonished"] = "😲",
["mailbox_closed"] = "📪",
["ballot_box_with_ballot"] = "🗳️",
["mount_fuji"] = "🗻",
["signal_strength"] = "📶",
["laptop"] = "💻",
["construction_site"] = "🏗️",
["woman_in_lotus_position"] = "🧘♀️",
["fries"] = "🍟",
["mailbox_with_no_mail"] = "📭",
["man_judge"] = "👨⚖️",
["dragon"] = "🐉",
["monorail"] = "🚝",
["gift_heart"] = "💝",
["hole"] = "🕳️",
["satisfied"] = "😆",
["flag_nu"] = "🇳🇺",
["flag_jm"] = "🇯🇲",
["robot_face"] = "🤖",
["flag_ch"] = "🇨🇭",
["man_swimming"] = "🏊♂️",
["apple"] = "🍎",
["truck"] = "🚚",
["closed_book"] = "📕",
["sleuth_or_spy"] = "🕵️",
["male_dancer"] = "🕺",
["blossom"] = "🌼",
["castle"] = "🏰",
["womens"] = "🚺",
["drooling_face"] = "🤤",
["construction"] = "🚧",
["chart_increasing"] = "📈",
["woman_bouncing_ball"] = "⛹️♀️",
["relaxed"] = "☺️",
["eyes"] = "👀",
["flag_eu"] = "🇪🇺",
["trumpet"] = "🎺",
["lady_liberty"] = "🗽",
["spy"] = "🕵️",
["lizard"] = "🦎",
["basketball_player"] = "⛹️",
["peace"] = "☮️",
["karate_uniform"] = "🥋",
["scissors"] = "✂️",
["heart"] = "❤️",
["carousel_horse"] = "🎠",
["flag_mz"] = "🇲🇿",
["purse"] = "👛",
["flag_tw"] = "🇹🇼",
["silver_medal"] = "🥈",
["athletic_shoe"] = "👟",
["woman_tipping_hand"] = "💁♀️",
["triangular_ruler"] = "📐",
["man_running"] = "🏃♂️",
["japanese_ogre"] = "👹",
["woman_firefighter"] = "👩🚒",
["aerial_tramway"] = "🚡",
["man_pouting"] = "🙎♂️",
["rabbit"] = "🐰",
["barber"] = "💈",
["tangerine"] = "🍊",
["shield"] = "🛡️",
["telephone"] = "☎️",
["mountain_bicyclist"] = "🚵",
["flag_ec"] = "🇪🇨",
["spider_web"] = "🕸️",
["railway_track"] = "🛤️",
["dove"] = "🕊️",
["clock230"] = "🕝",
["knife"] = "🔪",
["back"] = "🔙",
["rolling_on_the_floor_laughing"] = "🤣",
["plus_sign"] = "➕",
["curling_stone"] = "🥌",
["fearful"] = "😨",
["flag_re"] = "🇷🇪",
["carrot"] = "🥕",
["bowling"] = "🎳",
["strawberry"] = "🍓",
["flag_wal"] = "🏴",
["basketball"] = "🏀",
["japanese_free_of_charge_button"] = "🈚",
["flushed"] = "😳",
["key"] = "🔑",
["newspaper2"] = "🗞️",
["money_mouth_face"] = "🤑",
["rofl"] = "🤣",
["white_flag"] = "🏳️",
["spaghetti"] = "🍝",
["orthodox_cross"] = "☦️",
["vomiting_face"] = "🤮",
["floppy_disk"] = "💾",
["woman_factory_worker"] = "👩🏭",
["face_with_monocle"] = "🧐",
["sports_medal"] = "🏅",
["person_tipping_hand"] = "💁",
["airplane_arrival"] = "🛬",
["woman_judge"] = "👩⚖️",
["coconut"] = "🥥",
["door"] = "🚪",
["mouse"] = "🐭",
["fog"] = "🌫️",
["clock"] = "🕰️",
["family_mmg"] = "👨👨👧",
["sauropod"] = "🦕",
["rice"] = "🍚",
["dolphin"] = "🐬",
["butterfly"] = "🦋",
["v"] = "✌️",
["flag_tv"] = "🇹🇻",
["chipmunk"] = "🐿️",
["100"] = "💯",
["cloud_rain"] = "🌧️",
["pencil"] = "✏️",
["man_genie"] = "🧞♂️",
["ghost"] = "👻",
["gold_medal"] = "🥇",
["flag_tg"] = "🇹🇬",
["flag_gf"] = "🇬🇫",
["sunflower"] = "🌻",
["fax"] = "📠",
["dragon_face"] = "🐲",
["upside_down"] = "🙃",
["two_hearts"] = "💕",
["helmet_with_cross"] = "⛑️",
["radio"] = "📻",
["woman_gesturing_no"] = "🙅♀️",
["cloud_with_lightning"] = "🌩️",
["large_white_square"] = "⬜",
["bat"] = "🦇",
["socks"] = "🧦",
["persevere"] = "😣",
["bullettrain_side"] = "🚄",
["canoe"] = "🛶",
["man_raising_hand"] = "🙋♂️",
["flag_pw"] = "🇵🇼",
["cut_of_meat"] = "🥩",
["white_sun_behind_rain_cloud"] = "🌦️",
["dog"] = "🐶",
["clown_face"] = "🤡",
["poop"] = "💩",
["stuck_out_tongue_winking_eye"] = "😜",
["station"] = "🚉",
["flag_cx"] = "🇨🇽",
["cat"] = "🐱",
["woman_genie"] = "🧞♀️",
["man_detective"] = "🕵️♂️",
["right_button"] = "▶️",
["city_sunrise"] = "🌇",
["merman"] = "🧜♂️",
["u6307"] = "🈯",
["ear"] = "👂",
["flag_lc"] = "🇱🇨",
["clock1230"] = "🕧",
["factory"] = "🏭",
["pig2"] = "🐖",
["japanese_congratulations_button"] = "㊗️",
["confused"] = "😕",
["takeout_box"] = "🥡",
["fleur_de_lis"] = "⚜️",
["hammer_pick"] = "⚒️",
["family_mwgg"] = "👨👩👧👧",
["upside_down_face"] = "🙃",
["cup_with_straw"] = "🥤",
["raiseD_hands"] = "🙌",
["sandal"] = "👡",
["hamburger"] = "🍔",
["fork_knife_plate"] = "🍽️",
["cruise_ship"] = "🛳️",
["chestnut"] = "🌰",
["face_with_head_bandage"] = "🤕",
["flag_km"] = "🇰🇲",
["flag_qa"] = "🇶🇦",
["flag_la"] = "🇱🇦",
["briefcase"] = "💼",
["train"] = "🚋",
["fast_down_button"] = "⏬",
["rooster"] = "🐓",
["flag_dm"] = "🇩🇲",
["man_firefighter"] = "👨🚒",
["man_fairy"] = "🧚♂️",
["man_technologist"] = "👨💻",
["metal"] = "🤘",
["triangular_flag"] = "🚩",
["zebra"] = "🦓",
["jeans"] = "👖",
["billed_cap"] = "🧢",
["amphora"] = "🏺",
["whale2"] = "🐋",
["sleeping"] = "😴",
["soccer"] = "⚽",
["corn"] = "🌽",
["baby_bottle"] = "🍼",
["grapes"] = "🍇",
["flag_af"] = "🇦🇫",
["woman_pilot"] = "👩✈️",
["snake"] = "🐍",
["flag_au"] = "🇦🇺",
["star2"] = "🌟",
["egg"] = "🥚",
["spiral_calendar"] = "🗓️",
["deer"] = "🦌",
["clock12"] = "🕛",
["umbrella2"] = "☂️",
["frowning_face"] = "☹️",
["flag_li"] = "🇱🇮",
["pisces"] = "♓",
["eagle"] = "🦅",
["ram"] = "🐏",
["heart_eyes"] = "😍",
["speaking_head"] = "🗣️",
["clock6"] = "🕕",
["black_flag"] = "🏴",
["flag_cr"] = "🇨🇷",
["busts_in_silhouette"] = "👥",
["small_orange_diamond"] = "🔸",
["waxing_gibbous_moon"] = "🌔",
["accept"] = "🉑",
["woman_detective"] = "🕵️♀️",
["flag_lb"] = "🇱🇧",
["grin"] = "😁",
["cheese"] = "🧀",
["trex"] = "🦖",
["chart"] = "💹",
["tongue"] = "👅",
["ledger"] = "📒",
["droplet"] = "💧",
["postal_horn"] = "📯",
["high_heel"] = "👠",
["pager"] = "📟",
["flag_ee"] = "🇪🇪",
["flag_ru"] = "🇷🇺",
["part_alternation_mark"] = "〽️",
["man_cartwheeling"] = "🤸♂️",
["burrito"] = "🌯",
["black_heart"] = "🖤",
["white_squarebutton"] = "🔳",
["heartbeat"] = "💓",
["flag_to"] = "🇹🇴",
["ox"] = "🐂",
["memo"] = "📝",
["thumbdown"] = "👎",
["japanese_vacancy_button"] = "🈳",
["anguished"] = "😧",
["flag_bt"] = "🇧🇹",
["cross"] = "✝️",
["elder"] = "🧓",
["elephant"] = "🐘",
["older_woman"] = "👵",
["hand_with_index_and_middle_fingers_crossed"] = "🤞",
["man_in_business_suit_levitating"] = "🕴️",
["horse"] = "🐴",
["lips"] = "👄",
["woman_astronaut"] = "👩🚀",
["fallen_leaf"] = "🍂",
["racehorse"] = "🐎",
["ok_hand"] = "👌",
["hearts"] = "♥️",
["cinema"] = "🎦",
["motorbike"] = "🛵",
["face_with_rolling_eyes"] = "🙄",
["flag_nz"] = "🇳🇿",
["croissant"] = "🥐",
["dove_of_peace"] = "🕊️",
["bowl_with_spoon"] = "🥣",
["man_handball"] = "🤾♂️",
["candle"] = "🕯️",
["herb"] = "🌿",
["hugging"] = "🤗",
["hourglass_flowing_sand"] = "⏳",
["houses"] = "🏘️",
["hushed"] = "😯",
["man_cop"] = "👮♂️",
["woman_gesturing_ok"] = "🙆♀️",
["woman_cook"] = "👩🍳",
["flag_zw"] = "🇿🇼",
["black_circle"] = "⚫",
["fried_shrimp"] = "🍤",
["race_car"] = "🏎️",
["coffee"] = "☕",
["lock_with_pen"] = "🔏",
["man_office_worker"] = "👨💼",
["wolf"] = "🐺",
["flag_za"] = "🇿🇦",
["latin_cross"] = "✝️",
["flag_yt"] = "🇾🇹",
["flag_so"] = "🇸🇴",
["flag_jo"] = "🇯🇴",
["bookmark_tabs"] = "📑",
["blush"] = "😊",
["hugging_face"] = "🤗",
["bear"] = "🐻",
["flag_ws"] = "🇼🇸",
["flag_wf"] = "🇼🇫",
["bird"] = "🐦",
["flag_vn"] = "🇻🇳",
["man_shrug"] = "🤷♂️",
["flag_vi"] = "🇻🇮",
["japanese_here_button"] = "🈁",
["flag_bb"] = "🇧🇧",
["woman_teacher"] = "👩🏫",
["dromedary_camel"] = "🐪",
["flag_ve"] = "🇻🇪",
["calling"] = "📲",
["fencer"] = "🤺",
["raising_hand"] = "🙋",
["dizzy_face"] = "😵",
["ear_of_rice"] = "🌾",
["flag_me"] = "🇲🇪",
["flag_hr"] = "🇭🇷",
["confetti_ball"] = "🎊",
["full_moon"] = "🌕",
["flag_uz"] = "🇺🇿",
["classical_building"] = "🏛️",
["tiger"] = "🐯",
["flag_pa"] = "🇵🇦",
["vibration_mode"] = "📳",
["flag_us"] = "🇺🇸",
["name_badge"] = "📛",
["flag_um"] = "🇺🇲",
["volcano"] = "🌋",
["drum_with_drumsticks"] = "🥁",
["poodle"] = "🐩",
["worried"] = "😟",
["bee"] = "🐝",
["globe_with_meridians"] = "🌐",
["mailbox_with_mail"] = "📬",
["flag_tr"] = "🇹🇷",
["family_wgg"] = "👩👧👧",
["flag_tn"] = "🇹🇳",
["pancakes"] = "🥞",
["flag_id"] = "🇮🇩",
["flag_tm"] = "🇹🇲",
["fork_and_knife"] = "🍴",
["milk"] = "🥛",
["funeral_urn"] = "⚱️",
["flag_tl"] = "🇹🇱",
["card_box"] = "🗃️",
["flag_om"] = "🇴🇲",
["flag_tk"] = "🇹🇰",
["family_mgg"] = "👨👧👧",
["timer"] = "⏲️",
["flag_th"] = "🇹🇭",
["flag_tf"] = "🇹🇫",
["boy"] = "👦",
["third_place"] = "🥉",
["crayon"] = "🖍️",
["man_bowing"] = "🙇♂️",
["woman_haircut"] = "💇♀️",
["keyboard"] = "⌨️",
["helicopter"] = "🚁",
["flag_td"] = "🇹🇩",
["woman_massage"] = "💆♀️",
["womans_hat"] = "👒",
["cherries"] = "🍒",
["nerd"] = "🤓",
["question"] = "❓",
["wastebasket"] = "🗑️",
["flag_ta"] = "🇹🇦",
["thinking_face"] = "🤔",
["level_slider"] = "🎚️",
["military_medal"] = "🎖️",
["face_with_raised_eyebrow"] = "🤨",
["mouse2"] = "🐁",
["flag_bo"] = "🇧🇴",
["desktop"] = "🖥️",
["bust_in_silhouette"] = "👤",
["flag_ss"] = "🇸🇸",
["lipstick"] = "💄",
["zany_face"] = "🤪",
["rhino"] = "🦏",
["satellite_antenna"] = "📡",
["flag_sn"] = "🇸🇳",
["flag_sm"] = "🇸🇲",
["hibiscus"] = "🌺",
["flag_gm"] = "🇬🇲",
["tickets"] = "🎟️",
["panda_face"] = "🐼",
["wheel_of_dharma"] = "☸️",
["flag_sk"] = "🇸🇰",
["flag_si"] = "🇸🇮",
["liar"] = "🤥",
["woman_golfing"] = "🏌️♀️",
["bike"] = "🚲",
["baby_chick"] = "🐤",
["skier"] = "⛷️",
["japanese_acceptable_button"] = "🉑",
["flag_sg"] = "🇸🇬",
["city_night"] = "🌃",
["camera"] = "📷",
["flag_md"] = "🇲🇩",
["flag_se"] = "🇸🇪",
["slightly_frowning_face"] = "🙁",
["flag_sd"] = "🇸🇩",
["admission_tickets"] = "🎟️",
["dolls"] = "🎎",
["man_health_worker"] = "👨⚕️",
["flag_sc"] = "🇸🇨",
["hammer_and_wrench"] = "🛠️",
["asterisk"] = "*️⃣",
["notebook_with_decorative_color"] = "📔",
["flag_sa"] = "🇸🇦",
["flag_rw"] = "🇷🇼",
["old_key"] = "🗝️",
["spades"] = "♠️",
["flag_ro"] = "🇷🇴",
["flag_py"] = "🇵🇾",
["woman_artist"] = "👩🎨",
["brain"] = "🧠",
["flag_pk"] = "🇵🇰",
["family_mb"] = "👨👦",
["bright"] = "🔆",
["flag_gd"] = "🇬🇩",
["flag_pt"] = "🇵🇹",
["bellhop_bell"] = "🛎️",
["flag_pe"] = "🇵🇪",
["hand_splayed"] = "🖐️",
["park"] = "🏞️",
["flag_nr"] = "🇳🇷",
["gorilla"] = "🦍",
["flag_eg"] = "🇪🇬",
["flag_sb"] = "🇸🇧",
["man_dancing"] = "🕺",
["cake"] = "🍰",
["crab"] = "🦀",
["arrow_left_right"] = "↔️",
["man_artist"] = "👨🎨",
["flag_nl"] = "🇳🇱",
["shark"] = "🦈",
["airplane_small"] = "🛩️",
["oncoming_bus"] = "🚍",
["flag_jp"] = "🇯🇵",
["top"] = "🔝",
["flag_ni"] = "🇳🇮",
["ballot_box"] = "🗳️",
["red_circle"] = "🔴",
["motorcycle"] = "🏍️",
["woman"] = "👩",
["flag_ic"] = "🇮🇨",
["flag_nc"] = "🇳🇨",
["tanabata_tree"] = "🎋",
["fox"] = "🦊",
["unamused"] = "😒",
["flag_na"] = "🇳🇦",
["clock130"] = "🕜",
["flag_be"] = "🇧🇪",
["flag_my"] = "🇲🇾",
["flag_mx"] = "🇲🇽",
["flag_mw"] = "🇲🇼",
["flag_mv"] = "🇲🇻",
["cloud"] = "☁️",
["flag_mu"] = "🇲🇺",
["left_facing_fist"] = "🤛",
["flag_mt"] = "🇲🇹",
["flag_ms"] = "🇲🇸",
["camera_with_flash"] = "📸",
["mind_blown"] = "🤯",
["hot_pepper"] = "🌶️",
["family_wwbb"] = "👩👩👦👦",
["martial_arts_uniform"] = "🥋",
["umbrella_on_ground"] = "⛱️",
["innocent"] = "😇",
["japanese_monthly_amount_button"] = "🈷️",
["flag_mo"] = "🇲🇴",
["flag_vc"] = "🇻🇨",
["thumbsdown"] = "👎",
["clock7"] = "🕖",
["eye"] = "👁️",
["man_facepalm"] = "🤦♂️",
["first_quarter_moon_with_face"] = "🌛",
["zap"] = "⚡",
["rose"] = "🌹",
["boom"] = "💥",
["flag_ba"] = "🇧🇦",
["flag_mk"] = "🇲🇰",
["man_guard"] = "💂♂️",
["wavy_dash"] = "〰️",
["flag_mh"] = "🇲🇭",
["star_and_crescent"] = "☪️",
["abc"] = "🔤",
["flag_mg"] = "🇲🇬",
["flag_mf"] = "🇲🇫",
["flag_mc"] = "🇲🇨",
["flag_ma"] = "🇲🇦",
["books"] = "📚",
["green_heart"] = "💚",
["hankey"] = "💩",
["flag_lv"] = "🇱🇻",
["waning_gibbious_moon"] = "🌖",
["flag_lu"] = "🇱🇺",
["flag_lt"] = "🇱🇹",
["black_nib"] = "✒️",
["bulb"] = "💡",
["leo"] = "♌",
["flag_lr"] = "🇱🇷",
["kayak"] = "🛶",
["map"] = "🗺️",
["goat"] = "🐐",
["flag_kz"] = "🇰🇿",
["flag_ky"] = "🇰🇾",
["shooting_star"] = "🌠",
["japanese_castle"] = "🏯",
["fencing"] = "🤺",
["boxing_glove"] = "🥊",
["violin"] = "🎻",
["woman_cartwheeling"] = "🤸♀️",
["flag_bd"] = "🇧🇩",
["postbox"] = "📮",
["envelope"] = "✉️",
["flag_ki"] = "🇰🇮",
["closed_umbrella"] = "🌂",
["kiwi"] = "🥝",
["flag_kg"] = "🇰🇬",
["curry"] = "🍛",
["sunrise_over_mountains"] = "🌄",
["clock830"] = "🕣",
["flag_ye"] = "🇾🇪",
["flag_dj"] = "🇩🇯",
["flag_it"] = "🇮🇹",
["woman_wearing_turban"] = "👳♀️",
["flag_is"] = "🇮🇸",
["arrows_cw"] = "🔃",
["crossed_swords"] = "⚔️",
["flag_ir"] = "🇮🇷",
["woman_frowning"] = "🙍♀️",
["deciduous_tree"] = "🌳",
["flag_iq"] = "🇮🇶",
["flag_io"] = "🇮🇴",
["children_crossing"] = "🚸",
["flag_in"] = "🇮🇳",
["man_astronaut"] = "👨🚀",
["flag_im"] = "🇮🇲",
["flag_il"] = "🇮🇱",
["cyclone"] = "🌀",
["joy"] = "😂",
["money_with_wings"] = "💸",
["french_flag"] = "🏳️",
["flag_ne"] = "🇳🇪",
["bicyclist"] = "🚴",
["waxing_crescent_moon"] = "🌒",
["flag_hu"] = "🇭🇺",
["flag_mn"] = "🇲🇳",
["derelict_house"] = "🏚️",
["flag_hm"] = "🇭🇲",
["flag_hk"] = "🇭🇰",
["flag_gy"] = "🇬🇾",
["man"] = "👨",
["red_triangle_down"] = "🔻",
["whale"] = "🐳",
["taxi"] = "🚕",
["family_mwbb"] = "👨👩👦👦",
["ambulance"] = "🚑",
["flag_gs"] = "🇬🇸",
["flag_gr"] = "🇬🇷",
["raised_back_of_hand"] = "🤚",
["flag_gp"] = "🇬🇵",
["flag_gn"] = "🇬🇳",
["flag_sl"] = "🇸🇱",
["speaking_head_in_silhouette"] = "🗣️",
["turtle"] = "🐢",
["woman_biking"] = "🚴♀️",
["hash"] = "#️⃣",
["table_tennis"] = "🏓",
["man_frowning"] = "🙍♂️",
["microphone"] = "🎤",
["tm"] = "™️",
["family_mg"] = "👨👧",
["incoming_envelope"] = "📨",
["flag_gi"] = "🇬🇮",
["man_vampire"] = "🧛♂️",
["flag_gg"] = "🇬🇬",
["metro"] = "🚇",
["new_moon"] = "🌑",
["flag_pm"] = "🇵🇲",
["flag_gb"] = "🇬🇧",
["beach"] = "🏖️",
["flag_fr"] = "🇫🇷",
["flag_fo"] = "🇫🇴",
["flag_fm"] = "🇫🇲",
["mens"] = "🚹",
["flashlight"] = "🔦",
["christmas_tree"] = "🎄",
["flag_ci"] = "🇨🇮",
["flag_er"] = "🇪🇷",
["flag_ea"] = "🇪🇦",
["flag_dz"] = "🇩🇿",
["yum"] = "😋",
["hourglass"] = "⌛",
["non_potable_water"] = "🚱",
["flag_dk"] = "🇩🇰",
["flag_je"] = "🇯🇪",
["flag_cw"] = "🇨🇼",
["clock3"] = "🕒",
["flag_dg"] = "🇩🇬",
["rugby_football"] = "🏉",
["couch_and_lamp"] = "🛋️",
["nose"] = "👃",
["flag_de"] = "🇩🇪",
["football"] = "🏈",
["pushpin"] = "📌",
["flag_ad"] = "🇦🇩",
["flag_cy"] = "🇨🇾",
["owl"] = "🦉",
["flag_cv"] = "🇨🇻",
["flag_cu"] = "🇨🇺",
["clubs"] = "♣️",
["left_fist"] = "🤛",
["flag_cp"] = "🇨🇵",
["flag_co"] = "🇨🇴",
["minidisc"] = "💽",
["white_sun_cloud"] = "🌥️",
["cupid"] = "💘",
["flag_cm"] = "🇨🇲",
["medal"] = "🏅",
["flag_cl"] = "🇨🇱",
["bamboo"] = "🎍",
["sparkler"] = "🎇",
["men_bunny_ears"] = "👯♂️",
["icecream"] = "🍦",
["squared_cross_mark"] = "❎",
["coat"] = "🧥",
["trolleybus"] = "🚎",
["sleepy"] = "😪",
["synagogue"] = "🕍",
["flag_ck"] = "🇨🇰",
["flag_es"] = "🇪🇸",
["smirk_cat"] = "😼",
["heavy_heart_excalamation"] = "❣️",
["japanese_not_free_of_charge_button"] = "🈶",
["flag_cg"] = "🇨🇬",
["sparkle"] = "❇️",
["cookie"] = "🍪",
["flag_cf"] = "🇨🇫",
["flag_cd"] = "🇨🇩",
["stuck_out_tongue_closed_eyes"] = "😝",
["flag_cc"] = "🇨🇨",
["flag_ca"] = "🇨🇦",
["cheese_wedge"] = "🧀",
["hatched_chick"] = "🐥",
["family_wb"] = "👩👦",
["smirk"] = "😏",
["handshake"] = "🤝",
["flag_bw"] = "🇧🇼",
["flag_bv"] = "🇧🇻",
["woman_surfing"] = "🏄♀️",
["handbag"] = "👜",
["thumbsup"] = "👍",
["flag_bq"] = "🇧🇶",
["star"] = "⭐",
["bomb"] = "💣",
["flag_sv"] = "🇸🇻",
["grey_question"] = "❔",
["man_juggling"] = "🤹♂️",
["flag_bm"] = "🇧🇲",
["hockey"] = "🏒",
["runner"] = "🏃",
["cherry_blossom"] = "🌸",
["leaves"] = "🍃",
["straight_ruler"] = "📏",
["flag_bj"] = "🇧🇯",
["horizontal_traffic_light"] = "🚥",
["angel"] = "👼",
["u5408"] = "🈴",
["satellite"] = "🛰️",
["confounding"] = "😖",
["flag_bg"] = "🇧🇬",
["u6709"] = "🈶",
["flag_vg"] = "🇻🇬",
["man_walking"] = "🚶♂️",
["flag_ml"] = "🇲🇱",
["tiger2"] = "🐅",
["lifter"] = "🏋️",
["cloud_with_tornado"] = "🌪️",
["crescent_moon"] = "🌙",
["flag_aw"] = "🇦🇼",
["stop_button"] = "⏹️",
["flag_as"] = "🇦🇸",
["man_bouncing_ball"] = "⛹️♂️",
["female"] = "♀️",
["ice_skate"] = "⛸️",
["nut_and_bolt"] = "🔩",
["foggy"] = "🌁",
["flag_ar"] = "🇦🇷",
["white_flower"] = "💮",
["man_water_polo"] = "🤽♂️",
["cat2"] = "🐈",
["art"] = "🎨",
["checkered_flag"] = "🏁",
["flag_ao"] = "🇦🇴",
["flag_am"] = "🇦🇲",
["flag_al"] = "🇦🇱",
["family_wwgg"] = "👩👩👧👧",
["flag_ai"] = "🇦🇮",
["red_triangle_up"] = "🔺",
["grimacing"] = "😬",
["radioactive"] = "☢️",
["imp"] = "👿",
["video_game"] = "🎮",
["flag_cz"] = "🇨🇿",
["registered"] = "®️",
["octagonal_sign"] = "🛑",
["motorboat"] = "🛥️",
["stop_sign"] = "🛑",
["stuffed_pita"] = "🥙",
["eject_button"] = "⏏️",
["speech_bubble_left"] = "🗨️",
["clock1130"] = "🕦",
["snowman2"] = "☃️",
["man_haircut"] = "💇♂️",
["clock1030"] = "🕥",
["clock930"] = "🕤",
["flag_ke"] = "🇰🇪",
["rice_cracker"] = "🍘",
["urn"] = "⚱️",
["clock530"] = "🕠",
["recycle"] = "♻️",
["clock430"] = "🕟",
["prince"] = "🤴",
["fire"] = "🔥",
["newspaper"] = "📰",
["candy"] = "🍬",
["flag_mm"] = "🇲🇲",
["clock5"] = "🕔",
["sob"] = "😭",
["book"] = "📖",
["eight_pointed_black_star"] = "✴️",
["phone"] = "📱",
["hotsprings"] = "♨️",
["u7121"] = "🈚",
["earth_africa"] = "🌍",
["japanese_discount_button"] = "🈹",
["anger_bubble"] = "🗯️",
["tomato"] = "🍅",
["woman_facepalm"] = "🤦♀️",
["flower_playing_cards"] = "🎴",
["diamonds"] = "♦️",
["flag_rs"] = "🇷🇸",
["locked"] = "🔒",
["page_facing_up"] = "📄",
["neutral_face"] = "😐",
["last_button"] = "⏮️",
["frog"] = "🐸",
["bell"] = "🔔",
["megaphone"] = "📣",
["paintbrush"] = "🖌️",
["mute"] = "🔇",
["oncoming_police_car"] = "🚔",
["loud_sound"] = "🔊",
["timer_clock"] = "⏲️",
["city_dusk"] = "🌆",
["repeat"] = "🔁",
["speaker"] = "🔈",
["raised_hand_with_fingers_splayed"] = "🖐️",
["cloud_snmow"] = "🌨️",
["black_square_button"] = "🔲",
["waning_crescent_moon"] = "🌘",
["medium_small_black_square"] = "◾",
["medium_black_square"] = "◼️",
["light_rail"] = "🚈",
["wind_chime"] = "🎐",
["small_black_square"] = "▪️",
["arrow_up_down"] = "↕️",
["face_palm"] = "🤦",
["large_orange_diamond"] = "🔶",
["small_blue_diamond"] = "🔹",
["blue_circle"] = "🔵",
["radio_button"] = "🔘",
["ballot_box_check_with_check"] = "☑️",
["soon"] = "🔜",
["family_wbb"] = "👩👦👦",
["white_sun_raid_cloud"] = "🌦️",
["railroad_track"] = "🛤️",
["capital_abcd"] = "🔠",
["on"] = "🔛",
["stuck_out_tongue"] = "😛",
["vhs"] = "📼",
["woman_mage"] = "🧙♀️",
["woman_scientist"] = "👩🔬",
["end"] = "🔚",
["fork_and_knife_with_plate"] = "🍽️",
["flag_ac"] = "🇦🇨",
["copyright"] = "©️",
["taurus"] = "♉",
["menorah"] = "🕎",
["arrows_ccw"] = "🔄",
["mother_christmas"] = "🤶",
["multiplication_sign"] = "✖️",
["division_sign"] = "➗",
["minus_sign"] = "➖",
["skull_and_crossbones"] = "☠️",
["man_zombie"] = "🧟♂️",
["arrow_down_right"] = "↘️",
["man_pilot"] = "👨✈️",
["loop"] = "➰",
["musical_notes"] = "🎶",
["lion_face"] = "🦁",
["open_mouth"] = "😮",
["notes"] = "🎶",
["abcd"] = "🔡",
["thunder_cloud_rain"] = "⛈️",
["handball"] = "🤾",
["articulated_lorry"] = "🚛",
["flag_np"] = "🇳🇵",
["octothorpe"] = "#️⃣",
["water_polo"] = "🤽",
["cold_sweat"] = "😰",
["flag_gl"] = "🇬🇱",
["arrow_curve_up"] = "⤴️",
["page_with_curl"] = "📃",
["arrow_hook_right"] = "↪️",
["currency_exchange"] = "💱",
["raised_eyebrow"] = "🤨",
["sun_with_face"] = "🌞",
["large_blue_diamond"] = "🔷",
["arrow_up_left"] = "↖️",
["ant"] = "🐜",
["checkmark"] = "✔️",
["japanese_no_vacancy_button"] = "🈵",
["police_car"] = "🚓",
["arrow_down"] = "⬇️",
["woman_with_headscarf"] = "🧕",
["hear_no_evil"] = "🙉",
["game_die"] = "🎲",
["flag_ae"] = "🇦🇪",
["flag_by"] = "🇧🇾",
["unicorn_face"] = "🦄",
["downwards_button"] = "🔽",
["reverse_button"] = "◀️",
["upwards_button"] = "🔼",
["left_button"] = "◀️",
["shaved_ice"] = "🍧",
["tulip"] = "🌷",
["repeat_once"] = "🔂",
["clock630"] = "🕡",
["rewind"] = "⏪",
["woman_mechanic"] = "👩🔧",
["fast_forward"] = "⏩",
["no_bell"] = "🔕",
["next_button"] = "⏭️",
["u5272"] = "🈹",
["stuffed_flatbread"] = "🥙",
["flag_at"] = "🇦🇹",
["play_pause"] = "⏯️",
["pause_button"] = "⏸️",
["men_wrestling"] = "🤼♂️",
["koko"] = "🈁",
["put_litter_in_bin"] = "🚮",
["no_good"] = "🙅",
["flag_tz"] = "🇹🇿",
["levitate"] = "🕴️",
["earth_asia"] = "🌏",
["baby_symbol"] = "🚼",
["flag_fj"] = "🇫🇯",
["person_frowning"] = "🙍",
["flag_un"] = "🇺🇳",
["hedgehog"] = "🦔",
["flag_br"] = "🇧🇷",
["japanese_goblin"] = "👺",
["customs"] = "🛃",
["passport_control"] = "🛂",
["ballpoint_pen"] = "🖊️",
["evergreen_tree"] = "🌲",
["heart_pulse"] = "💗",
["scarf"] = "🧣",
["facepalm"] = "🤦",
["koala"] = "🐨",
["desert"] = "🏜️",
["face_with_thermometer"] = "🤒",
["man_tipping_hand"] = "💁♂️",
["double_loop"] = "➿",
["clamp"] = "🗜️",
["pig_nose"] = "🐽",
["wink"] = "😉",
["flag_ie"] = "🇮🇪",
["diamond_with_dot"] = "💠",
["hot_dog"] = "🌭",
["mailbox"] = "📫",
["ramen"] = "🍜",
["squared_check_mark"] = "✅",
["eight_spoked_asterisk"] = "✳️",
["japanese_reserved_button"] = "🈯",
["microphone2"] = "🎙️",
["motor_scooter"] = "🛵",
["writing_hand"] = "✍️",
["watch"] = "⌚",
["notebook"] = "📓",
["trident"] = "🔱",
["woman_elf"] = "🧝♀️",
["fairy"] = "🧚",
["ticket"] = "🎫",
["flag_pn"] = "🇵🇳",
["ping_pong"] = "🏓",
["kiwifruit"] = "🥝",
["dim"] = "🔅",
["poo"] = "💩",
["flag_fi"] = "🇫🇮",
["cooking"] = "🍳",
["flag_zm"] = "🇿🇲",
["flag_tc"] = "🇹🇨",
["goal"] = "🥅",
["thinking"] = "🤔",
["ship"] = "🚢",
["pretzel"] = "🥨",
["horse_racing"] = "🏇",
["city_sunset"] = "🌇",
["family_mmbb"] = "👨👨👦👦",
["cricket_bat_ball"] = "🏏",
["exclamantion"] = "❗",
["no_mobile_phones"] = "📵",
["headphones"] = "🎧",
["flag_do"] = "🇩🇴",
["no_bicycles"] = "🚳",
["ophiucus"] = "⛎",
["do_not_litter"] = "🚯",
["bouquet"] = "💐",
["mountain_railway"] = "🚞",
["anger_symbol"] = "💢",
["older_man"] = "👴",
["thermometer"] = "🌡️",
["x"] = "❌",
["microscope"] = "🔬",
["card_index"] = "📇",
["wheelchair"] = "♿",
["no_entry"] = "⛔",
["u7981"] = "🈲",
["field_hockey"] = "🏑",
["u6e80"] = "🈵",
["arrow_up_right"] = "↗️",
["medical_symbol"] = "⚕️",
["palms_up"] = "🤲",
["computer_mouse"] = "🖱️",
["congratulations"] = "㊗️",
["japanese_bargain_button"] = "🉐",
["ideograph_advantage"] = "🉐",
["flag_aq"] = "🇦🇶",
["zipper_mouth"] = "🤐",
["man_surfing"] = "🏄♂️",
["potato"] = "🥔",
["feet"] = "🐾",
["gemini"] = "♊",
["ring"] = "💍",
["japanese_open_for_business_button"] = "🈺",
["smiling_imp"] = "😈",
["aries"] = "♈",
["u7533"] = "🈸",
["boar"] = "🐗",
["telephone_receiver"] = "📞",
["telescope"] = "🔭",
["train2"] = "🚆",
["japanese_application_button"] = "🈸",
["clock1"] = "🕐",
["flag_bf"] = "🇧🇫",
["flag_uv"] = "🇺🇾",
["mobile_phone_off"] = "📴",
["virgo"] = "♍",
["canned_food"] = "🥫",
["flag_ag"] = "🇦🇬",
["record_button"] = "⏺️",
["gloves"] = "🧤",
["slight_frown"] = "🙁",
["speech_bubble"] = "💬",
["shushing_face"] = "🤫",
["u7a7a"] = "🈳",
["capricorn"] = "♑",
["punch"] = "👊",
["dividers"] = "🗂️",
["relieved"] = "😌",
["sagittarius"] = "♐",
["bookmark"] = "🔖",
["cloud_with_rain"] = "🌧️",
["bacon"] = "🥓",
["love_you_gesture"] = "🤟",
["libra"] = "♎",
["snail"] = "🐌",
["cancer"] = "♋",
["cow"] = "🐮",
["place_of_worship"] = "🛐",
["yin_yang"] = "☯️",
["pear"] = "🍐",
["om_symbol"] = "🕉️",
["motorway"] = "🛣️",
["fire_engine"] = "🚒",
["balloon"] = "🎈",
["open_hands"] = "👐",
["heart_decoration"] = "💟",
["zipper_mouth_face"] = "🤐",
["flag_cn"] = "🇨🇳",
["cop"] = "👮",
["tophat"] = "🎩",
["snowboarder"] = "🏂",
["sparkling_heart"] = "💖",
["revolving_hearts"] = "💞",
["tent"] = "⛺",
["crown"] = "👑",
["shopping_bags"] = "🛍️",
["man_factory_worker"] = "👨🏭",
["blue_heart"] = "💙",
["yellow_heart"] = "💛",
["squid"] = "🦑",
["arrow_right"] = "➡️",
["baby"] = "👶",
["magnifying_glass_right"] = "🔎",
["kimono"] = "👘",
["flag_az"] = "🇦🇿",
["pen"] = "🖊️",
["double_exclamation"] = "‼️",
["unlocked"] = "🔓",
["red_dragon"] = "🀄",
["joy_cat"] = "😹",
["lock_with_key"] = "🔐",
["round_pushpin"] = "📍",
["flag_sy"] = "🇸🇾",
["joystick"] = "🕹️",
["clock8"] = "🕗",
["link"] = "🔗",
["spiral_notepad"] = "🗒️",
["card_file_box"] = "🗃️",
["blue_book"] = "📘",
["mermaid"] = "🧜♀️",
["green_book"] = "📗",
["japanese_passing_grade_button"] = "🈴",
["rolled_up_newspaper"] = "🗞️",
["santa"] = "🎅",
["clock9"] = "🕘",
["coffin"] = "⚰️",
["card_index_dividers"] = "🗂️",
["file_folder"] = "📁",
["first_quarter_moon"] = "🌓",
["footprints"] = "👣",
["orange_book"] = "📙",
["man_gesturing_no"] = "🙅♂️",
["dumpling"] = "🥟",
["airplane_departure"] = "🛫",
["wilted_rose"] = "🥀",
["flag_nf"] = "🇳🇫",
["tear_off_calendar"] = "📆",
["calendar"] = "📅",
["right_fist"] = "🤜",
["joker"] = "🃏",
["chart_decreasing"] = "📉",
["moneybag"] = "💰",
["arrow_hook_left"] = "↩️",
["outbox_tray"] = "📤",
["fuel_pump"] = "⛽",
["credit_card"] = "💳",
["package"] = "📦",
["email"] = "📧",
["avocado"] = "🥑",
["shrimp"] = "🦐",
["envelope_with_arrow"] = "📩",
["surfer"] = "🏄",
["fingers_crossed"] = "🤞",
["crossed_flags"] = "🎌",
["ski"] = "🎿",
["thermometer_face"] = "🤒",
["linked_paperclips"] = "🖇️",
["battery"] = "🔋",
["family_wg"] = "👩👧",
["flame"] = "🔥",
["man_mage"] = "🧙♂️",
["person_with_pouting_face"] = "🙎",
["mountain"] = "⛰️",
["sweat_smile"] = "😅",
["scorpion"] = "🦂",
["tropical_fish"] = "🐠",
["flag_va"] = "🇻🇦",
["gift"] = "🎁",
["robot"] = "🤖",
["ribbon"] = "🎀",
["man_mechanic"] = "👨🔧",
["streamers"] = "🎏",
["flag_sx"] = "🇸🇽",
["blowfish"] = "🐡",
["boxing"] = "🥊",
["woman_raising_hand"] = "🙋♀️",
["necktie"] = "👔",
["call_me"] = "🤙",
["skull_crossbones"] = "☠️",
["heart_eyes_cat"] = "😻",
["warning"] = "⚠️",
["beach_umbrella"] = "⛱️",
["child"] = "🧒",
["frowning"] = "☹️",
["thunder_cloud_and_rain"] = "⛈️",
["world_map"] = "🗺️",
["pick"] = "⛏️",
["flag_pg"] = "🇵🇬",
["bullseye"] = "🎯",
["bellhop"] = "🛎️",
["vs"] = "🆚",
["dice"] = "🎲",
["fire_truck"] = "🚒",
["clapper"] = "🎬",
["mantelpiece_clock"] = "🕰️",
["lemon"] = "🍋",
["racing_motorcycle"] = "🏍️",
["couch"] = "🛋️",
["genie"] = "🧞",
["man_elf"] = "🧝♂️",
["no_pedestrians"] = "🚷",
["speedboat"] = "🚤",
["blue_car"] = "🚙",
["bathtub"] = "🛁",
["toilet"] = "🚽",
["flag_bs"] = "🇧🇸",
["label"] = "🏷️",
["woman_mountain_biking"] = "🚵♀️",
["tractor"] = "🚜",
["prohibited"] = "🚫",
["alembic"] = "⚗️",
["woman_swimming"] = "🏊♀️",
["left_luggage"] = "🛅",
["prayer_beads"] = "📿",
["construction_worker"] = "👷",
["man_massage"] = "💆♂️",
["walking"] = "🚶",
["man_singer"] = "👨🎤",
["milky_way"] = "🌌",
["flag_bh"] = "🇧🇭",
["guardsman"] = "💂",
["crying_cat_face"] = "😿",
["rolling_eyes"] = "🙄",
["man_wearing_turban"] = "👳♂️",
["camel"] = "🐫",
["monkey_face"] = "🐵",
["dagger"] = "🗡️",
["orange_heart"] = "🧡",
["harvest_moon"] = "🎑",
["flag_bz"] = "🇧🇿",
["golfer"] = "🏌️",
["8ball"] = "🎱",
["building_construction"] = "🏗️",
["juggling"] = "🤹",
["family_mmgb"] = "👨👨👧👦",
["man_rowing"] = "🚣♂️",
["file_cabinet"] = "🗄️",
["gear"] = "⚙️",
["abandoned_house"] = "🏚️",
["blond_woman"] = "👱♀️",
["tools"] = "🛠️",
["fountain_pen"] = "🖋️",
["shuffle_button"] = "🔀",
["family_wwg"] = "👩👩👧",
["hammer"] = "🔨",
["bento"] = "🍱",
["wrench"] = "🔧",
["bar_chart"] = "📊",
["euro"] = "💶",
["rage"] = "😡",
["yen"] = "💴",
["dollar"] = "💵",
["tired_face"] = "😫",
["triumph"] = "😤",
["haircut"] = "💇",
["izakaya_lantern"] = "🏮",
["flag_sh"] = "🇸🇭",
["flying_saucer"] = "🛸",
["rabbit2"] = "🐇",
["full_moon_with_face"] = "🌝",
["pouting_cat"] = "😾",
["dark_sunglasses"] = "🕶️",
["disappointed_relieved"] = "😥",
["spoon"] = "🥄",
["boot"] = "👢",
["face_with_hand_over_mouth"] = "🤭",
["point_up_2"] = "👆",
["sa"] = "🈂️",
["sweet_potato"] = "🍠",
["man_construction_worker"] = "👷♂️",
["fish_cake"] = "🍥",
["sneeze"] = "🤧",
["flag_kw"] = "🇰🇼",
["traffic_light"] = "🚦",
["partly_sunny"] = "⛅",
["woman_juggling"] = "🤹♀️",
["electric_plug"] = "🔌",
["green_apple"] = "🍏",
["nail_care"] = "💅",
["eyeglasses"] = "👓",
["flag_no"] = "🇳🇴",
["man_cook"] = "👨🍳",
["potable_water"] = "🚰",
["baseball"] = "⚾",
["family_wwgb"] = "👩👩👧👦",
["gun"] = "🔫",
["broken_heart"] = "💔",
["woman_farmer"] = "👩🌾",
["blond_man"] = "👱♂️",
["crystal_ball"] = "🔮",
["ruler"] = "📏",
["tv"] = "📺",
["bearded_person"] = "🧔",
["alien"] = "👽",
["shamrock"] = "☘️",
["woman_office_worker"] = "👩💼",
["alarm_clock"] = "⏰",
["movie_camera"] = "🎥",
["money_mouth"] = "🤑",
["flag_pr"] = "🇵🇷",
["shaking_hands"] = "🤝",
["flag_bn"] = "🇧🇳",
["dvd"] = "📀",
["bus_stop"] = "🚏",
["cloud_tornado"] = "🌪️",
["family_mgb"] = "👨👧👦",
["fast_up_button"] = "⏫",
["cricket"] = "🏏",
["cd"] = "💿",
["flag_gw"] = "🇬🇼",
["trackball"] = "🖲️",
["desert_island"] = "🏝️",
["popcorn"] = "🍿",
["printer"] = "🖨️",
["flag_st"] = "🇸🇹",
["man_in_lotus_position"] = "🧘♂️",
["flag_bl"] = "🇧🇱",
["red_car"] = "🚗",
["scooter"] = "🛴",
["man_with_turban"] = "👳",
["suspension_railway"] = "🚟",
["shinto_shrine"] = "⛩️",
["kaaba"] = "🕋",
["point_right"] = "👉",
["office"] = "🏢",
["pouch"] = "👝",
["flag_hn"] = "🇭🇳",
["no_mouth"] = "😶",
["nauseated_face"] = "🤢",
["mushroom"] = "🍄",
["woman_walking"] = "🚶♀️",
["house"] = "🏠",
["statue_of_liberty"] = "🗽",
["family"] = "👪",
["stadium"] = "🏟️",
["elf"] = "🧝",
["rainbow"] = "🌈",
["fireworks"] = "🎆",
["dress"] = "👗",
["cloud_with_snow"] = "🌨️",
["lying_face"] = "🤥",
["beach_with_umbrella"] = "🏖️",
["turkey"] = "🦃",
["sunrise"] = "🌅",
["grandma"] = "👵",
["sparkles"] = "✨",
["om"] = "🕉️",
["white_sun_with_small_cloud"] = "🌤️",
["green_salad"] = "🥗",
["right_facing_fist"] = "🤜",
["thumbup"] = "👍",
["second_place"] = "🥈",
["1234"] = "🔢",
["stew"] = "🍲",
["snow_capped_mountain"] = "🏔️",
["speak_no_evil"] = "🙊",
["wind_blowing_face"] = "🌬️",
["scorpio"] = "♏",
["ferris_wheel"] = "🎡",
["flag_bi"] = "🇧🇮",
["flag_sz"] = "🇸🇿",
["man_climbing"] = "🧗♂️",
["fox_face"] = "🦊",
["oil_drum"] = "🛢️",
["smiley_cat"] = "😺",
["rowboat"] = "🚣",
["scales"] = "⚖️",
["monkey"] = "🐒",
["passenger_ship"] = "🛳️",
["dollar_sign"] = "💲",
["mage"] = "🧙",
["cowboy"] = "🤠",
["girl"] = "👧",
["meat_on_bone"] = "🍖",
["shirt"] = "👕",
["worship_symbol"] = "🛐",
["dancers"] = "👯",
["watermelon"] = "🍉",
["cow2"] = "🐄",
["arrow_left"] = "⬅️",
["clipboard"] = "📋",
["tram"] = "🚊",
["woman_technologist"] = "👩💻",
["flag_ug"] = "🇺🇬",
["bikini"] = "👙",
["baggage_claim"] = "🛄",
["steam_locomotive"] = "🚂",
["person_with_blonde_hair"] = "👱",
["woman_shrug"] = "🤷♀️",
["oncoming_car"] = "🚗",
["cry"] = "😢",
["small_white_square"] = "▫️",
["pray"] = "🙏",
["railway_car"] = "🚃",
["point_left"] = "👈",
["duck"] = "🦆",
["ocean"] = "🌊",
["weight_lifter"] = "🏋️",
["flag_kn"] = "🇰🇳",
["mans_shoe"] = "👞",
["clap"] = "👏",
["sandwich"] = "🥪",
["rocket"] = "🚀",
["rice_ball"] = "🍙",
["ok_woman"] = "🙆",
["woman_climbing"] = "🧗♀️",
["man_student"] = "👨🎓",
["bread"] = "🍞",
["disappointed"] = "😞",
["merperson"] = "🧜",
["woman_handball"] = "🤾♀️",
["hamster"] = "🐹",
["woman_health_worker"] = "👩⚕️",
["man_gesturing_ok"] = "🙆♂️",
["mrs_claus"] = "🤶",
["lollipop"] = "🍭",
["women_wrestling"] = "🤼♀️",
["woman_fairy"] = "🧚♀️",
["man_biking"] = "🚴♂️",
["juggler"] = "🤹",
["flag_kh"] = "🇰🇭",
["u55b6"] = "🈺",
["tennis"] = "🎾",
["man_golfing"] = "🏌️♂️",
["third_place_medal"] = "🥉",
["clock2"] = "🕑",
["nerd_face"] = "🤓",
["laughing"] = "😆",
["first_place_medal"] = "🥇",
["family_mwg"] = "👨👩👧",
["comet"] = "☄️",
["sick"] = "🤢",
["grey_exclamation"] = "❕",
["rat"] = "🐀",
["penguin"] = "🐧",
["woman_water_polo"] = "🤽♀️",
["helmet_with_white_cross"] = "⛑️",
["adult"] = "🧑",
["space_invader"] = "👾",
["male"] = "♂️",
["last_quarter_moon_with_faces"] = "🌜",
["man_with_gua_pi_mao"] = "👲",
["performing_arts"] = "🎭",
["archery"] = "🏹",
["rosette"] = "🏵️",
["family_mwgb"] = "👨👩👧👦",
["woman_pouting"] = "🙎♀️",
["pudding"] = "🍮",
["bicycle"] = "🚲",
["earth_americas"] = "🌎",
["flag_tt"] = "🇹🇹",
["person_with_ball"] = "⛹️",
["swimmer"] = "🏊",
["sailboat"] = "⛵",
["vampire"] = "🧛",
["beetle"] = "🐞",
["flag_gq"] = "🇬🇶",
["selfie"] = "🤳",
["bow_and_arrow"] = "🏹",
["running_shirt_with_sash"] = "🎽",
["japanese_prohibited_button"] = "🈲",
["badminton"] = "🏸",
["golf"] = "⛳",
["smile_cat"] = "😸",
["woman_rowing"] = "🚣♀️",
["glass_of_milk"] = "🥛",
["film_frames"] = "🎞️",
["smile"] = "😄",
["oden"] = "🍢",
["sheep"] = "🐑",
["man_teacher"] = "👨🏫",
["woman_cop"] = "👮♀️",
["palm_tre"] = "🌴",
["lion"] = "🦁",
["umbrella"] = "☔",
["sign_of_the_horns"] = "🤘",
["house_with_garden"] = "🏡",
["head_bandage"] = "🤕",
["clock10"] = "🕙",
["cloud_lightning"] = "🌩️",
["flag_mq"] = "🇲🇶",
["exclamation_question"] = "⁉️",
["restroom"] = "🚻",
["lock"] = "🔒",
["bus"] = "🚌"
}
|
---------------------------------------------------------------------------------------------------
-- Issue: https://github.com/SmartDeviceLink/sdl_core/issues/2803
---------------------------------------------------------------------------------------------------
-- Description: Check that SDL is able to resume HMI level of application after unexpected disconnect
--
-- Steps:
-- 1. App_1 is registered and activated (FULL level)
-- 2. IGN_OFF/IGN_ON cycle is performed
-- 3. Wait 35 sec
-- 4. App_1 is registered
-- SDL does:
-- - not resume HMI level App_1
-- 5. App_2 is registered and activated (FULL level)
-- 6. Unexpected disconnect and reconnect are performed
-- SDL does:
-- - resume HMI level of App_2
---------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local runner = require('user_modules/script_runner')
local common = require('user_modules/sequences/actions')
local utils = require("user_modules/utils")
local color = require("user_modules/consts").color
local SDL = require('SDL')
--[[ Test Configuration ]]
runner.testSettings.isSelfIncluded = false
--[[ Local Functions ]]
local function ignitionOff()
local isOnSDLCloseSent = false
common.getHMIConnection():SendNotification("BasicCommunication.OnExitAllApplications", { reason = "SUSPEND" })
common.getHMIConnection():ExpectNotification("BasicCommunication.OnSDLPersistenceComplete")
:Do(function()
common.getHMIConnection():SendNotification("BasicCommunication.OnExitAllApplications", { reason = "IGNITION_OFF" })
common.getHMIConnection():ExpectNotification("BasicCommunication.OnSDLClose")
:Do(function()
isOnSDLCloseSent = true
SDL.DeleteFile()
end)
end)
utils.wait(3000)
:Do(function()
if isOnSDLCloseSent == false then utils.cprint(color.magenta, "BC.OnSDLClose was not sent") end
for i = 1, common.mobile.getAppsCount() do
common.mobile.deleteSession(i)
end
StopSDL()
end)
end
local function unexpectedDisconnect()
common.getHMIConnection():ExpectNotification("BasicCommunication.OnAppUnregistered", { unexpectedDisconnect = true })
:Times(common.mobile.getAppsCount())
common.mobile.disconnect()
utils.wait(1000)
end
local function checkAbsenceOfHMILevelResumption(pAppId)
common.getHMIConnection():ExpectRequest("BasicCommunication.ActivateApp")
:Times(0)
common.getMobileSession(pAppId):ExpectNotification("OnHMIStatus")
:Times(0)
utils.wait(5000)
end
local function checkPresenceHMILevelResumption(pAppId)
common.getHMIConnection():ExpectRequest("BasicCommunication.ActivateApp", { appID = common.getHMIAppId(pAppId) })
:Do(function(_, data)
common.getHMIConnection():SendResponse(data.id, "BasicCommunication.ActivateApp", "SUCCESS", {})
end)
common.getMobileSession(pAppId):ExpectNotification("OnHMIStatus", { hmiLevel = "FULL" })
end
--[[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", common.preconditions)
runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start)
runner.Step("Register App 1", common.app.registerNoPTU, { 1 })
runner.Step("Activate App 1", common.activateApp, { 1 })
runner.Title("Test")
runner.Step("Ignition Off", ignitionOff)
runner.Step("Ignition On", common.start)
runner.Step("Wait 35 s", utils.wait, { 35000 })
runner.Step("Register App 1", common.app.registerNoPTU, { 1 })
runner.Step("Check No HMI level resumption", checkAbsenceOfHMILevelResumption, { 1 })
runner.Step("Register App 2", common.app.registerNoPTU, { 2 })
runner.Step("Activate App 2", common.activateApp, { 2 })
runner.Step("Unexpected disconnect", unexpectedDisconnect)
runner.Step("Connect mobile", common.mobile.connect)
runner.Step("Register App 2", common.app.registerNoPTU, { 2 })
runner.Step("Check Yes HMI level resumption", checkPresenceHMILevelResumption, { 2 })
runner.Title("Postconditions")
runner.Step("Stop SDL", common.postconditions)
|
local Tunnel = module("vrp", "lib/Tunnel")
local Proxy = module("vrp", "lib/Proxy")
vRP = Proxy.getInterface("vRP")
vRPclient = Tunnel.getInterface("vRP", "vrp_coke")
RegisterNetEvent('vrp_coke:check')
AddEventHandler('vrp_coke:check', function()
local _source = source
local user_id = vRP.getUserId({source})
local weight = vRP.getInventoryWeight({user_id})
local maxWeight = vRP.getInventoryMaxWeight({user_id})
if maxWeight <= weight then
TriggerClientEvent('mythic_notify:client:SendAlert', source, { type = 'error', text = "Du har ikke nok plads", length = '5000', style = {}})
else
TriggerClientEvent('vrp_coke:buy2', source)
end
end)
RegisterNetEvent('vrp_coke:progress')
AddEventHandler('vrp_coke:progress', function()
local _source = source
local user_id = vRP.getUserId({source})
local weed = vRP.getInventoryItemAmount({user_id, 'cokeblade'})
if weed > 0 then
TriggerClientEvent('vrp_coke:Progress', source)
else
TriggerClientEvent('mythic_notify:client:SendAlert', source, { type = 'error', text = 'Du har desværre ikke nogle blade', length = '5000', style = {}})
end
end)
RegisterNetEvent('vrp_coke:omdan')
AddEventHandler('vrp_coke:omdan', function()
local _source = source
local user_id = vRP.getUserId({source})
local weedQuantity = vRP.getInventoryItemAmount({user_id, 'cokeblade'})
if weedQuantity > 0 then
vRP.giveInventoryItem({user_id,'kokain',weedQuantity,false})
vRP.tryGetInventoryItem({user_id,'cokeblade',weedQuantity,false})
TriggerClientEvent('mythic_notify:client:SendAlert', source, { type = 'success', text = 'Du har omdannet ' .. weedQuantity .. ' Kokain Blade til', length = '5000', style = {}})
else
TriggerClientEvent('mythic_notify:client:SendAlert', source, { type = 'error', text = "Du har ingen Blade", length = '5000', style = {}})
end
end)
RegisterServerEvent('vrp_coke:buy')
AddEventHandler('vrp_coke:buy', function()
local _source = source
local user_id = vRP.getUserId({source})
local WeedPrice = 2
local money = vRP.getMoney({user_id})
local WeedQuantity = math.random(1,9)
if money > 30 then
vRP.tryPayment({user_id,WeedQuantity * WeedPrice})
vRP.giveInventoryItem({user_id,'weed',WeedQuantity, true})
TriggerClientEvent('mythic_notify:client:SendAlert', source, { type = 'Success', text = 'Du har nu købt '.. WeedQuantity .. ' blade for ' .. WeedQuantity * WeedPrice .. ' $', length = '5000', style = {}})
else
TriggerClientEvent('mythic_notify:client:SendAlert', source, { type = 'error', text = 'Du har ikke nok penge', length = '5000', style = {}})
end
end)
|
local spam = {}
local zaman = {}
local spamkapatsure = 700
function komutkullandi( commandName )
if getElementData(source, "komutkullanimikapat") == false or getElementData(source, "komutkullanimikapat") == 0 then
spam[source] = tonumber(spam[source] or 0) + 1
if spam[source] >= 9 then
local playerName = getPlayerName( source ):gsub('_', ' ')
outputChatBox('[Melancia]#D0D0D0 Bu kadar sık komut kullanımı yapmayınız.',source, 195,184,116,true)
exports.mrp_anticheat:changeProtectedElementDataEx(source, "komutkullanimikapat", true)
setElementData(source, "komutkullanimikapat", true)
cancelEvent()
end
if isTimer(zaman[source]) then
killTimer(zaman[source])
end
zaman[source] = setTimer( function (source)
spam[source] = 0
if isElement(source) and getElementData(source, "komutkullanimikapat") == true or getElementData(source, "komutkullanimikapat") then
exports.mrp_anticheat:changeProtectedElementDataEx(source, "komutkullanimikapat", false)
setElementData(source, "komutkullanimikapat", false)
end
end, spamkapatsure, 1, source)
else
cancelEvent()
end
end
addEventHandler('onPlayerCommand', root, komutkullandi)
|
require("moonsc").import_tags()
-- The child process will return success if its var1 is set to 1,
-- failure otherwise. For this test we try passing in var1 by param
-- and by namelist and check that we either get two successes or two
-- failures. This test will fail schema validation due to multiple
-- declarations of var1, but should run correctly.
local SUB1 = [[
require("moonsc").import_tags()
return _scxml{ initial="sub01",
_datamodel{ _data{ id="var1", expr="0" }},
_state{ id="sub01",
_transition{ cond="var1==1", target="subFinal1",
_send{ target="#_parent", event="success" },
},
_transition{ target="subFinal1",
_send{ target="#_parent", event="failure" },
},
},
_final{ id="subFinal1" },
}]]
local SUB2 = [[
require("moonsc").import_tags()
return _scxml{ initial="sub02",
_datamodel{ _data{ id="var1", expr="0" }},
_state{ id="sub02",
_transition{ cond="var1==1", target="subFinal2",
_send{ target="#_parent", event="success" },
},
_transition{ target="subFinal2",
_send{ target="#_parent", event="failure" },
},
},
_final{ id="subFinal2" },
}]]
local SUB3 = [[
require("moonsc").import_tags()
return _scxml{ initial="sub03",
_datamodel{ _data{ id="var1", expr="0" }},
_state{ id="sub03",
_transition{ cond="var1==1", target="subFinal3",
_send{ target="#_parent", event="success" },
},
_transition{ target="subFinal3",
_send{ target="#_parent", event="failure" },
},
},
_final{ id="subFinal3" },
}]]
return _scxml{ initial="s0",
_datamodel{ _data{ id="var1", expr="1" }},
_state{ id="s0", initial="s01",
_onentry{ _send{ event="timeout", delay="2s" }},
_transition{ event="timeout", target="fail" },
_state{ id="s01",
_invoke{ type="scxml", namelist="var1", _content{ text=SUB1 }},
_transition{ event="success", target="s02" },
_transition{ event="failure", target="s03" },
},
_state{ id="s02",
_invoke{ type="scxml", _param{ name="var1", expr="1" }, _content{ text=SUB2 }},
_transition{ event="success", target="pass" },
_transition{ event="failure", target="fail" },
},
_state{ id="s03",
_invoke{ type="scxml", _param{ name="var1", expr="1" }, _content{ text=SUB3 }},
_transition{ event="failure", target="pass" },
_transition{ event="success", target="fail" },
},
},
_final{id='pass'},
_final{id='fail'},
}
|
require("runtime-core/src/helpers/renderSlot")
require("runtime-core/src/h")
require("@vue/shared")
describe('renderSlot', function()
mockWarn()
it('should render slot', function()
local child = nil
local vnode = renderSlot({default=function()
{child = h('child')}
end
}, 'default')
expect(vnode.children):toEqual({child})
end
)
it('should render slot fallback', function()
local vnode = renderSlot({}, 'default', {}, function()
{'fallback'}
end
)
expect(vnode.children):toEqual({'fallback'})
end
)
it('should warn render ssr slot', function()
renderSlot({default=function(a, b, c)
{h('child')}
end
}, 'default')
expect('SSR-optimized slot function detected'):toHaveBeenWarned()
end
)
end
)
|
P3D = {}
P3D.BlankHeader = "P3D\255\012\000\000\000\012\000\000\000"
P3D.Identifiers = {
ATC = 0x3000602,
Anim = 0x3F0000C,
Anim_Coll = 0x3F00008,
Anim_Dyna_Phys = 0x3F0000E,
Anim_Dyna_Phys_Wrapper = 0x3F0000F,
Anim_Obj_Wrapper = 0x3F00010,
Animated_Object = 0x20001,
Animated_Object_Animation = 0x20002,
Animated_Object_Factory = 0x20000,
Animation = 0x121000,
Animation_Channel_Count = 0x121007,
Animation_Group = 0x121001,
Animation_Group_List = 0x121002,
Animation_Header = 0x121006,
Animation_Size = 0x121004,
Animation_Sync_Frame = 0x121402,
Billboard_Quad_Group = 0x17006,
Black_Magic = 0x1025,
Boolean_Channel = 0x121108,
Bounding_Box = 0x10003,
Bounding_Sphere = 0x10004,
Breakable_Object = 0x3001000,
Camera = 0x2200,
Channel_Interpolation_Mode = 0x121110,
Collision_Axis_Aligned_Bounding_Box = 0x7010006,
Collision_Cylinder = 0x7010003,
Collision_Effect = 0x3000600,
Collision_Object = 0x7010000,
Collision_Object_Attribute = 0x7010023,
Collision_Oriented_Bounding_Box = 0x7010004,
Collision_Sphere = 0x7010002,
Collision_Vector = 0x7010007,
Collision_Volume = 0x7010001,
Collision_Volume_Owner = 0x7010021,
Collision_Volume_Owner_Name = 0x7010022,
Collision_Wall = 0x7010005,
Colour_Channel = 0x121109,
Colour_List = 0x10008,
Composite_Drawable = 0x4512,
Composite_Drawable_2 = 0x123000,
Composite_Drawable_Effect = 0x4518,
Composite_Drawable_Effect_List = 0x4517,
Composite_Drawable_Primitive = 0x123001,
Composite_Drawable_Prop = 0x4516,
Composite_Drawable_Prop_List = 0x4514,
Composite_Drawable_Skin = 0x4515,
Composite_Drawable_Skin_List = 0x4513,
Composite_Drawable_Sort_Order = 0x4519,
Compressed_Quaternion_Channel = 0x121111,
Dyna_Phys = 0x3F00002,
Entity_Channel = 0x121107,
Export_Info = 0x7030,
Export_Info_Named_Integer = 0x7032,
Export_Info_Named_String = 0x7031,
Expression = 0x21000,
Expression_Group = 0x21001,
Expression_Mixer = 0x21002,
Fence = 0x3F00007,
Fence_2 = 0x3000000,
Float_1_Channel = 0x121100,
Float_2_Channel = 0x121101,
Follow_Camera_Data = 0x3000100,
Frame_Controller = 0x121201,
Frontend_Group = 0x18004,
Frontend_Image_Resource = 0x18100,
Frontend_Language = 0x1800E,
Frontend_Layer = 0x18003,
Frontend_Multi_Sprite = 0x18006,
Frontend_Multi_Text = 0x18007,
Frontend_Page = 0x18002,
Frontend_Polygon = 0x18009,
Frontend_Project = 0x18000,
Frontend_Pure3D_Object = 0x18008,
Frontend_Pure3D_Resource = 0x18101,
Frontend_Screen = 0x18001,
Frontend_String_Hard_Coded = 0x1800C,
Frontend_String_Text_Bible = 0x1800B,
Frontend_Text_Bible = 0x1800D,
Frontend_Text_Bible_Resource = 0x18105,
Frontend_Text_Style_Resource = 0x18104,
Game_Attr = 0x12000,
Game_Attribute_Integer_Parameter = 0x12001,
Grid = 0x1000,
Grid_Cell = 0x1001,
History = 0x7000,
Image = 0x19001,
Image_2 = 0x3510,
Image_Data = 0x19002,
Image_Data_2 = 0x3511,
Index_List = 0x1000A,
Inst_Particle_System = 0x3001001,
Inst_Stat_Entity = 0x3F00009,
Inst_Stat_Phys = 0x3F0000A,
Instance_List = 0x3000008,
Integer_Channel = 0x12110E,
Intersect = 0x3F00003,
Intersect_Mesh = 0x1008,
Intersect_Mesh_2 = 0x1009,
Intersection = 0x3000004,
Lens_Flare = 0x3F0000D,
Light = 0x13000,
Light_Direction = 0x13001,
Light_Group = 0x2380,
Light_Position = 0x13002,
Light_Shadow = 0x13004,
Locator = 0x3000005,
Locator_2 = 0x1003,
Locator_3 = 0x14000,
Locator_Counts = 0x1023,
Locator_Matrix = 0x300000C,
Matrix_List = 0x1000B,
Matrix_Palette = 0x1000D,
Mesh = 0x10000,
Mesh_Stats = 0x1001D,
Multi_Controller = 0x48A0,
Multi_Controller_2 = 0x121202,
Multi_Controller_Tracks = 0x48A1,
Normal_List = 0x10006,
Old_Base_Emitter = 0x15805,
Old_Billboard_Display_Info = 0x17003,
Old_Billboard_Perspective_Info = 0x17004,
Old_Billboard_Quad = 0x17001,
Old_Billboard_Quad_Group = 0x17002,
Old_Emitter_Animation = 0x15809,
Old_Expression_Offsets = 0x10018,
Old_Frame_Controller = 0x121200,
Old_Generator_Animation = 0x1580A,
Old_Offset_List = 0x1000E,
Old_Particle_Animation = 0x15808,
Old_Particle_Instancing_Info = 0x1580B,
Old_Primitive_Group = 0x10002,
Old_Scenegraph_Branch = 0x120102,
Old_Scenegraph_Drawable = 0x120107,
Old_Scenegraph_Light_Group = 0x120109,
Old_Scenegraph_Root = 0x120101,
Old_Scenegraph_Sort_Order = 0x12010A,
Old_Scenegraph_Transform = 0x120103,
Old_Scenegraph_Visibility = 0x120104,
Old_Sprite_Emitter = 0x15806,
Old_Vector_Offset_List = 0x121301,
Old_Vertex_Anim_Key_Frame = 0x121304,
Packed_Normal_List = 0x10010,
Particle_Point_Generator = 0x15B00,
Particle_System = 0x15000,
Particle_System = 0x1580C,
Particle_System_2 = 0x15801,
Particle_System_Factory = 0x15800,
Path = 0x300000B,
Ph = 0xC111,
Ph_Axis_Aligned_Bounding_Box = 0xC007,
Ph_Cylinder = 0xC004,
Ph_Inertia_Matrix = 0xC001,
Ph_Oriented_Bounding_Box = 0xC005,
Ph_Sphere = 0xC003,
Ph_Vector = 0xC010,
Ph_Volume = 0xC002,
Physics_Inertia_Matrix = 0x7011001,
Physics_Joint = 0x7011020,
Physics_Object = 0x7011000,
Physics_Vector = 0x7011002,
Position_List = 0x10005,
Primitive_Group = 0x10020,
Primitive_Group_Memory_Image_Index = 0x10013,
Primitive_Group_Memory_Image_Vertex = 0x10012,
Primitive_Group_Memory_Image_Vertex_Description = 0x10014,
Quaternion_Channel = 0x121105,
Render_Status = 0x10017,
Road = 0x3000003,
Road_2 = 0x1005,
Road_Data_Segment = 0x3000009,
Road_Segment = 0x3000002,
Root = 0xFF443350,
Scenegraph = 0x120100,
Scenegraph_Branch = 0x12010C,
Scenegraph_Drawable = 0x12010F,
Scenegraph_Root = 0x12010B,
Scenegraph_Transform = 0x12010D,
Set = 0x3000110,
Shader = 0x11000,
Shader_Colour_Parameter = 0x11005,
Shader_Float_Parameter = 0x11004,
Shader_Integer_Parameter = 0x11003,
Shader_Texture_Parameter = 0x11002,
Skeleton = 0x4500,
Skeleton_2 = 0x23000,
Skeleton_Joint = 0x4501,
Skeleton_Joint_2 = 0x23001,
Skeleton_Joint_Bone_Preserve = 0x4504,
Skeleton_Joint_Mirror_Map = 0x4503,
Skeleton_Limb = 0x23003,
Skeleton_Partition = 0x23002,
Skin = 0x10001,
Sort_Order = 0x122000,
Spline = 0x3000007,
Sprite = 0x19005,
Sprite_Particle_Emitter = 0x15900,
State_Prop_Callback_Data = 0x8020005,
State_Prop_Data_V1 = 0x8020000,
State_Prop_Event_Data = 0x8020004,
State_Prop_Frame_Controller_Data = 0x8020003,
State_Prop_State_Data_V1 = 0x8020001,
State_Prop_Visibilities_Data = 0x8020002,
Static_Entity = 0x3F00000,
Static_Phys = 0x3F00001,
Surface_Type_List = 0x300000E,
Texture = 0x19000,
Texture_2 = 0x3500,
Texture_Animation = 0x3520,
Texture_Font = 0x22000,
Texture_Glyph_List = 0x22001,
Tree = 0x3F00004,
Tree_Node = 0x3F00005,
Tree_Node_2 = 0x3F00006,
Trigger_Volume = 0x3000006,
Trigger_Volume_2 = 0x1004,
UV_List = 0x10007,
Unknown1013 = 0x1013,
Unknown1014 = 0x1014,
Unknown1021 = 0x1021,
Unknown1022 = 0x1022,
Unknown1024 = 0x1024,
Unknown121203 = 0x121203,
Unknown121204 = 0x121204,
Unknown13003 = 0x13003,
Unknown13008 = 0x13008,
Unknown15101 = 0x15101,
Unknown15102 = 0x15102,
Unknown15103 = 0x15103,
Unknown15140 = 0x15140,
Unknown15200 = 0x15200,
Unknown15210 = 0x15210,
Unknown15211 = 0x15211,
Unknown15212 = 0x15212,
Unknown15213 = 0x15213,
Unknown15214 = 0x15214,
Unknown15215 = 0x15215,
Unknown15216 = 0x15216,
Unknown15217 = 0x15217,
Unknown15218 = 0x15218,
Unknown15219 = 0x15219,
Unknown1521A = 0x1521A,
Unknown1521B = 0x1521B,
Unknown1521C = 0x1521C,
Unknown1521D = 0x1521D,
Unknown1521E = 0x1521E,
Unknown1521F = 0x1521F,
Unknown15220 = 0x15220,
Unknown15221 = 0x15221,
Unknown15222 = 0x15222,
Unknown15223 = 0x15223,
Unknown15224 = 0x15224,
Unknown15225 = 0x15225,
Unknown15226 = 0x15226,
Unknown15227 = 0x15227,
Unknown15228 = 0x15228,
Unknown15229 = 0x15229,
Unknown15400 = 0x15400,
Unknown15401 = 0x15401,
Unknown15402 = 0x15402,
Unknown15501 = 0x15501,
Unknown15502 = 0x15502,
Unknown15F00 = 0x15F00,
Unknown17000 = 0x17000,
Unknown17005 = 0x17005,
Unknown17007 = 0x17007,
Unknown17009 = 0x17009,
Unknown1700A = 0x1700A,
Unknown1700D = 0x1700D,
Unknown18102 = 0x18102,
Unknown300000A = 0x300000A,
Unknown3521 = 0x3521,
Unknown4201 = 0x4201,
Unknown4216 = 0x4216,
Unknown4290 = 0x4290,
Unknown4291 = 0x4291,
Unknown42A0 = 0x42A0,
Unknown4700 = 0x4700,
Unknown4702 = 0x4702,
Unknown4800 = 0x4800,
Unknown4801 = 0x4801,
Unknown4802 = 0x4802,
Unknown4803 = 0x4803,
Unknown4804 = 0x4804,
Unknown4805 = 0x4805,
Unknown4900 = 0x4900,
Unknown4901 = 0x4901,
Unknown4902 = 0x4902,
Unknown4903 = 0x4903,
Unknown4904 = 0x4904,
Unknown4905 = 0x4905,
Unknown4A01 = 0x4A01,
Unknown4A10 = 0x4A10,
Unknown4A11 = 0x4A11,
Unknown4A20 = 0x4A20,
Unknown4A82 = 0x4A82,
Unknown9150 = 0x9150,
Unknown_1010 = 0x1010,
Unknown_1011 = 0x1011,
Unknown_4520 = 0x4520,
Vector_1D_OF_Channel = 0x121102,
Vector_2D_OF_Channel = 0x121103,
Vector_3D_OF_Channel = 0x121104,
Vertex_Compression_Hint = 0x10021,
Vertex_Shader = 0x10011,
Weight_List = 0x1000C,
World_Sphere = 0x3F0000B,
}
local pack = string.pack
local unpack = string.unpack
local concat = table.concat
function P3D.UnpackChunkHeader(str, StartPosition)
if StartPosition == nil then StartPosition = 1 end
return unpack("<III", str, StartPosition)
end
function P3D.String1ToInt(str, StartPosition)
if StartPosition == nil then StartPosition = 1 end
return unpack("<B", str, StartPosition)
end
P3D.IntToString1 = string.char
function P3D.SetInt1(Chunk, Offset, NewValue)
return Chunk:sub(1, Offset - 1) .. P3D.IntToString1(NewValue) .. Chunk:sub(Offset + 1)
end
function P3D.String2ToInt(str, StartPosition)
if StartPosition == nil then StartPosition = 1 end
return unpack("<h", str, StartPosition)
end
function P3D.IntToString2(int)
return pack("<h", int)
end
function P3D.SetIn2(Chunk, Offset, NewValue)
return Chunk:sub(1, Offset - 1) .. P3D.IntToString2(NewValue) .. Chunk:sub(Offset + 4)
end
function P3D.String4ToInt(str, StartPosition)
if StartPosition == nil then StartPosition = 1 end
return unpack("<i", str, StartPosition)
end
function P3D.IntToString4(int)
return pack("<i", int)
end
function P3D.SetInt4(Chunk, Offset, NewValue)
return Chunk:sub(1, Offset - 1) .. P3D.IntToString4(NewValue) .. Chunk:sub(Offset + 4)
end
function P3D.AddInt4(Chunk, Offset, NewValue)
local orig = P3D.String4ToInt(Chunk, Offset)
return P3D.SetInt4(Chunk, Offset, orig + NewValue)
end
function P3D.String4ToFloat(str, StartPosition)
if StartPosition == nil then StartPosition = 1 end
return unpack("<f", str, StartPosition)
end
function P3D.FloatToString4(float)
return pack("<f", float)
end
function P3D.SetFloat(Chunk, Offset, NewValue)
return Chunk:sub(1, Offset - 1) .. P3D.FloatToString4(NewValue) .. Chunk:sub(Offset + 4)
end
function P3D.String4ToARGB(str, StartPosition)
if StartPosition == nil then StartPosition = 1 end
local B, G, R, A = unpack("<BBBB", str, StartPosition)
return A, R, G, B
end
function P3D.ARGBToString4(A, R, G, B)
return pack("<BBBB", B, G, R, A)
end
function P3D.SetARGB(Chunk, Offset, A, R, G, B)
return Chunk:sub(1, Offset - 1) .. P3D.ARGBToString4(A, R, G, B) .. Chunk:sub(Offset + 4)
end
function P3D.String8ToVector2(str, StartPosition)
if StartPosition == nil then StartPosition = 1 end
return unpack("<ff", str, StartPosition)
end
function P3D.Vector2ToString8(X, Y)
return pack("<ff", X, Y)
end
function P3D.SetVector2(Chunk, Offset, X, Y)
return Chunk:sub(1, Offset - 1) .. P3D.Vector2ToString8(X, Y) .. Chunk:sub(Offset + 8)
end
function P3D.String12ToVector3(str, StartPosition)
if StartPosition == nil then StartPosition = 1 end
return unpack("<fff", str, StartPosition)
end
function P3D.Vector3ToString12(X, Y, Z)
return pack("<fff", X, Y, Z)
end
function P3D.SetVector3(Chunk, Offset, X, Y, Z)
return Chunk:sub(1, Offset - 1) .. P3D.Vector3ToString12(X, Y, Z) .. Chunk:sub(Offset + 12)
end
function P3D.String16ToVector4(str, StartPosition)
if StartPosition == nil then StartPosition = 1 end
return unpack("<ffff", str, StartPosition)
end
function P3D.Vector4ToString16(X, Y, Z, W)
return pack("<ffff", X, Y, Z, W)
end
function P3D.SetVector4(Chunk, Offset, X, Y, Z, W)
return Chunk:sub(1, Offset - 1) .. P3D.Vector4ToString16(X, Y, Z, W) .. Chunk:sub(Offset + 16)
end
function P3D.String64ToMatrix(str, StartPosition)
if StartPosition == nil then StartPosition = 1 end
return unpack("<ffffffffffffffff", str, StartPosition)
end
function P3D.MatrixToString64(M11, M12, M13, M14, M21, M22, M23, M24, M31, M32, M33, M34, M41, M42, M43, M44)
return pack("<ffffffffffffffff", M11, M12, M13, M14, M21, M22, M23, M24, M31, M32, M33, M34, M41, M42, M43, M44)
end
function P3D.SetMatrix(Chunk, Offset, M11, M12, M13, M14, M21, M22, M23, M24, M31, M32, M33, M34, M41, M42, M43, M44)
return Chunk:sub(1, Offset - 1) .. P3D.MatrixToString64(M11, M12, M13, M14, M21, M22, M23, M24, M31, M32, M33, M34, M41, M42, M43, M44) .. Chunk:sub(Offset + 64)
end
function P3D.MatrixIdentity()
return {M11=1,M12=0,M13=0,M14=0,M21=0,M22=1,M23=0,M24=0,M31=0,M32=0,M33=1,M34=0,M41=0,M42=0,M43=0,M44=1}
end
function P3D.MatrixRotateY(Matrix, angle)
angle = math.rad(angle)
local cos = math.cos(angle)
local sin = math.sin(angle)
local x, y, z = Matrix.M41, Matrix.M42, Matrix.M43
Matric = P3D.MatrixIdentity()
Matrix.M11 = cos
Matrix.M13 = sin * -1
Matrix.M31 = sin
Matrix.M33 = cos
Matrix.M41 = x
Matrix.M42 = y
Matrix.M43 = z
end
function P3D.GetString(str, StartPosition)
if StartPosition == nil then StartPosition = 1 end
local output = unpack("<s1", str, StartPosition)
return output, output:len()
end
function P3D.SetString(Chunk, Offset, NewString)
local OrigName, OrigLen = P3D.GetString(Chunk, Offset)
local New = Chunk:sub(1, Offset - 1) .. pack("<s1", NewString) .. Chunk:sub(Offset + OrigLen + 1)
local Delta = NewString:len() - OrigLen
return New, Delta, OrigName
end
function P3D.GetFourCC(str, StartPosition)
if StartPosition == nil then StartPosition = 1 end
return unpack(str, "<c4", StartPosition)
end
function P3D.SetFourCC(Chunk, Offset, NewValue)
return Chunk:sub(1, Offset - 1) .. pack("<c4", NewValue) .. Chunk:sub(Offset + 4)
end
function P3D.RemoveString(str, Start, End)
return str:sub(1, Start - 1) .. str:sub(End)
end
function P3D.MakeFourCC(str)
str = str:sub(1, 4)
local strLen = str:len()
str = str .. string.rep("\0", 4 - strLen)
return str
end
function P3D.MakeP3DString(str)
if str == nil then return nil end
local strLen = str:len()
local diff = strLen % 4
if diff > 0 then
str = str .. string.rep("\0", 4 - diff)
end
return str
end
function P3D.CleanP3DString(str)
if str == nil then return nil end
local strLen = str:len()
if strLen == 0 then return str end
local l = str:find("\0")
if l == nil then return str end
return str:sub(1, l-1)
end
function P3D.FindSubchunks(Chunk, ID, StartPosition, EndPosition)
if StartPosition == nil then StartPosition = 1 end
if EndPosition == nil then EndPosition = Chunk:len() end
local Position = StartPosition + P3D.String4ToInt(Chunk, StartPosition + 4)
return function()
while Position < EndPosition do
local ChunkID, ChunkValueLength, ChunkLength = P3D.UnpackChunkHeader(Chunk, Position)
Position = Position + ChunkLength
if ID == nil or ChunkID == ID then
return Position - ChunkLength, ChunkLength, ChunkID
end
end
return nil
end
end
function P3D.FindSubchunk(Chunk, ID, StartPosition, EndPosition)
return P3D.FindSubchunks(Chunk, ID, StartPosition, EndPosition)()
end
-- Decompress a compressed *block* within a P3D
function P3D.DecompressBlock(Source, Length, SourceIndex)
local Written = 0
if SourceIndex == nil then SourceIndex = 1 end
local DestTbl = {}
local DestinationPos = 1
while Written < Length do
local Unknown = P3D.String1ToInt(Source, SourceIndex)
SourceIndex = SourceIndex + 1
if Unknown <= 15 then
if Unknown == 0 then
if P3D.String1ToInt(Source, SourceIndex) == 0 then
local Unknown2 = 0
repeat
SourceIndex = SourceIndex + 1
Unknown2 = P3D.String1ToInt(Source, SourceIndex)
Unknown = Unknown + 255
until Unknown2 ~= 0
end
Unknown = Unknown + P3D.String1ToInt(Source, SourceIndex)
SourceIndex = SourceIndex + 1
DestTbl[#DestTbl + 1], DestTbl[#DestTbl + 2], DestTbl[#DestTbl + 3], DestTbl[#DestTbl + 4], DestTbl[#DestTbl + 5], DestTbl[#DestTbl + 6], DestTbl[#DestTbl + 7], DestTbl[#DestTbl + 8], DestTbl[#DestTbl + 9], DestTbl[#DestTbl + 10], DestTbl[#DestTbl + 11], DestTbl[#DestTbl + 12], DestTbl[#DestTbl + 13], DestTbl[#DestTbl + 14], DestTbl[#DestTbl + 15] = unpack("<c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1", Source, SourceIndex)
DestinationPos = DestinationPos + 15
SourceIndex = SourceIndex + 15
Written = Written + 15
end
repeat
DestTbl[#DestTbl + 1] = Source:sub(SourceIndex, SourceIndex)
SourceIndex = SourceIndex + 1
DestinationPos = DestinationPos + 1
Written = Written + 1
Unknown = Unknown - 1
until Unknown <= 0
else
local Unknown2 = Unknown % 16
if Unknown2 == 0 then
local Unknown3 = 15
if P3D.String1ToInt(Source, SourceIndex) == 0 then
local Unknown4
repeat
SourceIndex = SourceIndex + 1
Unknown4 = P3D.String1ToInt(Source, SourceIndex)
Unknown3 = Unknown3 + 255
until Unknown4 ~= 0
end
Unknown2 = Unknown2 + P3D.String1ToInt(Source, SourceIndex) + Unknown3
SourceIndex = SourceIndex + 1
end
local Unknown6 = DestinationPos - (math.floor(Unknown / 16) | (16 * P3D.String1ToInt(Source, SourceIndex)))
local Unknown5 = math.floor(Unknown2 / 4)
SourceIndex = SourceIndex + 1
repeat
DestTbl[#DestTbl + 1] = DestTbl[Unknown6]
DestTbl[#DestTbl + 1] = DestTbl[Unknown6 + 1]
DestTbl[#DestTbl + 1] = DestTbl[Unknown6 + 2]
DestTbl[#DestTbl + 1] = DestTbl[Unknown6 + 3]
Unknown6 = Unknown6 + 4
DestinationPos = DestinationPos + 4
Unknown5 = Unknown5 - 1
until Unknown5 <= 0
local Unknown7 = Unknown2 % 4
while Unknown7 > 0 do
DestTbl[#DestTbl + 1] = DestTbl[Unknown6]
DestinationPos = DestinationPos + 1
Unknown6 = Unknown6 + 1
Unknown7 = Unknown7 - 1
end
Written = Written + Unknown2
end
end
return concat(DestTbl), DestinationPos
end
-- Decompress a compressed P3D, returns the original P3D if not compressed
function P3D.Decompress(File)
if File:sub(1, 4) == "P3DZ" then
local UncompressedLength = P3D.String4ToInt(File, 5)
local DecompressedLength = 0
local pos = 9
local UncompressedTbl = {}
local CompressedLength, UncompressedBlock
while DecompressedLength < UncompressedLength do
CompressedLength, UncompressedBlock, pos = unpack("<ii", File, pos)
UncompressedTbl[#UncompressedTbl + 1] = P3D.DecompressBlock(File, UncompressedBlock, pos)
pos = pos + CompressedLength
DecompressedLength = DecompressedLength + UncompressedBlock
end
return concat(UncompressedTbl)
else
return File
end
end
-- Class data start
P3D.P3DChunk = {Raw, ChunkTypes = {}, Chunks = {}}
function P3D.P3DChunk:__tostring()
return self:Output()
end
function P3D.P3DChunk:new(Data)
if Data == nil then
Data = {}
setmetatable(Data, self)
self.__index = self
return Data
end
Data.Raw = P3D.Decompress(Data.Raw)
Data.ChunkTypes = {}
Data.Chunks = {}
local ValueLen
Data.ChunkType, ValueLen = P3D.UnpackChunkHeader(Data.Raw)
if ValueLen > 12 then
Data.ValueStr = Data.Raw:sub(13, ValueLen)
else
Data.ValueStr = ""
end
local i
for ChunkPos, ChunkLen, ChunkID in P3D.FindSubchunks(Data.Raw, nil) do
i = #Data.ChunkTypes + 1
Data.ChunkTypes[i] = ChunkID
Data.Chunks[i] = Data.Raw:sub(ChunkPos, ChunkPos + ChunkLen - 1)
end
self.__index = self
return setmetatable(Data, self)
end
function P3D.P3DChunk:create()
return P3D.P3DChunk:new{Raw = P3D.BlankHeader}
end
function P3D.P3DChunk:newChildClass(type)
self.__index = self
return setmetatable({type = type or "none", parentClass = self}, self)
end
function P3D.P3DChunk:GetChunkCount()
return #self.ChunkTypes
end
function P3D.P3DChunk:RemoveChunkAtIndex(idx)
table.remove(self.ChunkTypes, idx)
table.remove(self.Chunks, idx)
end
function P3D.P3DChunk:GetChunkAtIndex(idx)
return self.Chunks[idx], self.ChunkTypes[idx]
end
function P3D.P3DChunk:SetChunkAtIndex(idx, ChunkData)
if #self.ChunkTypes < idx then return end
local OldLen = self.Chunks[idx]:len()
self.ChunkTypes[idx] = P3D.UnpackChunkHeader(ChunkData)
self.Chunks[idx] = ChunkData
end
function P3D.P3DChunk:AddChunk(ChunkData, idx)
local ChunkID = P3D.UnpackChunkHeader(ChunkData)
if idx then
table.insert(self.ChunkTypes, idx, ChunkID)
table.insert(self.Chunks, idx, ChunkData)
else
idx = #self.ChunkTypes + 1
self.ChunkTypes[idx] = ChunkID
self.Chunks[idx] = ChunkData
end
return idx, ChunkID
end
function P3D.P3DChunk:AddChildChunks(RootChunk)
local i = #self.ChunkTypes + 1
for idx in RootChunk:GetChunkIndexes() do
self:AddChunk(RootChunk:GetChunkAtIndex(idx), i)
end
end
function P3D.P3DChunk:Output()
local chunks = concat(self.Chunks)
local len = 12 + self.ValueStr:len()
return pack("<III", self.ChunkType, len, len + chunks:len()) .. self.ValueStr .. chunks
end
function P3D.P3DChunk:GetName()
local name = self.Name or P3D.GetString(self.ValueStr)
self.Name = name
return name
end
function P3D.P3DChunk:SetName(NewName)
NewName = P3D.MakeP3DString(NewName)
self.ValueStr = P3D.SetString(self.ValueStr, 1, NewName)
self.Name = NewName
end
function P3D.P3DChunk:GetChunkIndexes(ChunkID)
local i = #self.ChunkTypes
return function()
while i > 0 do
local ChunkType = self.ChunkTypes[i]
i = i - 1
if ChunkID == nil or ChunkType == ChunkID then
return i + 1, ChunkType
end
end
return nil
end
end
function P3D.P3DChunk:GetChunkIndex(ChunkID)
return self:GetChunkIndexes(ChunkID)()
end
--Texture Chunk
P3D.TextureP3DChunk = P3D.P3DChunk:newChildClass("Texture")
function P3D.TextureP3DChunk:new(Data)
local o = P3D.TextureP3DChunk.parentClass.new(self, Data)
o.Name, o.Version, o.Width, o.Height, o.Bpp, o.AlphaDepth, o.NumMipMaps, o.TextureType, o.Usage, o.Priority = unpack("<s1iiiiiiiii", o.ValueStr)
return o
end
function P3D.TextureP3DChunk:create(Name,Version,Width,Height,Bpp,AlphaDepth,NumMipMaps,TextureType,Usage,Priority)
local Len = 12 + Name:len() + 1 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4
return P3D.TextureP3DChunk:new{Raw = pack("<IIIs1iiiiiiiii", P3D.Identifiers.Texture, Len, Len, Name, Version, Width, Height, Bpp, AlphaDepth, NumMipMaps, TextureType, Usage, Priority)}
end
function P3D.TextureP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4
return pack("<IIIs1iiiiiiiii", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Version, self.Width, self.Height, self.Bpp, self.AlphaDepth, self.NumMipMaps, self.TextureType, self.Usage, self.Priority) .. chunks
end
--Image Chunk
P3D.ImageP3DChunk = P3D.P3DChunk:newChildClass("Image")
function P3D.ImageP3DChunk:new(Data)
local o = P3D.ImageP3DChunk.parentClass.new(self, Data)
o.Name, o.Version, o.Width, o.Height, o.Bpp, o.Palettized, o.HasAlpha, o.Format = unpack("<s1iiiiiii", o.ValueStr)
return o
end
function P3D.ImageP3DChunk:create(Name,Version,Width,Height,Bpp,Palettized,HasAlpha,Format)
local Len = 12 + Name:len() + 1 + 4 + 4 + 4 + 4 + 4 + 4 + 4
return P3D.ImageP3DChunk:new{Raw = pack("<IIIs1iiiiiii", P3D.Identifiers.Image, Len, Len, Name, Version, Width, Height, Bpp, Palettized, HasAlpha, Format)}
end
function P3D.ImageP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + 4 + 4 + 4 + 4 + 4 + 4
return pack("<IIIs1iiiiiii", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Version, self.Width, self.Height, self.Bpp, self.Palettized, self.HasAlpha, self.Format) .. chunks
end
--Shader Chunk
P3D.ShaderP3DChunk = P3D.P3DChunk:newChildClass("Shader")
function P3D.ShaderP3DChunk:new(Data)
local o = P3D.ShaderP3DChunk.parentClass.new(self, Data)
o.Name, o.Version, o.PDDIShader, o.HasTranslucency, o.VertexNeeds, o.VertexMask, o.NumParams = unpack("<s1is1iiii", o.ValueStr)
return o
end
function P3D.ShaderP3DChunk:create(Name,Version,PDDIShader,HasTranslucency,VertexNeeds,VertexMask)
local Len = 12 + Name:len() + 1 + 4 + PDDIShader:len() + 1 + 4 + 4 + 4 + 4
return P3D.ShaderP3DChunk:new{Raw = pack("<IIIs1is1iiii", P3D.Identifiers.Shader, Len, Len, Name, Version, PDDIShader, HasTranslucency, VertexNeeds, VertexMask, 0)}
end
local ShaderParamTypes = {[P3D.Identifiers.Shader_Integer_Parameter] = true, [P3D.Identifiers.Shader_Texture_Parameter] = true, [P3D.Identifiers.Shader_Colour_Parameter] = true, [P3D.Identifiers.Shader_Float_Parameter] = true}
function P3D.ShaderP3DChunk:GetParameterCount()
local ParamN = 0
for i=1,#self.ChunkTypes do
if ShaderParamTypes[self.ChunkTypes[i]] then ParamN = ParamN + 1 end
end
return ParamN
end
function P3D.ShaderP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + self.PDDIShader:len() + 1 + 4 + 4 + 4 + 4
return pack("<IIIs1is1iiii", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Version, self.PDDIShader, self.HasTranslucency, self.VertexNeeds, self.VertexMask, self:GetParameterCount()) .. chunks
end
function P3D.ShaderP3DChunk:SetIntParameter(Name, Value)
Name = P3D.MakeFourCC(Name)
for idx in self:GetChunkIndexes(P3D.Identifiers.Shader_Integer_Parameter) do
local ChunkData = self:GetChunkAtIndex(idx)
if ChunkData:sub(13, 16) == Name then
ChunkData = P3D.SetInt4(ChunkData, 17, Value)
self:SetChunkAtIndex(idx, ChunkData)
return
end
end
end
function P3D.ShaderP3DChunk:GetIntParameter(Name)
Name = P3D.MakeFourCC(Name)
for idx in self:GetChunkIndexes(P3D.Identifiers.Shader_Integer_Parameter) do
local ChunkData = self:GetChunkAtIndex(idx)
if ChunkData:sub(13, 16) == Name then
return P3D.String4ToInt(ChunkData, 17)
end
end
return nil
end
function P3D.ShaderP3DChunk:SetTextureParameter(Name, Value)
Name = P3D.MakeFourCC(Name)
Value = P3D.MakeP3DString(Value)
for idx in self:GetChunkIndexes(P3D.Identifiers.Shader_Texture_Parameter) do
local ChunkData = self:GetChunkAtIndex(idx)
if ChunkData:sub(13, 16) == Name then
local newVal, Delta = P3D.SetString(ChunkData, 17, Value)
newVal = P3D.AddInt4(newVal, 5, Delta)
newVal = P3D.AddInt4(newVal, 9, Delta)
self:SetChunkAtIndex(idx, newVal)
return
end
end
end
function P3D.ShaderP3DChunk:GetTextureParameter(Name)
Name = P3D.MakeFourCC(Name)
for idx in self:GetChunkIndexes(P3D.Identifiers.Shader_Texture_Parameter) do
local ChunkData = self:GetChunkAtIndex(idx)
if ChunkData:sub(13, 16) == Name then
return P3D.GetString(ChunkData, 17)
end
end
return nil
end
function P3D.ShaderP3DChunk:SetColourParameter(Name, A, R, G, B)
Name = P3D.MakeFourCC(Name)
for idx in self:GetChunkIndexes(P3D.Identifiers.Shader_Colour_Parameter) do
local ChunkData = self:GetChunkAtIndex(idx)
if ChunkData:sub(13, 16) == Name then
ChunkData = ChunkData:sub(1, 16) .. P3D.ARGBToString4(A, R, G, B)
self:SetChunkAtIndex(idx, ChunkData)
return
end
end
end
function P3D.ShaderP3DChunk:GetColourParameter(Name)
Name = P3D.MakeFourCC(Name)
for idx in self:GetChunkIndexes(P3D.Identifiers.Shader_Colour_Parameter) do
local ChunkData = self:GetChunkAtIndex(idx)
if ChunkData:sub(13, 16) == Name then
return P3D.String4ToARGB(ChunkData, 17)
end
end
return nil
end
function P3D.ShaderP3DChunk:SetFloatParameter(Name, Value)
Name = P3D.MakeFourCC(Name)
for idx in self:GetChunkIndexes(P3D.Identifiers.Shader_Float_Parameter) do
local ChunkData = self:GetChunkAtIndex(idx)
if ChunkData:sub(13, 16) == Name then
ChunkData = P3D.SetFloat(ChunkData, 17, Value)
self:SetChunkAtIndex(idx, ChunkData)
return
end
end
end
function P3D.ShaderP3DChunk:GetFloatParameter(Name)
Name = P3D.MakeFourCC(Name)
for idx in self:GetChunkIndexes(P3D.Identifiers.Shader_Float_Parameter) do
local ChunkData = self:GetChunkAtIndex(idx)
if ChunkData:sub(13, 16) == Name then
return P3D.String4ToFloat(ChunkData, 17)
end
end
return nil
end
--Static Phys Chunk
P3D.StaticPhysP3DChunk = P3D.P3DChunk:newChildClass("Static Phys")
function P3D.StaticPhysP3DChunk:new(Data)
local o = P3D.StaticPhysP3DChunk.parentClass.new(self, Data)
o.Name, o.Unknown = unpack("<s1i", o.ValueStr)
return o
end
function P3D.StaticPhysP3DChunk:create(Name,Unknown)
local Len = 12 + Name:len() + 1 + 4
return P3D.StaticPhysP3DChunk:new{Raw = pack("<IIIs1i", P3D.Identifiers.Static_Phys, Len, Len, Name, Unknown)}
end
function P3D.StaticPhysP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4
return pack("<IIIs1i", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Unknown) .. chunks
end
--Static Entity Chunk
P3D.StaticEntityP3DChunk = P3D.P3DChunk:newChildClass("Static Entity")
function P3D.StaticEntityP3DChunk:new(Data)
local o = P3D.StaticEntityP3DChunk.parentClass.new(self, Data)
o.Name, o.Unknown, o.RenderOrder = unpack("<s1ii", o.ValueStr)
return o
end
function P3D.StaticEntityP3DChunk:create(Name,Unknown,RenderOrder)
local Len = 12 + Name:len() + 1 + 4 + 4
return P3D.StaticEntityP3DChunk:new{Raw = pack("<IIIs1ii", P3D.Identifiers.Static_Entity, Len, Len, Name, Unknown, RenderOrder)}
end
function P3D.StaticEntityP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + 4
return pack("<IIIs1ii", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Unknown, self.RenderOrder) .. chunks
end
--Inst Stat Phys Chunk
P3D.InstStatPhysP3DChunk = P3D.P3DChunk:newChildClass("Inst Stat Phys")
function P3D.InstStatPhysP3DChunk:new(Data)
local o = P3D.InstStatPhysP3DChunk.parentClass.new(self, Data)
o.Name, o.Unknown, o.RenderOrder = unpack("<s1ii", o.ValueStr)
return o
end
function P3D.InstStatPhysP3DChunk:create(Name,Unknown,RenderOrder)
local Len = 12 + Name:len() + 1 + 4 + 4
return P3D.InstStatPhysP3DChunk:new{Raw = pack("<IIIs1ii", P3D.Identifiers.Inst_Stat_Phys, Len, Len, Name, Unknown, RenderOrder)}
end
function P3D.InstStatPhysP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + 4
return pack("<IIIs1ii", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Unknown, self.RenderOrder) .. chunks
end
--Inst Stat Entity Chunk
P3D.InstStatEntityP3DChunk = P3D.P3DChunk:newChildClass("Inst Stat Entity")
function P3D.InstStatEntityP3DChunk:new(Data)
local o = P3D.InstStatEntityP3DChunk.parentClass.new(self, Data)
o.Name, o.Unknown, o.RenderOrder = unpack("<s1ii", o.ValueStr)
return o
end
function P3D.InstStatEntityP3DChunk:create(Name,Unknown,RenderOrder)
local Len = 12 + Name:len() + 1 + 4 + 4
return P3D.InstStatEntityP3DChunk:new{Raw = pack("<IIIs1ii", P3D.Identifiers.Inst_Stat_Entity, Len, Len, Name, Unknown, RenderOrder)}
end
function P3D.InstStatEntityP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + Name:len() + 1 + 4 + 4
return pack("<IIIs1ii", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Unknown, self.RenderOrder) .. chunks
end
--Dyna Phys Chunk
P3D.DynaPhysP3DChunk = P3D.P3DChunk:newChildClass("Dyna Phys")
function P3D.DynaPhysP3DChunk:new(Data)
local o = P3D.DynaPhysP3DChunk.parentClass.new(self, Data)
o.Name, o.Unknown, o.RenderOrder = unpack("<s1ii", o.ValueStr)
return o
end
function P3D.DynaPhysP3DChunk:create(Name,Unknown,RenderOrder)
local Len = 12 + Name:len() + 1 + 4 + 4
return P3D.DynaPhysP3DChunk:new{Raw = pack("<IIIs1ii", P3D.Identifiers.Dyna_Phys, Len, Len, Name, Unknown, RenderOrder)}
end
function P3D.DynaPhysP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + 4
return pack("<IIIs1ii", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Unknown, self.RenderOrder) .. chunks
end
--Anim Chunk
P3D.AnimP3DChunk = P3D.P3DChunk:newChildClass("Anim")
function P3D.AnimP3DChunk:new(Data)
local o = P3D.AnimP3DChunk.parentClass.new(self, Data)
o.Name, o.Unknown, o.RenderOrder = unpack("<s1ii", o.ValueStr)
return o
end
function P3D.AnimP3DChunk:create(Name,Unknown,RenderOrder)
local Len = 12 + Name:len() + 1 + 4 + 4
return P3D.AnimP3DChunk:new{Raw = pack("<IIIs1ii", P3D.Identifiers.Anim, Len, Len, Name, Unknown, RenderOrder)}
end
function P3D.AnimP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + 4
return pack("<IIIs1ii", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Unknown, self.RenderOrder) .. chunks
end
--Anim Coll Chunk
P3D.AnimCollP3DChunk = P3D.P3DChunk:newChildClass("Anim Coll")
function P3D.AnimCollP3DChunk:new(Data)
local o = P3D.AnimCollP3DChunk.parentClass.new(self, Data)
o.Name, o.Unknown, o.RenderOrder = unpack("<s1ii", o.ValueStr)
return o
end
function P3D.AnimCollP3DChunk:create(Name,Unknown,RenderOrder)
local Len = 12 + Name:len() + 1 + 4 + 4
return P3D.AnimCollP3DChunk:new{Raw = pack("<IIIs1ii", P3D.Identifiers.Anim_Coll, Len, Len, Name, Unknown, RenderOrder)}
end
function P3D.AnimCollP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + 4
return pack("<IIIs1ii", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Unknown, self.RenderOrder) .. chunks
end
--Anim Dyna Phys Chunk
P3D.AnimDynaPhysP3DChunk = P3D.P3DChunk:newChildClass("Anim Dyna Phys")
function P3D.AnimDynaPhysP3DChunk:new(Data)
local o = P3D.AnimDynaPhysP3DChunk.parentClass.new(self, Data)
o.Name, o.Unknown, o.RenderOrder = unpack("<s1ii", o.ValueStr)
return o
end
function P3D.AnimDynaPhysP3DChunk:create(Name,Unknown,RenderOrder)
local Len = 12 + Name:len() + 1 + 4 + 4
return P3D.AnimDynaPhysP3DChunk:new{Raw = pack("<IIIs1ii", P3D.Identifiers.Anim_Dyna_Phys, Len, Len, Name, Unknown, RenderOrder)}
end
function P3D.AnimDynaPhysP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + 4
return pack("<IIIs1ii", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Unknown, self.RenderOrder) .. chunks
end
--Anim Obj Wrapper Chunk
P3D.AnimObjWrapperP3DChunk = P3D.P3DChunk:newChildClass("Anim Obj Wrapper")
function P3D.AnimObjWrapperP3DChunk:new(Data)
local o = P3D.AnimObjWrapperP3DChunk.parentClass.new(self, Data)
o.Name, o.Unknown, o.Unknown2 = unpack("<s1BB", o.ValueStr)
return o
end
function P3D.AnimObjWrapperP3DChunk:create(Name,Unknown,Unknown2)
local Len = 12 + Name:len() + 1 + 1 + 1
return P3D.AnimObjWrapperP3DChunk:new{Raw = pack("<IIIs1BB", P3D.Identifiers.Anim_Obj_Wrapper, Len, Len, Name, Unknown, Unknown2)}
end
function P3D.AnimObjWrapperP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 1 + 1
return pack("<IIIs1BB", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Unknown, self.Unknown2) .. chunks
end
--Breakable Object Chunk
P3D.BreakableObjectP3DChunk = P3D.P3DChunk:newChildClass("Breakable Object")
function P3D.BreakableObjectP3DChunk:new(Data)
local o = P3D.BreakableObjectP3DChunk.parentClass.new(self, Data)
o.Index, o.Count = unpack("<ii", o.ValueStr)
return o
end
function P3D.BreakableObjectP3DChunk:create(Index,Count)
local Len = 12 + 4 + 4
return P3D.BreakableObjectP3DChunk:new{Raw = pack("<IIIii", P3D.Identifiers.Breakable_Object, Len, Len, Index, Count)}
end
function P3D.BreakableObjectP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + 4 + 4
return pack("<IIIii", self.ChunkType, Len, Len + chunks:len(), self.Index, self.Count) .. chunks
end
--World Sphere Chunk
P3D.WorldSphereP3DChunk = P3D.P3DChunk:newChildClass("World Sphere")
function P3D.WorldSphereP3DChunk:new(Data)
local o = P3D.WorldSphereP3DChunk.parentClass.new(self, Data)
o.Name, o.Unknown, o.NumMeshes, o.NumBillboardQuadGroups = unpack("<s1iii", o.ValueStr)
return o
end
function P3D.WorldSphereP3DChunk:create(Name,Unknown)
local Len = 12 + Name:len() + 1 + 4 + 4 + 4
return P3D.WorldSphereP3DChunk:new{Raw = pack("<IIIs1iii", P3D.Identifiers.World_Sphere, Len, Len, Name, Unknown, 0, 0)}
end
function P3D.WorldSphereP3DChunk:GetOldBillboardQuadGroupAndMeshCount()
local OBQGN = 0
local MeshN = 0
for i=1,#self.ChunkTypes do
if self.ChunkTypes[i] == P3D.Identifiers.Old_Billboard_Quad_Group then
OBQGN = OBQGN + 1
elseif self.ChunkTypes[i] == P3D.Identifiers.Mesh then
MeshN = MeshN + 1
end
end
return OBQGN, MeshN
end
function P3D.WorldSphereP3DChunk:Output()
local OBQGN, MeshN = self:GetOldBillboardQuadGroupAndMeshCount()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + 4 + 4
return pack("<IIIs1iii", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Unknown, MeshN, OBQGN) .. chunks
end
--Mesh Chunk
P3D.MeshP3DChunk = P3D.P3DChunk:newChildClass("Mesh")
function P3D.MeshP3DChunk:new(Data)
local o = P3D.MeshP3DChunk.parentClass.new(self, Data)
o.Name, o.Version, o.NumPrimitiveGroups = unpack("<s1ii", o.ValueStr)
return o
end
function P3D.MeshP3DChunk:create(Name,Version)
local Len = 12 + Name:len() + 1 + 4 + 4
return P3D.MeshP3DChunk:new{Raw = pack("<IIIs1ii", P3D.Identifiers.Mesh, Len, Len, Name, Version, 0)}
end
function P3D.MeshP3DChunk:GetOldPrimitiveGroupCount()
local OPGN = 0
for i=1,#self.ChunkTypes do
if self.ChunkTypes[i] == P3D.Identifiers.Old_Primitive_Group then
OPGN = OPGN + 1
end
end
return OPGN
end
function P3D.MeshP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + 4
return pack("<IIIs1ii", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Version, self:GetOldPrimitiveGroupCount()) .. chunks
end
--Old Primitive Group Chunk
P3D.OldPrimitiveGroupP3DChunk = P3D.P3DChunk:newChildClass("Old Primitive Group")
function P3D.OldPrimitiveGroupP3DChunk:new(Data)
local o = P3D.OldPrimitiveGroupP3DChunk.parentClass.new(self, Data)
o.Version, o.ShaderName, o.PrimitiveType, o.VertexType, o.NumVertices, o.NumIndices, o.NumMatrices = unpack("<is1iiiii", o.ValueStr)
return o
end
function P3D.OldPrimitiveGroupP3DChunk:create(Version,ShaderName,PrimitiveType,VertexType,NumVertices,NumIndices,NumMatrices)
local Len = 12 + 4 + ShaderName:len() + 1 + 4 + 4 + 4 + 4 + 4
return P3D.OldPrimitiveGroupP3DChunk:new{Raw = pack("<IIIis1iiiii", P3D.Identifiers.Old_Primitive_Group, Len, Len, Version, ShaderName, PrimitiveType, VertexType, NumVertices, NumIndices, NumMatrices)}
end
function P3D.OldPrimitiveGroupP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + 4 + self.ShaderName:len() + 1 + 4 + 4 + 4 + 4 + 4
return pack("<IIIis1iiiii", self.ChunkType, Len, Len + chunks:len(), self.Version, self.ShaderName, self.PrimitiveType, self.VertexType, self.NumVertices, self.NumIndices, self.NumMatrices) .. chunks
end
--Colour List chunk
P3D.ColourListP3DChunk = P3D.P3DChunk:newChildClass("Colour List")
function P3D.ColourListP3DChunk:new(Data)
local o = P3D.ColourListP3DChunk.parentClass.new(self, Data)
local NumColours = unpack("<i", o.ValueStr)
o.Colours = {}
local idx = 5
for i=0,NumColours - 1 do
local col = {A=0,R=0,G=0,B=0}
col.A, col.R, col.G, col.B = P3D.String4ToARGB(o.ValueStr, idx + i * 4)
o.Colours[#o.Colours + 1] = col
end
return o
end
function P3D.ColourListP3DChunk:create(...)
local ColoursN = #arg
local len = 16 + ColoursN * 4
local colours = {}
for i=1,ColoursN do
local col = arg[i]
colours[#colours + 1] = ARGBToString4(col.A, col.R, col.G, col.B)
end
return P3D.MeshP3DChunk:new{Raw = pack("<IIIi", P3D.Identifiers.Colour_List, len, len, ColoursN) .. concat(colours)}
end
function P3D.ColourListP3DChunk:GetColoursCount()
return #self.Colours
end
function P3D.ColourListP3DChunk:Output()
local ColoursN = self:GetColoursCount()
local len = 16 + ColoursN * 4
local colours = {}
for i=1,ColoursN do
local col = self.Colours[i]
colours[#colours + 1] = P3D.ARGBToString4(col.A, col.R, col.G, col.B)
end
return pack("<IIIi", self.ChunkType, len, len, ColoursN) .. concat(colours)
end
--Position List chunk
P3D.PositionListP3DChunk = P3D.P3DChunk:newChildClass("Position List")
function P3D.PositionListP3DChunk:new(Data)
local o = P3D.PositionListP3DChunk.parentClass.new(self, Data)
local NumPositions = unpack("<i", o.ValueStr)
o.Positions = {}
local idx = 5
for i=0,NumPositions - 1 do
local pos = {X=0,Y=0,Z=0}
pos.X, pos.Y, pos.Z = P3D.String12ToVector3(o.ValueStr, idx + i * 12)
o.Positions[#o.Positions + 1] = pos
end
return o
end
function P3D.PositionListP3DChunk:GetPositionsCount()
return #self.Positions
end
function P3D.PositionListP3DChunk:create(...)
local PositionsN = #arg
local len = 16 + PositionsN * 12
local positions = {}
for i=1,PositionsN do
local pos = arg[i]
positions[#positions + 1] = P3D.Vector3ToString12(pos,X, pos.Y, pos.Z)
end
return P3D.MeshP3DChunk:new{Raw = pack("<IIIi", P3D.Identifiers.Colour_List, len, len, PositionsN) .. concat(positions)}
end
function P3D.PositionListP3DChunk:Output()
local PositionsN = self:GetPositionsCount()
local len = 16 + PositionsN * 12
local positions = {}
for i=1,PositionsN do
local pos = self.Positions[i]
positions[#positions + 1] = P3D.Vector3ToString12(pos,X, pos.Y, pos.Z)
end
return pack("<IIIi", self.ChunkType, len, len, PositionsN) .. concat(positions)
end
--Lens Flare Chunk
P3D.LensFlareP3DChunk = P3D.P3DChunk:newChildClass("Lens Flare")
function P3D.LensFlareP3DChunk:new(Data)
local o = P3D.LensFlareP3DChunk.parentClass.new(self, Data)
o.Name, o.Unknown, o.NumBillboardQuadGroups = unpack("<s1ii", o.ValueStr)
return o
end
function P3D.LensFlareP3DChunk:create(Name,Unknown)
local Len = 12 + Name:len() + 1 + 4 + 4
return P3D.LensFlareP3DChunk:new{Raw = pack("<IIIs1ii", P3D.Identifiers.Lens_Flare, Len, Len, Name, Unknown, 0)}
end
function P3D.LensFlareP3DChunk:GetOldBillboardQuadGroupCount()
local OBQGN = 0
for i=1,#self.ChunkTypes do
if self.ChunkTypes[i] == P3D.Identifiers.Old_Billboard_Quad_Group then
OBQGN = OBQGN + 1
end
end
return OBQGN
end
function P3D.LensFlareP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + 4
return pack("<IIIs1ii", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Unknown, self:GetOldBillboardQuadGroupCount()) .. chunks
end
--Old Billboard Quad Group Chunk
P3D.OldBillboardQuadGroupP3DChunk = P3D.P3DChunk:newChildClass("Old Billboard Quad Group")
function P3D.OldBillboardQuadGroupP3DChunk:new(Data)
local o = P3D.OldBillboardQuadGroupP3DChunk.parentClass.new(self, Data)
o.Version, o.Name, o.Shader, o.ZTest, o.ZWrite, o.Fog, o.NumQuads = unpack("<is1s1iiii", o.ValueStr)
return o
end
function P3D.OldBillboardQuadGroupP3DChunk:create(Version,Name,Shader,ZTest,ZWrite,Fog)
local Len = 12 + 4 + Name:len() + 1 + Shader:len() + 1 + 4 + 4 + 4 + 4
return P3D.OldBillboardQuadGroupP3DChunk:new{Raw = pack("<IIIis1s1iiii", P3D.Identifiers.Old_Billboard_Quad_Group, Len, Len, Version, Name, Shader, ZTest, ZWrite, Fog, 0)}
end
function P3D.OldBillboardQuadGroupP3DChunk:GetOldBillboardQuadCount()
local OBQN = 0
for i=1,#self.ChunkTypes do
if self.ChunkTypes[i] == P3D.Identifiers.Old_Billboard_Quad then
OBQN = OBQN + 1
end
end
return OBQN
end
function P3D.OldBillboardQuadGroupP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + 4 + self.Name:len() + 1 + self.Shader:len() + 1 + 4 + 4 + 4 + 4
return pack("<IIIis1s1iiii", self.ChunkType, Len, Len + chunks:len(), self.Version, self.Name, self.Shader, self.ZTest, self.ZWrite, self.Fog, self:GetOldBillboardQuadCount()) .. chunks
end
--Old Billboard Quad Chunk
P3D.OldBillboardQuadP3DChunk = P3D.P3DChunk:newChildClass("Old Billboard Quad")
function P3D.OldBillboardQuadP3DChunk:new(Data)
local o = P3D.OldBillboardQuadP3DChunk.parentClass.new(self, Data)
o.Translate = {X=0,Y=0,Z=0}
o.Colour = {A=0,R=0,G=0,B=0}
o.UV1 = {X=0,Y=0}
o.UV2 = {X=0,Y=0}
o.UV3 = {X=0,Y=0}
o.UV4 = {X=0,Y=0}
o.UVOffset = {X=0,Y=0}
o.Version, o.Name, o.BillboardMode, o.Translate.X, o.Translate.Y, o.Translate.Z, o.Colour.B, o.Colour.G, o.Colour.R, o.Colour.A, o.UV1.X, o.UV1.Y, o.UV2.X, o.UV2.Y, o.UV3.X, o.UV3.Y, o.UV4.X, o.UV4.Y, o.Width, o.Height, o.Distance, o.UVOffset.X, o.UVOffset.Y = unpack("<is1ifffBBBBfffffffffffff", o.ValueStr)
return o
end
function P3D.OldBillboardQuadP3DChunk:create(Version,Name,BillboardMode,Translate,Colour,UV1,UV2,UV3,UV4,Width,Height,Distance,UVOffset)
local Len = 12 + 4 + Name:len() + 1 + 4 + 12 + 4+ 8+ 8+ 8+ 8 + 4 + 4 + 4+ 8
return P3D.OldBillboardQuadP3DChunk:new{Raw = pack("<IIIis1ifffBBBBfffffffffffff", P3D.Identifiers.Old_Billboard_Quad, Len, Len, Version, Name, BillboardMode, Translate.X, Translate.Y, Translate.Z, Colour.B, Colour.G, Colour.R, Colour.A, UV1.X, UV1.Y, UV2.X, UV2.Y, UV3.X, UV3.Y, UV4.X, UV4.Y, Width, Height, Distance, UVOffset.X, UVOffset.Y)}
end
function P3D.OldBillboardQuadP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + 4 + self.Name:len() + 1 + 4 + 12 + 4+ 8+ 8+ 8+ 8 + 4 + 4 + 4+ 8
return pack("<IIIis1ifffBBBBfffffffffffff", self.ChunkType, Len, Len + chunks:len(), self.Version, self.Name, self.BillboardMode, self.Translate.X, self.Translate.Y, self.Translate.Z, self.Colour.B, self.Colour.G, self.Colour.R, self.Colour.A, self.UV1.X, self.UV1.Y, self.UV2.X, self.UV2.Y, self.UV3.X, self.UV3.Y, self.UV4.X, self.UV4.Y, self.Width, self.Height, self.Distance, self.UVOffset.X, self.UVOffset.Y) .. chunks
end
--Light Chunk
P3D.LightP3DChunk = P3D.P3DChunk:newChildClass("Light")
function P3D.LightP3DChunk:new(Data)
local o = P3D.LightP3DChunk.parentClass.new(self, Data)
o.Colour = {A=0,R=0,G=0,B=0}
o.Name, o.Version, o.Type, o.Colour.B, o.Colour.G, o.Colour.R, o.Colour.A, o.Constant, o.Linear, o.Squared, o.Enabled = unpack("<s1iiBBBBfffi", o.ValueStr)
return o
end
function P3D.LightP3DChunk:create(Name,Version,Type,Colour,Constant,Linear,Squared,Enabled)
local Len = 12 + Name:len() + 1 + 4 + 4 + 4 + 4 + 4 + 4 + 4
return P3D.LightP3DChunk:new{Raw = pack("<IIIs1iiBBBBfffi", P3D.Identifiers.Light, Len, Len, Name, Version, Type, Colour.B, Colour.G, Colour.R, Colour.A, Constant, Linear, Squared, Enabled)}
end
function P3D.LightP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + 4 + 4 + 4 + 4 + 4 + 4
return pack("<IIIs1iiBBBBfffi", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Version, self.Type, self.Colour.B, self.Colour.G, self.Colour.R, self.Colour.A, self.Constant, self.Linear, self.Squared, self.Enabled) .. chunks
end
--Skin Chunk
P3D.SkinP3DChunk = P3D.P3DChunk:newChildClass("Skin")
function P3D.SkinP3DChunk:new(Data)
local o = P3D.SkinP3DChunk.parentClass.new(self, Data)
o.Name, o.Version, o.SkeletonName, o.NumPrimitiveGroups = unpack("<s1is1i", o.ValueStr)
return o
end
function P3D.SkinP3DChunk:create(Name,Version,SkeletonName)
local Len = 12 + Name:len() + 1 + 4 + SkeletonName:len() + 1 + 4
return P3D.SkinP3DChunk:new{Raw = pack("<IIIs1is1i", P3D.Identifiers.Skin, Len, Len, Name, Version, SkeletonName, 0)}
end
function P3D.SkinP3DChunk:GetOldPrimitiveGroupCount()
local OPGN = 0
for i=1,#self.ChunkTypes do
if self.ChunkTypes[i] == P3D.Identifiers.Old_Primitive_Group then
OPGN = OPGN + 1
end
end
return OPGN
end
function P3D.SkinP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + self.SkeletonName:len() + 1 + 4
return pack("<IIIs1is1i", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Version, self.SkeletonName, self:GetOldPrimitiveGroupCount()) .. chunks
end
--Composite Drawable Chunk
P3D.CompositeDrawableP3DChunk = P3D.P3DChunk:newChildClass("Composite Drawable")
function P3D.CompositeDrawableP3DChunk:new(Data)
local o = P3D.CompositeDrawableP3DChunk.parentClass.new(self, Data)
o.Name, o.SkeletonName = unpack("<s1s1", o.ValueStr)
return o
end
function P3D.CompositeDrawableP3DChunk:create(Name,SkeletonName)
local Len = 12 + Name:len() + 1 + SkeletonName:len() + 1
return P3D.CompositeDrawableP3DChunk:new{Raw = pack("<IIIs1s1", P3D.Identifiers.Composite_Drawable, Len, Len, Name, SkeletonName)}
end
function P3D.CompositeDrawableP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + self.SkeletonName:len() + 1
return pack("<IIIs1s1", self.ChunkType, Len, Len + chunks:len(), self.Name, self.SkeletonName) .. chunks
end
--Composite Drawable Skin List Chunk
P3D.CompositeDrawableSkinListP3DChunk = P3D.P3DChunk:newChildClass("Composite Drawable Skin List")
function P3D.CompositeDrawableSkinListP3DChunk:new(Data)
local o = P3D.CompositeDrawableSkinListP3DChunk.parentClass.new(self, Data)
o.NumElements = unpack("<i", o.ValueStr)
return o
end
function P3D.CompositeDrawableSkinListP3DChunk:create()
local Len = 12 + 4
return P3D.CompositeDrawableSkinListP3DChunk:new{Raw = pack("<IIIi", P3D.Identifiers.Composite_Drawable_Skin_List, Len, Len, 0)}
end
function P3D.CompositeDrawableSkinListP3DChunk:GetElementCount()
return #self.Chunks
end
function P3D.CompositeDrawableSkinListP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + 4
return pack("<IIIi", self.ChunkType, Len, Len + chunks:len(), self:GetElementCount()) .. chunks
end
--Composite Drawable Skin Chunk
P3D.CompositeDrawableSkinP3DChunk = P3D.P3DChunk:newChildClass("Composite Drawable Skin")
function P3D.CompositeDrawableSkinP3DChunk:new(Data)
local o = P3D.CompositeDrawableSkinP3DChunk.parentClass.new(self, Data)
o.Name, o.IsTranslucent = unpack("<s1i", o.ValueStr)
return o
end
function P3D.CompositeDrawableSkinP3DChunk:create(Name,IsTranslucent)
local Len = 12 + Name:len() + 1 + 4
return P3D.CompositeDrawableSkinP3DChunk:new{Raw = pack("<IIIs1i", P3D.Identifiers.Composite_Drawable_Skin, Len, Len, Name, IsTranslucent)}
end
function P3D.CompositeDrawableSkinP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4
return pack("<IIIs1i", self.ChunkType, Len, Len + chunks:len(), self.Name, self.IsTranslucent) .. chunks
end
--Composite Drawable Prop List Chunk
P3D.CompositeDrawablePropListP3DChunk = P3D.P3DChunk:newChildClass("Composite Drawable Prop List")
function P3D.CompositeDrawablePropListP3DChunk:new(Data)
local o = P3D.CompositeDrawablePropListP3DChunk.parentClass.new(self, Data)
o.NumElements = unpack("<i", o.ValueStr)
return o
end
function P3D.CompositeDrawablePropListP3DChunk:create()
local Len = 12 + 4
return P3D.CompositeDrawablePropListP3DChunk:new{Raw = pack("<IIIi", P3D.Identifiers.Composite_Drawable_Prop_List, Len, Len, 0)}
end
function P3D.CompositeDrawablePropListP3DChunk:GetElementCount()
return #self.Chunks
end
function P3D.CompositeDrawablePropListP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + 4
return pack("<IIIi", self.ChunkType, Len, Len + chunks:len(), self:GetElementCount()) .. chunks
end
--Composite Drawable Prop Chunk
P3D.CompositeDrawablePropP3DChunk = P3D.P3DChunk:newChildClass("Composite Drawable Prop")
function P3D.CompositeDrawablePropP3DChunk:new(Data)
local o = P3D.CompositeDrawablePropP3DChunk.parentClass.new(self, Data)
o.Name, o.IsTranslucent, o.SkeletonJointID = unpack("<s1ii", o.ValueStr)
return o
end
function P3D.CompositeDrawablePropP3DChunk:create(Name,IsTranslucent,SkeletonJointID)
local Len = 12 + Name:len() + 1 + 4 + 4
return P3D.CompositeDrawablePropP3DChunk:new{Raw = pack("<IIIs1ii", P3D.Identifiers.Composite_Drawable_Prop, Len, Len, Name, IsTranslucent, SkeletonJointID)}
end
function P3D.CompositeDrawablePropP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + 4
return pack("<IIIs1ii", self.ChunkType, Len, Len + chunks:len(), self.Name, self.IsTranslucent, self.SkeletonJointID) .. chunks
end
--Composite Drawable Effect List Chunk
P3D.CompositeDrawableEffectListP3DChunk = P3D.P3DChunk:newChildClass("Composite Drawable Effect List")
function P3D.CompositeDrawableEffectListP3DChunk:new(Data)
local o = P3D.CompositeDrawableEffectListP3DChunk.parentClass.new(self, Data)
o.NumElements = unpack("<i", o.ValueStr)
return o
end
function P3D.CompositeDrawableEffectListP3DChunk:create()
local Len = 12 + 4
return P3D.CompositeDrawableEffectListP3DChunk:new{Raw = pack("<IIIi", P3D.Identifiers.Composite_Drawable_Effect_List, Len, Len, 0)}
end
function P3D.CompositeDrawableEffectListP3DChunk:GetElementCount()
return #self.Chunks
end
function P3D.CompositeDrawableEffectListP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + 4
return pack("<IIIi", self.ChunkType, Len, Len + chunks:len(), self:GetElementCount()) .. chunks
end
--Composite Drawable Effect Chunk
P3D.CompositeDrawableEffectP3DChunk = P3D.P3DChunk:newChildClass("Composite Drawable Effect")
function P3D.CompositeDrawableEffectP3DChunk:new(Data)
local o = P3D.CompositeDrawableEffectP3DChunk.parentClass.new(self, Data)
o.Name, o.IsTranslucent, o.SkeletonJointID = unpack("<s1ii", o.ValueStr)
return o
end
function P3D.CompositeDrawableEffectP3DChunk:create(Name,IsTranslucent,SkeletonJointID)
local Len = 12 + Name:len() + 1 + 4 + 4
return P3D.CompositeDrawableEffectP3DChunk:new{Raw = pack("<IIIs1ii", P3D.Identifiers.Composite_Drawable_Effect, Len, Len, Name, IsTranslucent, SkeletonJointID)}
end
function P3D.CompositeDrawableEffectP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + 4
return pack("<IIIs1ii", self.ChunkType, Len, Len + chunks:len(), self.Name, self.IsTranslucent, self.SkeletonJointID) .. chunks
end
--Collision Effect Chunk
P3D.CollisionEffectP3DChunk = P3D.P3DChunk:newChildClass("Collision Effect")
function P3D.CollisionEffectP3DChunk:new(Data)
local o = P3D.CollisionEffectP3DChunk.parentClass.new(self, Data)
o.Classtype, o.ATCEntry, o.SoundResourceDataName = unpack("<iis1", o.ValueStr)
return o
end
function P3D.CollisionEffectP3DChunk:create(Classtype,ATCEntry,SoundResourceDataName)
local Len = 12 + 4 + 4 + SoundResourceDataName:len() + 1
return P3D.CollisionEffectP3DChunk:new{Raw = pack("<IIIiis1", P3D.Identifiers.Collision_Effect, Len, Len, Classtype, ATCEntry, SoundResourceDataName)}
end
function P3D.CollisionEffectP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + 4 + 4 + self.SoundResourceDataName:len() + 1
return pack("<IIIiis1", self.ChunkType, Len, Len + chunks:len(), self.Classtype, self.ATCEntry, self.SoundResourceDataName) .. chunks
end
--State Prop Data V1 Chunk
P3D.StatePropDataV1P3DChunk = P3D.P3DChunk:newChildClass("State Prop Data V1")
function P3D.StatePropDataV1P3DChunk:new(Data)
local o = P3D.StatePropDataV1P3DChunk.parentClass.new(self, Data)
o.Version, o.Name, o.ObjectFactoryName, o.NumStates = unpack("<is1s1i", o.ValueStr)
return o
end
function P3D.StatePropDataV1P3DChunk:create(Version,Name,ObjectFactoryName)
local Len = 12 + 4 + Name:len() + 1 + ObjectFactoryName:len() + 1 + 4
return P3D.StatePropDataV1P3DChunk:new{Raw = pack("<IIIis1s1i", P3D.Identifiers.State_Prop_Data_V1, Len, Len, Version, Name, ObjectFactoryName, 0)}
end
function P3D.StatePropDataV1P3DChunk:GetStateCount()
local StateN = 0
for i=1,#self.ChunkTypes do
if self.ChunkTypes[i] == P3D.Identifiers.State_Prop_State_Data_V1 then
StateN = StateN + 1
end
end
return StateN
end
function P3D.StatePropDataV1P3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + 4 + self.Name:len() + 1 + self.ObjectFactoryName:len() + 1 + 4
return pack("<IIIis1s1i", self.ChunkType, Len, Len + chunks:len(), self.Version, self.Name, self.ObjectFactoryName, self:GetStateCount()) .. chunks
end
--State Prop State Data V1 Chunk
P3D.StatePropStateDataV1P3DChunk = P3D.P3DChunk:newChildClass("State Prop State Data V1")
function P3D.StatePropStateDataV1P3DChunk:new(Data)
local o = P3D.StatePropStateDataV1P3DChunk.parentClass.new(self, Data)
o.Name, o.AutoTransition, o.OutState, o.NumDrawables, o.NumFrameControllers, o.NumEvents, o.NumCallbacks, o.OutFrame = unpack("<s1iiiiiif", o.ValueStr)
return o
end
function P3D.StatePropStateDataV1P3DChunk:create(Name,AutoTransition,OutState,OutFrame)
local Len = 12 + Name:len() + 1 + 4 + 4 + 4 + 4 + 4 + 4 + 4
return P3D.StatePropStateDataV1P3DChunk:new{Raw = pack("<IIIs1iiiiiif", P3D.Identifiers.State_Prop_State_Data_V1, Len, Len, Name, AutoTransition, OutState, 0, 0, 0, 0, OutFrame)}
end
function P3D.StatePropStateDataV1P3DChunk:GetCounts()
local DrawableN = 0
local FrameControllerN = 0
local EventN = 0
local CallbackN = 0
for i=1,#self.ChunkTypes do
local type = self.ChunkTypes[i]
if type == P3D.Identifiers.State_Prop_Visibilities_Data then
DrawableN = DrawableN + 1
elseif type == P3D.Identifiers.State_Prop_Frame_Controller_Data then
FrameControllerN = FrameControllerN + 1
elseif type == P3D.Identifiers.State_Prop_Event_Data then
EventN = EventN + 1
elseif type == P3D.Identifiers.State_Prop_Callback_Data then
CallbackN = CallbackN + 1
end
end
return DrawableN, FrameControllerN, EventN, CallbackN
end
function P3D.StatePropStateDataV1P3DChunk:Output()
local DrawableN, FrameControllerN, EventN, CallbackN = self:GetCounts()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + 4 + 4 + 4 + 4 + 4 + 4
return pack("<IIIs1iiiiiif", self.ChunkType, Len, Len + chunks:len(), self.Name, self.AutoTransition, self.OutState, DrawableN, FrameControllerN, EventN, CallbackN, self.OutFrame) .. chunks
end
--Locator Chunk TODO: Handle types
P3D.LocatorP3DChunk = P3D.P3DChunk:newChildClass("Locator")
function P3D.LocatorP3DChunk:new(Data)
local o = P3D.LocatorP3DChunk.parentClass.new(self, Data)
o.Name, o.Type, o.DataLen = unpack("<s1ii", o.ValueStr)
local idx = o.Name:len() + 1 + 4 + 4 + 1
o.Position = {X=0,Y=0,Z=0}
o.Data, o.Position.X, o.Position.Y, o.Position.Z, o.NumTriggers = unpack("<c" .. o.DataLen * 4 .. "fffi", o.ValueStr, idx)
return o
end
function P3D.LocatorP3DChunk:createType9(Name, Position, Type, UnknownStr1, UnknownStr2, Unknown1, Unknown2)
local dataTbl = {UnknownStr1}
for i=1,4 - UnknownStr1:len() % 4 do
dataTbl[#dataTbl + 1] = "\0"
end
dataTbl[#dataTbl + 1] = UnknownStr2
for i=1,4 - UnknownStr2:len() % 4 do
dataTbl[#dataTbl + 1] = "\0"
end
dataTbl[#dataTbl + 1] = Type
for i=1,4 - Type:len() % 4 do
dataTbl[#dataTbl + 1] = "\0"
end
local data = concat(dataTbl)
local Len = 12 + Name:len() + 1 + 4 + 4 + data:len() + 4 + 4 + 12 + 4
return P3D.LocatorP3DChunk:new{Raw = pack("<IIIs1iic" .. data:len() .. "iifffi", P3D.Identifiers.Locator, Len, Len, Name, 9, data:len() / 4 + 2, data, Unknown1, Unknown2, Position.X, Position.Y, Position.Z, 0)}
end
function P3D.LocatorP3DChunk:GetType0Data()
local Event, idx = unpack("<I", self.ValueStr, self.Name:len() + 1 + 4 + 4 + 1)
local Parameter = nil
if self.DataLen >= 2 then Parameter = unpack("<I", self.ValueStr, idx) end
return Event, Parameter
end
function P3D.LocatorP3DChunk:GetType9Data()
local data, Unknown1, Unknown2 = unpack("<c" .. (self.DataLen - 2) * 4 .. "ii", self.ValueStr, self.Name:len() + 1 + 4 + 4 + 1)
local UnknownStr1, UnknownStr2, Type
local index = 1
local position = 1
local buffer = {}
for i=1,#data do
if data:byte(i) ~= 0 then
buffer[#buffer + 1] = data:sub(i, i)
else
if #buffer > 0 then
if index == 1 then
UnknownStr1 = concat(buffer)
elseif index == 2 then
UnknownStr2 = concat(buffer)
elseif index == 3 then
Type = concat(buffer)
end
buffer = {}
index = index + 1
end
end
end
return Type, UnknownStr1, UnknownStr2, Unknown1, Unknown2
end
function P3D.LocatorP3DChunk:GetTriggerCount()
local TriggerN = 0
for i=1,#self.ChunkTypes do
if self.ChunkTypes[i] == P3D.Identifiers.Trigger_Volume then
TriggerN = TriggerN + 1
end
end
return TriggerN
end
function P3D.LocatorP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + 4 + self.Data:len() + 12 + 4
return pack("<IIIs1iic" .. self.DataLen * 4 .."fffi", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Type, self.DataLen, self.Data, self.Position.X, self.Position.Y, self.Position.Z, self:GetTriggerCount()) .. chunks
end
--Skeleton Chunk
P3D.SkeletonP3DChunk = P3D.P3DChunk:newChildClass("Skeleton")
function P3D.SkeletonP3DChunk:new(Data)
local o = P3D.SkeletonP3DChunk.parentClass.new(self, Data)
o.Name, o.Version, o.NumJoints = unpack("<s1ii", o.ValueStr)
return o
end
function P3D.SkeletonP3DChunk:create(Name,Version)
local Len = 12 + Name:len() + 1 + 4 + 4
return P3D.SkeletonP3DChunk:new{Raw = pack("<IIIs1ii", P3D.Identifiers.Skeleton, Len, Len, Name, Version, 0)}
end
function P3D.SkeletonP3DChunk:GetJointCount()
local JointN = 0
for i=1,#self.ChunkTypes do
if self.ChunkTypes[i] == P3D.Identifiers.Skeleton_Joint then
JointN = JointN + 1
end
end
return JointN
end
function P3D.SkeletonP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + 4
return pack("<IIIs1ii", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Version, self:GetJointCount()) .. chunks
end
--Skeleton Joint Chunk
P3D.SkeletonJointP3DChunk = P3D.P3DChunk:newChildClass("Skeleton Joint")
function P3D.SkeletonJointP3DChunk:new(Data)
local o = P3D.SkeletonJointP3DChunk.parentClass.new(self, Data)
o.RestPose = P3D.MatrixIdentity()
o.Name, o.Parent, o.DOF, o.FreeAxis, o.PrimaryAxis, o.SecondaryAxis, o.TwistAxis, o.RestPose.M11, o.RestPose.M12, o.RestPose.M13, o.RestPose.M14, o.RestPose.M21, o.RestPose.M22, o.RestPose.M23, o.RestPose.M34, o.RestPose.M31, o.RestPose.M32, o.RestPose.M33, o.RestPose.M34, o.RestPose.M41, o.RestPose.M42, o.RestPose.M43, o.RestPose.M44 = unpack("<s1iiiiiiffffffffffffffff", o.ValueStr)
return o
end
function P3D.SkeletonJointP3DChunk:create(Name,Parent,DOF,FreeAxis,PrimaryAxis,SecondaryAxis,TwistAxis,RestPose)
local Len = 12 + Name:len() + 1 + 4 + 4 + 4 + 4 + 4 + 4 + 64
return P3D.SkeletonJointP3DChunk:new{Raw = pack("<IIIs1iiiiiiffffffffffffffff", P3D.Identifiers.Skeleton_Joint, Len, Len, Name, Parent, DOF, FreeAxis, PrimaryAxis, SecondaryAxis, TwistAxis, RestPose.M11, RestPose.M12, RestPose.M13, RestPose.M14, RestPose.M21, RestPose.M22, RestPose.M23, RestPose.M34, RestPose.M31, RestPose.M32, RestPose.M33, RestPose.M34, RestPose.M41, RestPose.M42, RestPose.M43, RestPose.M44)}
end
function P3D.SkeletonJointP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + 4 + 4 + 4 + 4 + 4 + 64
return pack("<IIIs1iiiiiiffffffffffffffff", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Parent, self.DOF, self.FreeAxis, self.PrimaryAxis, self.SecondaryAxis, self.TwistAxis, self.RestPose.M11, self.RestPose.M12, self.RestPose.M13, self.RestPose.M14, self.RestPose.M21, self.RestPose.M22, self.RestPose.M23, self.RestPose.M34, self.RestPose.M31, self.RestPose.M32, self.RestPose.M33, self.RestPose.M34, self.RestPose.M41, self.RestPose.M42, self.RestPose.M43, self.RestPose.M44) .. chunks
end
--Old Frame Controller Chunk
P3D.OldFrameControllerP3DChunk = P3D.P3DChunk:newChildClass("Old Frame Controller")
function P3D.OldFrameControllerP3DChunk:new(Data)
local o = P3D.OldFrameControllerP3DChunk.parentClass.new(self, Data)
o.Version, o.Name, o.Type, o.FrameOffset, o.HierarchyName, o.AnimationName = unpack("<is1c4fs1s1", o.ValueStr)
return o
end
function P3D.OldFrameControllerP3DChunk:create(Version,Name,Type,FrameOffset,HierarchyName,AnimationName)
local Len = 12 + 4 + Name:len() + 1 + 4 + 4 + HierarchyName:len() + 1 + AnimationName:len() + 1
return P3D.OldFrameControllerP3DChunk:new{Raw = pack("<IIIis1c4fs1s1", P3D.Identifiers.Old_Frame_Controller, Len, Len, Version, Name, Type, FrameOffset, HierarchyName, AnimationName)}
end
function P3D.OldFrameControllerP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + 4 + self.Name:len() + 1 + 4 + 4 + self.HierarchyName:len() + 1 + self.AnimationName:len() + 1
return pack("<IIIis1c4fs1s1", self.ChunkType, Len, Len + chunks:len(), self.Version, self.Name, self.Type, self.FrameOffset, self.HierarchyName, self.AnimationName) .. chunks
end
--Physics Object Chunk
P3D.PhysicsObjectP3DChunk = P3D.P3DChunk:newChildClass("Physics Object")
function P3D.PhysicsObjectP3DChunk:new(Data)
local o = P3D.PhysicsObjectP3DChunk.parentClass.new(self, Data)
o.Name, o.Version, o.MaterialName, o.NumJoints, o.Volume, o.RestingSensitivity = unpack("<s1is1iff", o.ValueStr)
return o
end
function P3D.PhysicsObjectP3DChunk:create(Name,Version,MaterialName,Volume,RestingSensitivity)
local Len = 12 + Name:len() + 1 + 4 + MaterialName:len() + 1 + 4 + 4 + 4
return P3D.PhysicsObjectP3DChunk:new{Raw = pack("<IIIs1is1iff", P3D.Identifiers.Physics_Object, Len, Len, Name, Version, MaterialName, 0, Volume, RestingSensitivity)}
end
function P3D.PhysicsObjectP3DChunk:GetJointCount()
local JointN = 0
for i=1,#self.ChunkTypes do
if self.ChunkTypes[i] == P3D.Identifiers.Physics_Joint then
JointN = JointN + 1
end
end
return JointN
end
function P3D.PhysicsObjectP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + self.MaterialName:len() + 1 + 4 + 4 + 4
return pack("<IIIs1is1iff", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Version, self.MaterialName, self:GetJointCount(), self.Volume, self.RestingSensitivity) .. chunks
end
--Collision Object Chunk
P3D.CollisionObjectP3DChunk = P3D.P3DChunk:newChildClass("Collision Object")
function P3D.CollisionObjectP3DChunk:new(Data)
local o = P3D.CollisionObjectP3DChunk.parentClass.new(self, Data)
o.Name, o.Version, o.MaterialName, o.NumSubObject, o.NumOwner = unpack("<s1is1ii", o.ValueStr)
return o
end
function P3D.CollisionObjectP3DChunk:create(Name,Version,MaterialName)
local Len = 12 + Name:len() + 1 + 4 + MaterialName:len() + 1 + 4 + 4
return P3D.CollisionObjectP3DChunk:new{Raw = pack("<IIIs1is1ii", P3D.Identifiers.Collision_Object, Len, Len, Name, Version, MaterialName, 0, 0)}
end
function P3D.CollisionObjectP3DChunk:GetOwnerCount()
local OwnerN = 0
for i=1,#self.ChunkTypes do
if self.ChunkTypes[i] == P3D.Identifiers.Collision_Volume_Owner then
OwnerN = OwnerN + 1
end
end
return OwnerN
end
function P3D.CollisionObjectP3DChunk:Output()
local OwnerN = self:GetOwnerCount()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + self.MaterialName:len() + 1 + 4 + 4
return pack("<IIIs1is1ii", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Version, self.MaterialName, #self.Chunks - OwnerN, OwnerN) .. chunks
end
--Collision Volume Chunk
P3D.CollisionVolumeP3DChunk = P3D.P3DChunk:newChildClass("Collision Volume")
function P3D.CollisionVolumeP3DChunk:new(Data)
local o = P3D.CollisionVolumeP3DChunk.parentClass.new(self, Data)
o.ObjectReferenceIndex, o.OwnerIndex, o.NumSubVolume = unpack("<iii", o.ValueStr)
return o
end
function P3D.CollisionVolumeP3DChunk:create(ObjectReferenceIndex,OwnerIndex)
local Len = 12 + 4 + 4 + 4
return P3D.CollisionVolumeP3DChunk:new{Raw = pack("<IIIiii", P3D.Identifiers.Collision_Volume, Len, Len, ObjectReferenceIndex, OwnerIndex, 0)}
end
function P3D.CollisionVolumeP3DChunk:GetVolumeCount()
local VolumeN = 0
for i=1,#self.ChunkTypes do
if self.ChunkTypes[i] == P3D.Identifiers.Collision_Volume then
VolumeN = VolumeN + 1
end
end
return VolumeN
end
function P3D.CollisionVolumeP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + 4 + 4 + 4
return pack("<IIIiii", self.ChunkType, Len, Len + chunks:len(), self.ObjectReferenceIndex, self.OwnerIndex, self:GetVolumeCount()) .. chunks
end
--Multi Controller Chunk
P3D.MultiControllerP3DChunk = P3D.P3DChunk:newChildClass("Multi Controller")
function P3D.MultiControllerP3DChunk:new(Data)
local o = P3D.MultiControllerP3DChunk.parentClass.new(self, Data)
o.Name, o.Version, o.Length, o.Framerate, o.NumTracks = unpack("<s1iffi", o.ValueStr)
return o
end
function P3D.MultiControllerP3DChunk:create(Name,Version,Length,Framerate)
local Len = 12 + Name:len() + 1 + 4 + 4 + 4 + 4
return P3D.MultiControllerP3DChunk:new{Raw = pack("<IIIs1iffi", P3D.Identifiers.Multi_Controller, Len, Len, Name, Version, Length, Framerate, 0)}
end
function P3D.MultiControllerP3DChunk:GetTrackCount()
local TrackN = 0
for i=1,#self.ChunkTypes do
if self.ChunkTypes[i] == P3D.Identifiers.Multi_Controller_Tracks then
local MultiControllerTracksChunk = P3D.MultiControllerTracksP3DChunk:new{Raw = self.Chunks[i]}
TrackN = TrackN + MultiControllerTracksChunk:GetTrackCount()
end
end
return TrackN
end
function P3D.MultiControllerP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + 4 + 4 + 4
return pack("<IIIs1iffi", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Version, self.Length, self.Framerate, self:GetTrackCount()) .. chunks
end
--Multi Controller Tracks chunk
P3D.MultiControllerTracksP3DChunk = P3D.P3DChunk:newChildClass("Multi Controller Tracks")
function P3D.MultiControllerTracksP3DChunk:new(Data)
local o = P3D.MultiControllerTracksP3DChunk.parentClass.new(self, Data)
local NumTracks = unpack("<i", o.ValueStr)
o.Tracks = {}
local idx = 5
for i=0,NumTracks - 1 do
local track = {Name="",StartTime=0,EndTime=0,Scale=0}
track.Name, track.StartTime, track.EndTime, track.Scale = unpack("<s1fff", o.ValueStr, idx)
idx = idx + track.Name:len() + 1 + 4 + 4 + 4
o.Tracks[#o.Tracks + 1] = track
end
return o
end
function P3D.MultiControllerTracksP3DChunk:create(...)
local TracksN = #arg
local len = 16
local tracks = {}
for i=1,TracksN do
local track = arg[i]
tracks[#tracks + 1] = pack("<s1fff", track.Name, track.StartTime, track.EndTime, track.Scale)
len = len + track.Name:len() + 1 + 4 + 4 + 4
end
return P3D.MeshP3DChunk:new{Raw = pack("<IIIi", P3D.Identifiers.Multi_Controller_Tracks, len, len, TracksN) .. concat(tracks)}
end
function P3D.MultiControllerTracksP3DChunk:GetTrackCount()
return #self.Tracks
end
function P3D.MultiControllerTracksP3DChunk:Output()
local TracksN = self:GetTrackCount()
local len = 16
local tracks = {}
for i=1,TracksN do
local track = self.Tracks[i]
tracks[#tracks + 1] = pack("<s1fff", track.Name, track.StartTime, track.EndTime, track.Scale)
len = len + track.Name:len() + 1 + 4 + 4 + 4
end
return pack("<IIIi", P3D.Identifiers.Multi_Controller_Tracks, len, len, TracksN) .. concat(tracks)
end
--Animation Chunk
P3D.AnimationP3DChunk = P3D.P3DChunk:newChildClass("Animation")
function P3D.AnimationP3DChunk:new(Data)
local o = P3D.AnimationP3DChunk.parentClass.new(self, Data)
o.Version, o.Name, o.AnimationType, o.NumFrames, o.FrameRate, o.Cyclic = unpack("<is1c4ffi", o.ValueStr)
return o
end
function P3D.AnimationP3DChunk:create(Version,Name,AnimationType,NumFrames,FrameRate,Cyclic)
local Len = 12 + 4 + Name:len() + 1 + AnimationType:len() + 4 + 4 + 4
return P3D.AnimationP3DChunk:new{Raw = pack("<IIIis1c4ffi", P3D.Identifiers.Animation, Len, Len, Version, Name, AnimationType, NumFrames, FrameRate, Cyclic)}
end
function P3D.AnimationP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + 4 + self.Name:len() + 1 + self.AnimationType:len() + 4 + 4 + 4
return pack("<IIIis1c4ffi", self.ChunkType, Len, Len + chunks:len(), self.Version, self.Name, self.AnimationType, self.NumFrames, self.FrameRate, self.Cyclic) .. chunks
end
--Particle System 2 Chunk
P3D.ParticleSystem2P3DChunk = P3D.P3DChunk:newChildClass("Particle System 2")
function P3D.ParticleSystem2P3DChunk:new(Data)
local o = P3D.ParticleSystem2P3DChunk.parentClass.new(self, Data)
o.Version, o.Name, o.Unknown = unpack("<is1s1", o.ValueStr)
return o
end
function P3D.ParticleSystem2P3DChunk:create(Version,Name,Unknown)
local Len = 12 + 4 + Name:len() + 1 + Unknown:len() + 1
return P3D.ParticleSystem2P3DChunk:new{Raw = pack("<IIIis1s1", P3D.Identifiers.Particle_System_2, Len, Len, Version, Name, Unknown)}
end
function P3D.ParticleSystem2P3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + 4 + self.Name:len() + 1 + self.Unknown:len() + 1
return pack("<IIIis1s1", self.ChunkType, Len, Len + chunks:len(), self.Version, self.Name, self.Unknown) .. chunks
end
--Particle System Factory Chunk
P3D.ParticleSystemFactoryP3DChunk = P3D.P3DChunk:newChildClass("Particle System Factory")
function P3D.ParticleSystemFactoryP3DChunk:new(Data)
local o = P3D.ParticleSystemFactoryP3DChunk.parentClass.new(self, Data)
o.Version, o.Name, o.FrameRate, o.NumAnimFrames, o.NumOLFrames, o.CycleAnim, o.EnableSorting, o.NumEmitters = unpack("<is1fiihhi", o.ValueStr)
return o
end
function P3D.ParticleSystemFactoryP3DChunk:create(Version,Name,FrameRate,NumAnimFrames,NumOLFrames,CycleAnim,EnableSorting)
local Len = 12 + 4 + Name:len() + 1 + 4 + 4 + 4 + 2 + 2 + 4
return P3D.ParticleSystemFactoryP3DChunk:new{Raw = pack("<IIIis1fiihhi", P3D.Identifiers.Particle_System_Factory, Len, Len, Version, Name, FrameRate, NumAnimFrames, NumOLFrames, CycleAnim, EnableSorting, 0)}
end
function P3D.ParticleSystemFactoryP3DChunk:GetEmitterCount()
local EmitterN = 0
for i=1,#self.ChunkTypes do
if self.ChunkTypes[i] == P3D.Identifiers.Old_Sprite_Emitter then
EmitterN = EmitterN + 1
end
end
return EmitterN
end
function P3D.ParticleSystemFactoryP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + 4 + self.Name:len() + 1 + 4 + 4 + 4 + 2 + 2 + 4
return pack("<IIIis1fiihhi", self.ChunkType, Len, Len + chunks:len(), self.Version, self.Name, self.FrameRate, self.NumAnimFrames, self.NumOLFrames, self.CycleAnim, self.EnableSorting, self:GetEmitterCount()) .. chunks
end
--Instance List Chunk
P3D.InstanceListP3DChunk = P3D.P3DChunk:newChildClass("Instance List")
function P3D.InstanceListP3DChunk:new(Data)
local o = P3D.InstanceListP3DChunk.parentClass.new(self, Data)
o.Name = unpack("<s1", o.ValueStr)
o.Data = o.ValueStr:sub(o.Name:len() + 1)
return o
end
function P3D.InstanceListP3DChunk:create(Name,Data)
local Len = 12 + Name:len() + 1 + Data:len()
return P3D.InstanceListP3DChunk:new{Raw = pack("<IIIs1i", P3D.Identifiers.Instance_List, Len, Len, Name) .. Data}
end
function P3D.InstanceListP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + self.Data:len()
return pack("<IIIs1", self.ChunkType, Len, Len + chunks:len(), self.Name) .. self.Data .. chunks
end
--Scenegraph Chunk
P3D.ScenegraphP3DChunk = P3D.P3DChunk:newChildClass("Scenegraph")
function P3D.ScenegraphP3DChunk:new(Data)
local o = P3D.ScenegraphP3DChunk.parentClass.new(self, Data)
o.Name = unpack("<s1", o.ValueStr)
o.Data = o.ValueStr:sub(o.Name:len() + 1)
return o
end
function P3D.ScenegraphP3DChunk:create(Name,Data)
local Len = 12 + Name:len() + 1 + Data:len()
return P3D.ScenegraphP3DChunk:new{Raw = pack("<IIIs1", P3D.Identifiers.Scenegraph, Len, Len, Name) .. Data}
end
function P3D.ScenegraphP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + self.Data:len()
return pack("<IIIs1", self.ChunkType, Len, Len + chunks:len(), self.Name) .. self.Data .. chunks
end
--Old Scenegraph Root Chunk
P3D.OldScenegraphRootP3DChunk = P3D.P3DChunk:newChildClass("Old Scenegraph Root")
function P3D.OldScenegraphRootP3DChunk:new(Data)
local o = P3D.OldScenegraphRootP3DChunk.parentClass.new(self, Data)
return o
end
--Old Scenegraph Branch Chunk
P3D.OldScenegraphBranchP3DChunk = P3D.P3DChunk:newChildClass("Old Scenegraph Branch")
function P3D.OldScenegraphBranchP3DChunk:new(Data)
local o = P3D.OldScenegraphBranchP3DChunk.parentClass.new(self, Data)
o.Name, o.NumChildren = unpack("<s1i", o.ValueStr)
return o
end
function P3D.OldScenegraphBranchP3DChunk:create(Name)
local Len = 12 + Name:len() + 1 + 4
return P3D.OldScenegraphBranchP3DChunk:new{Raw = pack("<IIIs1i", P3D.Identifiers.Old_Scenegraph_Branch, Len, Len, Name, 0)}
end
function P3D.OldScenegraphBranchP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4
return pack("<IIIs1i", self.ChunkType, Len, Len + chunks:len(), self.Name, #self.Chunks) .. chunks
end
--Old Scenegraph Transform Chunk
P3D.OldScenegraphTransformP3DChunk = P3D.P3DChunk:newChildClass("Old Scenegraph Transform")
function P3D.OldScenegraphTransformP3DChunk:new(Data)
local o = P3D.OldScenegraphTransformP3DChunk.parentClass.new(self, Data)
o.Transform = P3D.MatrixIdentity()
o.Name, o.NumChildren, o.Transform.M11, o.Transform.M12, o.Transform.M13, o.Transform.M14, o.Transform.M21, o.Transform.M22, o.Transform.M23, o.Transform.M34, o.Transform.M31, o.Transform.M32, o.Transform.M33, o.Transform.M34, o.Transform.M41, o.Transform.M42, o.Transform.M43, o.Transform.M44 = unpack("<s1iffffffffffffffff", o.ValueStr)
return o
end
function P3D.OldScenegraphTransformP3DChunk:create(Name,Transform)
local Len = 12 + Name:len() + 1 + 4 + 64
return P3D.OldScenegraphTransformP3DChunk:new{Raw = pack("<IIIs1iffffffffffffffff", P3D.Identifiers.Old_Scenegraph_Transform, Len, Len, Name, 0, Transform.M11, Transform.M12, Transform.M13, Transform.M14, Transform.M21, Transform.M22, Transform.M23, Transform.M34, Transform.M31, Transform.M32, Transform.M33, Transform.M34, Transform.M41, Transform.M42, Transform.M43, Transform.M44)}
end
function P3D.OldScenegraphTransformP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + 64
return pack("<IIIs1iffffffffffffffff", self.ChunkType, Len, Len + chunks:len(), self.Name, #self.Chunks, self.Transform.M11, self.Transform.M12, self.Transform.M13, self.Transform.M14, self.Transform.M21, self.Transform.M22, self.Transform.M23, self.Transform.M34, self.Transform.M31, self.Transform.M32, self.Transform.M33, self.Transform.M34, self.Transform.M41, self.Transform.M42, self.Transform.M43, self.Transform.M44) .. chunks
end
--Old Scenegraph Drawable Chunk
P3D.OldScenegraphDrawableP3DChunk = P3D.P3DChunk:newChildClass("Old Scenegraph Drawable")
function P3D.OldScenegraphDrawableP3DChunk:new(Data)
local o = P3D.OldScenegraphDrawableP3DChunk.parentClass.new(self, Data)
o.Name, o.DrawableName, o.IsTranslucent = unpack("<s1s1i", o.ValueStr)
return o
end
function P3D.OldScenegraphDrawableP3DChunk:create(Name,DrawableName,IsTranslucent)
local Len = 12 + Name:len() + 1 + DrawableName:len() + 1 + 4
return P3D.OldScenegraphDrawableP3DChunk:new{Raw = pack("<IIIs1s1i", P3D.Identifiers.Old_Scenegraph_Drawable, Len, Len, Name, DrawableName, IsTranslucent)}
end
function P3D.OldScenegraphDrawableP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + self.DrawableName:len() + 1 + 4
return pack("<IIIs1s1i", self.ChunkType, Len, Len + chunks:len(), self.Name, self.DrawableName, self.IsTranslucent) .. chunks
end
--Animation Group List Chunk
P3D.AnimationGroupListP3DChunk = P3D.P3DChunk:newChildClass("Animation Group List")
function P3D.AnimationGroupListP3DChunk:new(Data)
local o = P3D.AnimationGroupListP3DChunk.parentClass.new(self, Data)
o.Version, o.NumGroups = unpack("<ii", o.ValueStr)
return o
end
function P3D.AnimationGroupListP3DChunk:create(Version)
local Len = 12 + 4 + 4
return P3D.AnimationGroupListP3DChunk:new{Raw = pack("<IIIii", P3D.Identifiers.Animation_Group_List, Len, Len, Version, 0)}
end
function P3D.AnimationGroupListP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + 4 + 4
return pack("<IIIii", self.ChunkType, Len, Len + chunks:len(), self.Version, #self.Chunks) .. chunks
end
--Animation Group Chunk
P3D.AnimationGroupP3DChunk = P3D.P3DChunk:newChildClass("Animation Group")
function P3D.AnimationGroupP3DChunk:new(Data)
local o = P3D.AnimationGroupP3DChunk.parentClass.new(self, Data)
o.Version, o.Name, o.GroupId, o.NumChannels = unpack("<is1ii", o.ValueStr)
return o
end
function P3D.AnimationGroupP3DChunk:create(Version,Name,GroupId)
local Len = 12 + 4 + Name:len() + 1 + 4 + 4
return P3D.AnimationGroupP3DChunk:new{Raw = pack("<IIIis1ii", P3D.Identifiers.Animation_Group, Len, Len, Version, Name, GroupId, 0)}
end
function P3D.AnimationGroupP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + 4 + self.Name:len() + 1 + 4 + 4
return pack("<IIIis1ii", self.ChunkType, Len, Len + chunks:len(), self.Version, self.Name, self.GroupId, #self.Chunks) .. chunks
end
--Compressed Quaternion Channel Chunk
P3D.CompressedQuaternionChannelP3DChunk = P3D.P3DChunk:newChildClass("Compressed Quaternion Channel")
function P3D.CompressedQuaternionChannelP3DChunk:new(Data)
local o = P3D.CompressedQuaternionChannelP3DChunk.parentClass.new(self, Data)
o.Version, o.Param, o.NumFrames = unpack("<ic4i", o.ValueStr)
local idx = 1 + 4 + 4 + 4
o.Frames = {unpack("<" .. string.rep("h", o.NumFrames), o.ValueStr, idx)}
o.Frames[#o.Frames] = nil
idx = idx + o.NumFrames * 2
o.Values = {}
for i=1,o.NumFrames do
local value = {X=0,Y=0,Z=0,W=0}
value.W, value.X, value.Y, value.Z = unpack("<hhhh", o.ValueStr, idx)
value.X = value.X / 32767
value.Y = value.Y / 32767
value.Z = value.Z / 32767
value.W = value.W / 32767
o.Values[#o.Values + 1] = value
idx = idx + 8
end
return o
end
--TODO: Create
function P3D.CompressedQuaternionChannelP3DChunk:GetFrameCount()
return #self.Frames
end
function P3D.CompressedQuaternionChannelP3DChunk:Output()
local chunks = concat(self.Chunks)
local FramesN = self:GetFrameCount()
local values = {}
for i=1,FramesN do
local value = self.Values[i]
values[#values + 1] = pack("hhhh", math.floor(value.W * 32767), math.floor(value.X * 32767), math.floor(value.Y * 32767), math.floor(value.X * 32767))
end
local Len = 12 + 4 + 4 + 4 + FramesN * 2 + FramesN * 8
return pack("<IIIic4i" .. string.rep("h", #self.Frames), self.ChunkType, Len, Len + chunks:len(), self.Version, self.Param, FramesN, table.unpack(self.Frames)) .. concat(values) .. chunks
end
--Follow Camera Data Chunk
P3D.FollowCameraDataP3DChunk = P3D.P3DChunk:newChildClass("Follow Camera Data")
function P3D.FollowCameraDataP3DChunk:new(Data)
local o = P3D.FollowCameraDataP3DChunk.parentClass.new(self, Data)
o.Look = {X=0,Y=0,Z=0}
o.Index, o.Unknown, o.Angle, o.Distance, o.Look.X, o.Look.Y, o.Look.Z = unpack("<iffffff", o.ValueStr)
return o
end
function P3D.FollowCameraDataP3DChunk:create(Index,Unknown,Angle,Distance,Look)
local Len = 12 + 4 + 4 + 4 + 4 + 12
return P3D.FollowCameraDataP3DChunk:new{Raw = pack("<IIIiffffff", P3D.Identifiers.Follow_Camera_Data, Len, Len, Index, Unknown, Angle, Distance, Look.X, Look.Y, Look.Z)}
end
function P3D.FollowCameraDataP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + 4 + 4 + 4 + 4 + 12
return pack("<IIIiffffff", self.ChunkType, Len, Len + chunks:len(), self.Index, self.Unknown, self.Angle, self.Distance, self.Look.X, self.Look.Y, self.Look.Z) .. chunks
end
--Sprite Chunk
P3D.SpriteP3DChunk = P3D.P3DChunk:newChildClass("Sprite")
function P3D.SpriteP3DChunk:new(Data)
local o = P3D.SpriteP3DChunk.parentClass.new(self, Data)
o.Name, o.NativeX, o.NativeY, o.Shader, o.ImageWidth, o.ImageHeight, o.ImageCount, o.BlitBorder = unpack("<s1iis1iiii", o.ValueStr)
return o
end
function P3D.SpriteP3DChunk:create(Name,NativeX,NativeY,Shader,ImageWidth,ImageHeight,ImageCount,BlitBorder)
local Len = 12 + Name:len() + 1 + 4 + 4 + Shader:len() + 1 + 4 + 4 + 4 + 4
return P3D.SpriteP3DChunk:new{Raw = pack("<IIIs1iis1iiii", P3D.Identifiers.Sprite, Len, Len, Name, NativeX, NativeY, Shader, ImageWidth, ImageHeight, ImageCount, BlitBorder)}
end
function P3D.SpriteP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + 4 + self.Shader:len() + 1 + 4 + 4 + 4 + 4
return pack("<IIIs1iis1iiii", self.ChunkType, Len, Len + chunks:len(), self.Name, self.NativeX, self.NativeY, self.Shader, self.ImageWidth, self.ImageHeight, self.ImageCount, self.BlitBorder) .. chunks
end
function P3D.SpriteP3DChunk:RemoveChunkAtIndex(idx)
local ID = self.ChunkTypes[idx]
P3D.SpriteP3DChunk.parentClass.RemoveChunkAtIndex(self, idx)
if ID == P3D.Identifiers.Image then
self.ImageCount = self.ImageCount - 1
end
end
function P3D.SpriteP3DChunk:AddChunk(ChunkData, idx)
local _, ID = P3D.SpriteP3DChunk.parentClass.AddChunk(self, ChunkData, idx)
if ID == P3D.Identifiers.Image then
self.ImageCount = self.ImageCount + 1
end
end
--Image Chunk
P3D.ImageP3DChunk = P3D.P3DChunk:newChildClass("Image")
P3D.ImageP3DChunk.Formats = {
Raw = 0,
PNG = 1,
TGA = 2,
BMP = 3,
IPU = 4,
DXT = 5,
DXT1 = 6,
DXT2 = 7,
DXT3 = 8,
DXT4 = 9,
DXT5 = 10,
PS24Bit = 11,
PS28Bit = 12,
PS216Bit = 13,
PS232Bit = 14,
GC4Bit = 15,
GC8Bit = 16,
GC16Bit = 17,
GC32Bit = 18,
GCDXT1 = 19,
Other = 20,
Invalid = 21,
PSP4Bit = 25,
}
function P3D.ImageP3DChunk:new(Data)
local o = P3D.ImageP3DChunk.parentClass.new(self, Data)
o.Name, o.Version, o.Width, o.Height, o.Bpp, o.Palettized, o.HasAlpha, o.Format = unpack("<s1iiiiiii", o.ValueStr)
return o
end
function P3D.ImageP3DChunk:create(Name,Version,Width,Height,Bpp,Palettized,HasAlpha,Format)
local Len = 12 + Name:len() + 1 + 4 + 4 + 4 + 4 + 4 + 4 + 4
return P3D.ImageP3DChunk:new{Raw = pack("<IIIs1iiiiiii", P3D.Identifiers.Image, Len, Len, Name, Version, Width, Height, Bpp, Palettized, HasAlpha, Format)}
end
function P3D.ImageP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + 4 + 4 + 4 + 4 + 4 + 4
return pack("<IIIs1iiiiiii", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Version, self.Width, self.Height, self.Bpp, self.Palettized, self.HasAlpha, self.Format) .. chunks
end
--Image Data Chunk
P3D.ImageDataP3DChunk = P3D.P3DChunk:newChildClass("Image Data")
function P3D.ImageDataP3DChunk:new(Data)
local o = P3D.ImageDataP3DChunk.parentClass.new(self, Data)
o.ImageDataSize = unpack("<i", o.ValueStr)
o.ImageData = unpack("<c" .. o.ImageDataSize, o.ValueStr, 5)
return o
end
function P3D.ImageDataP3DChunk:create(ImageData)
local ImageDataSize = ImageData:len()
local Len = 12 + 4 + ImageDataSize
return P3D.ImageDataP3DChunk:new{Raw = pack("<IIIic" .. ImageDataSize, P3D.Identifiers.Image_Data, Len, Len, ImageDataSize, ImageData)}
end
function P3D.ImageDataP3DChunk:Output()
local chunks = concat(self.Chunks)
local ImageDataSize = self.ImageData:len()
local Len = 12 + 4 + ImageDataSize
return pack("<IIIic" .. ImageDataSize, self.ChunkType, Len, Len + chunks:len(), ImageDataSize, self.ImageData) .. chunks
end
--Frontend Text Bible Chunk
P3D.FrontendTextBibleP3DChunk = P3D.P3DChunk:newChildClass("Frontend Text Bible")
function P3D.FrontendTextBibleP3DChunk:new(Data)
local o = P3D.FrontendTextBibleP3DChunk.parentClass.new(self, Data)
o.Name, o.NumLanguages, o.Languages = unpack("<s1is1", o.ValueStr)
return o
end
--TODO: Handle create and addition/removal of languages
function P3D.FrontendTextBibleP3DChunk:GetLanguageCount()
local LanguageN = 0
for i=1,#self.ChunkTypes do
if self.ChunkTypes[i] == P3D.Identifiers.Frontend_Language then
LanguageN = LanguageN + 1
end
end
return LanguageN
end
function P3D.FrontendTextBibleP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + self.Languages:len() + 1
return pack("<IIIs1is1", self.ChunkType, Len, Len + chunks:len(), self.Name, self:GetLanguageCount(), self.Languages) .. chunks
end
--Frontend Language Chunk
P3D.FrontendLanguageP3DChunk = P3D.P3DChunk:newChildClass("Frontend Language")
function P3D.FrontendLanguageP3DChunk:new(Data)
local o = P3D.FrontendLanguageP3DChunk.parentClass.new(self, Data)
o.Name, o.Language, o.NumEntries, o.Modulo, o.BufferSize = unpack("<s1c1iii", o.ValueStr)
local idx = 1 + o.Name:len() + 1 + 1 + 4 + 4 + 4
o.Hashes = {unpack("<" .. string.rep("I", o.NumEntries), o.ValueStr, idx)}
o.Hashes[#o.Hashes] = nil
idx = idx + 4 * o.NumEntries
o.Offsets = {unpack("<" .. string.rep("I", o.NumEntries), o.ValueStr, idx)}
o.Offsets[#o.Offsets] = nil
idx = idx + 4 * o.NumEntries
o.Buffer = unpack("<c" .. o.BufferSize, o.ValueStr, idx)
return o
end
function P3D.FrontendLanguageP3DChunk:GetValueFromHash(Hash)
local index = nil
for i=1,#self.Hashes do
if self.Hashes[i] == Hash then
index = i
break
end
end
if not index then return nil end
local out = {}
for i=self.Offsets[index] + 1,#self.Buffer,2 do
local s = unpack("<H", self.Buffer, i)
if s == 0 then break end
out[#out + 1] = s
end
return utf8.char(table.unpack(out))
end
function P3D.FrontendLanguageP3DChunk:GetValueFromName(Name)
local Hash = self:GetNameHash(Name)
return self:GetValueFromHash(Hash)
end
function P3D.FrontendLanguageP3DChunk:GetNameHash(Name)
local Hash = 0
local chars = {unpack("<" .. string.rep("B", #Name), Name)}
for i=1,#Name do
local c = chars[i]
Hash = (c + (Hash << 6)) % self.Modulo
end
return Hash
end
function P3D.FrontendLanguageP3DChunk:AddValue(Name, String)
local ucs2 = {}
for p,c in utf8.codes(String) do
if c == 0 then break end
ucs2[#ucs2 + 1] = c
end
ucs2[#ucs2 + 1] = 0
String = pack("<" .. string.rep("H", #ucs2), table.unpack(ucs2))
self.Hashes[#self.Hashes + 1] = self:GetNameHash(Name)
self.Offsets[#self.Offsets + 1] = #self.Buffer
self.Buffer = self.Buffer .. String
end
--TODO: Handle create, handle remove, handle insert, handle edit, handle bulk add
function P3D.FrontendLanguageP3DChunk:GetEntryCount()
return #self.Hashes
end
function P3D.FrontendLanguageP3DChunk:Output()
local chunks = concat(self.Chunks)
local EntriesN = self:GetEntryCount()
local BufferSize = self.Buffer:len()
local Len = 12 + self.Name:len() + 1 + 1 + 4 + 4 + 4 + 4 * EntriesN + 4 * EntriesN + BufferSize
local output = {}
output[1] = pack("<IIIs1c1iii", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Language, EntriesN, self.Modulo, BufferSize)
output[2] = pack("<" .. string.rep("I", EntriesN), table.unpack(self.Hashes))
output[3] = pack("<" .. string.rep("I", EntriesN), table.unpack(self.Offsets))
output[4] = pack("<c" .. BufferSize, self.Buffer)
output[5] = chunks
return concat(output)
end
--Trigger Volume Chunk
P3D.TriggerVolumeP3DChunk = P3D.P3DChunk:newChildClass("Trigger Volume")
function P3D.TriggerVolumeP3DChunk:new(Data)
local o = P3D.TriggerVolumeP3DChunk.parentClass.new(self, Data)
o.HalfExtents = {X=0,Y=0,Z=0}
o.Matrix = P3D.MatrixIdentity()
o.Name, o.IsRect, o.HalfExtents.X, o.HalfExtents.Y, o.HalfExtents.Z, o.Matrix.M11, o.Matrix.M12, o.Matrix.M13, o.Matrix.M14, o.Matrix.M21, o.Matrix.M22, o.Matrix.M23, o.Matrix.M34, o.Matrix.M31, o.Matrix.M32, o.Matrix.M33, o.Matrix.M34, o.Matrix.M41, o.Matrix.M42, o.Matrix.M43, o.Matrix.M44 = unpack("<s1ifffffffffffffffffff", o.ValueStr)
return o
end
function P3D.TriggerVolumeP3DChunk:create(Name,IsRect,HalfExtents,Matrix)
local Len = 12 + Name:len() + 1 + 4 + 12 + 64
return P3D.TriggerVolumeP3DChunk:new{Raw = pack("<IIIs1ifffffffffffffffffff", P3D.Identifiers.Trigger_Volume, Len, Len, Name, IsRect, HalfExtents.X, HalfExtents.Y, HalfExtents.Z, Matrix.M11, Matrix.M12, Matrix.M13, Matrix.M14, Matrix.M21, Matrix.M22, Matrix.M23, Matrix.M34, Matrix.M31, Matrix.M32, Matrix.M33, Matrix.M34, Matrix.M41, Matrix.M42, Matrix.M43, Matrix.M44)}
end
function P3D.TriggerVolumeP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + 12 + 64
return pack("<IIIs1ifffffffffffffffffff", self.ChunkType, Len, Len + chunks:len(), self.Name, self.IsRect, self.HalfExtents.X, self.HalfExtents.Y, self.HalfExtents.Z, self.Matrix.M11, self.Matrix.M12, self.Matrix.M13, self.Matrix.M14, self.Matrix.M21, self.Matrix.M22, self.Matrix.M23, self.Matrix.M34, self.Matrix.M31, self.Matrix.M32, self.Matrix.M33, self.Matrix.M34, self.Matrix.M41, self.Matrix.M42, self.Matrix.M43, self.Matrix.M44) .. chunks
end
--Frontend Project Chunk
P3D.FrontendProjectP3DChunk = P3D.P3DChunk:newChildClass("Frontend Project")
function P3D.FrontendProjectP3DChunk:new(Data)
local o = P3D.FrontendProjectP3DChunk.parentClass.new(self, Data)
o.Name, o.Version, o.ResolutionX, o.ResolutionY, o.Platform, o.PagePath, o.ResourcePath, o.ScreenPath = unpack("<s1iiis1s1s1s1", o.ValueStr)
return o
end
function P3D.FrontendProjectP3DChunk:create(Name,Version,ResolutionX,ResolutionY,Platform,PagePath,ResourcePath,ScreenPath)
local Len = 12 + Name:len() + 1 + 4 + 4 + 4 + Platform:len() + 1 + PagePath:len() + 1 + ResourcePath:len() + 1 + ScreenPath:len() + 1
return P3D.FrontendProjectP3DChunk:new{Raw = pack("<IIIs1iiis1s1s1s1", P3D.Identifiers.Frontend_Project, Len, Len, Name, Version, ResolutionX, ResolutionY, Platform, PagePath, ResourcePath, ScreenPath)}
end
function P3D.FrontendProjectP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + 4 + 4 + self.Platform:len() + 1 + self.PagePath:len() + 1 + self.ResourcePath:len() + 1 + self.ScreenPath:len() + 1
return pack("<IIIs1iiis1s1s1s1", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Version, self.ResolutionX, self.ResolutionY, self.Platform, self.PagePath, self.ResourcePath, self.ScreenPath) .. chunks
end
--Frontend Page Chunk
P3D.FrontendPageP3DChunk = P3D.P3DChunk:newChildClass("Frontend Page")
function P3D.FrontendPageP3DChunk:new(Data)
local o = P3D.FrontendPageP3DChunk.parentClass.new(self, Data)
o.Name, o.Version, o.ResolutionX, o.ResolutionY = unpack("<s1iii", o.ValueStr)
return o
end
function P3D.FrontendPageP3DChunk:create(Name,Version,ResolutionX,ResolutionY)
local Len = 12 + Name:len() + 1 + 4 + 4 + 4
return P3D.FrontendPageP3DChunk:new{Raw = pack("<IIIs1iii", P3D.Identifiers.Frontend_Page, Len, Len, Name, Version, ResolutionX, ResolutionY)}
end
function P3D.FrontendPageP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + 4 + 4
return pack("<IIIs1iii", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Version, self.ResolutionX, self.ResolutionY) .. chunks
end
--Frontend Layer Chunk
P3D.FrontendLayerP3DChunk = P3D.P3DChunk:newChildClass("Frontend Layer")
function P3D.FrontendLayerP3DChunk:new(Data)
local o = P3D.FrontendLayerP3DChunk.parentClass.new(self, Data)
o.Name, o.Version, o.Visible, o.Editable, o.Alpha = unpack("<s1iiii", o.ValueStr)
return o
end
function P3D.FrontendLayerP3DChunk:create(Name,Version,Visible,Editable,Alpha)
local Len = 12 + Name:len() + 1 + 4 + 4 + 4 + 4
return P3D.FrontendLayerP3DChunk:new{Raw = pack("<IIIs1iiii", P3D.Identifiers.Frontend_Layer, Len, Len, Name, Version, Visible, Editable, Alpha)}
end
function P3D.FrontendLayerP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + 4 + 4 + 4
return pack("<IIIs1iiii", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Version, self.Visible, self.Editable, self.Alpha) .. chunks
end
--Frontend Multi Text Chunk
P3D.FrontendMultiTextP3DChunk = P3D.P3DChunk:newChildClass("Frontend Multi Text")
P3D.FrontendMultiTextP3DChunk.Justifications = {
Left = 0,
Right = 1,
Top = 2,
Bottom = 3,
Centre = 4,
}
function P3D.FrontendMultiTextP3DChunk:new(Data)
local o = P3D.FrontendMultiTextP3DChunk.parentClass.new(self, Data)
o.Colour = {A=0,R=0,G=0,B=0}
o.ShadowColour = {A=0,R=0,G=0,B=0}
o.Name, o.Version, o.PositionX, o.PositionY, o.DimensionX, o.DimensionY, o.JustificationX, o.JustificationY, o.Colour.B, o.Colour.G, o.Colour.R, o.Colour.A, o.Translucency, o.RotationValue, o.TextStyleName, o.ShadowEnabled, o.ShadowColour.B, o.ShadowColour.G, o.ShadowColour.R, o.ShadowColour.A, o.ShadowOffsetX, o.ShadowOffsetY, o.CurrentText = unpack("<s1iiiiiiiBBBBifs1BBBBBiii", o.ValueStr)
return o
end
function P3D.FrontendMultiTextP3DChunk:create(Name,Version,PositionX,PositionY,DimensionX,DimensionY,JustificationX,JustificationY,Colour,Translucency,RotationValue,TextStyleName,ShadowEnabled,ShadowColour,ShadowOffsetX,ShadowOffsetY,CurrentText)
local Len = 12 + Name:len() + 1 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + TextStyleName:len() + 1 + 1 + 4 + 4 + 4 + 4
return P3D.FrontendMultiTextP3DChunk:new{Raw = pack("<IIIs1iiiiiiiBBBBifs1BBBBBiii", P3D.Identifiers.Frontend_Multi_Text, Len, Len, Name, Version, PositionX, PositionY, DimensionX, DimensionY, JustificationX, JustificationY, Colour.B, Colour.G, Colour.R, Colour.A, Translucency, RotationValue, TextStyleName, ShadowEnabled, ShadowColour.B, ShadowColour.G, ShadowColour.R, ShadowColour.A, ShadowOffsetX, ShadowOffsetY, CurrentText)}
end
function P3D.FrontendMultiTextP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + self.TextStyleName:len() + 1 + 1 + 4 + 4 + 4 + 4
return pack("<IIIs1iiiiiiiBBBBifs1BBBBBiii", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Version, self.PositionX, self.PositionY, self.DimensionX, self.DimensionY, self.JustificationX, self.JustificationY, self.Colour.B, self.Colour.G, self.Colour.R, self.Colour.A, self.Translucency, self.RotationValue, self.TextStyleName, self.ShadowEnabled, self.ShadowColour.B, self.ShadowColour.G, self.ShadowColour.R, self.ShadowColour.A, self.ShadowOffsetX, self.ShadowOffsetY, self.CurrentText) .. chunks
end
--Frontend Text Style Resource Chunk
P3D.FrontendTextStyleResourceP3DChunk = P3D.P3DChunk:newChildClass("Frontend Text Style Resource")
function P3D.FrontendTextStyleResourceP3DChunk:new(Data)
local o = P3D.FrontendTextStyleResourceP3DChunk.parentClass.new(self, Data)
o.Name, o.Version, o.Filename, o.InventoryName = unpack("<s1is1s1", o.ValueStr)
return o
end
function P3D.FrontendTextStyleResourceP3DChunk:create(Name,Version,Filename,InventoryName)
local Len = 12 + Name:len() + 1 + 4 + Filename:len() + 1 + InventoryName:len() + 1
return P3D.FrontendTextStyleResourceP3DChunk:new{Raw = pack("<IIIs1is1s1", P3D.Identifiers.Frontend_Text_Style_Resource, Len, Len, Name, Version, Filename, InventoryName)}
end
function P3D.FrontendTextStyleResourceP3DChunk:Output()
local chunks = table.concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + self.Filename:len() + 1 + self.InventoryName:len() + 1
return pack("<IIIs1is1s1", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Version, self.Filename, self.InventoryName) .. chunks
end
--Frontend String Text Bible Chunk
P3D.FrontendStringTextBibleP3DChunk = P3D.P3DChunk:newChildClass("Frontend String Text Bible")
function P3D.FrontendStringTextBibleP3DChunk:new(Data)
local o = P3D.FrontendStringTextBibleP3DChunk.parentClass.new(self, Data)
o.BibleName, o.StringId = unpack("<s1s1", o.ValueStr)
return o
end
function P3D.FrontendStringTextBibleP3DChunk:create(BibleName,StringId)
local Len = 12 + BibleName:len() + 1 + StringId:len() + 1
return P3D.FrontendStringTextBibleP3DChunk:new{Raw = pack("<IIIs1s1", P3D.Identifiers.Frontend_String_Text_Bible, Len, Len, BibleName, StringId)}
end
function P3D.FrontendStringTextBibleP3DChunk:Output()
local chunks = concat(self.Chunks)
local Len = 12 + self.BibleName:len() + 1 + self.StringId:len() + 1
return pack("<IIIs1s1", self.ChunkType, Len, Len + chunks:len(), self.BibleName, self.StringId) .. chunks
end
--Road Data Segment Chunk
P3D.RoadDataSegmentP3DChunk = P3D.P3DChunk:newChildClass("Road Data Segment")
function P3D.RoadDataSegmentP3DChunk:new(Data)
local o = P3D.RoadDataSegmentP3DChunk.parentClass.new(self, Data)
o.Position = {X=0,Y=0,Z=0}
o.Position2 = {X=0,Y=0,Z=0}
o.Position3 = {X=0,Y=0,Z=0}
o.Name, o.Unknown, o.Lanes, o.Unknown2, o.Position.X, o.Position.Y, o.Position.Z, o.Position2.X, o.Position2.Y, o.Position2.Z, o.Position3.X, o.Position3.Y, o.Position3.Z = unpack("<s1iiifffffffff", o.ValueStr)
return o
end
function P3D.RoadDataSegmentP3DChunk:create(Name,Unknown,Lanes,Unknown2,Position,Position2,Position3)
local Len = 12 + Name:len() + 1 + 4 + 4 + 4 + 12 + 12 + 12
return P3D.RoadDataSegmentP3DChunk:new{Raw = pack("<IIIs1iiifffffffff", P3D.Identifiers.Road_Data_Segment, Len, Len, Name, Unknown, Lanes, Unknown2, Position.X, Position.Y, Position.Z, Position2.X, Position2.Y, Position2.Z, Position3.X, Position3.Y, Position3.Z)}
end
function P3D.RoadDataSegmentP3DChunk:Output()
local chunks = table.concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + 4 + 4 + 12 + 12 + 12
return pack("<IIIs1iiifffffffff", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Unknown, self.Lanes, self.Unknown2, self.Position.X, self.Position.Y, self.Position.Z, self.Position2.X, self.Position2.Y, self.Position2.Z, self.Position3.X, self.Position3.Y, self.Position3.Z) .. chunks
end
--Road Segment Chunk
P3D.RoadSegmentP3DChunk = P3D.P3DChunk:newChildClass("Road Segment")
function P3D.RoadSegmentP3DChunk:new(Data)
local o = P3D.RoadSegmentP3DChunk.parentClass.new(self, Data)
o.Transform = P3D.MatrixIdentity()
o.Unknown = P3D.MatrixIdentity()
o.Name, o.CubeShape, o.Transform.M11, o.Transform.M12, o.Transform.M13, o.Transform.M14, o.Transform.M21, o.Transform.M22, o.Transform.M23, o.Transform.M34, o.Transform.M31, o.Transform.M32, o.Transform.M33, o.Transform.M34, o.Transform.M41, o.Transform.M42, o.Transform.M43, o.Transform.M44, o.Unknown.M11, o.Unknown.M12, o.Unknown.M13, o.Unknown.M14, o.Unknown.M21, o.Unknown.M22, o.Unknown.M23, o.Unknown.M34, o.Unknown.M31, o.Unknown.M32, o.Unknown.M33, o.Unknown.M34, o.Unknown.M41, o.Unknown.M42, o.Unknown.M43, o.Unknown.M44 = unpack("<s1s1ffffffffffffffffffffffffffffffff", o.ValueStr)
return o
end
function P3D.RoadSegmentP3DChunk:create(Name,CubeShape,Transform,Unknown)
local Len = 12 + Name:len() + 1 + CubeShape:len() + 1 + 64 + 64
return P3D.RoadSegmentP3DChunk:new{Raw = pack("<IIIs1s1ffffffffffffffffffffffffffffffff", P3D.Identifiers.Road_Segment, Len, Len, Name, CubeShape, Transform.M11, Transform.M12, Transform.M13, Transform.M14, Transform.M21, Transform.M22, Transform.M23, Transform.M34, Transform.M31, Transform.M32, Transform.M33, Transform.M34, Transform.M41, Transform.M42, Transform.M43, Transform.M44, Unknown.M11, Unknown.M12, Unknown.M13, Unknown.M14, Unknown.M21, Unknown.M22, Unknown.M23, Unknown.M34, Unknown.M31, Unknown.M32, Unknown.M33, Unknown.M34, Unknown.M41, Unknown.M42, Unknown.M43, Unknown.M44)}
end
function P3D.RoadSegmentP3DChunk:Output()
local chunks = table.concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + self.CubeShape:len() + 1 + 64 + 64
return pack("<IIIs1s1ffffffffffffffffffffffffffffffff", self.ChunkType, Len, Len + chunks:len(), self.Name, self.CubeShape, self.Transform.M11, self.Transform.M12, self.Transform.M13, self.Transform.M14, self.Transform.M21, self.Transform.M22, self.Transform.M23, self.Transform.M34, self.Transform.M31, self.Transform.M32, self.Transform.M33, self.Transform.M34, self.Transform.M41, self.Transform.M42, self.Transform.M43, self.Transform.M44, self.Unknown.M11, self.Unknown.M12, self.Unknown.M13, self.Unknown.M14, self.Unknown.M21, self.Unknown.M22, self.Unknown.M23, self.Unknown.M34, self.Unknown.M31, self.Unknown.M32, self.Unknown.M33, self.Unknown.M34, self.Unknown.M41, self.Unknown.M42, self.Unknown.M43, self.Unknown.M44) .. chunks
end
--Road Chunk
P3D.RoadP3DChunk = P3D.P3DChunk:newChildClass("Road")
function P3D.RoadP3DChunk:new(Data)
local o = P3D.RoadP3DChunk.parentClass.new(self, Data)
o.Name, o.Unknown, o.StartIntersectionLocatorNode, o.EndIntersectionLocatorNode, o.MaximumCars, o.Speed, o.Intelligence, o.Shortcut, o.Unknown4 = unpack("<s1is1s1iBBBB", o.ValueStr)
return o
end
function P3D.RoadP3DChunk:create(Name,Unknown,StartIntersectionLocatorNode,EndIntersectionLocatorNode,MaximumCars,Speed,Intelligence,Shortcut,Unknown4)
local Len = 12 + Name:len() + 1 + 4 + StartIntersectionLocatorNode:len() + 1 + EndIntersectionLocatorNode:len() + 1 + 4 + 1 + 1 + 1 + 1
return P3D.RoadP3DChunk:new{Raw = pack("<IIIs1is1s1iBBBB", P3D.Identifiers.Road, Len, Len, Name, Unknown, StartIntersectionLocatorNode, EndIntersectionLocatorNode, MaximumCars, Speed, Intelligence, Shortcut, Unknown4)}
end
function P3D.RoadP3DChunk:Output()
local chunks = table.concat(self.Chunks)
local Len = 12 + self.Name:len() + 1 + 4 + self.StartIntersectionLocatorNode:len() + 1 + self.EndIntersectionLocatorNode:len() + 1 + 4 + 1 + 1 + 1 + 1
return pack("<IIIs1is1s1iBBBB", self.ChunkType, Len, Len + chunks:len(), self.Name, self.Unknown, self.StartIntersectionLocatorNode, self.EndIntersectionLocatorNode, self.MaximumCars, self.Speed, self.Intelligence, self.Shortcut, self.Unknown4) .. chunks
end
|
--- GENERATED CODE - DO NOT MODIFY
-- Amazon Simple Notification Service (sns-2010-03-31)
local M = {}
M.metadata = {
api_version = "2010-03-31",
json_version = "",
protocol = "query",
checksum_format = "",
endpoint_prefix = "sns",
service_abbreviation = "Amazon SNS",
service_full_name = "Amazon Simple Notification Service",
signature_version = "v4",
target_prefix = "",
timestamp_format = "",
global_endpoint = "",
uid = "sns-2010-03-31",
}
local keys = {}
local asserts = {}
keys.SubscriptionLimitExceededException = { ["message"] = true, nil }
function asserts.AssertSubscriptionLimitExceededException(struct)
assert(struct)
assert(type(struct) == "table", "Expected SubscriptionLimitExceededException to be of type 'table'")
if struct["message"] then asserts.Assertstring(struct["message"]) end
for k,_ in pairs(struct) do
assert(keys.SubscriptionLimitExceededException[k], "SubscriptionLimitExceededException contains unknown key " .. tostring(k))
end
end
--- Create a structure of type SubscriptionLimitExceededException
-- <p>Indicates that the customer already owns the maximum allowed number of subscriptions.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * message [string]
-- @return SubscriptionLimitExceededException structure as a key-value pair table
function M.SubscriptionLimitExceededException(args)
assert(args, "You must provide an argument table when creating SubscriptionLimitExceededException")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["message"] = args["message"],
}
asserts.AssertSubscriptionLimitExceededException(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.CheckIfPhoneNumberIsOptedOutInput = { ["phoneNumber"] = true, nil }
function asserts.AssertCheckIfPhoneNumberIsOptedOutInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected CheckIfPhoneNumberIsOptedOutInput to be of type 'table'")
assert(struct["phoneNumber"], "Expected key phoneNumber to exist in table")
if struct["phoneNumber"] then asserts.AssertPhoneNumber(struct["phoneNumber"]) end
for k,_ in pairs(struct) do
assert(keys.CheckIfPhoneNumberIsOptedOutInput[k], "CheckIfPhoneNumberIsOptedOutInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type CheckIfPhoneNumberIsOptedOutInput
-- <p>The input for the <code>CheckIfPhoneNumberIsOptedOut</code> action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * phoneNumber [PhoneNumber] <p>The phone number for which you want to check the opt out status.</p>
-- Required key: phoneNumber
-- @return CheckIfPhoneNumberIsOptedOutInput structure as a key-value pair table
function M.CheckIfPhoneNumberIsOptedOutInput(args)
assert(args, "You must provide an argument table when creating CheckIfPhoneNumberIsOptedOutInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["phoneNumber"] = args["phoneNumber"],
}
asserts.AssertCheckIfPhoneNumberIsOptedOutInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.GetEndpointAttributesResponse = { ["Attributes"] = true, nil }
function asserts.AssertGetEndpointAttributesResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected GetEndpointAttributesResponse to be of type 'table'")
if struct["Attributes"] then asserts.AssertMapStringToString(struct["Attributes"]) end
for k,_ in pairs(struct) do
assert(keys.GetEndpointAttributesResponse[k], "GetEndpointAttributesResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type GetEndpointAttributesResponse
-- <p>Response from GetEndpointAttributes of the EndpointArn.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * Attributes [MapStringToString] <p>Attributes include the following:</p> <ul> <li> <p> <code>CustomUserData</code> -- arbitrary user data to associate with the endpoint. Amazon SNS does not use this data. The data must be in UTF-8 format and less than 2KB.</p> </li> <li> <p> <code>Enabled</code> -- flag that enables/disables delivery to the endpoint. Amazon SNS will set this to false when a notification service indicates to Amazon SNS that the endpoint is invalid. Users can set it back to true, typically after updating Token.</p> </li> <li> <p> <code>Token</code> -- device token, also referred to as a registration id, for an app and mobile device. This is returned from the notification service when an app and mobile device are registered with the notification service.</p> </li> </ul>
-- @return GetEndpointAttributesResponse structure as a key-value pair table
function M.GetEndpointAttributesResponse(args)
assert(args, "You must provide an argument table when creating GetEndpointAttributesResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["Attributes"] = args["Attributes"],
}
asserts.AssertGetEndpointAttributesResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.GetEndpointAttributesInput = { ["EndpointArn"] = true, nil }
function asserts.AssertGetEndpointAttributesInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected GetEndpointAttributesInput to be of type 'table'")
assert(struct["EndpointArn"], "Expected key EndpointArn to exist in table")
if struct["EndpointArn"] then asserts.AssertString(struct["EndpointArn"]) end
for k,_ in pairs(struct) do
assert(keys.GetEndpointAttributesInput[k], "GetEndpointAttributesInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type GetEndpointAttributesInput
-- <p>Input for GetEndpointAttributes action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * EndpointArn [String] <p>EndpointArn for GetEndpointAttributes input.</p>
-- Required key: EndpointArn
-- @return GetEndpointAttributesInput structure as a key-value pair table
function M.GetEndpointAttributesInput(args)
assert(args, "You must provide an argument table when creating GetEndpointAttributesInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["EndpointArn"] = args["EndpointArn"],
}
asserts.AssertGetEndpointAttributesInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.SetTopicAttributesInput = { ["AttributeName"] = true, ["AttributeValue"] = true, ["TopicArn"] = true, nil }
function asserts.AssertSetTopicAttributesInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected SetTopicAttributesInput to be of type 'table'")
assert(struct["TopicArn"], "Expected key TopicArn to exist in table")
assert(struct["AttributeName"], "Expected key AttributeName to exist in table")
if struct["AttributeName"] then asserts.AssertattributeName(struct["AttributeName"]) end
if struct["AttributeValue"] then asserts.AssertattributeValue(struct["AttributeValue"]) end
if struct["TopicArn"] then asserts.AsserttopicARN(struct["TopicArn"]) end
for k,_ in pairs(struct) do
assert(keys.SetTopicAttributesInput[k], "SetTopicAttributesInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type SetTopicAttributesInput
-- <p>Input for SetTopicAttributes action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * AttributeName [attributeName] <p>The name of the attribute you want to set. Only a subset of the topic's attributes are mutable.</p> <p>Valid values: <code>Policy</code> | <code>DisplayName</code> | <code>DeliveryPolicy</code> </p>
-- * AttributeValue [attributeValue] <p>The new value for the attribute.</p>
-- * TopicArn [topicARN] <p>The ARN of the topic to modify.</p>
-- Required key: TopicArn
-- Required key: AttributeName
-- @return SetTopicAttributesInput structure as a key-value pair table
function M.SetTopicAttributesInput(args)
assert(args, "You must provide an argument table when creating SetTopicAttributesInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["AttributeName"] = args["AttributeName"],
["AttributeValue"] = args["AttributeValue"],
["TopicArn"] = args["TopicArn"],
}
asserts.AssertSetTopicAttributesInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.CreatePlatformApplicationInput = { ["Platform"] = true, ["Name"] = true, ["Attributes"] = true, nil }
function asserts.AssertCreatePlatformApplicationInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected CreatePlatformApplicationInput to be of type 'table'")
assert(struct["Name"], "Expected key Name to exist in table")
assert(struct["Platform"], "Expected key Platform to exist in table")
assert(struct["Attributes"], "Expected key Attributes to exist in table")
if struct["Platform"] then asserts.AssertString(struct["Platform"]) end
if struct["Name"] then asserts.AssertString(struct["Name"]) end
if struct["Attributes"] then asserts.AssertMapStringToString(struct["Attributes"]) end
for k,_ in pairs(struct) do
assert(keys.CreatePlatformApplicationInput[k], "CreatePlatformApplicationInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type CreatePlatformApplicationInput
-- <p>Input for CreatePlatformApplication action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * Platform [String] <p>The following platforms are supported: ADM (Amazon Device Messaging), APNS (Apple Push Notification Service), APNS_SANDBOX, and GCM (Google Cloud Messaging).</p>
-- * Name [String] <p>Application names must be made up of only uppercase and lowercase ASCII letters, numbers, underscores, hyphens, and periods, and must be between 1 and 256 characters long.</p>
-- * Attributes [MapStringToString] <p>For a list of attributes, see <a href="http://docs.aws.amazon.com/sns/latest/api/API_SetPlatformApplicationAttributes.html">SetPlatformApplicationAttributes</a> </p>
-- Required key: Name
-- Required key: Platform
-- Required key: Attributes
-- @return CreatePlatformApplicationInput structure as a key-value pair table
function M.CreatePlatformApplicationInput(args)
assert(args, "You must provide an argument table when creating CreatePlatformApplicationInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["Platform"] = args["Platform"],
["Name"] = args["Name"],
["Attributes"] = args["Attributes"],
}
asserts.AssertCreatePlatformApplicationInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.CreatePlatformEndpointInput = { ["Attributes"] = true, ["Token"] = true, ["PlatformApplicationArn"] = true, ["CustomUserData"] = true, nil }
function asserts.AssertCreatePlatformEndpointInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected CreatePlatformEndpointInput to be of type 'table'")
assert(struct["PlatformApplicationArn"], "Expected key PlatformApplicationArn to exist in table")
assert(struct["Token"], "Expected key Token to exist in table")
if struct["Attributes"] then asserts.AssertMapStringToString(struct["Attributes"]) end
if struct["Token"] then asserts.AssertString(struct["Token"]) end
if struct["PlatformApplicationArn"] then asserts.AssertString(struct["PlatformApplicationArn"]) end
if struct["CustomUserData"] then asserts.AssertString(struct["CustomUserData"]) end
for k,_ in pairs(struct) do
assert(keys.CreatePlatformEndpointInput[k], "CreatePlatformEndpointInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type CreatePlatformEndpointInput
-- <p>Input for CreatePlatformEndpoint action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * Attributes [MapStringToString] <p>For a list of attributes, see <a href="http://docs.aws.amazon.com/sns/latest/api/API_SetEndpointAttributes.html">SetEndpointAttributes</a>.</p>
-- * Token [String] <p>Unique identifier created by the notification service for an app on a device. The specific name for Token will vary, depending on which notification service is being used. For example, when using APNS as the notification service, you need the device token. Alternatively, when using GCM or ADM, the device token equivalent is called the registration ID.</p>
-- * PlatformApplicationArn [String] <p>PlatformApplicationArn returned from CreatePlatformApplication is used to create a an endpoint.</p>
-- * CustomUserData [String] <p>Arbitrary user data to associate with the endpoint. Amazon SNS does not use this data. The data must be in UTF-8 format and less than 2KB.</p>
-- Required key: PlatformApplicationArn
-- Required key: Token
-- @return CreatePlatformEndpointInput structure as a key-value pair table
function M.CreatePlatformEndpointInput(args)
assert(args, "You must provide an argument table when creating CreatePlatformEndpointInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["Attributes"] = args["Attributes"],
["Token"] = args["Token"],
["PlatformApplicationArn"] = args["PlatformApplicationArn"],
["CustomUserData"] = args["CustomUserData"],
}
asserts.AssertCreatePlatformEndpointInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ConfirmSubscriptionInput = { ["Token"] = true, ["AuthenticateOnUnsubscribe"] = true, ["TopicArn"] = true, nil }
function asserts.AssertConfirmSubscriptionInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected ConfirmSubscriptionInput to be of type 'table'")
assert(struct["TopicArn"], "Expected key TopicArn to exist in table")
assert(struct["Token"], "Expected key Token to exist in table")
if struct["Token"] then asserts.Asserttoken(struct["Token"]) end
if struct["AuthenticateOnUnsubscribe"] then asserts.AssertauthenticateOnUnsubscribe(struct["AuthenticateOnUnsubscribe"]) end
if struct["TopicArn"] then asserts.AsserttopicARN(struct["TopicArn"]) end
for k,_ in pairs(struct) do
assert(keys.ConfirmSubscriptionInput[k], "ConfirmSubscriptionInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ConfirmSubscriptionInput
-- <p>Input for ConfirmSubscription action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * Token [token] <p>Short-lived token sent to an endpoint during the <code>Subscribe</code> action.</p>
-- * AuthenticateOnUnsubscribe [authenticateOnUnsubscribe] <p>Disallows unauthenticated unsubscribes of the subscription. If the value of this parameter is <code>true</code> and the request has an AWS signature, then only the topic owner and the subscription owner can unsubscribe the endpoint. The unsubscribe action requires AWS authentication. </p>
-- * TopicArn [topicARN] <p>The ARN of the topic for which you wish to confirm a subscription.</p>
-- Required key: TopicArn
-- Required key: Token
-- @return ConfirmSubscriptionInput structure as a key-value pair table
function M.ConfirmSubscriptionInput(args)
assert(args, "You must provide an argument table when creating ConfirmSubscriptionInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["Token"] = args["Token"],
["AuthenticateOnUnsubscribe"] = args["AuthenticateOnUnsubscribe"],
["TopicArn"] = args["TopicArn"],
}
asserts.AssertConfirmSubscriptionInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ListSubscriptionsByTopicInput = { ["NextToken"] = true, ["TopicArn"] = true, nil }
function asserts.AssertListSubscriptionsByTopicInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected ListSubscriptionsByTopicInput to be of type 'table'")
assert(struct["TopicArn"], "Expected key TopicArn to exist in table")
if struct["NextToken"] then asserts.AssertnextToken(struct["NextToken"]) end
if struct["TopicArn"] then asserts.AsserttopicARN(struct["TopicArn"]) end
for k,_ in pairs(struct) do
assert(keys.ListSubscriptionsByTopicInput[k], "ListSubscriptionsByTopicInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ListSubscriptionsByTopicInput
-- <p>Input for ListSubscriptionsByTopic action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * NextToken [nextToken] <p>Token returned by the previous <code>ListSubscriptionsByTopic</code> request.</p>
-- * TopicArn [topicARN] <p>The ARN of the topic for which you wish to find subscriptions.</p>
-- Required key: TopicArn
-- @return ListSubscriptionsByTopicInput structure as a key-value pair table
function M.ListSubscriptionsByTopicInput(args)
assert(args, "You must provide an argument table when creating ListSubscriptionsByTopicInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["NextToken"] = args["NextToken"],
["TopicArn"] = args["TopicArn"],
}
asserts.AssertListSubscriptionsByTopicInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.PlatformApplication = { ["Attributes"] = true, ["PlatformApplicationArn"] = true, nil }
function asserts.AssertPlatformApplication(struct)
assert(struct)
assert(type(struct) == "table", "Expected PlatformApplication to be of type 'table'")
if struct["Attributes"] then asserts.AssertMapStringToString(struct["Attributes"]) end
if struct["PlatformApplicationArn"] then asserts.AssertString(struct["PlatformApplicationArn"]) end
for k,_ in pairs(struct) do
assert(keys.PlatformApplication[k], "PlatformApplication contains unknown key " .. tostring(k))
end
end
--- Create a structure of type PlatformApplication
-- <p>Platform application object.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * Attributes [MapStringToString] <p>Attributes for platform application object.</p>
-- * PlatformApplicationArn [String] <p>PlatformApplicationArn for platform application object.</p>
-- @return PlatformApplication structure as a key-value pair table
function M.PlatformApplication(args)
assert(args, "You must provide an argument table when creating PlatformApplication")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["Attributes"] = args["Attributes"],
["PlatformApplicationArn"] = args["PlatformApplicationArn"],
}
asserts.AssertPlatformApplication(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.EndpointDisabledException = { ["message"] = true, nil }
function asserts.AssertEndpointDisabledException(struct)
assert(struct)
assert(type(struct) == "table", "Expected EndpointDisabledException to be of type 'table'")
if struct["message"] then asserts.Assertstring(struct["message"]) end
for k,_ in pairs(struct) do
assert(keys.EndpointDisabledException[k], "EndpointDisabledException contains unknown key " .. tostring(k))
end
end
--- Create a structure of type EndpointDisabledException
-- <p>Exception error indicating endpoint disabled.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * message [string] <p>Message for endpoint disabled.</p>
-- @return EndpointDisabledException structure as a key-value pair table
function M.EndpointDisabledException(args)
assert(args, "You must provide an argument table when creating EndpointDisabledException")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["message"] = args["message"],
}
asserts.AssertEndpointDisabledException(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.GetSMSAttributesResponse = { ["attributes"] = true, nil }
function asserts.AssertGetSMSAttributesResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected GetSMSAttributesResponse to be of type 'table'")
if struct["attributes"] then asserts.AssertMapStringToString(struct["attributes"]) end
for k,_ in pairs(struct) do
assert(keys.GetSMSAttributesResponse[k], "GetSMSAttributesResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type GetSMSAttributesResponse
-- <p>The response from the <code>GetSMSAttributes</code> request.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * attributes [MapStringToString] <p>The SMS attribute names and their values.</p>
-- @return GetSMSAttributesResponse structure as a key-value pair table
function M.GetSMSAttributesResponse(args)
assert(args, "You must provide an argument table when creating GetSMSAttributesResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["attributes"] = args["attributes"],
}
asserts.AssertGetSMSAttributesResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.Topic = { ["TopicArn"] = true, nil }
function asserts.AssertTopic(struct)
assert(struct)
assert(type(struct) == "table", "Expected Topic to be of type 'table'")
if struct["TopicArn"] then asserts.AsserttopicARN(struct["TopicArn"]) end
for k,_ in pairs(struct) do
assert(keys.Topic[k], "Topic contains unknown key " .. tostring(k))
end
end
--- Create a structure of type Topic
-- <p>A wrapper type for the topic's Amazon Resource Name (ARN). To retrieve a topic's attributes, use <code>GetTopicAttributes</code>.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * TopicArn [topicARN] <p>The topic's ARN.</p>
-- @return Topic structure as a key-value pair table
function M.Topic(args)
assert(args, "You must provide an argument table when creating Topic")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["TopicArn"] = args["TopicArn"],
}
asserts.AssertTopic(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ListPhoneNumbersOptedOutInput = { ["nextToken"] = true, nil }
function asserts.AssertListPhoneNumbersOptedOutInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected ListPhoneNumbersOptedOutInput to be of type 'table'")
if struct["nextToken"] then asserts.Assertstring(struct["nextToken"]) end
for k,_ in pairs(struct) do
assert(keys.ListPhoneNumbersOptedOutInput[k], "ListPhoneNumbersOptedOutInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ListPhoneNumbersOptedOutInput
-- <p>The input for the <code>ListPhoneNumbersOptedOut</code> action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * nextToken [string] <p>A <code>NextToken</code> string is used when you call the <code>ListPhoneNumbersOptedOut</code> action to retrieve additional records that are available after the first page of results.</p>
-- @return ListPhoneNumbersOptedOutInput structure as a key-value pair table
function M.ListPhoneNumbersOptedOutInput(args)
assert(args, "You must provide an argument table when creating ListPhoneNumbersOptedOutInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["nextToken"] = args["nextToken"],
}
asserts.AssertListPhoneNumbersOptedOutInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.Subscription = { ["Owner"] = true, ["Endpoint"] = true, ["Protocol"] = true, ["TopicArn"] = true, ["SubscriptionArn"] = true, nil }
function asserts.AssertSubscription(struct)
assert(struct)
assert(type(struct) == "table", "Expected Subscription to be of type 'table'")
if struct["Owner"] then asserts.Assertaccount(struct["Owner"]) end
if struct["Endpoint"] then asserts.Assertendpoint(struct["Endpoint"]) end
if struct["Protocol"] then asserts.Assertprotocol(struct["Protocol"]) end
if struct["TopicArn"] then asserts.AsserttopicARN(struct["TopicArn"]) end
if struct["SubscriptionArn"] then asserts.AssertsubscriptionARN(struct["SubscriptionArn"]) end
for k,_ in pairs(struct) do
assert(keys.Subscription[k], "Subscription contains unknown key " .. tostring(k))
end
end
--- Create a structure of type Subscription
-- <p>A wrapper type for the attributes of an Amazon SNS subscription.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * Owner [account] <p>The subscription's owner.</p>
-- * Endpoint [endpoint] <p>The subscription's endpoint (format depends on the protocol).</p>
-- * Protocol [protocol] <p>The subscription's protocol.</p>
-- * TopicArn [topicARN] <p>The ARN of the subscription's topic.</p>
-- * SubscriptionArn [subscriptionARN] <p>The subscription's ARN.</p>
-- @return Subscription structure as a key-value pair table
function M.Subscription(args)
assert(args, "You must provide an argument table when creating Subscription")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["Owner"] = args["Owner"],
["Endpoint"] = args["Endpoint"],
["Protocol"] = args["Protocol"],
["TopicArn"] = args["TopicArn"],
["SubscriptionArn"] = args["SubscriptionArn"],
}
asserts.AssertSubscription(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ListSubscriptionsResponse = { ["NextToken"] = true, ["Subscriptions"] = true, nil }
function asserts.AssertListSubscriptionsResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected ListSubscriptionsResponse to be of type 'table'")
if struct["NextToken"] then asserts.AssertnextToken(struct["NextToken"]) end
if struct["Subscriptions"] then asserts.AssertSubscriptionsList(struct["Subscriptions"]) end
for k,_ in pairs(struct) do
assert(keys.ListSubscriptionsResponse[k], "ListSubscriptionsResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ListSubscriptionsResponse
-- <p>Response for ListSubscriptions action</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * NextToken [nextToken] <p>Token to pass along to the next <code>ListSubscriptions</code> request. This element is returned if there are more subscriptions to retrieve.</p>
-- * Subscriptions [SubscriptionsList] <p>A list of subscriptions.</p>
-- @return ListSubscriptionsResponse structure as a key-value pair table
function M.ListSubscriptionsResponse(args)
assert(args, "You must provide an argument table when creating ListSubscriptionsResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["NextToken"] = args["NextToken"],
["Subscriptions"] = args["Subscriptions"],
}
asserts.AssertListSubscriptionsResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ListTopicsResponse = { ["Topics"] = true, ["NextToken"] = true, nil }
function asserts.AssertListTopicsResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected ListTopicsResponse to be of type 'table'")
if struct["Topics"] then asserts.AssertTopicsList(struct["Topics"]) end
if struct["NextToken"] then asserts.AssertnextToken(struct["NextToken"]) end
for k,_ in pairs(struct) do
assert(keys.ListTopicsResponse[k], "ListTopicsResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ListTopicsResponse
-- <p>Response for ListTopics action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * Topics [TopicsList] <p>A list of topic ARNs.</p>
-- * NextToken [nextToken] <p>Token to pass along to the next <code>ListTopics</code> request. This element is returned if there are additional topics to retrieve.</p>
-- @return ListTopicsResponse structure as a key-value pair table
function M.ListTopicsResponse(args)
assert(args, "You must provide an argument table when creating ListTopicsResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["Topics"] = args["Topics"],
["NextToken"] = args["NextToken"],
}
asserts.AssertListTopicsResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.OptInPhoneNumberInput = { ["phoneNumber"] = true, nil }
function asserts.AssertOptInPhoneNumberInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected OptInPhoneNumberInput to be of type 'table'")
assert(struct["phoneNumber"], "Expected key phoneNumber to exist in table")
if struct["phoneNumber"] then asserts.AssertPhoneNumber(struct["phoneNumber"]) end
for k,_ in pairs(struct) do
assert(keys.OptInPhoneNumberInput[k], "OptInPhoneNumberInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type OptInPhoneNumberInput
-- <p>Input for the OptInPhoneNumber action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * phoneNumber [PhoneNumber] <p>The phone number to opt in.</p>
-- Required key: phoneNumber
-- @return OptInPhoneNumberInput structure as a key-value pair table
function M.OptInPhoneNumberInput(args)
assert(args, "You must provide an argument table when creating OptInPhoneNumberInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["phoneNumber"] = args["phoneNumber"],
}
asserts.AssertOptInPhoneNumberInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ListPlatformApplicationsInput = { ["NextToken"] = true, nil }
function asserts.AssertListPlatformApplicationsInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected ListPlatformApplicationsInput to be of type 'table'")
if struct["NextToken"] then asserts.AssertString(struct["NextToken"]) end
for k,_ in pairs(struct) do
assert(keys.ListPlatformApplicationsInput[k], "ListPlatformApplicationsInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ListPlatformApplicationsInput
-- <p>Input for ListPlatformApplications action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * NextToken [String] <p>NextToken string is used when calling ListPlatformApplications action to retrieve additional records that are available after the first page results.</p>
-- @return ListPlatformApplicationsInput structure as a key-value pair table
function M.ListPlatformApplicationsInput(args)
assert(args, "You must provide an argument table when creating ListPlatformApplicationsInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["NextToken"] = args["NextToken"],
}
asserts.AssertListPlatformApplicationsInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.FilterPolicyLimitExceededException = { ["message"] = true, nil }
function asserts.AssertFilterPolicyLimitExceededException(struct)
assert(struct)
assert(type(struct) == "table", "Expected FilterPolicyLimitExceededException to be of type 'table'")
if struct["message"] then asserts.Assertstring(struct["message"]) end
for k,_ in pairs(struct) do
assert(keys.FilterPolicyLimitExceededException[k], "FilterPolicyLimitExceededException contains unknown key " .. tostring(k))
end
end
--- Create a structure of type FilterPolicyLimitExceededException
-- <p>Indicates that the number of filter polices in your AWS account exceeds the limit. To add more filter polices, submit an SNS Limit Increase case in the AWS Support Center.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * message [string]
-- @return FilterPolicyLimitExceededException structure as a key-value pair table
function M.FilterPolicyLimitExceededException(args)
assert(args, "You must provide an argument table when creating FilterPolicyLimitExceededException")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["message"] = args["message"],
}
asserts.AssertFilterPolicyLimitExceededException(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.GetSubscriptionAttributesInput = { ["SubscriptionArn"] = true, nil }
function asserts.AssertGetSubscriptionAttributesInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected GetSubscriptionAttributesInput to be of type 'table'")
assert(struct["SubscriptionArn"], "Expected key SubscriptionArn to exist in table")
if struct["SubscriptionArn"] then asserts.AssertsubscriptionARN(struct["SubscriptionArn"]) end
for k,_ in pairs(struct) do
assert(keys.GetSubscriptionAttributesInput[k], "GetSubscriptionAttributesInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type GetSubscriptionAttributesInput
-- <p>Input for GetSubscriptionAttributes.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * SubscriptionArn [subscriptionARN] <p>The ARN of the subscription whose properties you want to get.</p>
-- Required key: SubscriptionArn
-- @return GetSubscriptionAttributesInput structure as a key-value pair table
function M.GetSubscriptionAttributesInput(args)
assert(args, "You must provide an argument table when creating GetSubscriptionAttributesInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["SubscriptionArn"] = args["SubscriptionArn"],
}
asserts.AssertGetSubscriptionAttributesInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.CreateEndpointResponse = { ["EndpointArn"] = true, nil }
function asserts.AssertCreateEndpointResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected CreateEndpointResponse to be of type 'table'")
if struct["EndpointArn"] then asserts.AssertString(struct["EndpointArn"]) end
for k,_ in pairs(struct) do
assert(keys.CreateEndpointResponse[k], "CreateEndpointResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type CreateEndpointResponse
-- <p>Response from CreateEndpoint action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * EndpointArn [String] <p>EndpointArn returned from CreateEndpoint action.</p>
-- @return CreateEndpointResponse structure as a key-value pair table
function M.CreateEndpointResponse(args)
assert(args, "You must provide an argument table when creating CreateEndpointResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["EndpointArn"] = args["EndpointArn"],
}
asserts.AssertCreateEndpointResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.NotFoundException = { ["message"] = true, nil }
function asserts.AssertNotFoundException(struct)
assert(struct)
assert(type(struct) == "table", "Expected NotFoundException to be of type 'table'")
if struct["message"] then asserts.Assertstring(struct["message"]) end
for k,_ in pairs(struct) do
assert(keys.NotFoundException[k], "NotFoundException contains unknown key " .. tostring(k))
end
end
--- Create a structure of type NotFoundException
-- <p>Indicates that the requested resource does not exist.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * message [string]
-- @return NotFoundException structure as a key-value pair table
function M.NotFoundException(args)
assert(args, "You must provide an argument table when creating NotFoundException")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["message"] = args["message"],
}
asserts.AssertNotFoundException(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.GetPlatformApplicationAttributesInput = { ["PlatformApplicationArn"] = true, nil }
function asserts.AssertGetPlatformApplicationAttributesInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected GetPlatformApplicationAttributesInput to be of type 'table'")
assert(struct["PlatformApplicationArn"], "Expected key PlatformApplicationArn to exist in table")
if struct["PlatformApplicationArn"] then asserts.AssertString(struct["PlatformApplicationArn"]) end
for k,_ in pairs(struct) do
assert(keys.GetPlatformApplicationAttributesInput[k], "GetPlatformApplicationAttributesInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type GetPlatformApplicationAttributesInput
-- <p>Input for GetPlatformApplicationAttributes action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * PlatformApplicationArn [String] <p>PlatformApplicationArn for GetPlatformApplicationAttributesInput.</p>
-- Required key: PlatformApplicationArn
-- @return GetPlatformApplicationAttributesInput structure as a key-value pair table
function M.GetPlatformApplicationAttributesInput(args)
assert(args, "You must provide an argument table when creating GetPlatformApplicationAttributesInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["PlatformApplicationArn"] = args["PlatformApplicationArn"],
}
asserts.AssertGetPlatformApplicationAttributesInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.GetSMSAttributesInput = { ["attributes"] = true, nil }
function asserts.AssertGetSMSAttributesInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected GetSMSAttributesInput to be of type 'table'")
if struct["attributes"] then asserts.AssertListString(struct["attributes"]) end
for k,_ in pairs(struct) do
assert(keys.GetSMSAttributesInput[k], "GetSMSAttributesInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type GetSMSAttributesInput
-- <p>The input for the <code>GetSMSAttributes</code> request.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * attributes [ListString] <p>A list of the individual attribute names, such as <code>MonthlySpendLimit</code>, for which you want values.</p> <p>For all attribute names, see <a href="http://docs.aws.amazon.com/sns/latest/api/API_SetSMSAttributes.html">SetSMSAttributes</a>.</p> <p>If you don't use this parameter, Amazon SNS returns all SMS attributes.</p>
-- @return GetSMSAttributesInput structure as a key-value pair table
function M.GetSMSAttributesInput(args)
assert(args, "You must provide an argument table when creating GetSMSAttributesInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["attributes"] = args["attributes"],
}
asserts.AssertGetSMSAttributesInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ConfirmSubscriptionResponse = { ["SubscriptionArn"] = true, nil }
function asserts.AssertConfirmSubscriptionResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected ConfirmSubscriptionResponse to be of type 'table'")
if struct["SubscriptionArn"] then asserts.AssertsubscriptionARN(struct["SubscriptionArn"]) end
for k,_ in pairs(struct) do
assert(keys.ConfirmSubscriptionResponse[k], "ConfirmSubscriptionResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ConfirmSubscriptionResponse
-- <p>Response for ConfirmSubscriptions action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * SubscriptionArn [subscriptionARN] <p>The ARN of the created subscription.</p>
-- @return ConfirmSubscriptionResponse structure as a key-value pair table
function M.ConfirmSubscriptionResponse(args)
assert(args, "You must provide an argument table when creating ConfirmSubscriptionResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["SubscriptionArn"] = args["SubscriptionArn"],
}
asserts.AssertConfirmSubscriptionResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.DeleteTopicInput = { ["TopicArn"] = true, nil }
function asserts.AssertDeleteTopicInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected DeleteTopicInput to be of type 'table'")
assert(struct["TopicArn"], "Expected key TopicArn to exist in table")
if struct["TopicArn"] then asserts.AsserttopicARN(struct["TopicArn"]) end
for k,_ in pairs(struct) do
assert(keys.DeleteTopicInput[k], "DeleteTopicInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type DeleteTopicInput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * TopicArn [topicARN] <p>The ARN of the topic you want to delete.</p>
-- Required key: TopicArn
-- @return DeleteTopicInput structure as a key-value pair table
function M.DeleteTopicInput(args)
assert(args, "You must provide an argument table when creating DeleteTopicInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["TopicArn"] = args["TopicArn"],
}
asserts.AssertDeleteTopicInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.TopicLimitExceededException = { ["message"] = true, nil }
function asserts.AssertTopicLimitExceededException(struct)
assert(struct)
assert(type(struct) == "table", "Expected TopicLimitExceededException to be of type 'table'")
if struct["message"] then asserts.Assertstring(struct["message"]) end
for k,_ in pairs(struct) do
assert(keys.TopicLimitExceededException[k], "TopicLimitExceededException contains unknown key " .. tostring(k))
end
end
--- Create a structure of type TopicLimitExceededException
-- <p>Indicates that the customer already owns the maximum allowed number of topics.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * message [string]
-- @return TopicLimitExceededException structure as a key-value pair table
function M.TopicLimitExceededException(args)
assert(args, "You must provide an argument table when creating TopicLimitExceededException")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["message"] = args["message"],
}
asserts.AssertTopicLimitExceededException(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.SetSMSAttributesInput = { ["attributes"] = true, nil }
function asserts.AssertSetSMSAttributesInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected SetSMSAttributesInput to be of type 'table'")
assert(struct["attributes"], "Expected key attributes to exist in table")
if struct["attributes"] then asserts.AssertMapStringToString(struct["attributes"]) end
for k,_ in pairs(struct) do
assert(keys.SetSMSAttributesInput[k], "SetSMSAttributesInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type SetSMSAttributesInput
-- <p>The input for the SetSMSAttributes action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * attributes [MapStringToString] <p>The default settings for sending SMS messages from your account. You can set values for the following attribute names:</p> <p> <code>MonthlySpendLimit</code> – The maximum amount in USD that you are willing to spend each month to send SMS messages. When Amazon SNS determines that sending an SMS message would incur a cost that exceeds this limit, it stops sending SMS messages within minutes.</p> <important> <p>Amazon SNS stops sending SMS messages within minutes of the limit being crossed. During that interval, if you continue to send SMS messages, you will incur costs that exceed your limit.</p> </important> <p>By default, the spend limit is set to the maximum allowed by Amazon SNS. If you want to raise the limit, submit an <a href="https://console.aws.amazon.com/support/home#/case/create?issueType=service-limit-increase&limitType=service-code-sns">SNS Limit Increase case</a>. For <b>New limit value</b>, enter your desired monthly spend limit. In the <b>Use Case Description</b> field, explain that you are requesting an SMS monthly spend limit increase.</p> <p> <code>DeliveryStatusIAMRole</code> – The ARN of the IAM role that allows Amazon SNS to write logs about SMS deliveries in CloudWatch Logs. For each SMS message that you send, Amazon SNS writes a log that includes the message price, the success or failure status, the reason for failure (if the message failed), the message dwell time, and other information.</p> <p> <code>DeliveryStatusSuccessSamplingRate</code> – The percentage of successful SMS deliveries for which Amazon SNS will write logs in CloudWatch Logs. The value can be an integer from 0 - 100. For example, to write logs only for failed deliveries, set this value to <code>0</code>. To write logs for 10% of your successful deliveries, set it to <code>10</code>.</p> <p> <code>DefaultSenderID</code> – A string, such as your business brand, that is displayed as the sender on the receiving device. Support for sender IDs varies by country. The sender ID can be 1 - 11 alphanumeric characters, and it must contain at least one letter.</p> <p> <code>DefaultSMSType</code> – The type of SMS message that you will send by default. You can assign the following values:</p> <ul> <li> <p> <code>Promotional</code> – (Default) Noncritical messages, such as marketing messages. Amazon SNS optimizes the message delivery to incur the lowest cost.</p> </li> <li> <p> <code>Transactional</code> – Critical messages that support customer transactions, such as one-time passcodes for multi-factor authentication. Amazon SNS optimizes the message delivery to achieve the highest reliability.</p> </li> </ul> <p> <code>UsageReportS3Bucket</code> – The name of the Amazon S3 bucket to receive daily SMS usage reports from Amazon SNS. Each day, Amazon SNS will deliver a usage report as a CSV file to the bucket. The report includes the following information for each SMS message that was successfully delivered by your account:</p> <ul> <li> <p>Time that the message was published (in UTC)</p> </li> <li> <p>Message ID</p> </li> <li> <p>Destination phone number</p> </li> <li> <p>Message type</p> </li> <li> <p>Delivery status</p> </li> <li> <p>Message price (in USD)</p> </li> <li> <p>Part number (a message is split into multiple parts if it is too long for a single message)</p> </li> <li> <p>Total number of parts</p> </li> </ul> <p>To receive the report, the bucket must have a policy that allows the Amazon SNS service principle to perform the <code>s3:PutObject</code> and <code>s3:GetBucketLocation</code> actions.</p> <p>For an example bucket policy and usage report, see <a href="http://docs.aws.amazon.com/sns/latest/dg/sms_stats.html">Monitoring SMS Activity</a> in the <i>Amazon SNS Developer Guide</i>.</p>
-- Required key: attributes
-- @return SetSMSAttributesInput structure as a key-value pair table
function M.SetSMSAttributesInput(args)
assert(args, "You must provide an argument table when creating SetSMSAttributesInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["attributes"] = args["attributes"],
}
asserts.AssertSetSMSAttributesInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ThrottledException = { ["message"] = true, nil }
function asserts.AssertThrottledException(struct)
assert(struct)
assert(type(struct) == "table", "Expected ThrottledException to be of type 'table'")
if struct["message"] then asserts.Assertstring(struct["message"]) end
for k,_ in pairs(struct) do
assert(keys.ThrottledException[k], "ThrottledException contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ThrottledException
-- <p>Indicates that the rate at which requests have been submitted for this action exceeds the limit for your account.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * message [string] <p>Throttled request.</p>
-- @return ThrottledException structure as a key-value pair table
function M.ThrottledException(args)
assert(args, "You must provide an argument table when creating ThrottledException")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["message"] = args["message"],
}
asserts.AssertThrottledException(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.OptInPhoneNumberResponse = { nil }
function asserts.AssertOptInPhoneNumberResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected OptInPhoneNumberResponse to be of type 'table'")
for k,_ in pairs(struct) do
assert(keys.OptInPhoneNumberResponse[k], "OptInPhoneNumberResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type OptInPhoneNumberResponse
-- <p>The response for the OptInPhoneNumber action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- @return OptInPhoneNumberResponse structure as a key-value pair table
function M.OptInPhoneNumberResponse(args)
assert(args, "You must provide an argument table when creating OptInPhoneNumberResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
}
asserts.AssertOptInPhoneNumberResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ListSubscriptionsByTopicResponse = { ["NextToken"] = true, ["Subscriptions"] = true, nil }
function asserts.AssertListSubscriptionsByTopicResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected ListSubscriptionsByTopicResponse to be of type 'table'")
if struct["NextToken"] then asserts.AssertnextToken(struct["NextToken"]) end
if struct["Subscriptions"] then asserts.AssertSubscriptionsList(struct["Subscriptions"]) end
for k,_ in pairs(struct) do
assert(keys.ListSubscriptionsByTopicResponse[k], "ListSubscriptionsByTopicResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ListSubscriptionsByTopicResponse
-- <p>Response for ListSubscriptionsByTopic action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * NextToken [nextToken] <p>Token to pass along to the next <code>ListSubscriptionsByTopic</code> request. This element is returned if there are more subscriptions to retrieve.</p>
-- * Subscriptions [SubscriptionsList] <p>A list of subscriptions.</p>
-- @return ListSubscriptionsByTopicResponse structure as a key-value pair table
function M.ListSubscriptionsByTopicResponse(args)
assert(args, "You must provide an argument table when creating ListSubscriptionsByTopicResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["NextToken"] = args["NextToken"],
["Subscriptions"] = args["Subscriptions"],
}
asserts.AssertListSubscriptionsByTopicResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.PublishInput = { ["MessageStructure"] = true, ["PhoneNumber"] = true, ["TargetArn"] = true, ["Message"] = true, ["MessageAttributes"] = true, ["TopicArn"] = true, ["Subject"] = true, nil }
function asserts.AssertPublishInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected PublishInput to be of type 'table'")
assert(struct["Message"], "Expected key Message to exist in table")
if struct["MessageStructure"] then asserts.AssertmessageStructure(struct["MessageStructure"]) end
if struct["PhoneNumber"] then asserts.AssertString(struct["PhoneNumber"]) end
if struct["TargetArn"] then asserts.AssertString(struct["TargetArn"]) end
if struct["Message"] then asserts.Assertmessage(struct["Message"]) end
if struct["MessageAttributes"] then asserts.AssertMessageAttributeMap(struct["MessageAttributes"]) end
if struct["TopicArn"] then asserts.AsserttopicARN(struct["TopicArn"]) end
if struct["Subject"] then asserts.Assertsubject(struct["Subject"]) end
for k,_ in pairs(struct) do
assert(keys.PublishInput[k], "PublishInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type PublishInput
-- <p>Input for Publish action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * MessageStructure [messageStructure] <p>Set <code>MessageStructure</code> to <code>json</code> if you want to send a different message for each protocol. For example, using one publish action, you can send a short message to your SMS subscribers and a longer message to your email subscribers. If you set <code>MessageStructure</code> to <code>json</code>, the value of the <code>Message</code> parameter must: </p> <ul> <li> <p>be a syntactically valid JSON object; and</p> </li> <li> <p>contain at least a top-level JSON key of "default" with a value that is a string.</p> </li> </ul> <p>You can define other top-level keys that define the message you want to send to a specific transport protocol (e.g., "http").</p> <p>For information about sending different messages for each protocol using the AWS Management Console, go to <a href="http://docs.aws.amazon.com/sns/latest/gsg/Publish.html#sns-message-formatting-by-protocol">Create Different Messages for Each Protocol</a> in the <i>Amazon Simple Notification Service Getting Started Guide</i>. </p> <p>Valid value: <code>json</code> </p>
-- * PhoneNumber [String] <p>The phone number to which you want to deliver an SMS message. Use E.164 format.</p> <p>If you don't specify a value for the <code>PhoneNumber</code> parameter, you must specify a value for the <code>TargetArn</code> or <code>TopicArn</code> parameters.</p>
-- * TargetArn [String] <p>Either TopicArn or EndpointArn, but not both.</p> <p>If you don't specify a value for the <code>TargetArn</code> parameter, you must specify a value for the <code>PhoneNumber</code> or <code>TopicArn</code> parameters.</p>
-- * Message [message] <p>The message you want to send.</p> <p>If you are publishing to a topic and you want to send the same message to all transport protocols, include the text of the message as a String value. If you want to send different messages for each transport protocol, set the value of the <code>MessageStructure</code> parameter to <code>json</code> and use a JSON object for the <code>Message</code> parameter. </p> <p/> <p>Constraints:</p> <ul> <li> <p>With the exception of SMS, messages must be UTF-8 encoded strings and at most 256 KB in size (262144 bytes, not 262144 characters).</p> </li> <li> <p>For SMS, each message can contain up to 140 bytes, and the character limit depends on the encoding scheme. For example, an SMS message can contain 160 GSM characters, 140 ASCII characters, or 70 UCS-2 characters. If you publish a message that exceeds the size limit, Amazon SNS sends it as multiple messages, each fitting within the size limit. Messages are not cut off in the middle of a word but on whole-word boundaries. The total size limit for a single SMS publish action is 1600 bytes.</p> </li> </ul> <p>JSON-specific constraints:</p> <ul> <li> <p>Keys in the JSON object that correspond to supported transport protocols must have simple JSON string values.</p> </li> <li> <p>The values will be parsed (unescaped) before they are used in outgoing messages.</p> </li> <li> <p>Outbound notifications are JSON encoded (meaning that the characters will be reescaped for sending).</p> </li> <li> <p>Values have a minimum length of 0 (the empty string, "", is allowed).</p> </li> <li> <p>Values have a maximum length bounded by the overall message size (so, including multiple protocols may limit message sizes).</p> </li> <li> <p>Non-string values will cause the key to be ignored.</p> </li> <li> <p>Keys that do not correspond to supported transport protocols are ignored.</p> </li> <li> <p>Duplicate keys are not allowed.</p> </li> <li> <p>Failure to parse or validate any key or value in the message will cause the <code>Publish</code> call to return an error (no partial delivery).</p> </li> </ul>
-- * MessageAttributes [MessageAttributeMap] <p>Message attributes for Publish action.</p>
-- * TopicArn [topicARN] <p>The topic you want to publish to.</p> <p>If you don't specify a value for the <code>TopicArn</code> parameter, you must specify a value for the <code>PhoneNumber</code> or <code>TargetArn</code> parameters.</p>
-- * Subject [subject] <p>Optional parameter to be used as the "Subject" line when the message is delivered to email endpoints. This field will also be included, if present, in the standard JSON messages delivered to other endpoints.</p> <p>Constraints: Subjects must be ASCII text that begins with a letter, number, or punctuation mark; must not include line breaks or control characters; and must be less than 100 characters long.</p>
-- Required key: Message
-- @return PublishInput structure as a key-value pair table
function M.PublishInput(args)
assert(args, "You must provide an argument table when creating PublishInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["MessageStructure"] = args["MessageStructure"],
["PhoneNumber"] = args["PhoneNumber"],
["TargetArn"] = args["TargetArn"],
["Message"] = args["Message"],
["MessageAttributes"] = args["MessageAttributes"],
["TopicArn"] = args["TopicArn"],
["Subject"] = args["Subject"],
}
asserts.AssertPublishInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.SetSubscriptionAttributesInput = { ["AttributeName"] = true, ["AttributeValue"] = true, ["SubscriptionArn"] = true, nil }
function asserts.AssertSetSubscriptionAttributesInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected SetSubscriptionAttributesInput to be of type 'table'")
assert(struct["SubscriptionArn"], "Expected key SubscriptionArn to exist in table")
assert(struct["AttributeName"], "Expected key AttributeName to exist in table")
if struct["AttributeName"] then asserts.AssertattributeName(struct["AttributeName"]) end
if struct["AttributeValue"] then asserts.AssertattributeValue(struct["AttributeValue"]) end
if struct["SubscriptionArn"] then asserts.AssertsubscriptionARN(struct["SubscriptionArn"]) end
for k,_ in pairs(struct) do
assert(keys.SetSubscriptionAttributesInput[k], "SetSubscriptionAttributesInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type SetSubscriptionAttributesInput
-- <p>Input for SetSubscriptionAttributes action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * AttributeName [attributeName] <p>The name of the attribute you want to set. Only a subset of the subscriptions attributes are mutable.</p> <p>Valid values: <code>DeliveryPolicy</code> | <code>FilterPolicy</code> | <code>RawMessageDelivery</code> </p>
-- * AttributeValue [attributeValue] <p>The new value for the attribute in JSON format.</p>
-- * SubscriptionArn [subscriptionARN] <p>The ARN of the subscription to modify.</p>
-- Required key: SubscriptionArn
-- Required key: AttributeName
-- @return SetSubscriptionAttributesInput structure as a key-value pair table
function M.SetSubscriptionAttributesInput(args)
assert(args, "You must provide an argument table when creating SetSubscriptionAttributesInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["AttributeName"] = args["AttributeName"],
["AttributeValue"] = args["AttributeValue"],
["SubscriptionArn"] = args["SubscriptionArn"],
}
asserts.AssertSetSubscriptionAttributesInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.GetSubscriptionAttributesResponse = { ["Attributes"] = true, nil }
function asserts.AssertGetSubscriptionAttributesResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected GetSubscriptionAttributesResponse to be of type 'table'")
if struct["Attributes"] then asserts.AssertSubscriptionAttributesMap(struct["Attributes"]) end
for k,_ in pairs(struct) do
assert(keys.GetSubscriptionAttributesResponse[k], "GetSubscriptionAttributesResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type GetSubscriptionAttributesResponse
-- <p>Response for GetSubscriptionAttributes action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * Attributes [SubscriptionAttributesMap] <p>A map of the subscription's attributes. Attributes in this map include the following:</p> <ul> <li> <p> <code>ConfirmationWasAuthenticated</code> -- <code>true</code> if the subscription confirmation request was authenticated.</p> </li> <li> <p> <code>DeliveryPolicy</code> -- The JSON serialization of the subscription's delivery policy.</p> </li> <li> <p> <code>EffectiveDeliveryPolicy</code> -- The JSON serialization of the effective delivery policy that takes into account the topic delivery policy and account system defaults.</p> </li> <li> <p> <code>FilterPolicy</code> -- The filter policy JSON that is assigned to the subscription.</p> </li> <li> <p> <code>Owner</code> -- The AWS account ID of the subscription's owner.</p> </li> <li> <p> <code>PendingConfirmation</code> -- <code>true</code> if the subscription hasn't been confirmed. To confirm a pending subscription, call the <code>ConfirmSubscription</code> action with a confirmation token.</p> </li> <li> <p> <code>RawMessageDelivery</code> -- <code>true</code> if raw message delivery is enabled for the subscription. Raw messages are free of JSON formatting and can be sent to HTTP/S and Amazon SQS endpoints.</p> </li> <li> <p> <code>SubscriptionArn</code> -- The subscription's ARN.</p> </li> <li> <p> <code>TopicArn</code> -- The topic ARN that the subscription is associated with.</p> </li> </ul>
-- @return GetSubscriptionAttributesResponse structure as a key-value pair table
function M.GetSubscriptionAttributesResponse(args)
assert(args, "You must provide an argument table when creating GetSubscriptionAttributesResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["Attributes"] = args["Attributes"],
}
asserts.AssertGetSubscriptionAttributesResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.CreateTopicResponse = { ["TopicArn"] = true, nil }
function asserts.AssertCreateTopicResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected CreateTopicResponse to be of type 'table'")
if struct["TopicArn"] then asserts.AsserttopicARN(struct["TopicArn"]) end
for k,_ in pairs(struct) do
assert(keys.CreateTopicResponse[k], "CreateTopicResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type CreateTopicResponse
-- <p>Response from CreateTopic action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * TopicArn [topicARN] <p>The Amazon Resource Name (ARN) assigned to the created topic.</p>
-- @return CreateTopicResponse structure as a key-value pair table
function M.CreateTopicResponse(args)
assert(args, "You must provide an argument table when creating CreateTopicResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["TopicArn"] = args["TopicArn"],
}
asserts.AssertCreateTopicResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.InternalErrorException = { ["message"] = true, nil }
function asserts.AssertInternalErrorException(struct)
assert(struct)
assert(type(struct) == "table", "Expected InternalErrorException to be of type 'table'")
if struct["message"] then asserts.Assertstring(struct["message"]) end
for k,_ in pairs(struct) do
assert(keys.InternalErrorException[k], "InternalErrorException contains unknown key " .. tostring(k))
end
end
--- Create a structure of type InternalErrorException
-- <p>Indicates an internal service error.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * message [string]
-- @return InternalErrorException structure as a key-value pair table
function M.InternalErrorException(args)
assert(args, "You must provide an argument table when creating InternalErrorException")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["message"] = args["message"],
}
asserts.AssertInternalErrorException(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.GetTopicAttributesResponse = { ["Attributes"] = true, nil }
function asserts.AssertGetTopicAttributesResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected GetTopicAttributesResponse to be of type 'table'")
if struct["Attributes"] then asserts.AssertTopicAttributesMap(struct["Attributes"]) end
for k,_ in pairs(struct) do
assert(keys.GetTopicAttributesResponse[k], "GetTopicAttributesResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type GetTopicAttributesResponse
-- <p>Response for GetTopicAttributes action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * Attributes [TopicAttributesMap] <p>A map of the topic's attributes. Attributes in this map include the following:</p> <ul> <li> <p> <code>TopicArn</code> -- the topic's ARN</p> </li> <li> <p> <code>Owner</code> -- the AWS account ID of the topic's owner</p> </li> <li> <p> <code>Policy</code> -- the JSON serialization of the topic's access control policy</p> </li> <li> <p> <code>DisplayName</code> -- the human-readable name used in the "From" field for notifications to email and email-json endpoints</p> </li> <li> <p> <code>SubscriptionsPending</code> -- the number of subscriptions pending confirmation on this topic</p> </li> <li> <p> <code>SubscriptionsConfirmed</code> -- the number of confirmed subscriptions on this topic</p> </li> <li> <p> <code>SubscriptionsDeleted</code> -- the number of deleted subscriptions on this topic</p> </li> <li> <p> <code>DeliveryPolicy</code> -- the JSON serialization of the topic's delivery policy</p> </li> <li> <p> <code>EffectiveDeliveryPolicy</code> -- the JSON serialization of the effective delivery policy that takes into account system defaults</p> </li> </ul>
-- @return GetTopicAttributesResponse structure as a key-value pair table
function M.GetTopicAttributesResponse(args)
assert(args, "You must provide an argument table when creating GetTopicAttributesResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["Attributes"] = args["Attributes"],
}
asserts.AssertGetTopicAttributesResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ListPhoneNumbersOptedOutResponse = { ["phoneNumbers"] = true, ["nextToken"] = true, nil }
function asserts.AssertListPhoneNumbersOptedOutResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected ListPhoneNumbersOptedOutResponse to be of type 'table'")
if struct["phoneNumbers"] then asserts.AssertPhoneNumberList(struct["phoneNumbers"]) end
if struct["nextToken"] then asserts.Assertstring(struct["nextToken"]) end
for k,_ in pairs(struct) do
assert(keys.ListPhoneNumbersOptedOutResponse[k], "ListPhoneNumbersOptedOutResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ListPhoneNumbersOptedOutResponse
-- <p>The response from the <code>ListPhoneNumbersOptedOut</code> action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * phoneNumbers [PhoneNumberList] <p>A list of phone numbers that are opted out of receiving SMS messages. The list is paginated, and each page can contain up to 100 phone numbers.</p>
-- * nextToken [string] <p>A <code>NextToken</code> string is returned when you call the <code>ListPhoneNumbersOptedOut</code> action if additional records are available after the first page of results.</p>
-- @return ListPhoneNumbersOptedOutResponse structure as a key-value pair table
function M.ListPhoneNumbersOptedOutResponse(args)
assert(args, "You must provide an argument table when creating ListPhoneNumbersOptedOutResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["phoneNumbers"] = args["phoneNumbers"],
["nextToken"] = args["nextToken"],
}
asserts.AssertListPhoneNumbersOptedOutResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.CreatePlatformApplicationResponse = { ["PlatformApplicationArn"] = true, nil }
function asserts.AssertCreatePlatformApplicationResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected CreatePlatformApplicationResponse to be of type 'table'")
if struct["PlatformApplicationArn"] then asserts.AssertString(struct["PlatformApplicationArn"]) end
for k,_ in pairs(struct) do
assert(keys.CreatePlatformApplicationResponse[k], "CreatePlatformApplicationResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type CreatePlatformApplicationResponse
-- <p>Response from CreatePlatformApplication action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * PlatformApplicationArn [String] <p>PlatformApplicationArn is returned.</p>
-- @return CreatePlatformApplicationResponse structure as a key-value pair table
function M.CreatePlatformApplicationResponse(args)
assert(args, "You must provide an argument table when creating CreatePlatformApplicationResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["PlatformApplicationArn"] = args["PlatformApplicationArn"],
}
asserts.AssertCreatePlatformApplicationResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.AuthorizationErrorException = { ["message"] = true, nil }
function asserts.AssertAuthorizationErrorException(struct)
assert(struct)
assert(type(struct) == "table", "Expected AuthorizationErrorException to be of type 'table'")
if struct["message"] then asserts.Assertstring(struct["message"]) end
for k,_ in pairs(struct) do
assert(keys.AuthorizationErrorException[k], "AuthorizationErrorException contains unknown key " .. tostring(k))
end
end
--- Create a structure of type AuthorizationErrorException
-- <p>Indicates that the user has been denied access to the requested resource.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * message [string]
-- @return AuthorizationErrorException structure as a key-value pair table
function M.AuthorizationErrorException(args)
assert(args, "You must provide an argument table when creating AuthorizationErrorException")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["message"] = args["message"],
}
asserts.AssertAuthorizationErrorException(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.SetPlatformApplicationAttributesInput = { ["Attributes"] = true, ["PlatformApplicationArn"] = true, nil }
function asserts.AssertSetPlatformApplicationAttributesInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected SetPlatformApplicationAttributesInput to be of type 'table'")
assert(struct["PlatformApplicationArn"], "Expected key PlatformApplicationArn to exist in table")
assert(struct["Attributes"], "Expected key Attributes to exist in table")
if struct["Attributes"] then asserts.AssertMapStringToString(struct["Attributes"]) end
if struct["PlatformApplicationArn"] then asserts.AssertString(struct["PlatformApplicationArn"]) end
for k,_ in pairs(struct) do
assert(keys.SetPlatformApplicationAttributesInput[k], "SetPlatformApplicationAttributesInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type SetPlatformApplicationAttributesInput
-- <p>Input for SetPlatformApplicationAttributes action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * Attributes [MapStringToString] <p>A map of the platform application attributes. Attributes in this map include the following:</p> <ul> <li> <p> <code>PlatformCredential</code> -- The credential received from the notification service. For APNS/APNS_SANDBOX, PlatformCredential is private key. For GCM, PlatformCredential is "API key". For ADM, PlatformCredential is "client secret".</p> </li> <li> <p> <code>PlatformPrincipal</code> -- The principal received from the notification service. For APNS/APNS_SANDBOX, PlatformPrincipal is SSL certificate. For GCM, PlatformPrincipal is not applicable. For ADM, PlatformPrincipal is "client id".</p> </li> <li> <p> <code>EventEndpointCreated</code> -- Topic ARN to which EndpointCreated event notifications should be sent.</p> </li> <li> <p> <code>EventEndpointDeleted</code> -- Topic ARN to which EndpointDeleted event notifications should be sent.</p> </li> <li> <p> <code>EventEndpointUpdated</code> -- Topic ARN to which EndpointUpdate event notifications should be sent.</p> </li> <li> <p> <code>EventDeliveryFailure</code> -- Topic ARN to which DeliveryFailure event notifications should be sent upon Direct Publish delivery failure (permanent) to one of the application's endpoints.</p> </li> <li> <p> <code>SuccessFeedbackRoleArn</code> -- IAM role ARN used to give Amazon SNS write access to use CloudWatch Logs on your behalf.</p> </li> <li> <p> <code>FailureFeedbackRoleArn</code> -- IAM role ARN used to give Amazon SNS write access to use CloudWatch Logs on your behalf.</p> </li> <li> <p> <code>SuccessFeedbackSampleRate</code> -- Sample rate percentage (0-100) of successfully delivered messages.</p> </li> </ul>
-- * PlatformApplicationArn [String] <p>PlatformApplicationArn for SetPlatformApplicationAttributes action.</p>
-- Required key: PlatformApplicationArn
-- Required key: Attributes
-- @return SetPlatformApplicationAttributesInput structure as a key-value pair table
function M.SetPlatformApplicationAttributesInput(args)
assert(args, "You must provide an argument table when creating SetPlatformApplicationAttributesInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["Attributes"] = args["Attributes"],
["PlatformApplicationArn"] = args["PlatformApplicationArn"],
}
asserts.AssertSetPlatformApplicationAttributesInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.UnsubscribeInput = { ["SubscriptionArn"] = true, nil }
function asserts.AssertUnsubscribeInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected UnsubscribeInput to be of type 'table'")
assert(struct["SubscriptionArn"], "Expected key SubscriptionArn to exist in table")
if struct["SubscriptionArn"] then asserts.AssertsubscriptionARN(struct["SubscriptionArn"]) end
for k,_ in pairs(struct) do
assert(keys.UnsubscribeInput[k], "UnsubscribeInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type UnsubscribeInput
-- <p>Input for Unsubscribe action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * SubscriptionArn [subscriptionARN] <p>The ARN of the subscription to be deleted.</p>
-- Required key: SubscriptionArn
-- @return UnsubscribeInput structure as a key-value pair table
function M.UnsubscribeInput(args)
assert(args, "You must provide an argument table when creating UnsubscribeInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["SubscriptionArn"] = args["SubscriptionArn"],
}
asserts.AssertUnsubscribeInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.InvalidParameterValueException = { ["message"] = true, nil }
function asserts.AssertInvalidParameterValueException(struct)
assert(struct)
assert(type(struct) == "table", "Expected InvalidParameterValueException to be of type 'table'")
if struct["message"] then asserts.Assertstring(struct["message"]) end
for k,_ in pairs(struct) do
assert(keys.InvalidParameterValueException[k], "InvalidParameterValueException contains unknown key " .. tostring(k))
end
end
--- Create a structure of type InvalidParameterValueException
-- <p>Indicates that a request parameter does not comply with the associated constraints.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * message [string] <p>The parameter value is invalid.</p>
-- @return InvalidParameterValueException structure as a key-value pair table
function M.InvalidParameterValueException(args)
assert(args, "You must provide an argument table when creating InvalidParameterValueException")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["message"] = args["message"],
}
asserts.AssertInvalidParameterValueException(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ListEndpointsByPlatformApplicationResponse = { ["Endpoints"] = true, ["NextToken"] = true, nil }
function asserts.AssertListEndpointsByPlatformApplicationResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected ListEndpointsByPlatformApplicationResponse to be of type 'table'")
if struct["Endpoints"] then asserts.AssertListOfEndpoints(struct["Endpoints"]) end
if struct["NextToken"] then asserts.AssertString(struct["NextToken"]) end
for k,_ in pairs(struct) do
assert(keys.ListEndpointsByPlatformApplicationResponse[k], "ListEndpointsByPlatformApplicationResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ListEndpointsByPlatformApplicationResponse
-- <p>Response for ListEndpointsByPlatformApplication action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * Endpoints [ListOfEndpoints] <p>Endpoints returned for ListEndpointsByPlatformApplication action.</p>
-- * NextToken [String] <p>NextToken string is returned when calling ListEndpointsByPlatformApplication action if additional records are available after the first page results.</p>
-- @return ListEndpointsByPlatformApplicationResponse structure as a key-value pair table
function M.ListEndpointsByPlatformApplicationResponse(args)
assert(args, "You must provide an argument table when creating ListEndpointsByPlatformApplicationResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["Endpoints"] = args["Endpoints"],
["NextToken"] = args["NextToken"],
}
asserts.AssertListEndpointsByPlatformApplicationResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.SubscribeInput = { ["Attributes"] = true, ["Endpoint"] = true, ["Protocol"] = true, ["TopicArn"] = true, ["ReturnSubscriptionArn"] = true, nil }
function asserts.AssertSubscribeInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected SubscribeInput to be of type 'table'")
assert(struct["TopicArn"], "Expected key TopicArn to exist in table")
assert(struct["Protocol"], "Expected key Protocol to exist in table")
if struct["Attributes"] then asserts.AssertSubscriptionAttributesMap(struct["Attributes"]) end
if struct["Endpoint"] then asserts.Assertendpoint(struct["Endpoint"]) end
if struct["Protocol"] then asserts.Assertprotocol(struct["Protocol"]) end
if struct["TopicArn"] then asserts.AsserttopicARN(struct["TopicArn"]) end
if struct["ReturnSubscriptionArn"] then asserts.Assertboolean(struct["ReturnSubscriptionArn"]) end
for k,_ in pairs(struct) do
assert(keys.SubscribeInput[k], "SubscribeInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type SubscribeInput
-- <p>Input for Subscribe action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * Attributes [SubscriptionAttributesMap] <p>Assigns attributes to the subscription as a map of key-value pairs. You can assign any attribute that is supported by the <code>SetSubscriptionAttributes</code> action.</p>
-- * Endpoint [endpoint] <p>The endpoint that you want to receive notifications. Endpoints vary by protocol:</p> <ul> <li> <p>For the <code>http</code> protocol, the endpoint is an URL beginning with "http://"</p> </li> <li> <p>For the <code>https</code> protocol, the endpoint is a URL beginning with "https://"</p> </li> <li> <p>For the <code>email</code> protocol, the endpoint is an email address</p> </li> <li> <p>For the <code>email-json</code> protocol, the endpoint is an email address</p> </li> <li> <p>For the <code>sms</code> protocol, the endpoint is a phone number of an SMS-enabled device</p> </li> <li> <p>For the <code>sqs</code> protocol, the endpoint is the ARN of an Amazon SQS queue</p> </li> <li> <p>For the <code>application</code> protocol, the endpoint is the EndpointArn of a mobile app and device.</p> </li> <li> <p>For the <code>lambda</code> protocol, the endpoint is the ARN of an AWS Lambda function.</p> </li> </ul>
-- * Protocol [protocol] <p>The protocol you want to use. Supported protocols include:</p> <ul> <li> <p> <code>http</code> -- delivery of JSON-encoded message via HTTP POST</p> </li> <li> <p> <code>https</code> -- delivery of JSON-encoded message via HTTPS POST</p> </li> <li> <p> <code>email</code> -- delivery of message via SMTP</p> </li> <li> <p> <code>email-json</code> -- delivery of JSON-encoded message via SMTP</p> </li> <li> <p> <code>sms</code> -- delivery of message via SMS</p> </li> <li> <p> <code>sqs</code> -- delivery of JSON-encoded message to an Amazon SQS queue</p> </li> <li> <p> <code>application</code> -- delivery of JSON-encoded message to an EndpointArn for a mobile app and device.</p> </li> <li> <p> <code>lambda</code> -- delivery of JSON-encoded message to an AWS Lambda function.</p> </li> </ul>
-- * TopicArn [topicARN] <p>The ARN of the topic you want to subscribe to.</p>
-- * ReturnSubscriptionArn [boolean] <p>Sets whether the response from the <code>Subscribe</code> request includes the subscription ARN, even if the subscription is not yet confirmed.</p> <p>If you set this parameter to <code>false</code>, the response includes the ARN for confirmed subscriptions, but it includes an ARN value of "pending subscription" for subscriptions that are not yet confirmed. A subscription becomes confirmed when the subscriber calls the <code>ConfirmSubscription</code> action with a confirmation token.</p> <p>If you set this parameter to <code>true</code>, the response includes the ARN in all cases, even if the subscription is not yet confirmed.</p> <p>The default value is <code>false</code>.</p>
-- Required key: TopicArn
-- Required key: Protocol
-- @return SubscribeInput structure as a key-value pair table
function M.SubscribeInput(args)
assert(args, "You must provide an argument table when creating SubscribeInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["Attributes"] = args["Attributes"],
["Endpoint"] = args["Endpoint"],
["Protocol"] = args["Protocol"],
["TopicArn"] = args["TopicArn"],
["ReturnSubscriptionArn"] = args["ReturnSubscriptionArn"],
}
asserts.AssertSubscribeInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.DeletePlatformApplicationInput = { ["PlatformApplicationArn"] = true, nil }
function asserts.AssertDeletePlatformApplicationInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected DeletePlatformApplicationInput to be of type 'table'")
assert(struct["PlatformApplicationArn"], "Expected key PlatformApplicationArn to exist in table")
if struct["PlatformApplicationArn"] then asserts.AssertString(struct["PlatformApplicationArn"]) end
for k,_ in pairs(struct) do
assert(keys.DeletePlatformApplicationInput[k], "DeletePlatformApplicationInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type DeletePlatformApplicationInput
-- <p>Input for DeletePlatformApplication action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * PlatformApplicationArn [String] <p>PlatformApplicationArn of platform application object to delete.</p>
-- Required key: PlatformApplicationArn
-- @return DeletePlatformApplicationInput structure as a key-value pair table
function M.DeletePlatformApplicationInput(args)
assert(args, "You must provide an argument table when creating DeletePlatformApplicationInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["PlatformApplicationArn"] = args["PlatformApplicationArn"],
}
asserts.AssertDeletePlatformApplicationInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.PublishResponse = { ["MessageId"] = true, nil }
function asserts.AssertPublishResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected PublishResponse to be of type 'table'")
if struct["MessageId"] then asserts.AssertmessageId(struct["MessageId"]) end
for k,_ in pairs(struct) do
assert(keys.PublishResponse[k], "PublishResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type PublishResponse
-- <p>Response for Publish action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * MessageId [messageId] <p>Unique identifier assigned to the published message.</p> <p>Length Constraint: Maximum 100 characters</p>
-- @return PublishResponse structure as a key-value pair table
function M.PublishResponse(args)
assert(args, "You must provide an argument table when creating PublishResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["MessageId"] = args["MessageId"],
}
asserts.AssertPublishResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.MessageAttributeValue = { ["DataType"] = true, ["StringValue"] = true, ["BinaryValue"] = true, nil }
function asserts.AssertMessageAttributeValue(struct)
assert(struct)
assert(type(struct) == "table", "Expected MessageAttributeValue to be of type 'table'")
assert(struct["DataType"], "Expected key DataType to exist in table")
if struct["DataType"] then asserts.AssertString(struct["DataType"]) end
if struct["StringValue"] then asserts.AssertString(struct["StringValue"]) end
if struct["BinaryValue"] then asserts.AssertBinary(struct["BinaryValue"]) end
for k,_ in pairs(struct) do
assert(keys.MessageAttributeValue[k], "MessageAttributeValue contains unknown key " .. tostring(k))
end
end
--- Create a structure of type MessageAttributeValue
-- <p>The user-specified message attribute value. For string data types, the value attribute has the same restrictions on the content as the message body. For more information, see <a href="http://docs.aws.amazon.com/sns/latest/api/API_Publish.html">Publish</a>.</p> <p>Name, type, and value must not be empty or null. In addition, the message body should not be empty or null. All parts of the message attribute, including name, type, and value, are included in the message size restriction, which is currently 256 KB (262,144 bytes). For more information, see <a href="http://docs.aws.amazon.com/sns/latest/dg/SNSMessageAttributes.html">Using Amazon SNS Message Attributes</a>.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * DataType [String] <p>Amazon SNS supports the following logical data types: String, String.Array, Number, and Binary. For more information, see <a href="http://docs.aws.amazon.com/sns/latest/dg/SNSMessageAttributes.html#SNSMessageAttributes.DataTypes">Message Attribute Data Types</a>.</p>
-- * StringValue [String] <p>Strings are Unicode with UTF8 binary encoding. For a list of code values, see <a href="http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters">http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters</a>.</p>
-- * BinaryValue [Binary] <p>Binary type attributes can store any binary data, for example, compressed data, encrypted data, or images.</p>
-- Required key: DataType
-- @return MessageAttributeValue structure as a key-value pair table
function M.MessageAttributeValue(args)
assert(args, "You must provide an argument table when creating MessageAttributeValue")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["DataType"] = args["DataType"],
["StringValue"] = args["StringValue"],
["BinaryValue"] = args["BinaryValue"],
}
asserts.AssertMessageAttributeValue(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.CheckIfPhoneNumberIsOptedOutResponse = { ["isOptedOut"] = true, nil }
function asserts.AssertCheckIfPhoneNumberIsOptedOutResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected CheckIfPhoneNumberIsOptedOutResponse to be of type 'table'")
if struct["isOptedOut"] then asserts.Assertboolean(struct["isOptedOut"]) end
for k,_ in pairs(struct) do
assert(keys.CheckIfPhoneNumberIsOptedOutResponse[k], "CheckIfPhoneNumberIsOptedOutResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type CheckIfPhoneNumberIsOptedOutResponse
-- <p>The response from the <code>CheckIfPhoneNumberIsOptedOut</code> action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * isOptedOut [boolean] <p>Indicates whether the phone number is opted out:</p> <ul> <li> <p> <code>true</code> – The phone number is opted out, meaning you cannot publish SMS messages to it.</p> </li> <li> <p> <code>false</code> – The phone number is opted in, meaning you can publish SMS messages to it.</p> </li> </ul>
-- @return CheckIfPhoneNumberIsOptedOutResponse structure as a key-value pair table
function M.CheckIfPhoneNumberIsOptedOutResponse(args)
assert(args, "You must provide an argument table when creating CheckIfPhoneNumberIsOptedOutResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["isOptedOut"] = args["isOptedOut"],
}
asserts.AssertCheckIfPhoneNumberIsOptedOutResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ListEndpointsByPlatformApplicationInput = { ["NextToken"] = true, ["PlatformApplicationArn"] = true, nil }
function asserts.AssertListEndpointsByPlatformApplicationInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected ListEndpointsByPlatformApplicationInput to be of type 'table'")
assert(struct["PlatformApplicationArn"], "Expected key PlatformApplicationArn to exist in table")
if struct["NextToken"] then asserts.AssertString(struct["NextToken"]) end
if struct["PlatformApplicationArn"] then asserts.AssertString(struct["PlatformApplicationArn"]) end
for k,_ in pairs(struct) do
assert(keys.ListEndpointsByPlatformApplicationInput[k], "ListEndpointsByPlatformApplicationInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ListEndpointsByPlatformApplicationInput
-- <p>Input for ListEndpointsByPlatformApplication action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * NextToken [String] <p>NextToken string is used when calling ListEndpointsByPlatformApplication action to retrieve additional records that are available after the first page results.</p>
-- * PlatformApplicationArn [String] <p>PlatformApplicationArn for ListEndpointsByPlatformApplicationInput action.</p>
-- Required key: PlatformApplicationArn
-- @return ListEndpointsByPlatformApplicationInput structure as a key-value pair table
function M.ListEndpointsByPlatformApplicationInput(args)
assert(args, "You must provide an argument table when creating ListEndpointsByPlatformApplicationInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["NextToken"] = args["NextToken"],
["PlatformApplicationArn"] = args["PlatformApplicationArn"],
}
asserts.AssertListEndpointsByPlatformApplicationInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.SetSMSAttributesResponse = { nil }
function asserts.AssertSetSMSAttributesResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected SetSMSAttributesResponse to be of type 'table'")
for k,_ in pairs(struct) do
assert(keys.SetSMSAttributesResponse[k], "SetSMSAttributesResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type SetSMSAttributesResponse
-- <p>The response for the SetSMSAttributes action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- @return SetSMSAttributesResponse structure as a key-value pair table
function M.SetSMSAttributesResponse(args)
assert(args, "You must provide an argument table when creating SetSMSAttributesResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
}
asserts.AssertSetSMSAttributesResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.RemovePermissionInput = { ["TopicArn"] = true, ["Label"] = true, nil }
function asserts.AssertRemovePermissionInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected RemovePermissionInput to be of type 'table'")
assert(struct["TopicArn"], "Expected key TopicArn to exist in table")
assert(struct["Label"], "Expected key Label to exist in table")
if struct["TopicArn"] then asserts.AsserttopicARN(struct["TopicArn"]) end
if struct["Label"] then asserts.Assertlabel(struct["Label"]) end
for k,_ in pairs(struct) do
assert(keys.RemovePermissionInput[k], "RemovePermissionInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type RemovePermissionInput
-- <p>Input for RemovePermission action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * TopicArn [topicARN] <p>The ARN of the topic whose access control policy you wish to modify.</p>
-- * Label [label] <p>The unique label of the statement you want to remove.</p>
-- Required key: TopicArn
-- Required key: Label
-- @return RemovePermissionInput structure as a key-value pair table
function M.RemovePermissionInput(args)
assert(args, "You must provide an argument table when creating RemovePermissionInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["TopicArn"] = args["TopicArn"],
["Label"] = args["Label"],
}
asserts.AssertRemovePermissionInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.InvalidParameterException = { ["message"] = true, nil }
function asserts.AssertInvalidParameterException(struct)
assert(struct)
assert(type(struct) == "table", "Expected InvalidParameterException to be of type 'table'")
if struct["message"] then asserts.Assertstring(struct["message"]) end
for k,_ in pairs(struct) do
assert(keys.InvalidParameterException[k], "InvalidParameterException contains unknown key " .. tostring(k))
end
end
--- Create a structure of type InvalidParameterException
-- <p>Indicates that a request parameter does not comply with the associated constraints.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * message [string]
-- @return InvalidParameterException structure as a key-value pair table
function M.InvalidParameterException(args)
assert(args, "You must provide an argument table when creating InvalidParameterException")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["message"] = args["message"],
}
asserts.AssertInvalidParameterException(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.CreateTopicInput = { ["Name"] = true, nil }
function asserts.AssertCreateTopicInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected CreateTopicInput to be of type 'table'")
assert(struct["Name"], "Expected key Name to exist in table")
if struct["Name"] then asserts.AsserttopicName(struct["Name"]) end
for k,_ in pairs(struct) do
assert(keys.CreateTopicInput[k], "CreateTopicInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type CreateTopicInput
-- <p>Input for CreateTopic action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * Name [topicName] <p>The name of the topic you want to create.</p> <p>Constraints: Topic names must be made up of only uppercase and lowercase ASCII letters, numbers, underscores, and hyphens, and must be between 1 and 256 characters long.</p>
-- Required key: Name
-- @return CreateTopicInput structure as a key-value pair table
function M.CreateTopicInput(args)
assert(args, "You must provide an argument table when creating CreateTopicInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["Name"] = args["Name"],
}
asserts.AssertCreateTopicInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.DeleteEndpointInput = { ["EndpointArn"] = true, nil }
function asserts.AssertDeleteEndpointInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected DeleteEndpointInput to be of type 'table'")
assert(struct["EndpointArn"], "Expected key EndpointArn to exist in table")
if struct["EndpointArn"] then asserts.AssertString(struct["EndpointArn"]) end
for k,_ in pairs(struct) do
assert(keys.DeleteEndpointInput[k], "DeleteEndpointInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type DeleteEndpointInput
-- <p>Input for DeleteEndpoint action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * EndpointArn [String] <p>EndpointArn of endpoint to delete.</p>
-- Required key: EndpointArn
-- @return DeleteEndpointInput structure as a key-value pair table
function M.DeleteEndpointInput(args)
assert(args, "You must provide an argument table when creating DeleteEndpointInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["EndpointArn"] = args["EndpointArn"],
}
asserts.AssertDeleteEndpointInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.SetEndpointAttributesInput = { ["Attributes"] = true, ["EndpointArn"] = true, nil }
function asserts.AssertSetEndpointAttributesInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected SetEndpointAttributesInput to be of type 'table'")
assert(struct["EndpointArn"], "Expected key EndpointArn to exist in table")
assert(struct["Attributes"], "Expected key Attributes to exist in table")
if struct["Attributes"] then asserts.AssertMapStringToString(struct["Attributes"]) end
if struct["EndpointArn"] then asserts.AssertString(struct["EndpointArn"]) end
for k,_ in pairs(struct) do
assert(keys.SetEndpointAttributesInput[k], "SetEndpointAttributesInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type SetEndpointAttributesInput
-- <p>Input for SetEndpointAttributes action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * Attributes [MapStringToString] <p>A map of the endpoint attributes. Attributes in this map include the following:</p> <ul> <li> <p> <code>CustomUserData</code> -- arbitrary user data to associate with the endpoint. Amazon SNS does not use this data. The data must be in UTF-8 format and less than 2KB.</p> </li> <li> <p> <code>Enabled</code> -- flag that enables/disables delivery to the endpoint. Amazon SNS will set this to false when a notification service indicates to Amazon SNS that the endpoint is invalid. Users can set it back to true, typically after updating Token.</p> </li> <li> <p> <code>Token</code> -- device token, also referred to as a registration id, for an app and mobile device. This is returned from the notification service when an app and mobile device are registered with the notification service.</p> </li> </ul>
-- * EndpointArn [String] <p>EndpointArn used for SetEndpointAttributes action.</p>
-- Required key: EndpointArn
-- Required key: Attributes
-- @return SetEndpointAttributesInput structure as a key-value pair table
function M.SetEndpointAttributesInput(args)
assert(args, "You must provide an argument table when creating SetEndpointAttributesInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["Attributes"] = args["Attributes"],
["EndpointArn"] = args["EndpointArn"],
}
asserts.AssertSetEndpointAttributesInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.Endpoint = { ["Attributes"] = true, ["EndpointArn"] = true, nil }
function asserts.AssertEndpoint(struct)
assert(struct)
assert(type(struct) == "table", "Expected Endpoint to be of type 'table'")
if struct["Attributes"] then asserts.AssertMapStringToString(struct["Attributes"]) end
if struct["EndpointArn"] then asserts.AssertString(struct["EndpointArn"]) end
for k,_ in pairs(struct) do
assert(keys.Endpoint[k], "Endpoint contains unknown key " .. tostring(k))
end
end
--- Create a structure of type Endpoint
-- <p>Endpoint for mobile app and device.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * Attributes [MapStringToString] <p>Attributes for endpoint.</p>
-- * EndpointArn [String] <p>EndpointArn for mobile app and device.</p>
-- @return Endpoint structure as a key-value pair table
function M.Endpoint(args)
assert(args, "You must provide an argument table when creating Endpoint")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["Attributes"] = args["Attributes"],
["EndpointArn"] = args["EndpointArn"],
}
asserts.AssertEndpoint(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ListTopicsInput = { ["NextToken"] = true, nil }
function asserts.AssertListTopicsInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected ListTopicsInput to be of type 'table'")
if struct["NextToken"] then asserts.AssertnextToken(struct["NextToken"]) end
for k,_ in pairs(struct) do
assert(keys.ListTopicsInput[k], "ListTopicsInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ListTopicsInput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * NextToken [nextToken] <p>Token returned by the previous <code>ListTopics</code> request.</p>
-- @return ListTopicsInput structure as a key-value pair table
function M.ListTopicsInput(args)
assert(args, "You must provide an argument table when creating ListTopicsInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["NextToken"] = args["NextToken"],
}
asserts.AssertListTopicsInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ListSubscriptionsInput = { ["NextToken"] = true, nil }
function asserts.AssertListSubscriptionsInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected ListSubscriptionsInput to be of type 'table'")
if struct["NextToken"] then asserts.AssertnextToken(struct["NextToken"]) end
for k,_ in pairs(struct) do
assert(keys.ListSubscriptionsInput[k], "ListSubscriptionsInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ListSubscriptionsInput
-- <p>Input for ListSubscriptions action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * NextToken [nextToken] <p>Token returned by the previous <code>ListSubscriptions</code> request.</p>
-- @return ListSubscriptionsInput structure as a key-value pair table
function M.ListSubscriptionsInput(args)
assert(args, "You must provide an argument table when creating ListSubscriptionsInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["NextToken"] = args["NextToken"],
}
asserts.AssertListSubscriptionsInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.SubscribeResponse = { ["SubscriptionArn"] = true, nil }
function asserts.AssertSubscribeResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected SubscribeResponse to be of type 'table'")
if struct["SubscriptionArn"] then asserts.AssertsubscriptionARN(struct["SubscriptionArn"]) end
for k,_ in pairs(struct) do
assert(keys.SubscribeResponse[k], "SubscribeResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type SubscribeResponse
-- <p>Response for Subscribe action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * SubscriptionArn [subscriptionARN] <p>The ARN of the subscription if it is confirmed, or the string "pending confirmation" if the subscription requires confirmation. However, if the API request parameter <code>ReturnSubscriptionArn</code> is true, then the value is always the subscription ARN, even if the subscription requires confirmation.</p>
-- @return SubscribeResponse structure as a key-value pair table
function M.SubscribeResponse(args)
assert(args, "You must provide an argument table when creating SubscribeResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["SubscriptionArn"] = args["SubscriptionArn"],
}
asserts.AssertSubscribeResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ListPlatformApplicationsResponse = { ["NextToken"] = true, ["PlatformApplications"] = true, nil }
function asserts.AssertListPlatformApplicationsResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected ListPlatformApplicationsResponse to be of type 'table'")
if struct["NextToken"] then asserts.AssertString(struct["NextToken"]) end
if struct["PlatformApplications"] then asserts.AssertListOfPlatformApplications(struct["PlatformApplications"]) end
for k,_ in pairs(struct) do
assert(keys.ListPlatformApplicationsResponse[k], "ListPlatformApplicationsResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ListPlatformApplicationsResponse
-- <p>Response for ListPlatformApplications action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * NextToken [String] <p>NextToken string is returned when calling ListPlatformApplications action if additional records are available after the first page results.</p>
-- * PlatformApplications [ListOfPlatformApplications] <p>Platform applications returned when calling ListPlatformApplications action.</p>
-- @return ListPlatformApplicationsResponse structure as a key-value pair table
function M.ListPlatformApplicationsResponse(args)
assert(args, "You must provide an argument table when creating ListPlatformApplicationsResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["NextToken"] = args["NextToken"],
["PlatformApplications"] = args["PlatformApplications"],
}
asserts.AssertListPlatformApplicationsResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.GetTopicAttributesInput = { ["TopicArn"] = true, nil }
function asserts.AssertGetTopicAttributesInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected GetTopicAttributesInput to be of type 'table'")
assert(struct["TopicArn"], "Expected key TopicArn to exist in table")
if struct["TopicArn"] then asserts.AsserttopicARN(struct["TopicArn"]) end
for k,_ in pairs(struct) do
assert(keys.GetTopicAttributesInput[k], "GetTopicAttributesInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type GetTopicAttributesInput
-- <p>Input for GetTopicAttributes action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * TopicArn [topicARN] <p>The ARN of the topic whose properties you want to get.</p>
-- Required key: TopicArn
-- @return GetTopicAttributesInput structure as a key-value pair table
function M.GetTopicAttributesInput(args)
assert(args, "You must provide an argument table when creating GetTopicAttributesInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["TopicArn"] = args["TopicArn"],
}
asserts.AssertGetTopicAttributesInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.AddPermissionInput = { ["ActionName"] = true, ["AWSAccountId"] = true, ["TopicArn"] = true, ["Label"] = true, nil }
function asserts.AssertAddPermissionInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected AddPermissionInput to be of type 'table'")
assert(struct["TopicArn"], "Expected key TopicArn to exist in table")
assert(struct["Label"], "Expected key Label to exist in table")
assert(struct["AWSAccountId"], "Expected key AWSAccountId to exist in table")
assert(struct["ActionName"], "Expected key ActionName to exist in table")
if struct["ActionName"] then asserts.AssertActionsList(struct["ActionName"]) end
if struct["AWSAccountId"] then asserts.AssertDelegatesList(struct["AWSAccountId"]) end
if struct["TopicArn"] then asserts.AsserttopicARN(struct["TopicArn"]) end
if struct["Label"] then asserts.Assertlabel(struct["Label"]) end
for k,_ in pairs(struct) do
assert(keys.AddPermissionInput[k], "AddPermissionInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type AddPermissionInput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * ActionName [ActionsList] <p>The action you want to allow for the specified principal(s).</p> <p>Valid values: any Amazon SNS action name.</p>
-- * AWSAccountId [DelegatesList] <p>The AWS account IDs of the users (principals) who will be given access to the specified actions. The users must have AWS accounts, but do not need to be signed up for this service.</p>
-- * TopicArn [topicARN] <p>The ARN of the topic whose access control policy you wish to modify.</p>
-- * Label [label] <p>A unique identifier for the new policy statement.</p>
-- Required key: TopicArn
-- Required key: Label
-- Required key: AWSAccountId
-- Required key: ActionName
-- @return AddPermissionInput structure as a key-value pair table
function M.AddPermissionInput(args)
assert(args, "You must provide an argument table when creating AddPermissionInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["ActionName"] = args["ActionName"],
["AWSAccountId"] = args["AWSAccountId"],
["TopicArn"] = args["TopicArn"],
["Label"] = args["Label"],
}
asserts.AssertAddPermissionInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.GetPlatformApplicationAttributesResponse = { ["Attributes"] = true, nil }
function asserts.AssertGetPlatformApplicationAttributesResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected GetPlatformApplicationAttributesResponse to be of type 'table'")
if struct["Attributes"] then asserts.AssertMapStringToString(struct["Attributes"]) end
for k,_ in pairs(struct) do
assert(keys.GetPlatformApplicationAttributesResponse[k], "GetPlatformApplicationAttributesResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type GetPlatformApplicationAttributesResponse
-- <p>Response for GetPlatformApplicationAttributes action.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * Attributes [MapStringToString] <p>Attributes include the following:</p> <ul> <li> <p> <code>EventEndpointCreated</code> -- Topic ARN to which EndpointCreated event notifications should be sent.</p> </li> <li> <p> <code>EventEndpointDeleted</code> -- Topic ARN to which EndpointDeleted event notifications should be sent.</p> </li> <li> <p> <code>EventEndpointUpdated</code> -- Topic ARN to which EndpointUpdate event notifications should be sent.</p> </li> <li> <p> <code>EventDeliveryFailure</code> -- Topic ARN to which DeliveryFailure event notifications should be sent upon Direct Publish delivery failure (permanent) to one of the application's endpoints.</p> </li> </ul>
-- @return GetPlatformApplicationAttributesResponse structure as a key-value pair table
function M.GetPlatformApplicationAttributesResponse(args)
assert(args, "You must provide an argument table when creating GetPlatformApplicationAttributesResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["Attributes"] = args["Attributes"],
}
asserts.AssertGetPlatformApplicationAttributesResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.PlatformApplicationDisabledException = { ["message"] = true, nil }
function asserts.AssertPlatformApplicationDisabledException(struct)
assert(struct)
assert(type(struct) == "table", "Expected PlatformApplicationDisabledException to be of type 'table'")
if struct["message"] then asserts.Assertstring(struct["message"]) end
for k,_ in pairs(struct) do
assert(keys.PlatformApplicationDisabledException[k], "PlatformApplicationDisabledException contains unknown key " .. tostring(k))
end
end
--- Create a structure of type PlatformApplicationDisabledException
-- <p>Exception error indicating platform application disabled.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * message [string] <p>Message for platform application disabled.</p>
-- @return PlatformApplicationDisabledException structure as a key-value pair table
function M.PlatformApplicationDisabledException(args)
assert(args, "You must provide an argument table when creating PlatformApplicationDisabledException")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["message"] = args["message"],
}
asserts.AssertPlatformApplicationDisabledException(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
function asserts.Assertprotocol(str)
assert(str)
assert(type(str) == "string", "Expected protocol to be of type 'string'")
end
--
function M.protocol(str)
asserts.Assertprotocol(str)
return str
end
function asserts.Assertstring(str)
assert(str)
assert(type(str) == "string", "Expected string to be of type 'string'")
end
--
function M.string(str)
asserts.Assertstring(str)
return str
end
function asserts.AssertattributeName(str)
assert(str)
assert(type(str) == "string", "Expected attributeName to be of type 'string'")
end
--
function M.attributeName(str)
asserts.AssertattributeName(str)
return str
end
function asserts.AssertPhoneNumber(str)
assert(str)
assert(type(str) == "string", "Expected PhoneNumber to be of type 'string'")
end
--
function M.PhoneNumber(str)
asserts.AssertPhoneNumber(str)
return str
end
function asserts.AsserttopicName(str)
assert(str)
assert(type(str) == "string", "Expected topicName to be of type 'string'")
end
--
function M.topicName(str)
asserts.AsserttopicName(str)
return str
end
function asserts.Asserttoken(str)
assert(str)
assert(type(str) == "string", "Expected token to be of type 'string'")
end
--
function M.token(str)
asserts.Asserttoken(str)
return str
end
function asserts.Assertdelegate(str)
assert(str)
assert(type(str) == "string", "Expected delegate to be of type 'string'")
end
--
function M.delegate(str)
asserts.Assertdelegate(str)
return str
end
function asserts.AssertmessageId(str)
assert(str)
assert(type(str) == "string", "Expected messageId to be of type 'string'")
end
--
function M.messageId(str)
asserts.AssertmessageId(str)
return str
end
function asserts.Assertsubject(str)
assert(str)
assert(type(str) == "string", "Expected subject to be of type 'string'")
end
--
function M.subject(str)
asserts.Assertsubject(str)
return str
end
function asserts.AssertString(str)
assert(str)
assert(type(str) == "string", "Expected String to be of type 'string'")
end
--
function M.String(str)
asserts.AssertString(str)
return str
end
function asserts.Assertlabel(str)
assert(str)
assert(type(str) == "string", "Expected label to be of type 'string'")
end
--
function M.label(str)
asserts.Assertlabel(str)
return str
end
function asserts.Assertaction(str)
assert(str)
assert(type(str) == "string", "Expected action to be of type 'string'")
end
--
function M.action(str)
asserts.Assertaction(str)
return str
end
function asserts.AsserttopicARN(str)
assert(str)
assert(type(str) == "string", "Expected topicARN to be of type 'string'")
end
--
function M.topicARN(str)
asserts.AsserttopicARN(str)
return str
end
function asserts.Assertmessage(str)
assert(str)
assert(type(str) == "string", "Expected message to be of type 'string'")
end
--
function M.message(str)
asserts.Assertmessage(str)
return str
end
function asserts.Assertaccount(str)
assert(str)
assert(type(str) == "string", "Expected account to be of type 'string'")
end
--
function M.account(str)
asserts.Assertaccount(str)
return str
end
function asserts.Assertendpoint(str)
assert(str)
assert(type(str) == "string", "Expected endpoint to be of type 'string'")
end
--
function M.endpoint(str)
asserts.Assertendpoint(str)
return str
end
function asserts.AssertnextToken(str)
assert(str)
assert(type(str) == "string", "Expected nextToken to be of type 'string'")
end
--
function M.nextToken(str)
asserts.AssertnextToken(str)
return str
end
function asserts.AssertauthenticateOnUnsubscribe(str)
assert(str)
assert(type(str) == "string", "Expected authenticateOnUnsubscribe to be of type 'string'")
end
--
function M.authenticateOnUnsubscribe(str)
asserts.AssertauthenticateOnUnsubscribe(str)
return str
end
function asserts.AssertsubscriptionARN(str)
assert(str)
assert(type(str) == "string", "Expected subscriptionARN to be of type 'string'")
end
--
function M.subscriptionARN(str)
asserts.AssertsubscriptionARN(str)
return str
end
function asserts.AssertattributeValue(str)
assert(str)
assert(type(str) == "string", "Expected attributeValue to be of type 'string'")
end
--
function M.attributeValue(str)
asserts.AssertattributeValue(str)
return str
end
function asserts.AssertmessageStructure(str)
assert(str)
assert(type(str) == "string", "Expected messageStructure to be of type 'string'")
end
--
function M.messageStructure(str)
asserts.AssertmessageStructure(str)
return str
end
function asserts.Assertboolean(boolean)
assert(boolean)
assert(type(boolean) == "boolean", "Expected boolean to be of type 'boolean'")
end
function M.boolean(boolean)
asserts.Assertboolean(boolean)
return boolean
end
function asserts.AssertSubscriptionAttributesMap(map)
assert(map)
assert(type(map) == "table", "Expected SubscriptionAttributesMap to be of type 'table'")
for k,v in pairs(map) do
asserts.AssertattributeName(k)
asserts.AssertattributeValue(v)
end
end
function M.SubscriptionAttributesMap(map)
asserts.AssertSubscriptionAttributesMap(map)
return map
end
function asserts.AssertMessageAttributeMap(map)
assert(map)
assert(type(map) == "table", "Expected MessageAttributeMap to be of type 'table'")
for k,v in pairs(map) do
asserts.AssertString(k)
asserts.AssertMessageAttributeValue(v)
end
end
function M.MessageAttributeMap(map)
asserts.AssertMessageAttributeMap(map)
return map
end
function asserts.AssertMapStringToString(map)
assert(map)
assert(type(map) == "table", "Expected MapStringToString to be of type 'table'")
for k,v in pairs(map) do
asserts.AssertString(k)
asserts.AssertString(v)
end
end
function M.MapStringToString(map)
asserts.AssertMapStringToString(map)
return map
end
function asserts.AssertTopicAttributesMap(map)
assert(map)
assert(type(map) == "table", "Expected TopicAttributesMap to be of type 'table'")
for k,v in pairs(map) do
asserts.AssertattributeName(k)
asserts.AssertattributeValue(v)
end
end
function M.TopicAttributesMap(map)
asserts.AssertTopicAttributesMap(map)
return map
end
function asserts.AssertBinary(blob)
assert(blob)
assert(type(blob) == "string", "Expected Binary to be of type 'string'")
end
function M.Binary(blob)
asserts.AssertBinary(blob)
return blob
end
function asserts.AssertSubscriptionsList(list)
assert(list)
assert(type(list) == "table", "Expected SubscriptionsList to be of type ''table")
for _,v in ipairs(list) do
asserts.AssertSubscription(v)
end
end
--
-- List of Subscription objects
function M.SubscriptionsList(list)
asserts.AssertSubscriptionsList(list)
return list
end
function asserts.AssertActionsList(list)
assert(list)
assert(type(list) == "table", "Expected ActionsList to be of type ''table")
for _,v in ipairs(list) do
asserts.Assertaction(v)
end
end
--
-- List of action objects
function M.ActionsList(list)
asserts.AssertActionsList(list)
return list
end
function asserts.AssertTopicsList(list)
assert(list)
assert(type(list) == "table", "Expected TopicsList to be of type ''table")
for _,v in ipairs(list) do
asserts.AssertTopic(v)
end
end
--
-- List of Topic objects
function M.TopicsList(list)
asserts.AssertTopicsList(list)
return list
end
function asserts.AssertDelegatesList(list)
assert(list)
assert(type(list) == "table", "Expected DelegatesList to be of type ''table")
for _,v in ipairs(list) do
asserts.Assertdelegate(v)
end
end
--
-- List of delegate objects
function M.DelegatesList(list)
asserts.AssertDelegatesList(list)
return list
end
function asserts.AssertPhoneNumberList(list)
assert(list)
assert(type(list) == "table", "Expected PhoneNumberList to be of type ''table")
for _,v in ipairs(list) do
asserts.AssertPhoneNumber(v)
end
end
--
-- List of PhoneNumber objects
function M.PhoneNumberList(list)
asserts.AssertPhoneNumberList(list)
return list
end
function asserts.AssertListOfPlatformApplications(list)
assert(list)
assert(type(list) == "table", "Expected ListOfPlatformApplications to be of type ''table")
for _,v in ipairs(list) do
asserts.AssertPlatformApplication(v)
end
end
--
-- List of PlatformApplication objects
function M.ListOfPlatformApplications(list)
asserts.AssertListOfPlatformApplications(list)
return list
end
function asserts.AssertListString(list)
assert(list)
assert(type(list) == "table", "Expected ListString to be of type ''table")
for _,v in ipairs(list) do
asserts.AssertString(v)
end
end
--
-- List of String objects
function M.ListString(list)
asserts.AssertListString(list)
return list
end
function asserts.AssertListOfEndpoints(list)
assert(list)
assert(type(list) == "table", "Expected ListOfEndpoints to be of type ''table")
for _,v in ipairs(list) do
asserts.AssertEndpoint(v)
end
end
--
-- List of Endpoint objects
function M.ListOfEndpoints(list)
asserts.AssertListOfEndpoints(list)
return list
end
local content_type = require "aws-sdk.core.content_type"
local request_headers = require "aws-sdk.core.request_headers"
local request_handlers = require "aws-sdk.core.request_handlers"
local settings = {}
local function endpoint_for_region(region, use_dualstack)
if not use_dualstack then
if region == "us-east-1" then
return "sns.amazonaws.com"
end
end
local ss = { "sns" }
if use_dualstack then
ss[#ss + 1] = "dualstack"
end
ss[#ss + 1] = region
ss[#ss + 1] = "amazonaws.com"
if region == "cn-north-1" then
ss[#ss + 1] = "cn"
end
return table.concat(ss, ".")
end
function M.init(config)
assert(config, "You must provide a config table")
assert(config.region, "You must provide a region in the config table")
settings.service = M.metadata.endpoint_prefix
settings.protocol = M.metadata.protocol
settings.region = config.region
settings.endpoint = config.endpoint_override or endpoint_for_region(config.region, config.use_dualstack)
settings.signature_version = M.metadata.signature_version
settings.uri = (config.scheme or "https") .. "://" .. settings.endpoint
end
--
-- OPERATIONS
--
--- Call ListPlatformApplications asynchronously, invoking a callback when done
-- @param ListPlatformApplicationsInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.ListPlatformApplicationsAsync(ListPlatformApplicationsInput, cb)
assert(ListPlatformApplicationsInput, "You must provide a ListPlatformApplicationsInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".ListPlatformApplications",
}
for header,value in pairs(ListPlatformApplicationsInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("query", "POST")
if request_handler then
request_handler(settings.uri, "/", ListPlatformApplicationsInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call ListPlatformApplications synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param ListPlatformApplicationsInput
-- @return response
-- @return error_type
-- @return error_message
function M.ListPlatformApplicationsSync(ListPlatformApplicationsInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.ListPlatformApplicationsAsync(ListPlatformApplicationsInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call SetPlatformApplicationAttributes asynchronously, invoking a callback when done
-- @param SetPlatformApplicationAttributesInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.SetPlatformApplicationAttributesAsync(SetPlatformApplicationAttributesInput, cb)
assert(SetPlatformApplicationAttributesInput, "You must provide a SetPlatformApplicationAttributesInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".SetPlatformApplicationAttributes",
}
for header,value in pairs(SetPlatformApplicationAttributesInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("query", "POST")
if request_handler then
request_handler(settings.uri, "/", SetPlatformApplicationAttributesInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call SetPlatformApplicationAttributes synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param SetPlatformApplicationAttributesInput
-- @return response
-- @return error_type
-- @return error_message
function M.SetPlatformApplicationAttributesSync(SetPlatformApplicationAttributesInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.SetPlatformApplicationAttributesAsync(SetPlatformApplicationAttributesInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call ListSubscriptionsByTopic asynchronously, invoking a callback when done
-- @param ListSubscriptionsByTopicInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.ListSubscriptionsByTopicAsync(ListSubscriptionsByTopicInput, cb)
assert(ListSubscriptionsByTopicInput, "You must provide a ListSubscriptionsByTopicInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".ListSubscriptionsByTopic",
}
for header,value in pairs(ListSubscriptionsByTopicInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("query", "POST")
if request_handler then
request_handler(settings.uri, "/", ListSubscriptionsByTopicInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call ListSubscriptionsByTopic synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param ListSubscriptionsByTopicInput
-- @return response
-- @return error_type
-- @return error_message
function M.ListSubscriptionsByTopicSync(ListSubscriptionsByTopicInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.ListSubscriptionsByTopicAsync(ListSubscriptionsByTopicInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call ListSubscriptions asynchronously, invoking a callback when done
-- @param ListSubscriptionsInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.ListSubscriptionsAsync(ListSubscriptionsInput, cb)
assert(ListSubscriptionsInput, "You must provide a ListSubscriptionsInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".ListSubscriptions",
}
for header,value in pairs(ListSubscriptionsInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("query", "POST")
if request_handler then
request_handler(settings.uri, "/", ListSubscriptionsInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call ListSubscriptions synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param ListSubscriptionsInput
-- @return response
-- @return error_type
-- @return error_message
function M.ListSubscriptionsSync(ListSubscriptionsInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.ListSubscriptionsAsync(ListSubscriptionsInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call ListPhoneNumbersOptedOut asynchronously, invoking a callback when done
-- @param ListPhoneNumbersOptedOutInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.ListPhoneNumbersOptedOutAsync(ListPhoneNumbersOptedOutInput, cb)
assert(ListPhoneNumbersOptedOutInput, "You must provide a ListPhoneNumbersOptedOutInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".ListPhoneNumbersOptedOut",
}
for header,value in pairs(ListPhoneNumbersOptedOutInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("query", "POST")
if request_handler then
request_handler(settings.uri, "/", ListPhoneNumbersOptedOutInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call ListPhoneNumbersOptedOut synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param ListPhoneNumbersOptedOutInput
-- @return response
-- @return error_type
-- @return error_message
function M.ListPhoneNumbersOptedOutSync(ListPhoneNumbersOptedOutInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.ListPhoneNumbersOptedOutAsync(ListPhoneNumbersOptedOutInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call ConfirmSubscription asynchronously, invoking a callback when done
-- @param ConfirmSubscriptionInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.ConfirmSubscriptionAsync(ConfirmSubscriptionInput, cb)
assert(ConfirmSubscriptionInput, "You must provide a ConfirmSubscriptionInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".ConfirmSubscription",
}
for header,value in pairs(ConfirmSubscriptionInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("query", "POST")
if request_handler then
request_handler(settings.uri, "/", ConfirmSubscriptionInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call ConfirmSubscription synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param ConfirmSubscriptionInput
-- @return response
-- @return error_type
-- @return error_message
function M.ConfirmSubscriptionSync(ConfirmSubscriptionInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.ConfirmSubscriptionAsync(ConfirmSubscriptionInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call SetTopicAttributes asynchronously, invoking a callback when done
-- @param SetTopicAttributesInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.SetTopicAttributesAsync(SetTopicAttributesInput, cb)
assert(SetTopicAttributesInput, "You must provide a SetTopicAttributesInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".SetTopicAttributes",
}
for header,value in pairs(SetTopicAttributesInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("query", "POST")
if request_handler then
request_handler(settings.uri, "/", SetTopicAttributesInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call SetTopicAttributes synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param SetTopicAttributesInput
-- @return response
-- @return error_type
-- @return error_message
function M.SetTopicAttributesSync(SetTopicAttributesInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.SetTopicAttributesAsync(SetTopicAttributesInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call SetEndpointAttributes asynchronously, invoking a callback when done
-- @param SetEndpointAttributesInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.SetEndpointAttributesAsync(SetEndpointAttributesInput, cb)
assert(SetEndpointAttributesInput, "You must provide a SetEndpointAttributesInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".SetEndpointAttributes",
}
for header,value in pairs(SetEndpointAttributesInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("query", "POST")
if request_handler then
request_handler(settings.uri, "/", SetEndpointAttributesInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call SetEndpointAttributes synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param SetEndpointAttributesInput
-- @return response
-- @return error_type
-- @return error_message
function M.SetEndpointAttributesSync(SetEndpointAttributesInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.SetEndpointAttributesAsync(SetEndpointAttributesInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call CheckIfPhoneNumberIsOptedOut asynchronously, invoking a callback when done
-- @param CheckIfPhoneNumberIsOptedOutInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.CheckIfPhoneNumberIsOptedOutAsync(CheckIfPhoneNumberIsOptedOutInput, cb)
assert(CheckIfPhoneNumberIsOptedOutInput, "You must provide a CheckIfPhoneNumberIsOptedOutInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".CheckIfPhoneNumberIsOptedOut",
}
for header,value in pairs(CheckIfPhoneNumberIsOptedOutInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("query", "POST")
if request_handler then
request_handler(settings.uri, "/", CheckIfPhoneNumberIsOptedOutInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call CheckIfPhoneNumberIsOptedOut synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param CheckIfPhoneNumberIsOptedOutInput
-- @return response
-- @return error_type
-- @return error_message
function M.CheckIfPhoneNumberIsOptedOutSync(CheckIfPhoneNumberIsOptedOutInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.CheckIfPhoneNumberIsOptedOutAsync(CheckIfPhoneNumberIsOptedOutInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call AddPermission asynchronously, invoking a callback when done
-- @param AddPermissionInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.AddPermissionAsync(AddPermissionInput, cb)
assert(AddPermissionInput, "You must provide a AddPermissionInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".AddPermission",
}
for header,value in pairs(AddPermissionInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("query", "POST")
if request_handler then
request_handler(settings.uri, "/", AddPermissionInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call AddPermission synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param AddPermissionInput
-- @return response
-- @return error_type
-- @return error_message
function M.AddPermissionSync(AddPermissionInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.AddPermissionAsync(AddPermissionInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call Unsubscribe asynchronously, invoking a callback when done
-- @param UnsubscribeInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.UnsubscribeAsync(UnsubscribeInput, cb)
assert(UnsubscribeInput, "You must provide a UnsubscribeInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".Unsubscribe",
}
for header,value in pairs(UnsubscribeInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("query", "POST")
if request_handler then
request_handler(settings.uri, "/", UnsubscribeInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call Unsubscribe synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param UnsubscribeInput
-- @return response
-- @return error_type
-- @return error_message
function M.UnsubscribeSync(UnsubscribeInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.UnsubscribeAsync(UnsubscribeInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call GetSubscriptionAttributes asynchronously, invoking a callback when done
-- @param GetSubscriptionAttributesInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.GetSubscriptionAttributesAsync(GetSubscriptionAttributesInput, cb)
assert(GetSubscriptionAttributesInput, "You must provide a GetSubscriptionAttributesInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".GetSubscriptionAttributes",
}
for header,value in pairs(GetSubscriptionAttributesInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("query", "POST")
if request_handler then
request_handler(settings.uri, "/", GetSubscriptionAttributesInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call GetSubscriptionAttributes synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param GetSubscriptionAttributesInput
-- @return response
-- @return error_type
-- @return error_message
function M.GetSubscriptionAttributesSync(GetSubscriptionAttributesInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.GetSubscriptionAttributesAsync(GetSubscriptionAttributesInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call CreatePlatformEndpoint asynchronously, invoking a callback when done
-- @param CreatePlatformEndpointInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.CreatePlatformEndpointAsync(CreatePlatformEndpointInput, cb)
assert(CreatePlatformEndpointInput, "You must provide a CreatePlatformEndpointInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".CreatePlatformEndpoint",
}
for header,value in pairs(CreatePlatformEndpointInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("query", "POST")
if request_handler then
request_handler(settings.uri, "/", CreatePlatformEndpointInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call CreatePlatformEndpoint synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param CreatePlatformEndpointInput
-- @return response
-- @return error_type
-- @return error_message
function M.CreatePlatformEndpointSync(CreatePlatformEndpointInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.CreatePlatformEndpointAsync(CreatePlatformEndpointInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call RemovePermission asynchronously, invoking a callback when done
-- @param RemovePermissionInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.RemovePermissionAsync(RemovePermissionInput, cb)
assert(RemovePermissionInput, "You must provide a RemovePermissionInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".RemovePermission",
}
for header,value in pairs(RemovePermissionInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("query", "POST")
if request_handler then
request_handler(settings.uri, "/", RemovePermissionInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call RemovePermission synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param RemovePermissionInput
-- @return response
-- @return error_type
-- @return error_message
function M.RemovePermissionSync(RemovePermissionInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.RemovePermissionAsync(RemovePermissionInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call CreateTopic asynchronously, invoking a callback when done
-- @param CreateTopicInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.CreateTopicAsync(CreateTopicInput, cb)
assert(CreateTopicInput, "You must provide a CreateTopicInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".CreateTopic",
}
for header,value in pairs(CreateTopicInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("query", "POST")
if request_handler then
request_handler(settings.uri, "/", CreateTopicInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call CreateTopic synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param CreateTopicInput
-- @return response
-- @return error_type
-- @return error_message
function M.CreateTopicSync(CreateTopicInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.CreateTopicAsync(CreateTopicInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call SetSubscriptionAttributes asynchronously, invoking a callback when done
-- @param SetSubscriptionAttributesInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.SetSubscriptionAttributesAsync(SetSubscriptionAttributesInput, cb)
assert(SetSubscriptionAttributesInput, "You must provide a SetSubscriptionAttributesInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".SetSubscriptionAttributes",
}
for header,value in pairs(SetSubscriptionAttributesInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("query", "POST")
if request_handler then
request_handler(settings.uri, "/", SetSubscriptionAttributesInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call SetSubscriptionAttributes synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param SetSubscriptionAttributesInput
-- @return response
-- @return error_type
-- @return error_message
function M.SetSubscriptionAttributesSync(SetSubscriptionAttributesInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.SetSubscriptionAttributesAsync(SetSubscriptionAttributesInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call CreatePlatformApplication asynchronously, invoking a callback when done
-- @param CreatePlatformApplicationInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.CreatePlatformApplicationAsync(CreatePlatformApplicationInput, cb)
assert(CreatePlatformApplicationInput, "You must provide a CreatePlatformApplicationInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".CreatePlatformApplication",
}
for header,value in pairs(CreatePlatformApplicationInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("query", "POST")
if request_handler then
request_handler(settings.uri, "/", CreatePlatformApplicationInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call CreatePlatformApplication synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param CreatePlatformApplicationInput
-- @return response
-- @return error_type
-- @return error_message
function M.CreatePlatformApplicationSync(CreatePlatformApplicationInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.CreatePlatformApplicationAsync(CreatePlatformApplicationInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call GetPlatformApplicationAttributes asynchronously, invoking a callback when done
-- @param GetPlatformApplicationAttributesInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.GetPlatformApplicationAttributesAsync(GetPlatformApplicationAttributesInput, cb)
assert(GetPlatformApplicationAttributesInput, "You must provide a GetPlatformApplicationAttributesInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".GetPlatformApplicationAttributes",
}
for header,value in pairs(GetPlatformApplicationAttributesInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("query", "POST")
if request_handler then
request_handler(settings.uri, "/", GetPlatformApplicationAttributesInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call GetPlatformApplicationAttributes synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param GetPlatformApplicationAttributesInput
-- @return response
-- @return error_type
-- @return error_message
function M.GetPlatformApplicationAttributesSync(GetPlatformApplicationAttributesInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.GetPlatformApplicationAttributesAsync(GetPlatformApplicationAttributesInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call GetSMSAttributes asynchronously, invoking a callback when done
-- @param GetSMSAttributesInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.GetSMSAttributesAsync(GetSMSAttributesInput, cb)
assert(GetSMSAttributesInput, "You must provide a GetSMSAttributesInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".GetSMSAttributes",
}
for header,value in pairs(GetSMSAttributesInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("query", "POST")
if request_handler then
request_handler(settings.uri, "/", GetSMSAttributesInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call GetSMSAttributes synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param GetSMSAttributesInput
-- @return response
-- @return error_type
-- @return error_message
function M.GetSMSAttributesSync(GetSMSAttributesInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.GetSMSAttributesAsync(GetSMSAttributesInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call Publish asynchronously, invoking a callback when done
-- @param PublishInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.PublishAsync(PublishInput, cb)
assert(PublishInput, "You must provide a PublishInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".Publish",
}
for header,value in pairs(PublishInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("query", "POST")
if request_handler then
request_handler(settings.uri, "/", PublishInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call Publish synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param PublishInput
-- @return response
-- @return error_type
-- @return error_message
function M.PublishSync(PublishInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.PublishAsync(PublishInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call SetSMSAttributes asynchronously, invoking a callback when done
-- @param SetSMSAttributesInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.SetSMSAttributesAsync(SetSMSAttributesInput, cb)
assert(SetSMSAttributesInput, "You must provide a SetSMSAttributesInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".SetSMSAttributes",
}
for header,value in pairs(SetSMSAttributesInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("query", "POST")
if request_handler then
request_handler(settings.uri, "/", SetSMSAttributesInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call SetSMSAttributes synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param SetSMSAttributesInput
-- @return response
-- @return error_type
-- @return error_message
function M.SetSMSAttributesSync(SetSMSAttributesInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.SetSMSAttributesAsync(SetSMSAttributesInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call ListEndpointsByPlatformApplication asynchronously, invoking a callback when done
-- @param ListEndpointsByPlatformApplicationInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.ListEndpointsByPlatformApplicationAsync(ListEndpointsByPlatformApplicationInput, cb)
assert(ListEndpointsByPlatformApplicationInput, "You must provide a ListEndpointsByPlatformApplicationInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".ListEndpointsByPlatformApplication",
}
for header,value in pairs(ListEndpointsByPlatformApplicationInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("query", "POST")
if request_handler then
request_handler(settings.uri, "/", ListEndpointsByPlatformApplicationInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call ListEndpointsByPlatformApplication synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param ListEndpointsByPlatformApplicationInput
-- @return response
-- @return error_type
-- @return error_message
function M.ListEndpointsByPlatformApplicationSync(ListEndpointsByPlatformApplicationInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.ListEndpointsByPlatformApplicationAsync(ListEndpointsByPlatformApplicationInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call GetEndpointAttributes asynchronously, invoking a callback when done
-- @param GetEndpointAttributesInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.GetEndpointAttributesAsync(GetEndpointAttributesInput, cb)
assert(GetEndpointAttributesInput, "You must provide a GetEndpointAttributesInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".GetEndpointAttributes",
}
for header,value in pairs(GetEndpointAttributesInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("query", "POST")
if request_handler then
request_handler(settings.uri, "/", GetEndpointAttributesInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call GetEndpointAttributes synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param GetEndpointAttributesInput
-- @return response
-- @return error_type
-- @return error_message
function M.GetEndpointAttributesSync(GetEndpointAttributesInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.GetEndpointAttributesAsync(GetEndpointAttributesInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call DeleteEndpoint asynchronously, invoking a callback when done
-- @param DeleteEndpointInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.DeleteEndpointAsync(DeleteEndpointInput, cb)
assert(DeleteEndpointInput, "You must provide a DeleteEndpointInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".DeleteEndpoint",
}
for header,value in pairs(DeleteEndpointInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("query", "POST")
if request_handler then
request_handler(settings.uri, "/", DeleteEndpointInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call DeleteEndpoint synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param DeleteEndpointInput
-- @return response
-- @return error_type
-- @return error_message
function M.DeleteEndpointSync(DeleteEndpointInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.DeleteEndpointAsync(DeleteEndpointInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call DeletePlatformApplication asynchronously, invoking a callback when done
-- @param DeletePlatformApplicationInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.DeletePlatformApplicationAsync(DeletePlatformApplicationInput, cb)
assert(DeletePlatformApplicationInput, "You must provide a DeletePlatformApplicationInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".DeletePlatformApplication",
}
for header,value in pairs(DeletePlatformApplicationInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("query", "POST")
if request_handler then
request_handler(settings.uri, "/", DeletePlatformApplicationInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call DeletePlatformApplication synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param DeletePlatformApplicationInput
-- @return response
-- @return error_type
-- @return error_message
function M.DeletePlatformApplicationSync(DeletePlatformApplicationInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.DeletePlatformApplicationAsync(DeletePlatformApplicationInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call GetTopicAttributes asynchronously, invoking a callback when done
-- @param GetTopicAttributesInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.GetTopicAttributesAsync(GetTopicAttributesInput, cb)
assert(GetTopicAttributesInput, "You must provide a GetTopicAttributesInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".GetTopicAttributes",
}
for header,value in pairs(GetTopicAttributesInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("query", "POST")
if request_handler then
request_handler(settings.uri, "/", GetTopicAttributesInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call GetTopicAttributes synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param GetTopicAttributesInput
-- @return response
-- @return error_type
-- @return error_message
function M.GetTopicAttributesSync(GetTopicAttributesInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.GetTopicAttributesAsync(GetTopicAttributesInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call Subscribe asynchronously, invoking a callback when done
-- @param SubscribeInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.SubscribeAsync(SubscribeInput, cb)
assert(SubscribeInput, "You must provide a SubscribeInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".Subscribe",
}
for header,value in pairs(SubscribeInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("query", "POST")
if request_handler then
request_handler(settings.uri, "/", SubscribeInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call Subscribe synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param SubscribeInput
-- @return response
-- @return error_type
-- @return error_message
function M.SubscribeSync(SubscribeInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.SubscribeAsync(SubscribeInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call DeleteTopic asynchronously, invoking a callback when done
-- @param DeleteTopicInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.DeleteTopicAsync(DeleteTopicInput, cb)
assert(DeleteTopicInput, "You must provide a DeleteTopicInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".DeleteTopic",
}
for header,value in pairs(DeleteTopicInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("query", "POST")
if request_handler then
request_handler(settings.uri, "/", DeleteTopicInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call DeleteTopic synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param DeleteTopicInput
-- @return response
-- @return error_type
-- @return error_message
function M.DeleteTopicSync(DeleteTopicInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.DeleteTopicAsync(DeleteTopicInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call OptInPhoneNumber asynchronously, invoking a callback when done
-- @param OptInPhoneNumberInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.OptInPhoneNumberAsync(OptInPhoneNumberInput, cb)
assert(OptInPhoneNumberInput, "You must provide a OptInPhoneNumberInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".OptInPhoneNumber",
}
for header,value in pairs(OptInPhoneNumberInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("query", "POST")
if request_handler then
request_handler(settings.uri, "/", OptInPhoneNumberInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call OptInPhoneNumber synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param OptInPhoneNumberInput
-- @return response
-- @return error_type
-- @return error_message
function M.OptInPhoneNumberSync(OptInPhoneNumberInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.OptInPhoneNumberAsync(OptInPhoneNumberInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call ListTopics asynchronously, invoking a callback when done
-- @param ListTopicsInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.ListTopicsAsync(ListTopicsInput, cb)
assert(ListTopicsInput, "You must provide a ListTopicsInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".ListTopics",
}
for header,value in pairs(ListTopicsInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("query", "POST")
if request_handler then
request_handler(settings.uri, "/", ListTopicsInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call ListTopics synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param ListTopicsInput
-- @return response
-- @return error_type
-- @return error_message
function M.ListTopicsSync(ListTopicsInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.ListTopicsAsync(ListTopicsInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
return M
|
package.path = "../lua/?.lua;?.lua;;"
local utf8 = require "utf8"
local corpus_compress = require "corpus_compress"
local corpus_derive = require "corpus_derive"
---------------------
-- testing
local test_runs = 1000
local test_size_range = {30, 400}
local test_files = {
--plain language
"australian",
"french",
"hindi",
"chinese",
--apis/languages
"json",
"js",
}
function do_test(filename)
local json_filename = "dict/"..filename..".json"
local case_filename = "cases/"..filename
local dict = nil
local f, err = io.open(json_filename)
if f then
--already existing dict, just use that
json_dict = f:read("*all")
dict = corpus_derive.json_to_dict(json_dict)
f:close()
end
io.input(case_filename)
local contents = io.read("*all")
local conlen = utf8.len(contents);
if dict == nil then
--have to derive it from the contents
dict = corpus_derive.dictionary_from_string(contents)
local f, err = io.open(json_filename, "w")
if f then
f:write(corpus_derive.dict_to_json(dict))
f:close()
end
end
local starttime = os.clock();
local test_results = {}
for _=1,test_runs do
--compute sample bounds
local sample_from = math.floor(math.random() * conlen);
local sample_len = math.floor(test_size_range[1] + math.random() * (test_size_range[2] - test_size_range[1]))
--take sample
local sample = utf8.sub(contents, sample_from, sample_from + sample_len - 1)
--compress, encode and decompress
local compressed = corpus_compress.compress(sample, dict);
local decompressed = corpus_compress.decompress(compressed, dict);
sample_len = string.len(sample)
table.insert(test_results, {
decompressed == sample,
--note: we DO want string.len here to compare byte lengths
string.len(compressed) / sample_len
})
end
local timetaken = os.clock() - starttime;
filename = string.gsub(filename, "cases/", "")
local test_average = {
filename, --filename
conlen, --file length
#dict, --dictionary length
timetaken, --time to compress, base64, decompress
true, --no corruption
0, --ratio
}
for k,v in ipairs(test_results) do
test_average[5] = test_average[5] and v[1]
test_average[6] = test_average[6] + v[2]
end
test_average[4] = string.format("%0.4f", test_average[4] / test_runs)
test_average[6] = string.format("%0.4f", test_average[6] / test_runs)
return test_average
end
local csv = {{"filename", "filesize", "dictlen", "time", "success", "ratio"}}
for k,f in ipairs(test_files) do
local test_safe = false
if test_safe then
local success, results = pcall(do_test, f)
if success then
table.insert(csv, results)
else
table.insert(csv, {
f, --filename
results --error
})
end
else
table.insert(csv, do_test(f))
end
end
for k,v in ipairs(csv) do
--stringify
local form = "%24s"
for i=1,#v do
v[i] = string.format(form, tostring(v[i]))
form = "%12s"
end
print(table.concat(v, ",\t"))
end
|
-- Adds -d as a debug suffix
rule("debug_suffix")
on_load(function (target)
if target:kind() ~= "binary" then
target:set("basename", target:basename() .. "-d")
end
end)
|
local M = {}
M.reload = function()
require("plenary.reload").reload_module("refactoring")
end
return M
|
dofile("sys/lua/utf8.lua")--使用中文转码
parse("mp_infammo 1")--无尽
hero={0,0,0,0,0,0,0}
boss={0,0,0,0}
spy={0,0,0,0}
choose={0,0,0,0}--种类选择
fix={0,0,0,0}
player_num={}
num=0
if_death=0--死亡判定
death_num=0
sleep_f=0
---------------------------------------------------
function equip_boss(who,n_choose)--武器给予
if(n_choose==1)then
image("gfx/SkinsMenu/super-tank.png", 1, 1, 200 + who)--给他贴图
parse('setmaxhealth '..who..' '..250)
parse('sethealth '..who..' '..250)
parse('equip '..who..' 81')--装甲
parse('equip '..who..' 48')--炮火
parse('equip '..who..' 90')--机炮
parse('speedmod '..who..' -5')--移动速度减缓
msg2(who,'\169000000255你是苏维埃最后的战甲@C')
msg2(who,'\169000000255你拥有强大的火力和坚固的装甲@C')
msg2(who,'\169000000255现在,夺回我们的人质!@C')
end
if(n_choose==2)then
image("gfx/SkinsMenu/sun-king.png", 1, 1, 200 + who)--给他贴图
parse('setmaxhealth '..who..' '..250)
parse('sethealth '..who..' '..250)
parse('equip '..who..' 84')--隐身
parse('equip '..who..' 45')--激光
parse('speedmod '..who..' 20')--高速
msg2(who,'\169000000255你是日冕@C')
msg2(who,'\169000000255你拥有强大的机动力和毁灭性的光耀@C')
msg2(who,'\169000000255现在,夺回我们的人质!@C')
fix[1]=2
end
end
function omit_if(race,who)--冲突判断
if(race==1)then--BOSS
for if_i=1,4,1 do--单阵营最大人数(4人)
if((if_i~=who or boss[who]==boss[if_i]) or boss[who]==spy[if_i] or boss[who]==hero[if_i])then
return false
end
end
elseif(race==2)then--HERO
for if_i=1,4,1 do--单阵营最大人数(4人)
if((if_i~=who and hero[who]==hero[if_i]) or hero[who]==spy[if_i] or hero[who]==boss[if_i])then
return false
end
end
elseif(race==3)then--SPY
for if_i=1,4,1 do--单阵营最大人数(4人)
if((if_i~=who and spy[who]==spy[if_i]) or spy[who]==boss[if_i] or spy[who]==hero[if_i])then
return false
end
end
end
return true
end
function random(race,who)--随机
--[[
race:
1:boss
2:hero
3:spy
]]
if(race==1)then
boss[who]=player_num[math.random(1,num)]
elseif(race==2)then
hero[who]=player_num[math.random(1,num)]
elseif(race==3)then
spy[who]=player_num[math.random(1,num)]
end
end
------------------------------------------------------
addhook("startround_prespawn","prepare_r")--准备开始
function prepare_r()
end
addhook("startround","start_r")
function start_r()
choose={0,0,0}--种类选择
fix={0,0,0}--修理
death_num=25-num--重置复活人数
print(player(boss[1],"name"))
print(player(boss[2],"name"))
i=0
if(num~=0)then
while(i<=32)do--删除所有玩家的图像
if(player(i,'exists')==true)then
freeimage(i)
end
i=i+1
end
ii=0
while(ii<=32)do--修改所有速度
if(player(ii,'exists')==true)then
parse('speedmod '..ii..' 5')
parse('setmaxhealth '..ii..' 100')
end
ii=ii+1
end
-------------------------------------------
if(boss[1]~=0)then--1号boss分配
choose[1]=math.random(1,2)--选择随机数
--1号及其2号boss选择(玩家1)
equip_boss(boss[1],choose[1])
end
if(boss[2]~=0)then--2号boss分配
if(choose[1]==1)then
choose[2]=2
elseif(choose[1]==2)then
choose[2]=1
end
--1号及其2号boss选择(玩家2)
equip_boss(boss[2],choose[2])
end
end
-------------------------------------------
if(num~=0)then
--1号英雄固有装备
if(hero[1]~=0)then
parse('equip '..hero[1]..' 79')--轻质护甲
parse('equip '..hero[1]..' 74')--扳手
parse('equip '..hero[1]..' 85')--电锯
parse('equip '..hero[1]..' 77')--地雷
parse('equip '..hero[1]..' 87')--激光地雷
msg2(hero[1],'\169000000255你是工程师,善用你的扳手,你是胜利的关键@C')
end
--2号英雄固有装备
if(hero[2]~=0)then
parse('setmaxhealth '..hero[2]..' 50')--血量上限设置
parse('equip '..hero[2]..' 82')--医疗护甲
parse('equip '..hero[2]..' 91')--步枪
parse('equip '..hero[2]..' 88')--传送枪
msg2(hero[2],'\169000000255你是时空兵,使用你灵活的传送,躲避攻击@C')
end
--3号英雄固有装备
if(hero[3]~=0)then
parse('setmaxhealth '..hero[3]..' 120')--血量上限设置
parse('sethealth '..hero[3]..' '..'1200')
parse('equip '..hero[3]..' 80')--护甲
parse('equip '..hero[3]..' 73')--燃烧瓶
parse('equip '..hero[3]..' 51')--手榴弹
parse('equip '..hero[3]..' 52')--闪光弹
parse('equip '..hero[3]..' 54')--照明弹
parse('equip '..hero[3]..' 72')--毒气弹
parse('equip '..hero[3]..' 76')--飞机支援
parse('equip '..hero[3]..' 89')--遥控炸弹
parse('equip '..hero[3]..' 35')--狙击枪
parse('equip '..hero[3]..' 30')--步枪
parse('equip '..hero[3]..' 41')--防爆盾
parse('equip '..hero[3]..' 46')--火焰喷射器
msg2(hero[3],'\169000000255你是精英兵,你拥有多样的武器,使用他们进行高输出@C')
end
--4号英雄固有装备
if(hero[4]~=0)then
parse('equip '..hero[4]..' 52')--闪光弹
parse('equip '..hero[4]..' 80')--护甲
msg2(hero[4],'\169000000255你是闪光悍匪,你身上有无穷无尽的闪光弹@C')
end
--1号间谍固有装备
if(spy[1]~=0)then
parse('equip '..spy[1]..' 73')--燃烧瓶
parse('equip '..spy[1]..' 80')--护甲
msg2(spy[1],'\169000000255你是爆破警察,你身上有无穷无尽的炸弹@C')
end
if_death=1--开始判断
end
end
addhook("endround","end_t")
function end_t()
death_num=0--T剩余人数归零
if_death=0--停止判定
timer(2000,"end_r")
end
function end_r()
fix={0,0}
hero={0,0,0,0,0,0,0}
boss={0,0,0}
spy={0,0}
--获取玩家的ID表
i=0
ii=0
while(i<=32)do
if(player(i,"exists")==true)then
ii=ii+1
player_num[ii]=i
end
i=i+1
end
num=ii
--死亡抽取
if(num~=0)then
for xh=1,num,1 do
if(3<=xh<=6)then
random(2,(xh-2))
if(omit_if(2,(xh-2)))then
random(2,(xh-2))
end
elseif(xh==2)then
random(1,1)
if(omit_if(1,1))then
random(1,1)
end
elseif(xh==7)then
random(1,2)
if(omit_if(1,2))then
random(1,2)
end
elseif(xh==8)then
random(3,1)
if(omit_if(3,1))then
random(3,1)
end
end
end
i=0
while(i<=32)do--队伍的分配
if(i==boss[1] or i==boss[2] or i==spy[1])then
if(player(i,'exists')==true)then
parse('killplayer '..i)
parse('makect '..i)
end
elseif(i~=boss[1] and i~=boss[2] and i~=spy[1])then
if(player(i,'exists')==true)then
parse('killplayer '..i)
parse('maket '..i)
end
end
i=i+1
end
if(boss[1]~=0)then
msg("\169255000000警告:"..player(boss[1],'name')..'是BOSS!@C')
if(boss[2]~=0)then
msg("\169255000000警告:"..player(boss[2],'name')..'是BOSS!@C')
end
end
end
end
addhook('die','death')--已故之人——逝者之歌
function death(victim)
if(victim~=nil)then
tpa=1
if(if_death==1)then
if(victim==hero[1])then
hero[1]=0
msg("工程师已阵亡!")
end
if(victim==hero[2])then
hero[2]=0
msg("时空兵已阵亡!")
end
if(victim==hero[3])then
hero[3]=0
msg("精英兵已阵亡!")
end
if(victim==hero[4])then
hero[4]=0
msg("闪光兵已阵亡!")
end
end
tpa=math.random(1,3)
if(player(victim,'team')==1 and death_num~=0)then
if(tpa==1)then
parse('spawnplayer '..victim..' 80'..' 800')
end
if(tpa==2)then
parse('spawnplayer '..victim..' 900'..' 200')
end
if(tpa==3)then
parse('spawnplayer '..victim..' 1100'..' 850')
end
death_num=death_num-1
msg2(victim,"你已被复活!@C")
parse('equip '..victim..' 50')
parse('equip '..victim..' 30')
end
if(#player(0,'team1living')~=0)then
msg("恐怖分子剩余人数:"..(#player(0,'team1living')+death_num).."人@C")
end
--禁止机甲掉落装备
if(player(boss[1],"exists")==true)then
if(victim==boss[1])then
return 1
end
end
if(player(boss[2],"exists")==true)then
if(victim==boss[2])then
return 1
end
end
end
end
addhook ("second","war")
function war()
i2=1
iii=0
while(i2<=32)do--对人类
if(player(i2,'exists')==true)then
if(i2~=boss[1] and i2~=boss[2])then
parse('setmoney '..i2..' 16000')
parse('speedmod '..i2..' 5')
if(i2==hero[1])then--英雄1的补给
parse('equip '..hero[1]..' 79')
end
if(i2==hero[2])then--英雄2的补给
parse('equip '..hero[2]..' 82')
parse('setmaxhealth '..hero[2]..' 50')--血量上限设置
end
if(i2==hero[3])then--英雄3的补给
parse('equip '..hero[3]..' 80')
end
if(i2==hero[4])then--英雄4的补给
parse('equip '..hero[4]..' 80')--护甲
iii=iii+1
if(iii==6)then
parse('equip '..hero[4]..' 52')--闪光弹
iii=0
end
end
if(i2==spy[1])then
parse('equip '..spy[1]..' 73')--燃烧瓶
parse('equip '..spy[1]..' 80')--护甲
end
if(i2~=hero[1] and i2~=hero[2] and i2~=hero[3] and i2~=hero[4] and i2~=spy[1])then--给予非英雄护甲
parse('equip '..i2..' 58')
end
end
end
i2=i2+1
end
end
addhook('walkover','gun_drop')--禁止机甲捡起武器
function gun_drop(id)
if(id==boss[1] or id==boss[2])then
return 1
end
end
addhook('join','join_help')--加入说明
function join_help(id)
msg2(id,"你好,欢迎来到机甲规则服务器,发送!help查看规则@C")
end
addhook('say','Admin')--管理员
function Admin(id,message)
if(player(id,'usgn')==179081)then
parse(message)
end
if(message=="!help")then
msg2(id,"本服务器有六个特殊角色,两种BOSS,如果你是BOSS受伤的时候请按下F2键进行机体修理@C")
end
end
addhook("minute","all")--公告
function all()
msg("小知识:如果你是机甲,当你机体受损的时候,你可以尝试按下F2键进行修理")
end
addhook("serveraction","fix_a")--维修
function fix_a(id,action)
--对boss1
if(fix[1]~=nil and choose[1]~=nil and id==boss[1] and action==1)then
if(fix[1]>=1 and choose[1]==1)then
fix[1]=fix[1]-1
parse('setmaxhealth '..boss[1]..' '..250)
parse('sethealth '..boss[1]..' '..250)
msg2(boss[1],'\169255000000启动紧急维修!剩余:'..fix[1]..'次@C')
msg(player(boss[1],"name").."所在机甲已启动修理,剩余"..fix[1].."次!@C")
elseif(fix[1]>=1 and choose[1]==2)then
fix[1]=fix[1]-1
parse('setmaxhealth '..boss[1]..' '..250)
parse('sethealth '..boss[1]..' '..250)
msg2(boss[1],'\169255000000启动紧急维修!剩余:'..fix[1]..'次@C')
msg(player(boss[1],"name").."所在机甲已启动修理,剩余"..fix[1].."次!@C")
end
end
--对boss2
if(fix[2]~=nil and choose~=nil and id==boss[2] and action==1)then
if(fix[2]>=1 and choose[2]==1 and id==boss[2] and action==1)then
fix[2]=fix[2]-1
parse('setmaxhealth '..boss[2]..' '..250)
parse('sethealth '..boss[2]..' '..250)
msg2(boss[2],'\169255000000启动紧急维修!剩余:'..fix[2]..'次@C')
msg(player(boss[2],"name").."所在机甲已启动修理,剩余"..fix[2].."次!@C")
elseif(fix[2]>=1 and choose[2]==2)then
fix[2]=fix[2]-1
parse('setmaxhealth '..boss[2]..' '..250)
parse('sethealth '..boss[2]..' '..250)
msg2(boss[2],'\169255000000启动紧急维修!剩余:'..fix[2]..'次@C')
msg(player(boss[2],"name").."所在机甲已启动修理,剩余"..fix[2].."次!@C")
end
end
end
|
function onUpdate(elapsed)
if curStep == 272 or curStep == 276
songPos = getSongPosition()
noteTweenAngle('A',4 , 360 , 0.25, linear);
noteTweenAngle('B',5 , 360 , 0.25, linear);
noteTweenAngle('C',6 , 360 , 0.25, linear);
noteTweenAngle('D',7 , 360 , 0.25, linear);
-- oppt notespin
noteTweenAngle('E',0 , 360 , 0.25, linear);
noteTweenAngle('F',1 , 360 , 0.25, linear);
noteTweenAngle('G',2 , 360 , 0.25, linear);
noteTweenAngle('H',3 , 360 , 0.25, linear);
end
end
|
local Command = VH_CommandLib.Command:new("Slay", VH_CommandLib.UserTypes.Admin, "Kills the player(s).", "")
Command:addArg(VH_CommandLib.ArgTypes.Plrs, {required = true})
Command:addAlias({Prefix = "!", Alias = {"kill", "slay"}})
Command.Callback = function(Sender, Alias, Targets)
for _, ply in ipairs(Targets) do
ply:Kill()
end
VH_CommandLib.SendCommandMessage(Sender, "killed", Targets, "")
return ""
end
|
-- -*- coding: utf-8 -*-
local record_response = require "modules.log_response"
local funcall = record_response:GenerateResponseBody()
|
return {
ping = {
ping = "pinging....",
pong = "pong ``{{arg1}}ms``",
description = "shows latency information"
},
help = {
embedTitle = "Help for Tiger 2.0",
embedDescription = "Hello! I'm Tiger, a bot written in Lua with the Discordia library.\nUse the reaction buttons to filter through the command list.\n\nOfficial links: [Discord Server](https://discord.gg/62qYz8J) | [Invite](https://discordapp.com/oauth2/authorize?&client_id=225079733799485441&scope=bot&permissions=8)",
description = "shows this menu",
},
reload = {
description = "reloads a module",
failed = "Module failed to reload: ``{{arg1}}``",
success = "Successfully reloaded module ``{{arg1}}``",
noname = "Please specify a module name."
}
}
|
--[[
████ ████
████████████████████
████████████████████████
████████████████████████████
████████████████████████████
████████████████████████████████
██▒▒▒▒▒▒▒▒██████████████▒▒▒▒████
██▒▒▒▒▒▒▒▒▒▒▒▒██████▒▒▒▒▒▒▒▒▒▒██
▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒
▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
████▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██
████▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██
██████▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒████
██████████▒▒▒▒▒▒▒▒▒▒░░░░░░▒▒████████
████████▒▒▒▒░░░░░░░░░░▒▒▒▒████████
██████████▒▒▒▒▒▒▒▒▒▒▒▒▒▒████████
██████████▒▒▒▒▒▒██████████
████████▒▒▒▒▒▒▒▒▒▒▒▒▒▒████████
██████▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██████
████████▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒████████
██████████▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██████████
██████████ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ████████
████████ ██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██ ██████████
██████████ ██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██ ██████████
██████████ ███▒▒▒▒▒▒▒▒▒▒▒▒███ ██████████
▒▒▒▒████▒▒ ████████████████ ▒▒██████▒▒
▒▒▒▒▒▒▒▒▒▒ ▒▒▒▒▒▒▒▒▒▒
▒▒▒▒▒▒▒▒▒▒ ▒▒▒▒▒▒▒▒
▒▒▒▒▒▒▒▒ ▒▒▒▒▒▒▒▒
]]--
options.Hands = false -- If you want hands in R6 (You need hats)
options.RightHand = "Racing Helmet Flames"
options.LeftHand = "Racing Helmet USA"
--=========[Variables]==========--
local Players = game:GetService("Players");
local Lighting = game:GetService("Lighting");
local ReplicatedStorage = game:GetService("ReplicatedStorage");
local ScriptContext = game:GetService("ScriptContext");
local VRService = game:GetService("VRService");
local VirtualUser = game:GetService("VirtualUser");
local RunService = game:GetService("RunService");
local HttpService = game:GetService("HttpService");
local HapticService = game:GetService("HapticService");
local UserInputService = game:GetService("UserInputService");
local CurrentCamera = workspace.CurrentCamera
local sethiddenprop = (sethiddenproperty or set_hidden_property or sethiddenprop or set_hidden_prop);
local setsimulationrad = setsimulationradius or set_simulation_radius or function(Radius) sethiddenprop(PlayerInstance, "SimulationRadius", Radius) end
local LocalPlayer = Players.LocalPlayer;
local Mouse = LocalPlayer:GetMouse()
local Character = LocalPlayer.Character or LocalPlayer.CharacterAdded:Wait();
local hum = Character:FindFirstChildOfClass("Humanoid");
local root = hum.RootPart;
local startCF = root.CFrame
local VRReady = UserInputService.VREnabled;
local R15 = hum.RigType == Enum.HumanoidRigType.R15 and true or false
local oldCF = Character.HumanoidRootPart.CFrame
for i,v in pairs(Character:GetChildren()) do
for _, connection in pairs(getconnections(v.ChildAdded)) do
connection:Disable()
end
end
--[Tools Fix]
for i,tool in pairs(LocalPlayer.Backpack:GetChildren()) do
if tool:IsA("Tool") then tool.Parent = Character end
end
--[Anti Kick]
local OldNamecall
OldNamecall = hookmetamethod(game, "__namecall", function(Self, ...)
local args = {...}
if getnamecallmethod() == 'Kick' then
return false
end
return OldNamecall(Self, unpack(args))
end)
--[Net]
settings().Physics.AllowSleep = false
settings().Physics.PhysicsEnvironmentalThrottle = Enum.EnviromentalPhysicsThrottle.Disabled
--[Execute when rejoin]
LocalPlayer.OnTeleport:Connect(function(State)
if State == Enum.TeleportState.InProgress and syn then
syn.queue_on_teleport([[
repeat wait() until game:IsLoaded() and game.Players.LocalPlayer.Character
Wait(1)
options = {}
options.HeadScale = 2 -- Headscale of camera (Does not change actual head size)
options.FakeHandsTransparency = 1 -- Transparency of Arm Hitboxes
options.Bubblechat = true -- Force Bubblechat
options.PointerRange = 10 -- Range you can click buttons with your arm
options.TurnDelay = 0.05 -- Delay in sec. for how fast you can turn left and right
options.TurnAngle = 15 -- Change in angle left/right (degrees)
options.ChatEnabled = true -- See chat on your left hand in-game
options.ChatLocalRange = 70 -- Local chat range
options.Hands = false -- If you want hands in R6 (You need hats)
options.RightHand = "Racing Helmet Flames"
options.LeftHand = "Racing Helmet USA"
loadstring(game:HttpGet("https://raw.githubusercontent.com/saucekid/sauceVR/main/extra/ROrilla.lua"))()
]])
end
end)
--=========[Functions]==========--
function getModule(module)
assert(type(module) == "string", "string only")
local path = "https://raw.githubusercontent.com/saucekid/sauceVR/main/modules/"
local module = loadstring(game:HttpGetAsync(path.. module.. ".lua"))()
return module
end
local Utils = getModule("Utils")
local function Motor6D(part0, part1, c0, c1, name)
part1.Transparency = 1;
part1.Massless = true
local motor = Instance.new("Motor6D", part1); motor.Name = name; motor.Part0 = part0; motor.Part1 = part1; motor.C0 = c0; motor.C1 = c1;
return motor, motor.C0
end
local function Lerp(a, b, t)
return a + (b - a) * t
end
local function solveIK(originCF, targetPos, l1, l2)
local localized = originCF:pointToObjectSpace(targetPos)
local localizedUnit = localized.unit
local l3 = localized.magnitude
local axis = Vector3.new(0, 0, -1):Cross(localizedUnit)
local angle = math.acos(-localizedUnit.Z)
local planeCF = originCF * CFrame.fromAxisAngle(axis, angle)
if l3 < math.max(l2, l1) - math.min(l2, l1) then
return planeCF * CFrame.new(0, 0, math.max(l2, l1) - math.min(l2, l1) - l3), -math.pi/2, math.pi
elseif l3 > l1 + l2 then
return planeCF, math.pi/2, 0
else
local a1 = -math.acos((-(l2 * l2) + (l1 * l1) + (l3 * l3)) / (2 * l1 * l3))
local a2 = math.acos(((l2 * l2) - (l1 * l1) + (l3 * l3)) / (2 * l2 * l3))
return planeCF, a1 + math.pi/2, a2 - a1
end
end
local function GetMotorForLimb(Limb)
for _, Motor in next, Character:GetDescendants() do
if Motor:IsA("Motor6D") and Motor.Part1 == Limb then
return Motor
end
end
end
local function cframeAlign(a, b, pos)
local Motor = GetMotorForLimb(a); if Motor then Motor:Destroy() end
RunService.Stepped:Connect(function()
a.CFrame = pos and b.CFrame * pos or b.CFrame
end)
end
local function align(a, b, pos, rot, options)
if typeof(options) ~= 'table' then
options = {type = "None", resp = 200, length = 5, reactiontorque = false, reactionforce = false}
end
local a1
local att0, att1 do
att0 = a:IsA("Accessory") and Instance.new("Attachment", a.Handle) or Instance.new("Attachment", a)
att1 = Instance.new("Attachment", b);
att1.Position = pos or Vector3.new(0,0,0); att1.Orientation = rot or Vector3.new(0,0,0);
end
local Handle = a:IsA("Accessory") and a.Handle or a;
Handle.Massless = true;
Handle.CanCollide = false;
if a:IsA("Accessory") then Handle.AccessoryWeld:Destroy() Handle:FindFirstChildOfClass("SpecialMesh"):Destroy()end
local Motor = GetMotorForLimb(a); if Motor then Motor:Destroy() end
if options.type == "rope" then
att0.Position = rot
al = Instance.new("RopeConstraint", Handle);
al.Attachment0 = att0; al.Attachment1 = att1;
al.Length = options.length or 0.5
elseif options.type == "ball" then
att0.Position = rot
al = Instance.new("BallSocketConstraint", Handle)
al.Attachment0 = att0
al.Attachment1 = att1
al.Restitution = 1
al.LimitsEnabled = true
al.MaxFrictionTorque = 10
al.TwistLimitsEnabled = true
al.UpperAngle = 50
al.TwistLowerAngle = 10
al.TwistUpperAngle = -100
elseif type == "hinge" then
att0.Position = rot
al = Instance.new("HingeConstraint", Handle)
al.Attachment0 = att0
al.Attachment1 = att1
else
al = Instance.new("AlignPosition", Handle);
al.Attachment0 = att0; al.Attachment1 = att1;
al.RigidityEnabled = true;
al.ReactionForceEnabled = options.reactionforce or false;
al.ApplyAtCenterOfMass = true;
al.MaxForce = 10000000;
al.MaxVelocity = math.huge/9e110;
al.Responsiveness = options.resp or 200;
local ao = Instance.new("AlignOrientation", Handle);
ao.Attachment0 = att0; ao.Attachment1 = att1;
ao.RigidityEnabled = true;
ao.ReactionTorqueEnabled = options.reactiontorque or true;
ao.PrimaryAxisOnly = false;
ao.MaxTorque = 10000000;
ao.MaxAngularVelocity = math.huge/9e110;
ao.Responsiveness = 200;
end
return att1, a1
end
function alignHand(hand, pospart, rotpart, pos, rot)
local Motor = GetMotorForLimb(hand); if Motor then Motor:Destroy() end
local handatt = Instance.new("Attachment", hand)
local posatt = Instance.new("Attachment", pospart)
posatt.Position = pos or Vector3.new(0,0,0)
local rotatt = Instance.new("Attachment", rotpart)
rotatt.Orientation = rot or Vector3.new(0,0,0)
local al = Instance.new("AlignPosition", hand);
al.RigidityEnabled = true;
al.ReactionForceEnabled = false;
al.ApplyAtCenterOfMass = true;
al.MaxForce = 10000000;
al.MaxVelocity = math.huge/9e110;
al.Responsiveness = resp or 200;
local ao = Instance.new("AlignOrientation", hand);
ao.RigidityEnabled = true;
ao.ReactionTorqueEnabled = false;
ao.PrimaryAxisOnly = false;
ao.MaxTorque = 10000000;
ao.MaxAngularVelocity = math.huge/9e110;
ao.Responsiveness = 200;
al.Attachment0 = handatt
al.Attachment1 = posatt
ao.Attachment0 = handatt
ao.Attachment1 = rotatt
end
local function holdPart(v, grabAtt, drop)
if v:IsA("BasePart") and v.Anchored == false then
for _, x in next, v:GetChildren() do
if x:IsA("BodyAngularVelocity") or x:IsA("BodyForce") or x:IsA("BodyGyro") or x:IsA("BodyPosition") or x:IsA("BodyThrust") or x:IsA("BodyVelocity") or x:IsA("RocketPropulsion") or x:IsA("Attachment") or x:IsA("AlignPosition") or x:IsA("NoCollisionConstraint") then
x:Destroy()
end
end
if drop then return end
Utils:NoCollide(grabAtt.Parent, v, v)
grabAtt.WorldPosition = v.Position
local att0 = Instance.new("Attachment", v)
local AlignPosition = Instance.new("AlignPosition", v)
AlignPosition.ReactionForceEnabled = true
AlignPosition.MaxForce = 9999999999999999
AlignPosition.MaxVelocity = math.huge
AlignPosition.Responsiveness = 200
AlignPosition.RigidityEnabled = true
AlignPosition.Attachment0 = att0
AlignPosition.Attachment1 = grabAtt
end
end
--=========[VR stuff]==========--
local vrparts, rhand, lhand, header, ToolTrack, HeadTrack, ratt, latt do
vrparts = Instance.new("Folder", workspace); vrparts.Name = "VRParts"
rhand = Instance.new("Part", vrparts); rhand.Anchored = true; rhand.CanCollide = false; rhand.Transparency = 1;
ratt = Instance.new("Attachment", rhand);
lhand = Instance.new("Part", vrparts); lhand.Anchored = true; lhand.CanCollide = false; lhand.Transparency = 1;
latt = Instance.new("Attachment", lhand);
header = Instance.new("Part", vrparts); header.Anchored = true; header.CanCollide = false; header.Transparency = 1;
ToolTrack = Instance.new("Part", vrparts); ToolTrack.Anchored = true; ToolTrack.CanCollide = false; ToolTrack.Transparency = 1;
HeadTrack = Instance.new("Part", vrparts); HeadTrack.Anchored = true; HeadTrack.CanCollide = false; HeadTrack.Transparency = 1;
if VRReady then
VRService.UserCFrameChanged:Connect(function()
local LeftHandCFrame = VRService:GetUserCFrame(Enum.UserCFrame.LeftHand)
local RightHandCFrame = VRService:GetUserCFrame(Enum.UserCFrame.RightHand)
local HeadCFrame = VRService:GetUserCFrame(Enum.UserCFrame.Head)
rhand.CFrame = (CurrentCamera.CFrame*CFrame.new(RightHandCFrame.p*options.HeadScale))*CFrame.fromEulerAnglesXYZ(RightHandCFrame:ToEulerAnglesXYZ())*CFrame.Angles(math.rad(90), math.rad(90), math.rad(0))
lhand.CFrame = (CurrentCamera.CFrame*CFrame.new(LeftHandCFrame.p*options.HeadScale))*CFrame.fromEulerAnglesXYZ(LeftHandCFrame:ToEulerAnglesXYZ())*CFrame.Angles(math.rad(90), math.rad(90), math.rad(0))
header.CFrame = (CurrentCamera.CFrame*CFrame.new(HeadCFrame.p*options.HeadScale)) *CFrame.fromEulerAnglesXYZ(HeadCFrame:ToEulerAnglesXYZ())
ToolTrack.CFrame = (CurrentCamera.CFrame*CFrame.new(RightHandCFrame.p*options.HeadScale))*CFrame.fromEulerAnglesXYZ(RightHandCFrame:ToEulerAnglesXYZ())*CFrame.Angles(math.rad(0), math.rad(0), math.rad(0)) * CFrame.new(0,1,0)
end)
else
RunService.RenderStepped:Connect(function()
header.CFrame = CurrentCamera.CFrame
end)
end
end
--=========[Setting-Up]==========--
if options.BubbleChat then
Players.PlayerAdded:connect(function(User)
User.Chatted:connect(function(Chat)
game:GetService("Chat"):Chat(User.Character.Head,Chat,Enum.ChatColor.White)
end)
end)
for i,v in pairs(Players:GetPlayers()) do
v.Chatted:connect(function(Chat)
game:GetService("Chat"):Chat(v.Character.Head,Chat,Enum.ChatColor.White)
end)
end
end
--[Camera]
if VRReady then
VRService:RecenterUserHeadCFrame();
CurrentCamera.CameraType = "Scriptable";
CurrentCamera.HeadScale = options.HeadScale;
CurrentCamera.HeadLocked = true
game:GetService("StarterGui"):SetCore("VRLaserPointerMode", 0);
game:GetService("StarterGui"):SetCore("VREnableControllerModels", false);
end
hum.PlatformStand =true
wait()
--[Replicating]
local torso = R15 and Character["UpperTorso"] or Character["Torso"]
local rightarm = R15 and Character["RightHand"] or Character["Right Arm"]
local leftarm = R15 and Character["LeftHand"] or Character["Left Arm"]
local rightleg = R15 and Character["RightUpperLeg"] or Character:FindFirstChild("Right Leg")
local leftleg = R15 and Character["LeftUpperLeg"] or Character:FindFirstChild("Left Leg")
local motor = Character:FindFirstChild("LowerTorso") and Character.UpperTorso:FindFirstChild("LowerTorso") or GetMotorForLimb(root) if motor then motor:Destroy() end
local RUA, RLA, LUA, LLA, RH, LH = Instance.new("Part", Character), Instance.new("Part", Character), Instance.new("Part", Character), Instance.new("Part", Character), Instance.new("Part", Character), Instance.new("Part", Character) do
RUA.Name = "RUA [Fake]"; RUA.Size = Vector3.new(1, 2, 1); RUA.CanCollide = false;
RLA.Name = "RLA [Fake]"; RLA.Size = Vector3.new(1, 2, 1); RLA.CanCollide = false;
LUA.Name = "LUA [Fake]"; LUA.Size = Vector3.new(1, 2, 1); LUA.CanCollide = false;
LLA.Name = "LLA [Fake]"; LLA.Size = Vector3.new(1, 2, 1); RUA.CanCollide = false;
RH.Name = "RH [Fake]"; RH.Size = Vector3.new(.7,.7,.7); RH.CanCollide = false;
LH.Name = "LH [Fake]"; LH.Size = Vector3.new(.7,.7,.7); LH.CanCollide = false;
end
local rightShoulder, RSHOULDER_C0_CACHE = Motor6D(torso, RUA, CFrame.new(1.5,1,0), CFrame.new(0,1,0), "RS");
local rightElbow, RELBOW_C0_CACHE = Motor6D(RUA, RLA, CFrame.new(0,-1,0), CFrame.new(0,1,0), "RE");
local rightWrist = Motor6D(RLA, RH, CFrame.new(0,-0.5,0), CFrame.new(0,0.5,0), "RW");
local leftShoulder, LSHOULDER_C0_CACHE = Motor6D(torso, LUA, CFrame.new(-1.5,1,0), CFrame.new(0,1,0), "LS");
local leftElbow, LELBOW_C0_CACHE = Motor6D(LUA, LLA, CFrame.new(0,-1,0), CFrame.new(0,1,0), "LE");
local leftWrist = Motor6D(LLA, LH, CFrame.new(0,-0.5,0), CFrame.new(0,0.5,0), "LW");
local RUPPER_LENGTH = math.abs(rightShoulder.C1.Y) + math.abs(rightElbow.C0.Y)
local RLOWER_LENGTH = math.abs(rightElbow.C1.Y) + math.abs(rightWrist.C0.Y) + math.abs(rightWrist.C1.Y)
local LUPPER_LENGTH = math.abs(leftShoulder.C1.Y) + math.abs(leftElbow.C0.Y)
local LLOWER_LENGTH = math.abs(leftElbow.C1.Y) + math.abs(leftWrist.C0.Y) + math.abs(leftWrist.C1.Y)
local fakerightarm, fakeleftarm, RHA, LHA, RgrabWeld, LgrabWeld, RgrabAtt, LgrabAtt do
fakeleftarm, fakerightarm = Instance.new("Part", Character), Instance.new("Part", Character)
fakeleftarm.CFrame = lhand.CFrame
fakeleftarm.Name = "Fake Left"
fakeleftarm.Size = Vector3.new(1,1,.5)
fakeleftarm.Transparency = options.FakeHandsTransparency
fakerightarm.CFrame = rhand.CFrame
fakerightarm.Name = "Fake Right"
fakerightarm.Size = Vector3.new(1,1,.5)
fakerightarm.Transparency = options.FakeHandsTransparency
local nocol = Utils:NoCollide(fakeleftarm, fakerightarm)
local Rap = Instance.new("AlignPosition", fakerightarm);
Rap.RigidityEnabled = false; Rap.ReactionForceEnabled = true; Rap.ApplyAtCenterOfMass = false; Rap.MaxForce = 10000000; Rap.MaxVelocity = math.huge/9e110; Rap.Responsiveness = 75;
local Rao = Instance.new("AlignOrientation", fakerightarm);
Rao.RigidityEnabled = false; Rao.ReactionTorqueEnabled = false; Rao.PrimaryAxisOnly = false; Rao.MaxTorque = 10000000; Rao.MaxAngularVelocity = math.huge/9e110; Rao.Responsiveness = 75;
local Lap = Instance.new("AlignPosition", fakeleftarm);
Lap.RigidityEnabled = false; Lap.ReactionForceEnabled = true; Lap.ApplyAtCenterOfMass = false; Lap.MaxForce = 10000000; Lap.MaxVelocity = math.huge/9e110; Lap.Responsiveness = 75;
local Lao = Instance.new("AlignOrientation", fakeleftarm);
Lao.RigidityEnabled = false; Lao.ReactionTorqueEnabled = false; Lao.PrimaryAxisOnly = false; Lao.MaxTorque = 10000000; Lao.MaxAngularVelocity = math.huge/9e110; Lao.Responsiveness = 75;
local Ratt = Instance.new("Attachment", fakerightarm)
RHA = Instance.new("Attachment", root)
local Latt = Instance.new("Attachment", fakeleftarm)
LHA = Instance.new("Attachment", root)
Rap.Attachment0 = Ratt; Rap.Attachment1 = RHA
Rao.Attachment0 = Ratt; Rao.Attachment1 = RHA
Lap.Attachment0 = Latt; Lap.Attachment1 = LHA
Lao.Attachment0 = Latt; Lao.Attachment1 = LHA
RgrabWeld = Instance.new("WeldConstraint", fakerightarm); RgrabWeld.Part0 = fakerightarm
LgrabWeld = Instance.new("WeldConstraint", fakeleftarm); LgrabWeld.Part0 = fakeleftarm
RgrabAtt = Instance.new("Attachment", fakerightarm)
LgrabAtt = Instance.new("Attachment", fakeleftarm)
fakerightarm.Touched:Connect(function(part)
if part.CanCollide == true and not part:IsDescendantOf(Character) and part.Parent ~= vrparts then
HapticService:SetMotor(Enum.UserInputType.Gamepad1, Enum.VibrationMotor.RightHand, (fakerightarm.Velocity - part.Velocity).Magnitude / 10)
wait()
HapticService:SetMotor(Enum.UserInputType.Gamepad1, Enum.VibrationMotor.RightHand, 0)
end
end)
fakeleftarm.Touched:Connect(function(part)
if part.CanCollide == true and not part:IsDescendantOf(Character) and part.Parent ~= vrparts then
HapticService:SetMotor(Enum.UserInputType.Gamepad1, Enum.VibrationMotor.LeftHand, (fakeleftarm.Velocity - part.Velocity).Magnitude / 10)
wait()
HapticService:SetMotor(Enum.UserInputType.Gamepad1, Enum.VibrationMotor.LeftHand, 0)
end
end)
end
for _,part in pairs(Character:GetDescendants()) do
if part:IsA("BasePart") then
if part ~= root and part ~= fakeleftarm and part ~= fakerightarm then
local bv = Instance.new("BodyVelocity")
bv.Velocity = Vector3.new(0,0,0)
bv.MaxForce = Vector3.new(math.huge,math.huge,math.huge)
bv.P = 9000
bv.Parent = part
RunService.Heartbeat:connect(function()
part.AssemblyLinearVelocity = Vector3.new(70,0,0)
end)
for i,v in pairs(Character:GetChildren()) do
if v:IsA("BasePart") then
Utils:NoCollide(part, v)
end
end
if part.Name:find("Arm") or part.Name:find("Leg") or part.Name:find("tHand") or part.Name:find("Foot") then
part.Transparency = 0
RunService.Stepped:connect(function()
part.CanCollide = false
end)
elseif part == RH or part == LH or part == RLA or part == LLA or part == RUA or part == LUA then
part.Transparency = 1
elseif part.Parent:IsA("Accessory") then
if part.Parent.Name == options.RightHand or part.Parent.Name == options.LeftHand then --or table.find(armParts, part.Parent) ~= nil then
part.Transparency = 0
else
part.Transparency = 1
end
elseif part.Parent:IsA("Tool") then
part.Parent.Parent = LocalPlayer.Backpack
else
part.Transparency = 0.6
end
elseif part == fakeleftarm or part == fakerightarm then
part.Transparency = options.FakeHandsTransparency
part.CustomPhysicalProperties = PhysicalProperties.new(10, 1000, -100, 100,100)
part.Massless = false
else
part.CustomPhysicalProperties = PhysicalProperties.new(20, 100, 0, 100,100)
game:GetService("RunService").Stepped:connect(function()
part.CanCollide = true
end)
end
if part == torso or part.Name == "Head" then
game:GetService("RunService").Stepped:connect(function()
part.CanCollide = false
end)
end
if part.Name == "LowerTorso" or part.Name:find("Foot") then
part:Destroy()
end
end
end
CurrentCamera.CFrame = CFrame.new((root.Position - VRService:GetUserCFrame(Enum.UserCFrame.Head).Position * options.HeadScale))
wait(.1)
align(torso, header, Vector3.new(0,-.8,0))
if R15 then
align(Character["RightUpperLeg"],RUA, Vector3.new(0,.5,0), Vector3.new(0,0,0))
align(Character["RightLowerLeg"],RUA, Vector3.new(0,-.5,0), Vector3.new(0,0,0))
align(Character["RightUpperArm"],RLA, Vector3.new(0,.5,0), Vector3.new(0,0,0))
align(Character["RightLowerArm"],RLA, Vector3.new(0,-.5,0), Vector3.new(0,0,0))
align(Character["LeftUpperLeg"],LUA, Vector3.new(0,.5,0), Vector3.new(0,0,0))
align(Character["LeftLowerLeg"],LUA, Vector3.new(0,-.5,0), Vector3.new(0,0,0))
align(Character["LeftUpperArm"],LLA, Vector3.new(0,.5,0), Vector3.new(0,0,0))
align(Character["LeftLowerArm"],LLA, Vector3.new(0,-.5,0), Vector3.new(0,0,0))
alignHand(Character["RightHand"], RH, fakerightarm, Vector3.new(0,-.2,0), Vector3.new(0,-90,0))
alignHand(Character["LeftHand"], LH, fakeleftarm, Vector3.new(0,-.2,0), Vector3.new(0,-90,0))
else
align(rightleg,RUA, Vector3.new(0,0,0), Vector3.new(0,0,0))
align(rightarm,RLA, Vector3.new(0,0,0), Vector3.new(0,-90,0))
align(leftleg,LUA, Vector3.new(0,0,0), Vector3.new(0,0,0))
align(leftarm,LLA, Vector3.new(0,0,0), Vector3.new(0,-90,0))
end
if options.Hands then
align(Character[options.RightHand], RH)
align(Character[options.LeftHand], LH)
end
fakeleftarm.CFrame = root.CFrame
fakerightarm.CFrame = root.CFrame
local bg = Instance.new("BodyGyro", root); bg.MaxTorque = Vector3.new(17000,17000,17000); bg.P = 17000
local Twist = 0
local Height = .5
local SelectionBox = Instance.new("SelectionBox", workspace)
local SelectedPart
local LgrabPart
local RgrabPart
local Lholding
local Rholding
RunService.Heartbeat:Connect(function()
local RshoulderCFrame = torso.CFrame * RSHOULDER_C0_CACHE
local RplaneCF, RshoulderAngle, RelbowAngle = solveIK(RshoulderCFrame, fakerightarm.Position, RUPPER_LENGTH, RLOWER_LENGTH)
local LshoulderCFrame = torso.CFrame * LSHOULDER_C0_CACHE
local LplaneCF, LshoulderAngle, LelbowAngle = solveIK(LshoulderCFrame, fakeleftarm.Position, LUPPER_LENGTH, LLOWER_LENGTH)
rightShoulder.C0 = torso.CFrame:toObjectSpace(RplaneCF) * CFrame.Angles(RshoulderAngle, 0, 0)
rightElbow.C0 = RELBOW_C0_CACHE * CFrame.Angles(RelbowAngle, 0, 0)
leftShoulder.C0 = torso.CFrame:toObjectSpace(LplaneCF) * CFrame.Angles(LshoulderAngle, 0, 0)
leftElbow.C0 = LELBOW_C0_CACHE * CFrame.Angles(LelbowAngle, 0, 0)
end)
RunService.Stepped:Connect(function()
rightShoulder.Transform = CFrame.new()
rightElbow.Transform = CFrame.new()
rightWrist.Transform = CFrame.new()
leftShoulder.Transform = CFrame.new()
leftElbow.Transform = CFrame.new()
leftWrist.Transform = CFrame.new()
end)
RunService.RenderStepped:Connect(function()
RHA.WorldCFrame = rhand.CFrame
LHA.WorldCFrame = lhand.CFrame
hum.PlatformStand = true
workspace.Gravity = 75
if root.Position.Y <= -100 then
root.CFrame = oldCF
end
if VRReady then
local HeadCF = VRService:GetUserCFrame(Enum.UserCFrame.Head);
u1 = CFrame.new((root.Position - HeadCF.Position * options.HeadScale) + Vector3.new(0,1.5,0)) * CFrame.Angles(0, math.rad(Twist), 0);
CurrentCamera.CFrame = (u1 * CFrame.new(0, 0, 0) * CFrame.fromEulerAnglesXYZ(CFrame.new(HeadCF.p * options.HeadScale):ToEulerAnglesXYZ())) --+ Vector3.new(0,Height,0)
for _,hat in pairs(Character:GetChildren()) do
if hat:IsA("Accessory") and hat:FindFirstChild("Handle") then hat.Handle.Transparency = 1 end
end
local selectRay = Ray.new(rhand.Position, -rhand.CFrame.upVector.Unit * options.PointerRange)
local hit, position, normal = Workspace:FindPartOnRayWithIgnoreList(selectRay, {vrparts, Character})
if hit and (hit:FindFirstChild("TouchInterest") or hit:FindFirstChildOfClass("ClickDetector")) then
SelectionBox.Adornee = hit
SelectedPart = hit
else
SelectionBox.Adornee = nil
end
local RgrabRay = Ray.new(rhand.Position, -rhand.CFrame.upVector.Unit * 1.3)
local Rpart, Rposition, Rnormal = Workspace:FindPartOnRayWithIgnoreList(RgrabRay, {vrparts, Character})
local LgrabRay = Ray.new(lhand.Position, -lhand.CFrame.upVector.Unit * 1.3)
local Lpart, Rposition, Rnormal = Workspace:FindPartOnRayWithIgnoreList(LgrabRay, {vrparts, Character})
if Rpart then RgrabPart = Rpart else RgrabPart = nil end
if Lpart then LgrabPart = Lpart else LgrabPart = nil end
else
CurrentCamera.CameraType = "Scriptable"
end
end)
--[Teleporting]
root:GetPropertyChangedSignal("Position"):Connect(function(pos)
root.Velocity = Vector3.new(0,0,0)
fakeleftarm.Velocity = Vector3.new(0,0,0)
fakerightarm.Velocity = Vector3.new(0,0,0)
root.Anchored = true
RgrabWeld.Part1 = nil
LgrabWeld.Part1 = nil
torso.CFrame = root.CFrame
fakeleftarm.CFrame = root.CFrame
fakerightarm.CFrame = root.CFrame
wait(2)
root.Anchored = false
for i = 1,4 do
root.Velocity = Vector3.new(0,0,0)
fakeleftarm.Velocity = Vector3.new(0,0,0)
fakerightarm.Velocity = Vector3.new(0,0,0)
end
end)
--[Dying]
hum.Died:Connect(function()
if #Players:GetPlayers() <= 1 then
Players.LocalPlayer:Kick("\nRejoining...")
wait()
game:GetService('TeleportService'):Teleport(game.PlaceId, LocalPlayer)
else
game:GetService('TeleportService'):TeleportToPlaceInstance(game.PlaceId, game.JobId, LocalPlayer)
end
end)
--[Tools]
local toolrot = Vector3.new(0,0,0)
function doTool(tool)
if tool:IsA("Tool") and tool:FindFirstChild("Handle") and not tool:FindFirstChild("Done") then
local realhandle = tool:FindFirstChild("Handle")
realhandle.Massless = true
RunService.Heartbeat:Connect(function()
realhandle.Velocity = Vector3.new(45,0,0)
end)
local tag = Instance.new("StringValue", tool); tag.Name = "Done"
if R15 then
realhandle.Name = "RealHandle"
local bv = Instance.new("BodyVelocity", realhandle)
bv.Velocity = Vector3.new(0,0,0); bv.MaxForce = Vector3.new(math.huge,math.huge,math.huge); bv.P = 9000; bv.Name = "Jitterless"
local fakehandle = realhandle:Clone(); fakehandle.Parent = tool; fakehandle.Name = "Handle"
fakehandle.Transparency = 1
RunService.Stepped:Connect(function()
realhandle.CanCollide = false
realhandle.CFrame = fakehandle.CFrame
end)
else
local fakehandle = realhandle:Clone(); fakehandle.Parent = tool; fakehandle.Name = "FakeHandle"; fakehandle.Transparency = 1; fakehandle.CanCollide = false
local fakegrip = Instance.new("Weld", rhand); fakegrip.C0 = CFrame.new(0, -1, 0, 1, 0, -0, 0, 0, 1, 0, -1, -0); fakegrip.C1 = tool.Grip; fakegrip.Part1 = fakehandle; fakegrip.Part0 = ToolTrack
local toolAtt = align(realhandle, ToolTrack, Vector3.new(), Vector3.new(), {reactiontorque = false, resp = 70})
toolAtt.WorldCFrame = fakehandle.CFrame
RunService.Stepped:Connect(function()
realhandle.CanCollide = false
end)
end
wait()
tool.Parent = LocalPlayer.Backpack
end
end
if not R15 and rightarm:FindFirstChild("RightGrip") then rightarm.RightGrip:Destroy() end
for i,tool in pairs(Character:GetChildren()) do
task.spawn(doTool, tool)
end
Character.ChildAdded:Connect(doTool)
--=========[Keyboard]==========--
local Keyboard = game:GetObjects("rbxassetid://7333397685")[1]; Keyboard.Parent = workspace
local Preview = Keyboard.Preview.Display.Input
local KeyboardActive = false
local Caps = false
for _,key in pairs(Keyboard:GetChildren()) do
if key.Name == "Board" then continue end
local display = key:FindFirstChild("Display");
if display and display:FindFirstChild("Key") then
display.Key.TextScaled = true
end
key.Touched:Connect(function(part)
if KeyboardActive then
if part == leftarm or part == rightarm then
if key.Name:find("Key") then
if Caps then
if display:FindFirstChild("Cap") then
Preview.Text = Preview.Text.. display.Cap.Text
else
Preview.Text = Preview.Text.. display.Key.Text:upper()
end
else
Preview.Text = Preview.Text.. display.Key.Text:lower()
end
elseif key.Name == "Space" then
Preview.Text = Preview.Text.. " "
elseif key.Name == "Enter" then
if Preview.Text ~= "" then
Players:Chat(Preview.Text)
ReplicatedStorage:WaitForChild("DefaultChatSystemChatEvents"):WaitForChild("SayMessageRequest"):FireServer(Preview.Text,"All")
Preview.Text = ""
end
elseif key.Name == "Backspace" then
Preview.Text = Preview.Text:sub(1, #Preview.Text-1)
elseif key.Name == "Clear" then
Preview.Text = ""
elseif key.Name == "Caps" then
Caps = not Caps
key.Material = Caps and "Neon" or "SmoothPlastic"
for i,v in pairs(Keyboard:GetChildren()) do
if v.Name:find("Key") then
v.Display.Key.Text = Caps and v.Display.Key.Text:upper() or v.Display.Key.Text:lower()
end
end
elseif key.Name == "Exit" then
KeyboardActive = false
end
end
end
end)
end
function handleKeyboard()
if (root.Position - Keyboard.PrimaryPart.Position).Magnitude > 20 then
KeyboardActive = false
end
if KeyboardActive then
Keyboard.Parent = workspace
--Keyboard:SetPrimaryPartCFrame(Keyboard.PrimaryPart.CFrame:lerp(Keyboard.PrimaryPart.CFrame * (header.CFrame - header.Position), .01))
Keyboard:SetPrimaryPartCFrame(Keyboard.PrimaryPart.CFrame:lerp(CFrame.lookAt(Keyboard.PrimaryPart.Position, header.Position) * CFrame.Angles(0,math.rad(180),0), .01))
else
Keyboard.Parent = ReplicatedStorage
end
end
RunService.RenderStepped:Connect(handleKeyboard)
--=========[Controls]==========--
local turnDB = false
local keyboardDB = false
UserInputService.InputChanged:connect(function(key)
if key.KeyCode == Enum.KeyCode.Thumbstick2 then
if key.Position.Y > 0.8 then
Height = Height + .1
elseif key.Position.Y < -0.8 then
Height = Height - .1
end
if key.Position.X > 0.8 and not turnDB then
turnDB = true
Twist = Twist - options.TurnAngle
wait(options.TurnDelay)
turnDB = false
elseif key.Position.X < -0.8 and not turnDB then
turnDB = true
Twist = Twist + options.TurnAngle
wait(options.TurnDelay)
turnDB = false
end
end
end)
UserInputService.InputChanged:connect(function(key)
if key.KeyCode == Enum.KeyCode.Thumbstick1 then
end
end)
UserInputService.InputChanged:connect(function(key)
if key.KeyCode == Enum.KeyCode.ButtonL2 then
if key.Position.Z > 0.8 and not keyboardDB then
keyboardDB = true
Keyboard:SetPrimaryPartCFrame((header.CFrame + Vector3.new(0,1,0)) * CFrame.new(0,0,-8))
KeyboardActive = not KeyboardActive
wait(.5)
keyboardDB = false
end
end
end)
UserInputService.InputChanged:connect(function(key)
if key.KeyCode == Enum.KeyCode.ButtonR2 then
if not R15 then
for i,tool in pairs(Character:GetChildren()) do
if tool:IsA("Tool") then tool:Activate() end
end
end
if SelectedPart then
if key.Position.Z > 0.8 then
if SelectedPart:FindFirstChild("TouchInterest") then
firetouchinterest(rightarm, SelectedPart, 0)
elseif SelectedPart:FindFirstChildOfClass("ClickDetector") then
fireclickdetector(SelectedPart:FindFirstChildOfClass("ClickDetector"))
end
else
if SelectedPart:FindFirstChild("TouchInterest") then
firetouchinterest(rightarm, SelectedPart, 1)
end
end
end
end
end)
UserInputService.InputBegan:connect(function(key)
if key.KeyCode == Enum.KeyCode.ButtonR1 then
if RgrabPart then
if not RgrabPart.Parent:IsA("Accessory") and not RgrabPart.Parent:FindFirstChildOfClass("Humanoid") and (RgrabPart:IsGrounded() or RgrabPart.Anchored) then
RgrabWeld.Part1 = RgrabPart
root.Velocity = Vector3.new(0,0,0)
fakerightarm.Velocity = Vector3.new(0,0,0)
fakeleftarm.Velocity = Vector3.new(0,0,0)
root.Massless = true
fakerightarm.Massless = true
fakerightarm.CanCollide = false
else
Rholding = RgrabPart
holdPart(RgrabPart, RgrabAtt)
end
end
elseif key.KeyCode == Enum.KeyCode.ButtonL1 then
if LgrabPart then
if not LgrabPart.Parent:IsA("Accessory") and not LgrabPart.Parent:FindFirstChildOfClass("Humanoid") and (LgrabPart:IsGrounded() or LgrabPart.Anchored) then
LgrabWeld.Part1 = LgrabPart
root.Velocity = Vector3.new(0,0,0)
fakerightarm.Velocity = Vector3.new(0,0,0)
fakeleftarm.Velocity = Vector3.new(0,0,0)
root.Massless = false
fakeleftarm.Massless = true
fakeleftarm.CanCollide = false
else
Lholding = LgrabPart
holdPart(LgrabPart, LgrabAtt)
end
end
end
end)
UserInputService.InputEnded:connect(function(key)
if key.KeyCode == Enum.KeyCode.ButtonR1 then
RgrabWeld.Part1 = nil
fakerightarm.Massless = false
fakerightarm.CanCollide = true
if Rholding then
holdPart(Rholding, nil, true)
end
elseif key.KeyCode == Enum.KeyCode.ButtonL1 then
LgrabWeld.Part1 = nil
fakeleftarm.Massless = false
fakeleftarm.CanCollide = true
if Lholding then
holdPart(Lholding, nil, true)
end
end
end)
--=========[Cool Things]==========--
ViewHUDFunc = function()
local ViewportRange = ViewportRange or 32
local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local VRService = game:GetService("VRService")
local Players = game:GetService("Players")
local Client = Players.LocalPlayer
local Mouse = Client:GetMouse()
local Camera = workspace.CurrentCamera
local CameraPort = Camera.CFrame
local ViewHUD = script:FindFirstChild("ViewHUD") or game:GetObjects("rbxassetid://4480405425")[1]
local Viewport = ViewHUD.Viewport
local Viewcam = Instance.new("Camera")
local ViewPart = ViewHUD.Part
ViewHUD.Parent = game:GetService("CoreGui")
Viewcam.Parent = Viewport
Viewcam.CameraType = Enum.CameraType.Scriptable
Viewport.CurrentCamera = Viewcam
Viewport.BackgroundTransparency = 1
--[[Code]]--
local function Clone(Character)
local Arc = Character.Archivable
local Clone;
Character.Archivable = true
Clone = Character:Clone()
Character.Archivable = Arc
return Clone
end
local function GetPart(Name, Parent, Descendants)
for i = 1, #Descendants do
local Part = Descendants[i]
if Part.Name == Name and Part.Parent.Name == Parent then
return Part
end
end
end
local function OnPlayerAdded(Player)
if not ViewHUD or not ViewHUD.Parent then return end
local function CharacterAdded(Character)
if not ViewHUD or not ViewHUD.Parent then return end
Character:WaitForChild("Head")
Character:WaitForChild("Humanoid")
wait(3)
local FakeChar = Clone(Character)
local TrueRoot = Character:FindFirstChild("HumanoidRootPart") or Character:FindFirstChild("Head")
local Root = FakeChar:FindFirstChild("HumanoidRootPart") or FakeChar:FindFirstChild("Head")
local RenderConnection;
local Descendants = FakeChar:GetDescendants()
local RealDescendants = Character:GetDescendants()
local Correspondents = {};
FakeChar.Humanoid.DisplayDistanceType = "None"
for i = 1, #Descendants do
local Part = Descendants[i]
local Real = Part:IsA("BasePart") and GetPart(Part.Name, Part.Parent.Name, RealDescendants)
if Part:IsA("BasePart") and Real then
Part.Anchored = true
Part:BreakJoints()
if not string.find(Part.Name, "Fake") and Part.Name ~= "HumanoidRootPart" then
Part.Transparency = 0
else
Part.Transparency = 1
end
table.insert(Correspondents, {Part, Real})
end
end
RenderConnection = RunService.RenderStepped:Connect(function()
if not Character or not Character.Parent then
RenderConnection:Disconnect()
FakeChar:Destroy()
return
end
if (TrueRoot and (TrueRoot.Position - Camera.CFrame.p).Magnitude <= ViewportRange) or Player == Client or not TrueRoot then
for i = 1, #Correspondents do
local Part, Real = unpack(Correspondents[i])
if Part and Real and Part.Parent and Real.Parent then
Part.CFrame = Real.CFrame - Vector3.new(0,1,0)
elseif Part.Parent and not Real.Parent then
Part:Destroy()
end
end
end
end)
FakeChar.Parent = Viewcam
end
Player.CharacterAdded:Connect(CharacterAdded)
if Player.Character then
spawn(function()
CharacterAdded(Player.Character)
end)
end
end
local PlayerAdded = Players.PlayerAdded:Connect(OnPlayerAdded)
for _, Player in pairs(Players:GetPlayers()) do
OnPlayerAdded(Player)
end
ViewPart.Size = Vector3.new()
if VRReady then
Viewport.Position = UDim2.new(.62, 0, .89, 0)
Viewport.Size = UDim2.new(.3, 0, .3, 0)
Viewport.AnchorPoint = Vector2.new(.5, 1)
else
Viewport.Size = UDim2.new(0.3, 0, 0.3, 0)
end
local RenderStepped = RunService.RenderStepped:Connect(function()
local Render = Camera.CFrame
local Scale = Camera.ViewportSize
if VRReady then
Render = Render * VRService:GetUserCFrame(Enum.UserCFrame.Head)
end
CameraPort = CFrame.new(Render.p + Vector3.new(5, 2, 0), Render.p)
Viewport.Camera.CFrame = CameraPort
ViewPart.CFrame = Render * CFrame.new(0, 0, -16)
ViewHUD.Size = UDim2.new(0, Scale.X - 6, 0, Scale.Y - 6)
end)
--
local CharacterAdded
CharacterAdded = Client.CharacterAdded:Connect(function()
RenderStepped:Disconnect()
CharacterAdded:Disconnect()
PlayerAdded:Disconnect()
ViewHUD:Destroy()
ViewHUD = nil
end)
wait(9e9)
end;
ChatHUDFunc = function()
--[[
Variables
--]]
local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")
local VRService = game:GetService("VRService")
local Players = game:GetService("Players")
local Client = Players.LocalPlayer
local ChatHUD = game:GetObjects("rbxassetid://4476067885")[1]
local GlobalFrame = ChatHUD.GlobalFrame
local Template = GlobalFrame.Template
local LocalFrame = ChatHUD.LocalFrame
local Global = ChatHUD.Global
local Local = ChatHUD.Local
local Camera = workspace.CurrentCamera
Template.Parent = nil
ChatHUD.Parent = game:GetService("CoreGui")
--[[
Code
--]]
local Highlight = Global.Frame.BackgroundColor3
local Deselected = Local.Frame.BackgroundColor3
local OpenGlobalTab = function()
Global.Frame.BackgroundColor3 = Highlight
Local.Frame.BackgroundColor3 = Deselected
Global.Font = Enum.Font.SourceSansBold
Local.Font = Enum.Font.SourceSans
GlobalFrame.Visible = true
LocalFrame.Visible = false
end
local OpenLocalTab = function()
Global.Frame.BackgroundColor3 = Deselected
Local.Frame.BackgroundColor3 = Highlight
Global.Font = Enum.Font.SourceSans
Local.Font = Enum.Font.SourceSansBold
GlobalFrame.Visible = false
LocalFrame.Visible = true
end
Global.MouseButton1Down:Connect(OpenGlobalTab)
Local.MouseButton1Down:Connect(OpenLocalTab)
Global.MouseButton1Click:Connect(OpenGlobalTab)
Local.MouseButton1Click:Connect(OpenLocalTab)
OpenLocalTab()
--
local function GetPlayerDistance(Sender)
if Sender.Character and Sender.Character:FindFirstChild("Head") then
return math.floor((Sender.Character.Head.Position - Camera:GetRenderCFrame().p).Magnitude + 0.5)
end
end
local function NewGlobal(Message, Sender, Color)
local Frame = Template:Clone()
Frame.Text = ("[%s]: %s"):format(Sender.Name, Message)
Frame.User.Text = ("[%s]:"):format(Sender.Name)
Frame.User.TextColor3 = Color
Frame.BackgroundColor3 = Color
Frame.Parent = GlobalFrame
delay(60, function()
Frame:Destroy()
end)
end
local function NewLocal(Message, Sender, Color, Dist)
local Frame = Template:Clone()
Frame.Text = ("(%s) [%s]: %s"):format(tostring(Dist), Sender.Name, Message)
Frame.User.Text = ("(%s) [%s]:"):format(tostring(Dist), Sender.Name)
Frame.User.TextColor3 = Color
Frame.BackgroundColor3 = Color
Frame.Parent = LocalFrame
delay(60, function()
Frame:Destroy()
end)
end
local function OnNewChat(Message, Sender, Color)
if not ChatHUD or not ChatHUD.Parent then return end
NewGlobal(Message, Sender, Color)
local Distance = GetPlayerDistance(Sender)
if Distance and Distance <= options.ChatLocalRange then
NewLocal(Message, Sender, Color, Distance)
end
end
local function OnPlayerAdded(Player)
if not ChatHUD or not ChatHUD.Parent then return end
local Color = BrickColor.Random().Color
Player.Chatted:Connect(function(Message)
OnNewChat(Message, Player, Color)
end)
end
Players.PlayerAdded:Connect(OnPlayerAdded)
for _, Player in pairs(Players:GetPlayers()) do
OnPlayerAdded(Player)
end
--
local ChatPart = ChatHUD.Part
ChatHUD.Adornee = ChatPart
if VRReady then
ChatHUD.Parent = game:GetService("CoreGui")
ChatHUD.Enabled = true
ChatHUD.AlwaysOnTop = true
local OnInput = UserInputService.InputBegan:Connect(function(Input, Processed)
if not Processed then
if Input.KeyCode == Enum.KeyCode.ButtonB then
ChatHUD.Enabled = not ChatHUD.Enabled
end
end
end)
local RenderStepped = RunService.RenderStepped:Connect(function()
ChatPart.CFrame = lhand.CFrame * CFrame.Angles(math.rad(-90),math.rad(0), math.rad(0))
end)
local CharacterAdded
CharacterAdded = Client.CharacterAdded:Connect(function()
OnInput:Disconnect()
RenderStepped:Disconnect()
CharacterAdded:Disconnect()
ChatHUD:Destroy()
ChatHUD = nil
end)
end
wait(9e9)
end;
task.spawn(ChatHUDFunc)
task.spawn(ViewHUDFunc)
|
local qc = require 'Q/UTILS/lua/q_core'
local ffi = require 'Q/UTILS/lua/q_ffi'
local Q = require 'Q'
-- local dbg = require 'Q/UTILS/lua/debugger'
local qc = require 'Q/UTILS/lua/q_core'
local filenm = arg[1]
local Column = require 'Q/RUNTIME/COLUMN/code/lua/Column'
local col = Column{field_type='I4', filename=filenm,}
local dest_file = os.getenv("Q_DATA_DIR") .. "/cout.bin"
os.remove(dest_file)
local function add_test(ptr1,size1, ptr2, size2)
assert(size1 == size2 , "Chunks must be of same length")
local res_chunk = ffi.cast("int*", ffi.malloc(size1 * ffi.sizeof("int")))
qc["vvadd_I4_I4_I4"](ptr1, ptr2, size1, res_chunk)
fd = ffi.C.fopen(dest_file, "wb+")
ffi.C.fwrite(res_chunk, ffi.sizeof("int"), col:length(), fd)
ffi.C.fclose(fd)
return
end
-- local z = Q.vvadd(col,col, {junk = "junk"})
local size1, chunk1 = col:chunk(-1)
local size2, chunk2 = col:chunk(-1)
local start_time = qc.RDTSC()
add_test(chunk1, size1, chunk2, size2))
local stop_time = qc.RDTSC()
print("time taken", stop_time-start_time)
|
pc.checkedBalance = true
|
pac.OwnerNames =
{
"self",
"viewmodel",
"hands",
"active vehicle",
"active weapon",
"world",
}
local function find_ent(ent, str)
return
pac.StringFind(ent:GetClass(), str) or
pac.StringFind(ent:GetClass(), str, true) or
(ent.GetName and pac.StringFind(ent:GetName(), str)) or
(ent.GetName and pac.StringFind(ent:GetName(), str, true)) or
pac.StringFind(ent:GetModel(), str) or
pac.StringFind(ent:GetModel(), str, true)
end
local function check_owner(a, b)
return a:GetOwner() == b or (not b.CPPIGetOwner or b:CPPIGetOwner() == a or b:CPPIGetOwner() == true)
end
function pac.CalcEntityCRC(ent)
local pos = ent:GetPos()
local ang = ent:GetAngles()
local mdl = ent:GetModel():lower():gsub("\\", "/")
local x, y, z = math.Round(pos.x / 10) * 10, math.Round(pos.y / 10) * 10, math.Round(pos.z / 10) * 10
local p, _y, r = math.Round(ang.p / 10) * 10, math.Round(ang.y / 10) * 10, math.Round(ang.r / 10) * 10
local crc = x .. y .. z .. p .. _y .. r .. mdl
return util.CRC(crc)
end
SafeRemoveEntity(pac.WorldEntity)
pac.WorldEntity = NULL
function pac.HandleOwnerName(owner, name, ent, part, check_func)
local idx = tonumber(name)
if idx then
ent = Entity(idx)
if ent:IsValid() then
if owner:IsValid() and owner.GetViewModel and ent == owner:GetViewModel() then
part:SetOwnerName("viewmodel")
return ent
end
if owner:IsValid() and owner.GetHands and ent == owner:GetHands() then
part:SetOwnerName("hands")
return ent
end
if ent == pac.LocalPlayer then
part:SetOwnerName("self")
return ent
end
if ent.GetPersistent and ent:GetPersistent() then
part:SetOwnerName("persist " .. pac.CalcEntityCRC(ent))
end
return ent
end
return NULL
end
if name == "world" or (pac.WorldEntity:IsValid() and ent == pac.WorldEntity) then
if not pac.WorldEntity:IsValid() then
ent = pac.CreateEntity("models/error.mdl")
ent:SetPos(Vector(0,0,0))
-- go away ugh
ent:SetModelScale(0,0)
ent.IsPACWorldEntity = true
pac.WorldEntity = ent
end
return pac.WorldEntity
end
if name == "self" then
return owner
end
if owner:IsValid() then
if name == "active weapon" and owner.GetActiveWeapon and owner:GetActiveWeapon():IsValid() then
return owner:GetActiveWeapon()
end
if name == "active vehicle" and owner.GetVehicle and owner:GetVehicle():IsValid() then
return owner:GetVehicle()
end
if name == "hands" and owner == pac.LocalPlayer and pac.LocalHands:IsValid() then
return pac.LocalHands
end
if name == "hands" and owner.GetHands then
return owner:GetHands()
end
if name == "viewmodel" and owner.GetViewModel then
return owner:GetViewModel()
end
end
if name:find("persist ", nil, true) then
local crc = name:match("persist (.+)")
for _, val in pairs(ents.GetAll()) do
if val.GetPersistent and val:GetModel() and val:GetPersistent() and crc == pac.CalcEntityCRC(val) then
return val
end
end
end
if IsValid(ent) and (not check_func or check_func(ent)) and check_owner(ent, owner) and find_ent(ent, name) then
return ent
end
for _, val in pairs(ents.GetAll()) do
if val:IsValid() and (not check_func or check_func(val)) and check_owner(val, owner) and find_ent(val, name) then
return val
end
end
return NULL
end
|
--------------------------------
-- @module BoneData
-- @extend BaseData
-- @parent_module ccs
---@class ccs.BoneData:ccs.BaseData
local BoneData = {}
ccs.BoneData = BoneData
--------------------------------
---
---@param index number
---@return ccs.DisplayData
function BoneData:getDisplayData(index)
end
--------------------------------
---
---@return boolean
function BoneData:init()
end
--------------------------------
---
---@param displayData ccs.DisplayData
---@return ccs.BoneData
function BoneData:addDisplayData(displayData)
end
--------------------------------
---
---@return ccs.BoneData
function BoneData:create()
end
--------------------------------
--- js ctor
---@return ccs.BoneData
function BoneData:BoneData()
end
return nil
|
local ffi = require("ffi")
local base = require("rider.base")
local C = ffi.C
local ffi_cast = ffi.cast
local ffi_str = ffi.string
local ffi_new = ffi.new
local get_string_buf = base.get_string_buf
local FFI_OK = base.FFI_OK
local get_context_handle = base.get_context_handle
local registry = debug.getregistry()
local SOURCE_REQUEST = 0
local SOURCE_RESPONSE = 1
ffi.cdef[[
int envoy_http_lua_ffi_get_header_map(ContextBase* ctx, int source, envoy_lua_ffi_string_pairs* buffer);
int envoy_http_lua_ffi_get_header_map_size(ContextBase* ctx, int source);
int envoy_http_lua_ffi_get_header_map_value(ContextBase* ctx, int source, const char* key, int key_len, envoy_lua_ffi_str_t* value);
int envoy_http_lua_ffi_set_header_map_value(ContextBase* ctx, int source, const char* key, int key_len, const char* value, int value_len);
int envoy_http_lua_ffi_remove_header_map_value(ContextBase* ctx, int source, const char* key, int key_len);
int envoy_http_lua_ffi_get_query_parameters(ContextBase* ctx, envoy_lua_ffi_string_pairs* buf);
int envoy_http_lua_ffi_get_shared_table(ContextBase* ctx);
int envoy_http_lua_ffi_get_metadata(ContextBase* ctx, envoy_lua_ffi_str_t* filter_name, envoy_lua_ffi_str_t* key, envoy_lua_ffi_str_t* value);
int64_t envoy_http_lua_ffi_streaminfo_start_time(ContextBase *r);
const char* envoy_http_lua_ffi_upstream_host(ContextBase *r);
const char* envoy_http_lua_ffi_upstream_cluster(ContextBase *r);
const char* envoy_http_lua_ffi_downstream_local_address(ContextBase *r);
const char* envoy_http_lua_ffi_downstream_remote_address(ContextBase *r);
int64_t envoy_http_lua_ffi_get_current_time_milliseconds(ContextBase *r);
void envoy_http_lua_ffi_file_log(ContextBase *r, const char *buf, size_t len);
]]
local table_elt_type = ffi.typeof("envoy_lua_ffi_table_elt_t*")
local table_elt_size = ffi.sizeof("envoy_lua_ffi_table_elt_t")
if envoy.stream.shared == nil then
local proxy = {}
local mt = {
__index = function (t, k)
local ctx = get_context_handle()
if not ctx then
error("no context")
end
local ref = C.envoy_http_lua_ffi_get_shared_table(ctx)
if ref > 0 then
return registry[ref][k]
else
error("error get shared table reference: "..ref)
end
end,
__newindex = function (t, k, v)
local ctx = get_context_handle()
if not ctx then
error("no context")
end
local ref = C.envoy_http_lua_ffi_get_shared_table(ctx)
if ref > 0 then
registry[ref][k] = v
else
error("error get shared table reference: "..ref)
end
end
}
setmetatable(proxy, mt)
envoy.stream.shared = proxy
end
local function get_headers(source)
local ctx = get_context_handle()
if not ctx then
error("no context")
end
local header_map_size = C.envoy_http_lua_ffi_get_header_map_size(ctx, source)
if header_map_size == 0 then return nil end
local raw_buf = ffi_new("envoy_lua_ffi_table_elt_t[?]", header_map_size)
local pairs_buf = ffi_new("envoy_lua_ffi_string_pairs[1]", { [0] = {raw_buf, 0, header_map_size} })
local rc = C.envoy_http_lua_ffi_get_header_map(ctx, source, pairs_buf)
if rc ~= FFI_OK then
error("error get headers: "..tonumber(rc))
end
local result = {}
for i = 0, header_map_size - 1 do
local h = pairs_buf[0].data[i]
local key = ffi_str(h.key.data, h.key.len)
local val = ffi_str(h.value.data, h.value.len)
result[key] = val
end
return result
end
local function get_header_map_size(source)
local ctx = get_context_handle()
if not ctx then
error("no context")
end
return C.envoy_http_lua_ffi_get_header_map_size(ctx, source)
end
local function get_header_map_value(source, key)
local ctx = get_context_handle()
if not ctx then
error("no context")
end
if type(key) ~= "string" then
error("header name must be a string", 2)
end
local buffer = ffi_new("envoy_lua_ffi_str_t[1]")
local rc = C.envoy_http_lua_ffi_get_header_map_value(ctx, source, key, #key, buffer)
if rc ~= FFI_OK then
return nil
end
return ffi_str(buffer[0].data, buffer[0].len)
end
local function set_header_map_value(source, key, value)
local ctx = get_context_handle()
if not ctx then
error("no context")
end
if type(key) ~= "string" then
error("header name must be a string", 2)
end
if type(value) ~= "string" then
error("header value must be a string", 2)
end
local rc = C.envoy_http_lua_ffi_set_header_map_value(ctx, source, key, #key, value, #value)
if rc ~= FFI_OK then
error("error set header")
end
end
local function remove_header_map_value(source, key)
local ctx = get_context_handle()
if not ctx then
error("no context")
end
if type(key) ~= "string" then
error("header name must be a string", 2)
end
local rc = C.envoy_http_lua_ffi_remove_header_map_value(ctx, source, key, #key)
if rc ~= FFI_OK then
error("error remove header")
end
end
function envoy.req.get_header_map_size()
return get_header_map_size(SOURCE_REQUEST)
end
function envoy.resp.get_header_map_size()
return get_header_map_size(SOURCE_RESPONSE)
end
function envoy.req.get_headers()
return get_headers(SOURCE_REQUEST)
end
function envoy.resp.get_headers()
return get_headers(SOURCE_RESPONSE)
end
function envoy.req.get_header(key)
return get_header_map_value(SOURCE_REQUEST, key)
end
function envoy.resp.get_header(key)
return get_header_map_value(SOURCE_RESPONSE, key)
end
function envoy.req.set_header(key, value)
return set_header_map_value(SOURCE_REQUEST, key, value)
end
function envoy.resp.set_header(key, value)
return set_header_map_value(SOURCE_RESPONSE, key, value)
end
function envoy.req.remove_header(key)
return remove_header_map_value(SOURCE_REQUEST, key)
end
function envoy.resp.remove_header(key)
return remove_header_map_value(SOURCE_RESPONSE, key)
end
local MAX_QUERY_ARGS_DEFAULT = 100
local MIN_QUERY_ARGS = 1
local MAX_QUERY_ARGS = 100
function envoy.req.get_query_parameters(max_args)
local ctx = get_context_handle()
if not ctx then
error("no context")
end
if max_args == nil then
max_args = MAX_QUERY_ARGS_DEFAULT
else
if type(max_args) ~= "number" then
error("max_args must be a number", 2)
end
if max_args < MIN_QUERY_ARGS then
error("max_args must be >= " .. MIN_QUERY_ARGS, 2)
end
if max_args > MAX_QUERY_ARGS then
error("max_args must be <= " .. MAX_QUERY_ARGS, 2)
end
end
local raw_buf = ffi_new("envoy_lua_ffi_table_elt_t[?]", max_args)
local pairs_buf = ffi_new("envoy_lua_ffi_string_pairs[1]", { [0] = {raw_buf, 0, max_args} })
local rc = C.envoy_http_lua_ffi_get_query_parameters(r, pairs_buf)
if rc ~= FFI_OK then
error("error get queries: "..tonumber(rc))
end
if rc == 0 then
local queries = {}
local n = pairs_buf.size
local buf = pairs_buf.data
for i = 0, n - 1 do
local h = buf[i]
local key = h.key
key = ffi_str(key.data, key.len)
local val = h.value
val = ffi_str(val.data, val.len)
local existing = queries[key]
if existing then
if type(existing) == "table" then
existing[#existing + 1] = val
else
queries[key] = {existing, val}
end
else
queries[key] = val
end
queries[key] = val
end
return queries
end
return {}
end
function envoy.streaminfo.upstream_cluster()
local ctx = get_context_handle()
if not ctx then
error("no context")
end
local res = C.envoy_http_lua_ffi_upstream_cluster(ctx)
if res == nil then
return nil
end
return ffi_str(res)
end
function envoy.streaminfo.upstream_host()
local ctx = get_context_handle()
if not ctx then
error("no context")
end
local res = C.envoy_http_lua_ffi_upstream_host(ctx)
if res == nil then
return nil
end
return ffi_str(res)
end
function envoy.streaminfo.downstream_local_address()
local ctx = get_context_handle()
if not ctx then
error("no context")
end
local res = C.envoy_http_lua_ffi_downstream_local_address(ctx)
if res == nil then
return ""
end
return ffi_str(res)
end
function envoy.streaminfo.downstream_remote_address()
local ctx = get_context_handle()
if not ctx then
error("no context")
end
local res = C.envoy_http_lua_ffi_downstream_remote_address(ctx)
if res == nil then
return ""
end
return ffi_str(res)
end
function envoy.streaminfo.start_time()
local ctx = get_context_handle()
if not ctx then
error("no context")
end
return tonumber(C.envoy_http_lua_ffi_start_time(ctx))
end
function envoy.nowms()
local ctx = get_context_handle()
if not ctx then
error("no context")
end
return tonumber(C.envoy_http_lua_ffi_get_current_time_milliseconds(ctx))
end
function envoy.filelog(msg)
local ctx = get_context_handle()
if not ctx then
error("no context")
end
if type(msg) ~= "string" then
error("msg must be a string", 2)
end
C.envoy_http_lua_ffi_file_log(ctx, msg, #msg);
end
function envoy.req.get_metadata(key, filter_name)
local ctx = get_context_handle()
if not ctx then
error("no context")
end
if type(key) ~= "string" then
error("metadata key must be a string", 2)
end
if not filter_name then
error("filter name is required")
end
if type(filter_name) ~= "string" then
error("filter name must be a string", 2)
end
local filter_name_ = ffi_new("envoy_lua_ffi_str_t[1]", { [0] = {#filter_name, filter_name} })
local key_ = ffi_new("envoy_lua_ffi_str_t[1]", { [0] = {#key, key} })
local value = ffi_new("envoy_lua_ffi_str_t[1]")
local rc = C.envoy_http_lua_ffi_get_metadata(ctx, filter_name_, key_, value)
if rc == FFI_OK then
return ffi_str(value[0].data, value[0].len)
end
return nil
end
|
local HideNSeek
local BORDER_NODE_NAME = "hidenseek:border"
-- TODO: use Lua Voxel Manipulator
local function safe_set_border_node(pos)
local node = minetest.get_node(pos)
if node.name == "air" then
minetest.set_node(pos, { name = BORDER_NODE_NAME } )
end
end
local function safe_unset_border_node(pos)
local node = minetest.get_node(pos)
if node.name == BORDER_NODE_NAME then
minetest.set_node(pos, { name = "air" } )
end
end
local function make_column(x, y, z, h)
for i = 0, h - 1 do
local pos = { x = x, y = y + i, z = z }
safe_set_border_node(pos)
end
end
local function add_wall(pos, radius, height)
local x = radius
local z = 0
make_column(pos.x + radius, pos.y, pos.z, height)
make_column(pos.x - radius, pos.y, pos.z, height)
make_column(pos.x, pos.y, pos.z + radius, height)
make_column(pos.x, pos.y, pos.z - radius, height)
local p = 1 - radius
while x > z do
z = z + 1
if p <= 0 then
p = p + 2 * z + 1
else
x = x - 1
p = p + 2 * z - 2 * x + 1
end
if x < z then
break
end
make_column(x + pos.x, pos.y, z + pos.z, height)
make_column(-x + pos.x, pos.y, z + pos.z, height)
make_column(x + pos.x, pos.y, -z + pos.z, height)
make_column(-x + pos.x, pos.y, -z + pos.z, height)
if x ~= z then
make_column(z + pos.x, pos.y, x + pos.z, height)
make_column(-z + pos.x, pos.y, x + pos.z, height)
make_column(z + pos.x, pos.y, -x + pos.z, height)
make_column(-z + pos.x, pos.y, -x + pos.z, height)
end
end
return true
end
local function remove_wall(pos, radius, height)
for x = pos.x - radius, pos.x + radius do
for z = pos.z - radius, pos.z + radius do
for y = pos.y, pos.y + height do
safe_unset_border_node({ x = x, y = y, z = z })
end
end
end
end
local function command_handler(name, command)
local params = HideNSeek.util.split_string(command)
local pos = minetest.get_player_by_name(name):get_pos()
pos.x = math.round(pos.x)
pos.y = math.round(pos.y)
pos.z = math.round(pos.z)
local subcmd = params[1]
if subcmd ~= "circle" and subcmd ~= "rm" then
return false, "Unknown subcommand: " .. subcmd
end
local radius = tonumber(params[2])
local height = tonumber(params[3])
local is_force = params[4] == "force"
if not radius or radius <= 0 then
return false, "Radius should be integer > 0"
end
if not height or height <= 0 then
return false, "Height should be integer > 0"
end
if not is_force then
if radius > 50 then
return false, "Radius shouldn't be > 50"
end
if height > 50 then
return false, "Height shouldn't be > 50"
end
end
if subcmd == "circle" then
add_wall(pos, radius, height)
elseif subcmd == "rm" then
remove_wall(pos, radius, height)
end
return true
end
local function init(mod_namespace, is_reload)
HideNSeek = mod_namespace
if is_reload then
minetest.chat_send_all("Reload")
minetest.unregister_chatcommand("hs_border")
end
minetest.register_chatcommand("hs_border", {
privs = { hs_admin = true },
description = "Create map borders at current position",
params = "(circle <radius> <height>) | (rm <radius> <height>)",
func = command_handler,
})
end
return {
init = init
}
|
-- maps.lua
local map = vim.api.nvim_set_keymap
-- map the leader key
map('n', '<Space>', '', {})
vim.g.mapleader = ' ' -- 'vim.g' sets global variables
options = { noremap = true }
map('n', '<leader><esc>', ':nohlsearch<cr>', options)
map('n', '<leader>n', ':bnext<cr>', options)
map('n', '<leader>p', ':bprev<cr>', options)
|
local o = vim.g.onedark_color_overrides or {}
local colors = {
red = o.red or { gui = '#E06C75', cterm = '204', cterm16 = '1' },
dark_red = o.dark_red or { gui = '#BE5046', cterm = '196', cterm16 = '9' },
green = o.green or { gui = '#98C379', cterm = '114', cterm16 = '2' },
yellow = o.yellow or { gui = '#E5C07B', cterm = '180', cterm16 = '3' },
dark_yellow = o.dark_yellow or { gui = '#D19A66', cterm = '173', cterm16 = '11' },
blue = o.blue or { gui = '#61AFEF', cterm = '39', cterm16 = '4' },
purple = o.purple or { gui = '#C678DD', cterm = '170', cterm16 = '5' },
cyan = o.cyan or { gui = '#56B6C2', cterm = '38', cterm16 = '6' },
white = o.white or { gui = '#ABB2BF', cterm = '145', cterm16 = '7' },
black = o.black or { gui = '#282C34', cterm = '235', cterm16 = '0' },
visual_black = o.visual_black or { gui = 'NONE', cterm = 'NONE', cterm16 = '0' },
comment_grey = o.comment_grey or { gui = '#5C6370', cterm = '59', cterm16 = '15' },
gutter_fg_grey = o.gutter_fg_grey or { gui = '#4B5263', cterm = '238', cterm16 = '15' },
cursor_grey = o.cursor_grey or { gui = '#2C323C', cterm = '236', cterm16 = '8' },
visual_grey = o.visual_grey or { gui = '#3E4452', cterm = '237', cterm16 = '15' },
menu_grey = o.menu_grey or { gui = '#3E4452', cterm = '237', cterm16 = '8' },
special_grey = o.special_grey or { gui = '#3B4048', cterm = '238', cterm16 = '15' },
vertsplit = o.vertsplit or { gui = '#181A1F', cterm = '59', cterm16 = '15' },
}
if (vim.g.onedark_termcolors or 256) == 16 then
for _, color in pairs(colors) do
color.cterm = color.cterm16
color.cterm16 = nil
end
end
return colors
|
function lolzz(fibu, n, i) return ((i%n)==0) and io.write(fibu.."zz") end
function fizz(i) return lolzz("Fi", 3, i) end
function buzz(i) return lolzz("Bu", 5, i) end
function test(a, b) return a or b end
function fizzbuzz(i) return test(fizz(i), buzz(i)) or io.write(i) end
for i = 1, 100 do
fizzbuzz(i)
io.write(' ')
end
|
-- Tests:
-- info()
-- exists()
-- index()
-- get()
-- delete()
-- mget()
--
-- Importing modules
local util = require "lib.util"
-- Setting up environment
local _ENV = lunit.TEST_CASE "tests.integration.BasicTest"
function test()
local dataset_1 = util.subarr(dataset, 1, math.floor(#dataset/2))
local dataset_2 = util.subarr(dataset, math.floor(#dataset/2) + 1, #dataset)
operations.info()
operations.index(dataset_1)
operations.createExistingDocuments(dataset_1)
operations.existsNonExistingDocuments(dataset_2)
operations.getNonExistingDocuments(dataset_2)
operations.mgetNonExistingDocuments(dataset_2)
operations.deleteNonExistingDocuments(dataset_2)
operations.existsExistingDocuments(dataset_1)
operations.getExistingDocuments(dataset_1)
operations.mgetExistingDocuments(dataset_1)
operations.index(dataset_2)
operations.createExistingDocuments(dataset_2)
operations.deleteExistingDocuments(dataset_1)
operations.existsNonExistingDocuments(dataset_1)
operations.getNonExistingDocuments(dataset_1)
operations.mgetNonExistingDocuments(dataset_1)
operations.deleteNonExistingDocuments(dataset_1)
operations.existsExistingDocuments(dataset_2)
operations.getExistingDocuments(dataset_2)
operations.mgetExistingDocuments(dataset_2)
operations.deleteExistingDocuments(dataset_2)
operations.createNonExistingDocuments(dataset_2)
operations.getExistingDocuments(dataset_2)
operations.mgetExistingDocuments(dataset_2)
operations.deleteExistingDocuments(dataset_2)
operations.existsNonExistingDocuments(dataset_2)
operations.getNonExistingDocuments(dataset_2)
operations.mgetNonExistingDocuments(dataset_2)
operations.deleteNonExistingDocuments(dataset_2)
end
|
--- A simple wrapper around SendNUIMessage that you can use to
--- dispatch actions to the React frame.
---
---@param action string The action you wish to target
---@param data any The data you wish to send along with this action
function SendReactMessage(action, data)
SendNUIMessage({
action = action,
data = data
})
end
local currentResourceName = GetCurrentResourceName()
local debugIsEnabled = GetConvarInt(('%s-debugMode'):format(currentResourceName), 0) == 1
--- A simple debug print function that is dependent on a convar
--- will output a nice prettfied message if debugMode is on
function debugPrint(...)
if not debugIsEnabled then return end
local args <const> = { ... }
local appendStr = ''
for _, v in ipairs(args) do
appendStr = appendStr .. ' ' .. tostring(v)
end
local msgTemplate = '^3[%s]^0%s'
local finalMsg = msgTemplate:format(currentResourceName, appendStr)
print(finalMsg)
end
|
local sp = require 'bee.subprocess'
local nonil = require 'without-check-nil'
local client = require 'provider.client'
local platform = require 'bee.platform'
local completion = require 'provider.completion'
local m = {}
local function testFileEvents(initer)
initer.fileOperations = {
didCreate = {
filters = {
{
pattern = {
glob = '**',
--matches = 'file',
options = platform.OS == 'Windows',
}
}
}
},
didDelete = {
filters = {
{
pattern = {
glob = '**',
--matches = 'file',
options = platform.OS == 'Windows',
}
}
}
},
didRename = {
filters = {
{
pattern = {
glob = '**',
--matches = 'file',
options = platform.OS == 'Windows',
}
}
}
},
}
end
function m.getIniter()
local initer = {
-- 文本同步方式
textDocumentSync = {
-- 打开关闭文本时通知
openClose = true,
-- 文本增量更新
change = 2,
},
hoverProvider = true,
definitionProvider = true,
referencesProvider = true,
renameProvider = {
prepareProvider = true,
},
documentSymbolProvider = true,
workspaceSymbolProvider = true,
documentHighlightProvider = true,
codeActionProvider = {
codeActionKinds = {
'',
'quickfix',
'refactor.rewrite',
'refactor.extract',
},
resolveProvider = false,
},
signatureHelpProvider = {
triggerCharacters = { '(', ',' },
},
executeCommandProvider = {
commands = {
'lua.removeSpace:' .. sp:get_id(),
'lua.solve:' .. sp:get_id(),
'lua.jsonToLua:' .. sp:get_id(),
},
},
foldingRangeProvider = true,
documentOnTypeFormattingProvider = {
firstTriggerCharacter = '\n',
moreTriggerCharacter = nil, -- string[]
},
workspace = {}
--documentOnTypeFormattingProvider = {
-- firstTriggerCharacter = '}',
--},
}
--testFileEvents()
nonil.enable()
if not client.info.capabilities.textDocument.completion.dynamicRegistration then
initer.completionProvider = {
resolveProvider = true,
triggerCharacters = completion.allWords(),
}
end
nonil.disable()
return initer
end
return m
|
-- debug
function DumpComponent( comp )
for name,value in pairs(comp) do
if type(value) == "function" then
-- local info = debug.getinfo(value,"LnS")
-- print(string.format(" %s = function - %s", name, info.source..":"..tostring(info.linedefined)))
else
if value and type(value) == "table" and value.IsValid and type(value.IsValid) == "function" then
print(string.format(" %s = %s (valid:%s)", name, tostring(value),tostring(value:IsValid())))
else
print(string.format(" %s = %s", name, tostring(value)))
end
end
end
end
function DumpEntity(ent)
print("============================================ Dumping entity ",ent,"============================================")
print(ent.entity:GetDebugString())
print("--------------------------------------------------------------------------------------------------------------------")
for name,value in pairs(ent) do
if type(value) == "function" then
-- local info = debug.getinfo(value,"LnS")
-- print(string.format(" %s = function - %s", name, info.source..":"..tostring(info.linedefined)))
else
if value and type(value) == "table" and value.IsValid and type(value.IsValid) == "function" then
print(string.format(" %s = %s (valid:%s)", name, tostring(value),tostring(value:IsValid())))
else
print(string.format(" %s = %s", name, tostring(value)))
end
end
end
print("--------------------------------------------------------------------------------------------------------------------")
for i,v in pairs(ent.components) do
print(" Dumping component",i)
DumpComponent(v)
end
print("====================================================================================================================================")
end
-- debug end
PrefabFiles = {
}
Assets = {
-- Asset("SOUND", "sound/rabbit.fsb"),
-- Asset("SOUND", "sound/mole.fsb"),
}
STRINGS = GLOBAL.STRINGS
function TableMerge(t1, t2)
for k,v in pairs(t2) do
if type(v) == "table" then
if type(t1[k] or false) == "table" then
TableMerge(t1[k] or {}, t2[k] or {})
else
t1[k] = v
end
else
t1[k] = v
end
end
return t1
end
NEWSTRINGS = GLOBAL.require("my-mod-name-strings")
GLOBAL.STRINGS = TableMerge(GLOBAL.STRINGS, NEWSTRINGS)
-- constants
TUNING.WHATEVER = 42
-- configuration
if (GetModConfigData("property") == "low") then
TUNING.WHATEVER = 41
end
if (GetModConfigData("property") == "high") then
TUNING.WHATEVER = 43
end
local function do(act)
end
-- new GLOBAL Action "DO"
AddAction('DO', 'Do', do)
-- DO Action takes some time
-- AddStategraphActionHandler('wilson_client', GLOBAL.ActionHandler(GLOBAL.ACTIONS.DO, "dolongaction"))
-- AddStategraphActionHandler('wilson', GLOBAL.ActionHandler(GLOBAL.ACTIONS.DO, "dolongaction"))
-- what to do when player is trying to use an item with chiller component
-- mostly a check whether to provide the CHILL action or not based hovered item
function componentpostinit(inst, doer, target, actions, right)
-- print("using item with component perishable on something " .. tostring(right))
end
-- every prefab with the perishable component
AddComponentAction("USEITEM", "perishable", componentpostinit)
-- code below this statement is only executed on servers and not on clients
if not GLOBAL.TheNet:GetIsServer() then
return
end
-- ice adjustments: ----------------
-- all ice prefabs have the chiller component
function dosomething(inst)
-- inst:AddComponent("weapon")
end
AddPrefabPostInit("ice", dosomething)
-- other miscellaneous adjustments for specific items: ------
local function overwrite_hambat_damage(inst)
-- -- overwrite damage
-- if inst.components.weapon ~= nil then
-- local old_setdamage = inst.components.weapon.SetDamage
-- inst.components.weapon.SetDamage = function(self, dmg)
-- local new_dmg = dmg
-- new_dmg = new_dmg * 1.1
-- old_setdamage(self, new_dmg)
-- end
-- end
end
AddPrefabPostInit("hambat", overwrite_hambat_damage)
|
local label_text= false
return Def.ActorFrame {
LoadFont("Common Normal") .. {
Text=GetTimingDifficulty();
AltText="";
InitCommand=cmd(horizalign,left;zoom,0.675);
OnCommand= function(self)
label_text= self
self:shadowlength(1):settextf(Screen.String("TimingDifficulty"), "");
end,
};
LoadFont("Common Normal") .. {
Text=GetTimingDifficulty();
AltText="";
InitCommand=cmd(x,136;zoom,0.675;halign,0);
OnCommand=function(self)
self:shadowlength(1):skewx(-0.125):x(label_text:GetZoomedWidth()+8)
if GetTimingDifficulty() == 9 then
self:settext(Screen.String("Hardest Timing"));
(cmd(zoom,0.5;diffuse,ColorLightTone( Color("Orange")) ))(self);
else
self:settext( GetTimingDifficulty() );
end
end;
};
};
|
QBCore.Commands.Add("fix", "Repair your vehicle (Admin Only)", {}, false, function(source, args)
TriggerClientEvent('iens:repaira', source)
TriggerClientEvent('vehiclemod:client:fixEverything', source)
end, "admin")
QBCore.Functions.CreateUseableItem("repairkit", function(source, item)
local Player = QBCore.Functions.GetPlayer(source)
if Player.Functions.GetItemBySlot(item.slot) ~= nil then
TriggerClientEvent("qb-vehiclefailure:client:RepairVehicle", source)
end
end)
QBCore.Functions.CreateUseableItem("cleaningkit", function(source, item)
local Player = QBCore.Functions.GetPlayer(source)
if Player.Functions.GetItemBySlot(item.slot) ~= nil then
TriggerClientEvent("qb-vehiclefailure:client:CleanVehicle", source)
end
end)
QBCore.Functions.CreateUseableItem("advancedrepairkit", function(source, item)
local Player = QBCore.Functions.GetPlayer(source)
if Player.Functions.GetItemBySlot(item.slot) ~= nil then
TriggerClientEvent("qb-vehiclefailure:client:RepairVehicleFull", source)
end
end)
RegisterServerEvent('qb-vehiclefailure:removeItem')
AddEventHandler('qb-vehiclefailure:removeItem', function(item)
local src = source
local ply = QBCore.Functions.GetPlayer(src)
ply.Functions.RemoveItem(item, 1)
end)
RegisterServerEvent('qb-vehiclefailure:server:removewashingkit')
AddEventHandler('qb-vehiclefailure:server:removewashingkit', function(veh)
local src = source
local ply = QBCore.Functions.GetPlayer(src)
ply.Functions.RemoveItem("cleaningkit", 1)
TriggerClientEvent('qb-vehiclefailure:client:SyncWash', -1, veh)
end)
|
return {
source = {
type = 'dist',
location = 'https://github.com/libexpat/libexpat/releases/download/R_2_1_0/expat-2.1.0.tar.gz',
sha256sum = '823705472f816df21c8f6aa026dd162b280806838bb55b3432b0fb1fcca7eb86'
},
build = {
type = 'gnu',
},
install = {
libs = { 'expat' }
}
}
|
-- acid v0.0.1
-- ?
--
-- llllllll.co/t/?
--
--
--
-- ▼ instructions below ▼
--
-- ?
INSTRUMENTS={
"chord",
"lead",
"bass",
"kick",
"snare",
"clap",
"hat",
"reverb",
}
CHORD_ATTR={"mod1","mod2","attack","1","2","3","4"}
ACID_ATTR={"n","k","mod1","mod2","note","duration","amp"}
DRUMS_ATTR={"n","k","w","mod1","mod2","amp"}
include("acid/lib/utils")
s=require("sequins")
er=require("er")
grid__=include("acid/lib/grid_")
MusicUtil=require "musicutil"
lattice=require("lattice")
instrument_=include("acid/lib/instrument")
engine.name="Acid"
local shift=false
local inited=false
local CHORDS={"I","ii","iii","IV","V","vi","vii","i"}
function init()
params_init()
-- initialize grid
grid_=grid__:new({})
-- constant timer
timer=metro.init()
timer.time=1/15
timer.count=-1
timer.event=updater
timer:start()
end
-- asynchronous init
function init2()
inited=true
song={root=36,scale="Major",notes={},chord_progression=s{"I","I","I","I"},measure_length=64,chord_current=""}
song.measure_note=song.measure_length
sequencer=lattice:new{
ppqn=96
}
local step_global=0
local last_step={}
local current_notes={}
sequencer:new_pattern({
action=function(t)
-- do chord changes
song.measure_note=song.measure_note+1
if song.measure_note>song.measure_length then
song.measure_note=1
song.chord_current=song.chord_progression()
song.notes=MusicUtil.generate_chord_roman(song.root,song.scale,song.chord_current)
print("current chord: "..song.chord_current)
end
-- TODO: add chord to pulses
-- for _,ins in ipairs({"chord","bass","lead","kick","snare","clap","hat","reverb"}) do
for _,ins in ipairs({"chord","bass","kick","reverb"}) do
i_[ins]:pulse(song.notes)
end
end,
swing=60,
division=1/16
})
-- setup engine defaults
engine.acid_delay(clock.get_beat_sec()/8,2,0.015)
-- <debug>
params:set("clock_tempo",130)
params_randomize_all()
-- </debug>
sequencer:hard_restart()
end
function params_randomize_all()
-- for _,ins in ipairs({"kick","snare","hat","clap"}) do
-- params:set("acid_"..ins.."_reverb",5)
-- end
-- for _,ins in ipairs({"kick","snare","hat","clap","reverb"}) do
-- params:set("acid_"..ins.."_n",32)
-- params:set("acid_"..ins.."_k",math.random(15,40))
-- end
-- for _,ins in ipairs({"bass","lead"}) do
-- i_[ins].seed=math.random(1,100)
-- params:set("acid_"..ins.."_n",math.random(1,8))
-- params:set("acid_"..ins.."_k",math.random(50,100))
-- params:set("acid_"..ins.."_amp_1",12)
-- params:set("acid_"..ins.."_amp_2",12)
-- params:set("acid_"..ins.."_amp_3",4)
-- for _,thing in ipairs({"note","duration"}) do
-- params:set("acid_"..ins.."_"..thing,8)
-- for i=1,8 do
-- local k="acid_"..ins.."_"..thing.."_"..i
-- params:set(k,math.random(1,15))
-- end
-- end
-- i_[ins]:randomize_all()
-- end
params:set("acid_bass_n",16)
params:set("acid_bass_k",100)
params:set("acid_bass_reverb",5)
params:set("acid_chord_reverb",5)
params:set("acid_reverb_n",16)
params:set("acid_reverb_k",25)
params:set("acid_reverb_attack",0.1)
params:set("acid_reverb_decay",0.5)
params:set("acid_chord_n",32)
params:set("acid_chord_k",100/16/4)
params:set("acid_chord_attack",clock.get_beat_sec()*4)
params:set("acid_chord_decay",0.1)
params:set("acid_kick_n",8)
params:set("acid_kick_k",0)
params:set("acid_kick_reverb",0)
end
function params_randomize()
for _,ins in ipairs({"bass","lead"}) do
i_[ins].seed=math.floor(os.clock()*1000)
i_[ins]:randomize_all()
end
end
function params_init()
i_={}
local control1_8=controlspec.new(1,8,'lin',1,1,'',1/8,true)
local control1_7=controlspec.new(1,7,'lin',1,1,'',1/7,true)
local control0_7=controlspec.new(0,7,'lin',1,0,'',1/8,true)
local control0_15=controlspec.new(0,15,'lin',1,0,'',1/16,true)
local control0_100p=controlspec.new(0,100,'lin',1,50,'%',1/101,true)
local control0_255=controlspec.new(0,255,'lin',1,32,'',1/256,true)
local controlmeasure=controlspec.new(0.01,4,'lin',0.01,0.5,'measure',0.01/4)
local control_small_time=controlspec.new(0,1,'lin',0.01,0.1,'s',0.01/1)
local percussion={"kick","snare","clap","hat"}
local percussion_defaults={
kick={n=16,k=4/16*100,w=0},
snare={n=16,k=2/16*100,w=4},
clap={n=16,k=4/16*100,w=2},
hat={n=16,k=5/16*100,w=4},
}
local knw=function(ins)
-- er "n"
params:add_control("acid_"..ins.."_n","n",control0_255)
params:set_action("acid_"..ins.."_n",function(n)
i_[ins]:set_n(n)
end)
-- er "k"
params:add_control("acid_"..ins.."_k","k",control0_100p)
params:set_action("acid_"..ins.."_k",function(kp)
i_[ins]:set_kp(kp/100)
end)
-- er "w"
params:add_control("acid_"..ins.."_w","w",control0_100p)
params:set_action("acid_"..ins.."_w",function(wp)
i_[ins]:set_wp(wp/100)
end)
end
local shared_parms=function(ins,justmix)
params:add_separator(ins)
-- mixer volume
params:add_control("acid_"..ins.."_amp_scale","amp scale",control0_100p)
params:set_action("acid_"..ins.."_amp_scale",function(n)
i_[ins]:set_amp(n/100)
end)
knw(ins)
if justmix==true then
do return end
end
-- amp sequence
params:add_group("amps",8)
for i=1,8 do
local k="acid_"..ins.."_amp_"..i
params:add_control(k,i,control0_15)
params:set_action(k,function(v)
i_[ins]:set_amp(i,v)
end)
if i==1 then
params:set(k,8)
end
end
-- mods 1 and 2
for i=1,2 do
local k="acid_"..ins.."_mod"..i
params:add_control(k,"mod "..i,control0_100p)
params:set(k,50)
end
-- add attack/decay parameters for chords
if ins=="chord" then
params:add_control("acid_chord_attack","attack",controlmeasure)
params:add_control("acid_chord_decay","decay",controlmeasure)
for i=1,4 do
params:add_option("acid_chord_"..i,"chord "..i,CHORDS)
params:set_action("acid_chord_"..i,function(v)
song.chord_progression[i]=CHORDS[v]
end)
end
end
if ins=="lead" or ins=="bass" then
-- notes/durations
for _,thing in ipairs({"note","duration"}) do
params:add_group(thing.."s",9)
params:add_control("acid_"..ins.."_"..thing,"# "..thing.."s",control1_8)
params:set_action("acid_"..ins.."_"..thing,function(v)
i_[ins]:set_num_i(thing,v)
end)
for i=1,8 do
local k="acid_"..ins.."_"..thing.."_"..i
params:add_control(k,i,control0_15)
params:set_action(k,function(v)
--print("setting "..ins.." i to "..v)
i_[ins]:set_freq(thing,i,v)
end)
end
end
end
-- delay/reverb send
for _,fxname in ipairs({"delay","reverb"}) do
local k="acid_"..ins.."_"..fxname
params:add_control(k,fxname.." send",control0_100p)
params:set(k,0)
end
end
-- insert the parameters
local instruments={"chord","bass","lead"}
for _,ins in ipairs(instruments) do
i_[ins]=instrument_:new({id=ins})
shared_parms(ins)
end
for _,ins in ipairs(percussion) do
i_[ins]=instrument_:new({id=ins})
shared_parms(ins)
for _,erthing in ipairs({"n","k","w"}) do
params:set("acid_"..ins.."_"..erthing,percussion_defaults[ins][erthing])
end
end
-- effects
i_["reverb"]=instrument_:new({id="reverb"})
shared_parms("reverb",true)
params:add_control("acid_reverb_attack","reverb attack",control_small_time)
params:add_control("acid_reverb_decay","reverb decay",control_small_time)
end
function updater()
if not inited then
init2()
end
redraw()
end
function key(k,z)
if k==1 then
shift=z==1
end
if shift then
if k==1 then
elseif k==2 then
elseif k==3 then
end
else
if k==1 then
elseif k==2 then
elseif k==3 then
end
end
end
function enc(k,d)
if shift then
if k==1 then
elseif k==2 then
elseif k==3 then
end
else
if k==1 then
elseif k==2 then
elseif k==3 then
end
end
end
function redraw()
screen.clear()
screen.level(15)
local text={}
local ins=""
if grid_.page>0 then
ins=INSTRUMENTS[grid_.page]
end
-- mirror the grid
if grid_.page==0 then
-- show mixer
for _,ins in ipairs(INSTRUMENTS) do
table.insert(text,ins..": "..params:get("acid_"..ins.."_amp_scale").."%")
end
elseif grid_.page==1 then
for _,name in ipairs(CHORD_ATTR) do
table.insert(text,ins.." "..name..": "..params:get("acid_"..ins.."_"..name))
end
elseif grid_.page<=3 then
for i,name in ipairs(ACID_ATTR) do
if i<=4 then
table.insert(text,ins.." "..name..": "..params:get("acid_"..ins.."_"..name))
else
table.insert(text,ins.." "..name)
end
end
elseif grid_.page<=3 then
for i,name in ipairs(ACID_ATTR) do
if i<=4 then
table.insert(text,ins.." "..name..": "..params:get("acid_"..ins.."_"..name))
else
table.insert(text,ins.." "..name)
end
end
elseif grid_.page<=8 then
for i,name in ipairs(DRUMS_ATTR) do
if i<=5 then
table.insert(text,ins.." "..name..": "..params:get("acid_"..ins.."_"..name)..(i>1 and "%" or ""))
else
table.insert(text,ins.." "..name)
end
end
end
for i,t in ipairs(text) do
screen.move(5,8*i-2)
screen.text(t)
end
screen.update()
end
function rerun()
norns.script.load(norns.state.script)
end
function lmap(s,lo,hi,fn)
if fn==nil then
fn=util.linln
end
return fn(0,15,lo,hi,s)
end
|
-- function resetLayout()
-- local allScreens = hs.screen.allScreens()
-- -- if #allScreens == 3 then
-- local laptopScreen = allScreens[1]
-- local bigLtScreen = allScreens[2]
-- local bigRtScreen = allScreens[3]
-- local layoutsTop = hs.geometry.rect(0, 0, 1, 0.66)
-- local layoutsRtLow = hs.geometry.rect(0.5, 0.5, 0.5, 0.5)
-- local windowLayout = {
-- {"Discord", nil, laptopScreen, hs.layout.left75, nil, nil},
-- {"Mail", nil, laptopScreen, hs.layout.right70, nil, nil},
-- {"Calendar", nil, laptopScreen, layoutsTop, nil, nil},
-- {"Slack", nil, bigLtScreen, hs.layout.left30, nil, nil},
-- -- {"Google Chrome", "DOCs", bigRtScreen, hs.layout.right75, nil, nil},
-- {"Postman", nil, bigLtScreen, layoutsRtLow, nil, nil},
-- {"iTerm2", nil, bigRtScreen, hs.layout.left50, nil, nil},
-- {"Code", nil, bigRtScreen, hs.layout.right70, nil, nil},
-- {"IntelliJ IDEA", nil, bigRtScreen, hs.layout.right70, nil, nil},
-- }
-- hs.layout.apply(windowLayout)
-- end
|
return function(on_attach)
return {
filetypes = {"typescript", "javascript"},
on_attach = function(client, bufnr)
on_attach(client, bufnr)
-- tsserver, stop messing with prettier da fuck!
client.resolved_capabilities.document_formatting = false
require("nvim-lsp-ts-utils").setup {}
end
}
end
|
-- Copyright (c) 2015 Phil Leblanc -- see LICENSE file
------------------------------------------------------------
-- base58 tests
local base58 = require "plc.base58"
local function base58test()
assert(base58.encode('\x01') == '2')
assert(base58.encode('\x00\x01') == '12')
assert(base58.encode('') == '')
assert(base58.encode('\0\0') == '11')
assert(base58.encode('o hai') == 'DYB3oMS') --[1]
local x1 = "\x00\x01\x09\x66\x77\x60\x06\x95\x3D\x55\x67\x43"
.. "\x9E\x5E\x39\xF8\x6A\x0D\x27\x3B\xEE\xD6\x19\x67\xF6"
local e1 = "16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM" --[2]
assert(base58.encode(x1) == e1)
local x2 = "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f"
.. "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"
local e2 = "thX6LZfHDZZKUs92febYZhYRcXddmzfzF2NvTkPNE" --[3]
assert(base58.encode(x2) == e2)
assert(base58.decode('') == '')
assert(base58.decode('11') == '\0\0')
assert(base58.decode('DYB3oMS') == 'o hai')
assert(base58.decode(e1) == x1)
assert(base58.decode(e2) == x2)
end--base58test()
base58test()
print("test_base58: ok")
|
local root = root
local config = config
local awful = require("awful")
module("jweslley/tools")
function screenshot()
awful.util.spawn("screenshot", false)
end
function lock_screen()
awful.util.spawn("xscreensaver-command -lock")
end
function terminal()
awful.spawn(config.terminal)
end
function promptbox()
awful.screen.focused().mypromptbox:run()
end
function websearch()
awful.prompt.run {
prompt = "Web: ",
textbox = awful.screen.focused().mypromptbox.widget,
history_path = awful.util.get_cache_dir() .. "/history_web",
exe_callback = function(command)
awful.util.spawn(config.browser .. " 'https://duckduckgo.com/?q=" .. command .. "'", false)
awful.tag.viewonly(root.tags()[2])
end,
}
end
|
PCM = {
RequestId = 0x7e0,
ResponseId = 0x7e8,
ReadDataByIdentifier {
["f190"] = ascii("SALGA2EV9HA298784"),
["f124"] = ascii("HPLA-12345-AB"),
["f123"] = readf123(),
["fabc"] = nil,
["1e23"] = "231132"
},
-- Alternative 1:
Raw {
["22 F1 90"] = ascii("SALGA2EV9HA298784"),
["22 fabc"] = "10 33 11",
myCounter=0,
["221289"] = function (request)
myCounter = myCounter * 1;
return "62 1289" + toByteResponse(2, myCounter);
end
},
-- Alternative 2:
Raw {
{req = "22 F1 90", resp = ascii("SALGA2EV9HA298784")},
{req = "22 fabc", resp = "10 33 11"},
myCounter=0,
{req = "221289",
resp = function (request)
myCounter = myCounter * 1;
return "62 1289" + toByteResponse(2, myCounter);
end
},
},
-- Alternative 3:
Raw {
{"22 F1 90", ascii("SALGA2EV9HA298784")},
{"22 fa bc", "10 33 11"},
myCounter=0,
{"221289",
function (request)
myCounter = myCounter * 1;
return "62 1289" + toByteResponse(2, myCounter);
end
},
},
postReceive = function(request)
if request == "221789" then
return "221788";
end
end,
preSend = function(response)
if string.sub(response,1,2) == "621788" then
return "621789" .. string.sub(response,3);
end
end
}
|
--- === MenuHammer ===
---
--- Menuing system inspired by Spacemacs
---
----------------------------------------------------------------------------------------------------
---------------------------------- Menuhammer Definition -------------------------------------------
----------------------------------------------------------------------------------------------------
local mh = {}
mh.__index = mh
-- Metadata
mh.name = "MenuHammer"
mh.version = "0.3"
mh.author = "FryJay <darin.j.fry@gmail.com>"
mh.homepage = "https://github.com/FryJay/MenuHammer"
mh.license = "MIT - https://opensource.org/licenses/MIT"
mh.spoonPath = hs.spoons.scriptPath()
-- Setup the menu manager
MenuManager = dofile(mh.spoonPath.."/MenuManager.lua")
mh.menuManager = nil
----------------------------------------------------------------------------------------------------
------------------------------------------ Config file ---------------------------------------------
----------------------------------------------------------------------------------------------------
-- Load the defaults
dofile(mh.spoonPath.."/MenuConfigDefaults.lua")
-- Load the custom config
menuCustomConfig = hs.fs.pathToAbsolute(hs.configdir .. '/menuHammerCustomConfig.lua')
if menuCustomConfig then
require "menuHammerCustomConfig"
end
----------------------------------------------------------------------------------------------------
----------------------------------------- Apply options --------------------------------------------
----------------------------------------------------------------------------------------------------
-- Determine if menus should appear over fullscreen applications.
if menuShowInFullscreen then
-- Hide the dock icon. This is necessary for the menu to appear over full screen apps.
hs.dockicon.hide()
else
hs.dockicon.show()
end
-- Determine if the menu bar item should be shown
if showMenuBarItem then
-- The menu bar item to show current status
menuBarItem = hs.menubar.new()
-- Make it so that clicking on the menu bar item results in a reload of Hammerspoon
menuBarItem:setClickCallback(function() hs.reload() end)
end
----------------------------------------------------------------------------------------------------
---------------------------------------- Menuhammer Init -------------------------------------------
----------------------------------------------------------------------------------------------------
function mh:init()
print("MenuHammer initializing")
assert(menuHammerToggleKey, "No toggle key set")
assert(menuHammerMenuList, "No menu list configured.")
assert(menuItemColors, "No menu item colors defined.")
assert(menuItemPrefix, "No menu item prefixes defined.")
mh.menuManager = MenuManager.new(menuHammerToggleKey,
menuHammerMenuList,
menuItemColors,
menuItemPrefix,
showMenuBarItem)
assert(mh.menuManager, "Menu manager is nil")
end
function mh:enter()
print("MenuHammer is activating")
mh.menuManager:enter()
end
----------------------------------------------------------------------------------------------------
---------------------------------------- End Communication -----------------------------------------
----------------------------------------------------------------------------------------------------
-- Return the mh object.
return mh
|
-- See LICENSE for terms
local pairs, tostring, type, table, tonumber = pairs, tostring, type, table, tonumber
local Translate = ChoGGi.ComFuncs.Translate
local IsValidXWin = ChoGGi.ComFuncs.IsValidXWin
local TableConcat = ChoGGi.ComFuncs.TableConcat
local IsShiftPressed = ChoGGi.ComFuncs.IsShiftPressed
local Strings = ChoGGi.Strings
local image_str = Mods.ChoGGi_MapImagesPack.env.CurrentModPath .. "Maps/"
local dlg_locations
local map_data
local landsiteobj
local function ShowDialogs()
-- we only need to build once, not as if it'll change anytime soon (save as csv?, see if it's shorter to load)
if not map_data then
map_data = ChoGGi.ComFuncs.ExportMapDataToCSV(XAction:new{setting_breakthroughs = true, setting_skip_csv = true})
local map_info = ChoGGi_VLI_MapInfoDlg.RetMapLocation
for i = 1, #map_data do
local data = map_data[i]
data.coordinates = map_info(nil, data, true):lower()
-- change all strings to lowercase here instead of while searching
-- breakthroughs
for j = 1, #data do
data[j] = data[j]:lower()
end
-- only these three have case
if data.landing_spot then
data.landing_spot = data.landing_spot:lower()
end
data.map_name = data.map_name:lower()
data.topography = data.topography:lower()
end
end
--~ map_data = {}
--~ ex(map_data)
-- check if we already created finder, and make one if not
if not IsValidXWin(dlg_locations) then
dlg_locations = ChoGGi_VLI_MapInfoDlg:new({}, terminal.desktop, {})
end
end
if ChoGGi.testing then
vli = ShowDialogs
end
-- kill off image dialogs
function OnMsg.ChangeMapDone()
-- keep dialog opened after
--~ do return end
local dlgs = terminal.desktop
for i = #dlgs, 1, -1 do
local dlg = dlgs[i]
if dlg:IsKindOf("ChoGGi_VLI_MapInfoDlg")
or dlg.dialog_marker == "ChoGGi_VLI_MapInfoDlg_Examine"
then
dlg:Close()
end
end
end
local GetParentOfKind = ChoGGi.ComFuncs.GetParentOfKind
local function GetRootDialog(dlg)
return dlg.parent_dialog or GetParentOfKind(dlg, "ChoGGi_VLI_MapInfoDlg")
end
DefineClass.ChoGGi_VLI_MapInfoDlg = {
__parents = {"ChoGGi_XWindow"},
--~ obj = false,
obj_name = false,
dialog_width = 750.0,
dialog_height = 140.0,
-- actual amount of boxes
input_box_count_add = 0,
input_box_count_rem = 0,
-- ones with text
input_box_count_add2 = 0,
input_box_count_rem2 = 0,
-- boxes with text
input_boxs_add = false,
input_boxs_rem = false,
found_objs = false,
-- store dlg to set title
current_examine_dlg = false,
}
function ChoGGi_VLI_MapInfoDlg:Init(parent, context)
local g_Classes = g_Classes
self.title = T(7396, "Location")
self.title_image = "CommonAssets/UI/Menu/EV_OpenFirst.tga"
self.title_image_single = true
-- By the Power of Grayskull!
self:AddElements(parent, context)
self.idTopArea = g_Classes.ChoGGi_XDialogSection:new({
Id = "idTopArea",
Dock = "top",
Margins = box(0, 8, 0, 8),
}, self.idDialog)
self.idSearch = g_Classes.ChoGGi_XButton:new({
Id = "idSearch",
Dock = "left",
Text = T(10123, "Search"),
Background = g_Classes.ChoGGi_XButton.bg_green,
RolloverText = Strings[302535920001303--[[Search for text within %s.
Leave blank to skip search box.]]]:format(Translate(self.title)),
Margins = box(6, 0, 0, 0),
OnPress = self.FindText,
}, self.idTopArea)
self.idShowInfo = g_Classes.ChoGGi_XButton:new({
Id = "idShowInfo",
Dock = "left",
Text = T(126095410863, "Info"),
RolloverText = T(302535920011927, "Show a list of breakthroughs/map names/etc to use."),
Margins = box(6, 0, 0, 0),
OnPress = self.ShowInfoDialog,
}, self.idTopArea)
self.idAndOr = g_Classes.ChoGGi_XCheckButton:new({
Id = "idAndOr",
Dock = "left",
Margins = box(10, 0, 0, 0),
Text = T(302535920011920, "And / Or"),
RolloverText = T(302535920011921, "If you don't know what this means, then leave it checked (And)."),
}, self.idTopArea)
self.idAndOr:SetCheckBox(true)
self.idReuseResults = g_Classes.ChoGGi_XCheckButton:new({
Id = "idReuseResults",
Dock = "left",
Margins = box(10, 0, 0, 0),
Text = T(302535920011922, "Reuse Results"),
RolloverText = T(302535920011923, "Open all results in the same dialog."),
}, self.idTopArea)
self.idReuseResults:SetCheckBox(true)
-- inputs and ignores
self.idSearchArea = g_Classes.ChoGGi_XDialogSection:new({
Id = "idSearchArea",
}, self.idDialog)
-- inputs
self.idInputButtonArea = g_Classes.ChoGGi_XDialogSection:new({
Id = "idInputButtonArea",
Dock = "top",
}, self.idSearchArea)
self.idInputArea = g_Classes.ChoGGi_XDialogSection:new({
Id = "idInputArea",
Dock = "top",
}, self.idSearchArea)
self.idAddOne = g_Classes.ChoGGi_XButton:new({
Id = "idAddOne",
Dock = "left",
Text = T(302535920011918, "+ Input"),
RolloverText = T(302535920011919, "Add another text input field to use (leave input blank to ignore)."),
Margins = box(6, 0, 0, 0),
OnPress = function()
self:AddSearchBox("add")
end,
}, self.idInputButtonArea)
self.idAddTextArea = g_Classes.ChoGGi_XDialogSection:new({
Id = "idAddTextArea",
Dock = "bottom",
LayoutMethod = "VList",
Margins = box(10, 0, 0, 0),
}, self.idInputArea)
-- ignores
self.idIgnoreButtonArea = g_Classes.ChoGGi_XDialogSection:new({
Id = "idIgnoreButtonArea",
Dock = "top",
Margins = box(0, 4, 0, 0),
}, self.idSearchArea)
self.idIgnoreArea = g_Classes.ChoGGi_XDialogSection:new({
Id = "idIgnoreArea",
Dock = "top",
}, self.idSearchArea)
self.idRemOne = g_Classes.ChoGGi_XButton:new({
Id = "idRemOne",
Dock = "left",
Text = T(302535920011928, "+ Ignore"),
RolloverText = T(302535920011929, "Add another text input field to use to ignore text (leave input blank to ignore)."),
Margins = box(6, 0, 0, 0),
OnPress = function()
self:AddSearchBox("rem")
end,
}, self.idIgnoreButtonArea)
self.idRemTextArea = g_Classes.ChoGGi_XDialogSection:new({
Id = "idRemTextArea",
Dock = "bottom",
LayoutMethod = "VList",
Margins = box(8, 0, 0, 8),
}, self.idIgnoreArea)
-- add one search box by default
self.input_boxs_add = {}
self.input_boxs_rem = {}
self:AddSearchBox("add")
self:AddSearchBox("rem")
self.idSearch1:SetFocus()
self:PostInit()
end
function ChoGGi_VLI_MapInfoDlg:ShowInfoDialog()
local text = {}
local temp_data = {}
local c = 0
-- add breaks
local breaks = Presets.TechPreset.Breakthroughs
for i = 1, #breaks do
temp_data[i] = Translate(breaks[i].display_name)
end
c = #breaks
table.sort(temp_data)
c = c + 1
temp_data[c] = "\n"
table.append(text, temp_data)
-- map names
temp_data = {}
c = 0
local MapData = MapDataPresets
for id, data in pairs(MapData) do
if data.IsRandomMap then
c = c + 1
temp_data[c] = id
end
end
table.sort(temp_data)
c = c + 1
temp_data[c] = "\n"
table.append(text, temp_data)
-- named locations
temp_data = {}
c = 0
for _, location in pairs(MarsLocales) do
c = c + 1
temp_data[c] = Translate(location)
end
table.sort(temp_data)
table.append(text, temp_data)
ChoGGi.ComFuncs.OpenInMultiLineTextDlg(TableConcat(text, "\n"), {
has_params = true,
title = T(302535920011926, "Show Info"),
})
end
function ChoGGi_VLI_MapInfoDlg:AddSearchBox(input_type)
self = GetRootDialog(self)
local area, count, id, str_roll, str_hint
if input_type == "add" then
area = "idAddTextArea"
count = "input_box_count_add"
id = "idSearch"
str_roll = T(302535920011932, [[Search for text in map data.
Leave blank to skip search box.]])
str_hint = Strings[302535920001306--[[Enter text to find]]]
elseif input_type == "rem" then
area = "idRemTextArea"
count = "input_box_count_rem"
id = "idSearchRem"
str_roll = T(302535920011930, [[Search for text to remove from the results (overrides search text).
Leave blank to skip search box.]])
str_hint = Translate(T(302535920011931, "Enter text to ignore"))
end
self[count] = self[count] + 1
id = id .. self[count]
self[id] = ChoGGi_XTextInput:new({
Id = id,
--~ MinWidth = 600,
RolloverText = str_roll,
Hint = str_hint,
OnKbdKeyDown = function(self_input, vk, ...)
self.idSearchInput_OnKbdKeyDown(self_input, vk, input_type, ...)
end,
}, self[area])
self:SetHeight(self:GetHeight() + 21)
end
function ChoGGi_VLI_MapInfoDlg:FindText()
self = GetRootDialog(self)
-- always start off empty
self.found_objs = {}
local reuse = self.idReuseResults:GetCheck()
if not reuse or reuse and not IsValidXWin(self.current_examine_dlg) then
self.current_examine_dlg = ChoGGi.ComFuncs.OpenInExamineDlg(self.found_objs, {
has_params = true,
dialog_marker = "ChoGGi_VLI_MapInfoDlg_Examine",
tooltip_info = function(obj)
return image_str .. obj.map_name .. ".png"
end,
exec_tables = function(obj)
local key_location = self:RetMapLocation(obj, true)
local result, lat, long = landsiteobj:ConvertStrLocationToCoords(key_location)
if result then
landsiteobj:MoveToSelection(lat, long, nil, true)
landsiteobj:CalcMarkersVisibility()
else
CreateMarsMessageBox(T(6885, "Error"), T(4093, "Invalid coordinates.") .. ": " .. key_location, T(1000136, "OK"))
end
end,
})
end
-- get strings from input box(s)
self.input_box_count_add2 = 0
for i = 1, self.input_box_count_add do
local str = self["idSearch" .. i]:GetText()
-- no need to search blank ones
if str ~= "" and str ~= " " then
self.input_box_count_add2 = self.input_box_count_add2 + 1
self.input_boxs_add[self.input_box_count_add2] = str:lower()
end
end
-- get strings from input box(s)
self.input_box_count_rem2 = 0
for i = 1, self.input_box_count_rem do
local str = self["idSearchRem" .. i]:GetText()
-- no need to search blank ones
if str ~= "" and str ~= " " then
self.input_box_count_rem2 = self.input_box_count_rem2 + 1
self.input_boxs_rem[self.input_box_count_rem2] = str:lower()
end
end
-- build our list of objs
self:UpdateFoundObjects()
-- should do this nicer, but whatever
CreateRealTimeThread(function()
Sleep(10)
self.current_examine_dlg:SetPos(self:GetPos()+point(0, self.idDialog.box:sizey() + 25))
if reuse and IsValidXWin(self.current_examine_dlg) then
self.current_examine_dlg.obj = self.found_objs
self.current_examine_dlg:SetObj()
self:SetExamineTitle()
end
end)
end
function ChoGGi_VLI_MapInfoDlg:FindObject(key_name, value_name, rem)
local count = rem and self.input_box_count_rem2 or self.input_box_count_add2
local input = rem and "input_boxs_rem" or "input_boxs_add"
for i = 1, count do
local str = self[input][i]
if key_name .. value_name == str then
return str
-- :find(str, 1, true) (1, true means don't use lua patterns, just plain text)
elseif key_name:find(str, 1, true) then
return key_name
elseif value_name:find(str, 1, true) then
return value_name
end
end
end
local loc_key = {"","","","",""}
function ChoGGi_VLI_MapInfoDlg:RetMapLocation(map, merged)
if merged then
loc_key[1] = map.latitude_degree
loc_key[2] = map.latitude
loc_key[3] = map.longitude_degree
loc_key[4] = map.longitude
loc_key[5] = ""
else
loc_key[1] = map.latitude_degree
loc_key[2] = map.latitude
loc_key[3] = " "
loc_key[4] = map.longitude_degree
loc_key[5] = map.longitude
end
return TableConcat(loc_key)
end
function ChoGGi_VLI_MapInfoDlg:SetExamineTitle()
local title = T(3732, "Count") .. " " .. table.count(self.found_objs) .. ": + "
.. TableConcat(self.input_boxs_add, " ") .. ", - " .. TableConcat(self.input_boxs_rem, " ")
self.current_examine_dlg.override_title = true
self.current_examine_dlg.idCaption:SetTitle(self.current_examine_dlg, title)
end
function ChoGGi_VLI_MapInfoDlg:UpdateFoundObjects()
local andor = self.idAndOr:GetCheck()
local matches = {}
-- loopy time
for i = 1, #map_data do
local map = map_data[i]
local remove_found
table.clear(matches)
local key_location = self:RetMapLocation(map)
for key, value in pairs(map) do
local key_name, value_name = tostring(key), tostring(value)
-- always check for removes first
if self:FindObject(key_name, value_name, true) then
remove_found = true
elseif not self.found_objs[key_location] then
-- true is "and"
if andor then
local match = self:FindObject(key_name, value_name)
if match then
matches[match] = true
end
else
if self:FindObject(key_name, value_name) then
self.found_objs[key_location] = map
end
end
--
end
end
-- check if all strings were matched and add if so
if remove_found then
self.found_objs[key_location] = nil
elseif andor then
local found_count = 0
for _ in pairs(matches) do
found_count = found_count + 1
end
if found_count >= self.input_box_count_add2 or self.input_box_count_add2 == 1 and found_count > 0 then
self.found_objs[key_location] = map
end
end
end
-- done looping so set title
self:SetExamineTitle()
end
local const = const
function ChoGGi_VLI_MapInfoDlg:idSearchInput_OnKbdKeyDown(vk, input_type)
local old_self = self
self = GetRootDialog(self)
local count, id, length
if input_type == "add" then
count = "input_box_count_add"
id = "idSearch"
length = 9
elseif input_type == "rem" then
count = "input_box_count_rem"
id = "idSearchRem"
length = 12
end
if vk == const.vkEnter then
self:FindText()
return "break"
elseif vk == const.vkTab then
if self[count] == 1 then
return "break"
end
local current_idx = tonumber(old_self.Id:sub(length))
local is_shift = IsShiftPressed()
-- tab to go down, shift-tab to go up
if not is_shift and current_idx >= self[count] then
current_idx = 1
elseif is_shift and current_idx == 1 then
current_idx = self[count]
elseif is_shift then
current_idx = current_idx - 1
else
current_idx = current_idx + 1
end
self[id .. current_idx]:SetFocus()
return "break"
end
return ChoGGi_XTextInput.OnKbdKeyDown(old_self, vk)
end
-- fired when we go to first new game section
local function AddProfilesButton(toolbar)
if toolbar.idChoGGi_FindMaps then
return
end
toolbar.idChoGGi_FindMaps = ChoGGi.ComFuncs.RetToolbarButton{
parent = toolbar,
id = "idChoGGi_FindMaps",
roll_title = T(126095410863, "Info"),
text = T(302535920011924, "Find Maps"),
roll_text = T(302535920011925, [[Find maps with specific breakthroughs etc.
<color ChoGGi_red>Warning!</color> This will take some time to load the map info (10-15 seconds).]]),
onpress = function()
ShowDialogs()
end,
}
end
-- add settings button
local orig_SetPlanetCamera = SetPlanetCamera
function SetPlanetCamera(planet, state, ...)
-- fire only in mission setup menu
if not state then
CreateRealTimeThread(function()
WaitMsg("OnRender")
if Dialogs.PGMainMenu and Dialogs.PGMainMenu.idContent then
local pgmission = Dialogs.PGMainMenu.idContent.PGMission
if type(pgmission) == "table" then
local items_dlg = pgmission[1][1]
landsiteobj = items_dlg.context
local toolbar = items_dlg.idToolBar
if table.find(toolbar, "Id", "idrandom") then
AddProfilesButton(toolbar)
end
-- hook into toolbar button area so we can keep adding the button
local orig_RebuildActions = toolbar.RebuildActions
toolbar.RebuildActions = function(self, context, ...)
orig_RebuildActions(self, context, ...)
if table.find(toolbar, "Id", "idrandom") then
AddProfilesButton(toolbar)
end
end
end
end
end)
end
return orig_SetPlanetCamera(planet, state, ...)
end
|
local skynet = require "skynet"
local function debug_call(addr, cmd, ...)
return skynet.call(addr, "debug", cmd, ...)
end
return function()
local list = {}
local all = skynet.call(".launcher", "lua", "LIST")
for addr, desc in pairs(all) do
addr = string.gsub(addr, ':', "0x")
local mem = debug_call(addr, "MEM")
--[[if mem < 1024 then
mem = math.floor(mem).." Kb"
else
mem = math.floor(mem/1024).." Mb"
end]]
local stat = debug_call(addr, "STAT")
--v.address = skynet.address(addr)
table.insert(list, {
addr = addr,
desc = desc,
mem = mem//1,
task = stat.task,
mqlen = stat.mqlen,
})
end
return {
list = list
}
end
|
local GameObject = require('modules/GameObject')
local Enemy = class('Enemy', GameObject)
local EffectDeath = require('modules/EffectDeath')
local EffectSpawn = require('modules/EffectSpawn')
function Enemy:initialize( options )
GameObject.initialize( self, options )
self.speed = 1
self.health = 1
self.state_timer = 0
self.target = room.players[math.random(#room.players)]
self.image = love.graphics.newImage('sprites/enemy.png')
self.hit_sound = love.audio.newSource("sounds/hit.wav", "static")
room:addObject( 'effect', EffectSpawn:new( {x = self.x, y = self.y} ) )
self.type = 'enemy'
self.air = false
self.filter = function(item, other)
if other.type == 'player' then return 'slide'
elseif other.type == 'enemy' and other.air == self.air then return 'slide'
elseif other.type == 'enemy' then return 'cross'
elseif other.type == 'swordgood' then return 'cross'
elseif other.type == 'swordbad' then return 'cross'
elseif other.type == 'arrow' then return 'cross'
elseif other.type == 'magicgood' then return 'cross'
elseif other.type == 'magicbad' then return 'cross'
else return 'slide' end
end
end
function Enemy:update( dt )
if self.dir then
self.animations[self.state..self.dir]:update(dt)
else
self.animations[self.state]:update(dt)
end
end
function Enemy:draw()
GameObject.draw( self )
end
function Enemy:changeState( state )
self.state = state
if self.bos and self.bos[self.state] then
self.box = self.bos[state][1]
self.boy = self.bos[state][2]
end
if self.state_times and self.state_times[self.state] then
self:stateTimerReset()
end
end
function Enemy:stateTimerReset( )
if self.state == 'hurt' then
self.state_timer = self.state_times[self.state]
else
self.state_timer = math.random( self.state_times[self.state]/2, self.state_times[self.state] )
end
end
function Enemy:moveTowardsObject( dt, o )
local dirx, diry = o:ox() - self:ox(), o:oy() - self:oy()
local mag = math.sqrt( dirx^2 + diry^2 )
local uv = 1/mag
local movex, movey = self.speed*uv*dirx, self.speed*uv*diry
local x, y, cols, len = world:move(self, self.x + self.box + movex*dt, self.y + self.boy + movey*dt, self.filter )
self.x = x - self.box
self.y = y - self.boy
for i,v in ipairs(cols) do
if v.other.type == 'player' then
v.other:collision( self )
end
end
end
function Enemy:moveDirection( dt, dirx, diry )
local mag = math.sqrt( dirx^2 + diry^2 )
if math.abs(mag) < self.speed*dt then return end
local uv = 1/mag
local movex, movey = self.speed*uv*dirx, self.speed*uv*diry
local x, y, cols, len = world:move(self, self.x + self.box + movex*dt, self.y + self.boy + movey*dt, self.filter )
self.x = x - self.box
self.y = y - self.boy
for i,v in ipairs(cols) do
if v.other.type == 'player' then
v.other:collision( self )
end
end
end
function Enemy:collision( other )
if self.state ~= 'hurt' then
local dirx, diry = self:ox() - other:ox(), self:oy() - other:oy()
local mag = math.sqrt( dirx^2 + diry^2 )
local uv = 1/mag
local movex, movey = 16*uv*dirx, 16*uv*diry
local x, y, cols, len = world:move(self, self.x + self.box + movex, self.y + self.boy + movey, self.filter )
self.x = x - self.box
self.y = y - self.boy
for i,v in ipairs(cols) do
if v.other.type == 'enemy' and other.type == 'swordgood' then
v.other:push(other)
end
end
self.health = self.health - 1
self:changeState('hurt')
self.hit_sound:play()
if self.health <= 0 then
world:remove(self)
room:addObject( 'effect', EffectDeath:new( {x = self.x, y = self.y} ) )
end
end
end
function Enemy:push( other )
local dirx, diry = self:ox() - other:ox(), self:oy() - other:oy()
local mag = math.sqrt( dirx^2 + diry^2 )
local uv = 1/mag
local movex, movey = 16*uv*dirx, 16*uv*diry
local x, y, cols, len = world:move(self, self.x + self.box + movex, self.y + self.boy + movey, self.filter )
self.x = x - self.box
self.y = y - self.boy
for i,v in ipairs(cols) do
if v.other.type == 'enemy' then
v.other:push(other)
end
end
end
function Enemy:chooseTarget( )
if #room.players < 1 then
self.state = 'idle'
self.state_timer = 0
else
self.target = room.players[math.random(#room.players)]
end
end
return Enemy
|
yatm_oku:require("nodes/computer.lua")
yatm_oku:require("nodes/floppy_disk_drive.lua")
yatm_oku:require("nodes/micro_controller.lua")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.