ah_sce_unpacked/unpacked/Custom_Token Token Arranger 022907.ttslua
2024-03-10 09:56:22 -04:00

616 lines
20 KiB
Plaintext

-- Bundled by luabundle {"version":"1.6.0"}
local __bundle_require, __bundle_loaded, __bundle_register, __bundle_modules = (function(superRequire)
local loadingPlaceholder = {[{}] = true}
local register
local modules = {}
local require
local loaded = {}
register = function(name, body)
if not modules[name] then
modules[name] = body
end
end
require = function(name)
local loadedModule = loaded[name]
if loadedModule then
if loadedModule == loadingPlaceholder then
return nil
end
else
if not modules[name] then
if not superRequire then
local identifier = type(name) == 'string' and '\"' .. name .. '\"' or tostring(name)
error('Tried to require ' .. identifier .. ', but no such module has been registered')
else
return superRequire(name)
end
end
loaded[name] = loadingPlaceholder
loadedModule = modules[name](require, loaded, register, modules)
loaded[name] = loadedModule
end
return loadedModule
end
return require, loaded, register, modules
end)(nil)
__bundle_register("__root", function(require, _LOADED, __bundle_register, __bundle_modules)
require("accessories/TokenArranger")
end)
__bundle_register("accessories/TokenArranger", function(require, _LOADED, __bundle_register, __bundle_modules)
local chaosBagApi = require("chaosbag/ChaosBagApi")
local mythosAreaApi = require("core/MythosAreaApi")
-- common parameters
local buttonParameters = {}
buttonParameters.function_owner = self
buttonParameters.label = ""
buttonParameters.tooltip = "Increase / Decrease"
buttonParameters.color = { 0, 0, 0, 0 }
buttonParameters.width = 325
buttonParameters.height = 325
local inputParameters = {}
inputParameters.function_owner = self
inputParameters.font_size = 100
inputParameters.width = 250
inputParameters.height = inputParameters.font_size + 23
inputParameters.alignment = 3
inputParameters.validation = 2
inputParameters.tab = 2
local percentageLabel = {}
percentageLabel.function_owner = self
percentageLabel.click_function = "none"
percentageLabel.width = 0
percentageLabel.height = 0
-- variables with save function
local tokenPrecedence = {}
local percentage = false
local includeDrawnTokens = true
-- variables without save function
local updating = false
local TOKEN_NAMES = {
"Elder Sign",
"Skull",
"Cultist",
"Tablet",
"Elder Thing",
"Auto-fail",
"Bless",
"Curse",
"Frost",
""
}
-- saving the precedence settings and information on the most recently loaded data
function onSave()
return JSON.encode({
tokenPrecedence = tokenPrecedence,
percentage = percentage,
includeDrawnTokens = includeDrawnTokens
})
end
-- loading data, button creation and initial layouting
function onLoad(saveState)
if saveState ~= nil and saveState ~= "" then
local loadedData = JSON.decode(saveState)
tokenPrecedence = loadedData.tokenPrecedence
percentage = loadedData.percentage
includeDrawnTokens = loadedData.includeDrawnTokens
else
loadDefaultValues()
-- grab token metadata from mythos area
Wait.time(function() onTokenDataChanged(mythosAreaApi.returnTokenData()) end, 0.2)
end
createButtonsAndInputs()
-- maybe trigger layout() to draw percentage buttons
local objList = getObjectsWithTag("tempToken")
if #objList > 0 then
Wait.time(layout, 0.5)
end
-- context menu items
self.addContextMenuItem("Load default values", function()
loadDefaultValues()
updateUI()
layout()
end)
self.addContextMenuItem("Include drawn tokens", function()
includeDrawnTokens = not includeDrawnTokens
local text = includeDrawnTokens and " " or " not "
broadcastToAll("Token Arranger will" .. text .. "include currently drawn chaos tokens.", "Orange")
layout()
end)
self.addContextMenuItem("Toggle percentages", function()
if percentage then
percentage = false
else
percentage = "basic"
broadcastToAll("Percentages are unreliable when using tokens that draw other tokens (bless or curse for example).", "Yellow")
end
layout()
end)
self.addContextMenuItem("Toggle cumulative", function()
if percentage == "cumulative" then
percentage = "basic"
else
percentage = "cumulative"
end
broadcastToAll("Percentages are unreliable when using tokens that draw other tokens (bless or curse for example).", "Yellow")
layout()
end)
end
-- delete temporary tokens when destroyed
function onDestroy() deleteCopiedTokens() end
-- layout tokens when dropped (after 1.5 seconds)
function onDrop() Wait.time(layout, 1.5) end
-- delete temporary tokens when picked up
function onPickUp() deleteCopiedTokens() end
-- click_function for buttons on chaos tokens
function tokenClick(isRightClick, index)
local change = tonumber(isRightClick and "-1" or "1")
tokenPrecedence[TOKEN_NAMES[index]][1] = tokenPrecedence[TOKEN_NAMES[index]][1] + change
self.editInput({
index = index - 1,
value = tokenPrecedence[TOKEN_NAMES[index]][1]
})
layout()
end
-- input_function for input_boxes
function tokenInput(input, selected, index)
if selected == false then
local num = tonumber(input)
if num ~= nil then
tokenPrecedence[TOKEN_NAMES[index]][1] = num
end
layout()
end
end
-- loads the default precedence table
function loadDefaultValues()
-- 1st value: token modifiers for sorting
-- 2nd value: order for equivalent tokens (starts at 2 because of "+1" token)
tokenPrecedence = {
["Elder Sign"] = { 100, 2},
["Skull"] = { -1, 3},
["Cultist"] = { -2, 4},
["Tablet"] = { -3, 5},
["Elder Thing"] = { -4, 6},
["Auto-fail"] = { -100, 7},
["Bless"] = { 101, 8},
["Curse"] = { -101, 9},
["Frost"] = { -99, 10},
[""] = { 0, 11}
}
end
-- creates buttons and inputs
function createButtonsAndInputs()
local offset = 0.725
local pos = { x = { -1.067, 0.377 }, z = -2.175 }
-- button and inputs index 0-9
for i = 1, 10 do
if i < 6 then
buttonParameters.position = { pos.x[1], 0, pos.z + i * offset }
inputParameters.position = { pos.x[1] + offset, 0.1, pos.z + i * offset }
else
buttonParameters.position = { pos.x[2], 0, pos.z + (i - 5) * offset }
inputParameters.position = { pos.x[2] + offset, 0.1, pos.z + (i - 5) * offset }
end
buttonParameters.click_function = "tokenClick" .. i
inputParameters.input_function = "tokenInput" .. i
inputParameters.value = tokenPrecedence[TOKEN_NAMES[i]][1]
-- setting click-/inputfunction
self.setVar(buttonParameters.click_function, function(_, _, isRightClick) tokenClick(isRightClick, i) end)
self.setVar(inputParameters.input_function, function(_, _, input, selected) tokenInput(input, selected, i) end)
-- button/input creation
self.createButton(buttonParameters)
self.createInput(inputParameters)
end
-- index 10: "Update / Hide" button
self.createButton({
function_owner = self,
label = "Update / Hide",
click_function = "layout",
tooltip = "Left-Click: Update!\nRight-Click: Hide Tokens!",
position = { 0.725, 0.1, 2.025 },
color = { 1, 1, 1 },
width = 675,
height = 175
})
end
-- update input fields
function updateUI()
for i = 1, 10 do
self.editInput({
index = i - 1,
value = tokenPrecedence[TOKEN_NAMES[i]][1]
})
end
end
-- order function for data sorting
function tokenValueComparator(left, right)
if left.value ~= right.value then
return left.value > right.value
elseif left.order ~= right.order then
return left.order < right.order
else
return false
end
end
-- deletes previously placed tokens
function deleteCopiedTokens()
for _, token in ipairs(getObjectsWithTag("tempToken")) do
token.destruct()
end
-- this removes the percentage buttons (by index 11+)
local buttonCount = #self.getButtons()
if buttonCount < 12 then return end
for i = buttonCount, 12, -1 do
self.removeButton(i - 1)
end
end
-- creates buttons as labels as display for percentage values
function createPercentageButton(tokenCount, valueCount, tokenName)
local startPos = Vector(2.3, -0.04, 0.875 * valueCount)
if percentage == "cumulative" then
percentageLabel.scale = { 1.5, 1.5, 1.5 }
percentageLabel.position = startPos - Vector(0, 0, 2.85)
else
percentageLabel.scale = { 2, 2, 2 }
percentageLabel.position = startPos - Vector(0, 0, 2.675)
end
-- determine font_color
if tokenName == "Elder Sign" then
percentageLabel.font_color = { 0.35, 0.71, 0.85 }
elseif tokenName == "Auto-fail" then
percentageLabel.font_color = { 0.86, 0.1, 0.1 }
-- check if the tokenName contains letters (e.g. symbol token)
elseif string.match(tokenName, "%a") ~= nil then
percentageLabel.font_color = { 0.68, 0.53, 0.86 }
else
percentageLabel.font_color = { 0.85, 0.67, 0.33 }
end
-- create label for base percentage
local basePercentage = math.floor((tokenCount.row / tokenCount.total) * 10000) / 100
percentageLabel.label = string.format("%s", string.format("%05.2f", basePercentage) .. "%")
self.createButton(percentageLabel)
-- optionally create label for cumulative percentage
if percentage == "cumulative" then
percentageLabel.position = startPos - Vector(0, 0, 2.45)
percentageLabel.font_color = { 1, 1, 1 }
-- only display one digit for 100%
if tokenCount.sum == tokenCount.total then
percentageLabel.label = "100.0%"
else
local cumulativePercentage = math.floor((tokenCount.sum / tokenCount.total) * 10000) / 100
percentageLabel.label = string.format("%s", string.format("%05.2f", cumulativePercentage) .. "%")
end
self.createButton(percentageLabel)
end
end
-- main function (delete old tokens, clone chaos bag content, sort it and position it)
function layout(_, _, isRightClick)
if updating then return end
updating = true
deleteCopiedTokens()
-- stop here if right-clicked
if isRightClick then
updating = false
return
end
-- get ChaosBag and stop if not found
local chaosBag = chaosBagApi.findChaosBag()
if not chaosBag then
updating = false
return
end
-- clone tokens from chaos bag (default position above trash can)
local rawData = chaosBag.getData().ContainedObjects
-- optionally get the data for tokens in play
if includeDrawnTokens then
for _, token in pairs(chaosBagApi.getTokensInPlay()) do
if token ~= nil then table.insert(rawData, token.getData()) end
end
end
-- generate layout data
local data = {}
for i, objData in ipairs(rawData) do
objData["Tags"] = { "tempToken" }
local value = tonumber(objData.Nickname)
local precedence = tokenPrecedence[objData.Nickname]
-- remove GUID to avoid issues for high latency clients
objData["GUID"] = nil
-- store data with value / precendence
data[i] = {
token = objData,
value = value or precedence[1]
}
-- order for comparator function
if precedence ~= nil then
data[i].order = precedence[2]
else
data[i].order = value
end
end
-- sort table by value (symbols last if same value)
table.sort(data, tokenValueComparator)
-- laying out the tokens
local pos = self.getPosition() + Vector(3.55, -0.05, -3.95)
if percentage then pos.z = pos.z - 3.05 end
local location = { x = pos.x, y = pos.y, z = pos.z }
local rotation = self.getRotation()
local currentValue = data[1].value
local tokenCount = { row = 0, sum = 0, total = #data }
local valueCount = 1
local tokenName = false
for i, item in ipairs(data) do
-- this is true for the first token in a new row
if item.value ~= currentValue then
if percentage then
tokenCount.sum = tokenCount.sum + tokenCount.row
createPercentageButton(tokenCount, valueCount, tokenName)
end
location.x = location.x - 1.75
location.z = pos.z
currentValue = item.value
valueCount = valueCount + 1
tokenCount.row = 0
end
spawnObjectData({
data = item.token,
position = location,
rotation = rotation
})
tokenName = item.token.Nickname
location.z = location.z - 1.75
tokenCount.row = tokenCount.row + 1
end
-- this is repeated to create the button for the last token
if percentage then
tokenCount.sum = tokenCount.sum + tokenCount.row
createPercentageButton(tokenCount, valueCount, tokenName)
end
-- introducing a small delay to limit update calls
Wait.time(function() updating = false end, 0.1)
end
-- called from outside to set default values for tokens
function onTokenDataChanged(parameters)
local tokenData = parameters.tokenData or {}
local currentScenario = parameters.currentScenario or ""
local useFrontData = parameters.useFrontData
-- update token precedence
for key, table in pairs(tokenData) do
local modifier = table.modifier
if modifier == -999 then modifier = 0 end
tokenPrecedence[key][1] = modifier
end
updateUI()
layout()
end
end)
__bundle_register("chaosbag/ChaosBagApi", function(require, _LOADED, __bundle_register, __bundle_modules)
do
local ChaosBagApi = {}
-- respawns the chaos bag with a new state of tokens
---@param tokenList table List of chaos token ids
ChaosBagApi.setChaosBagState = function(tokenList)
return Global.call("setChaosBagState", tokenList)
end
-- returns a Table List of chaos token ids in the current chaos bag
-- requires copying the data into a new table because TTS is weird about handling table return values in Global
ChaosBagApi.getChaosBagState = function()
local chaosBagContentsCatcher = Global.call("getChaosBagState")
local chaosBagContents = {}
for _, v in ipairs(chaosBagContentsCatcher) do
table.insert(chaosBagContents, v)
end
return chaosBagContents
end
-- checks scripting zone for chaos bag (also called by a lot of objects!)
ChaosBagApi.findChaosBag = function()
return Global.call("findChaosBag")
end
-- returns a table of object references to the tokens in play (does not include sealed tokens!)
ChaosBagApi.getTokensInPlay = function()
return Global.call("getChaosTokensinPlay")
end
-- returns all sealed tokens on cards to the chaos bag
---@param playerColor string Color of the player to show the broadcast to
ChaosBagApi.releaseAllSealedTokens = function(playerColor)
return Global.call("releaseAllSealedTokens", playerColor)
end
-- returns all drawn tokens to the chaos bag
ChaosBagApi.returnChaosTokens = function()
return Global.call("returnChaosTokens")
end
-- removes the specified chaos token from the chaos bag
---@param id string ID of the chaos token
ChaosBagApi.removeChaosToken = function(id)
return Global.call("removeChaosToken", id)
end
-- returns a chaos token to the bag and calls all relevant functions
---@param token tts__Object Chaos token to return
ChaosBagApi.returnChaosTokenToBag = function(token)
return Global.call("returnChaosTokenToBag", token)
end
-- spawns the specified chaos token and puts it into the chaos bag
---@param id string ID of the chaos token
ChaosBagApi.spawnChaosToken = function(id)
return Global.call("spawnChaosToken", id)
end
-- Checks to see if the chaos bag can be manipulated. If a player is searching the bag when tokens
-- are drawn or replaced a TTS bug can cause those tokens to vanish. Any functions which change the
-- contents of the bag should check this method before doing so.
-- This method will broadcast a message to all players if the bag is being searched.
---@return any canTouch True if the bag is manipulated, false if it should be blocked.
ChaosBagApi.canTouchChaosTokens = function()
return Global.call("canTouchChaosTokens")
end
-- called by playermats (by the "Draw chaos token" button)
---@param mat tts__Object Playermat that triggered this
---@param drawAdditional boolean Controls whether additional tokens should be drawn
---@param tokenType? string Name of token (e.g. "Bless") to be drawn from the bag
---@param guidToBeResolved? string GUID of the sealed token to be resolved instead of drawing a token from the bag
ChaosBagApi.drawChaosToken = function(mat, drawAdditional, tokenType, guidToBeResolved)
return Global.call("drawChaosToken", {mat = mat, drawAdditional = drawAdditional, tokenType = tokenType, guidToBeResolved = guidToBeResolved})
end
-- returns a Table List of chaos token ids in the current chaos bag
-- requires copying the data into a new table because TTS is weird about handling table return values in Global
ChaosBagApi.getIdUrlMap = function()
return Global.getTable("ID_URL_MAP")
end
return ChaosBagApi
end
end)
__bundle_register("core/GUIDReferenceApi", function(require, _LOADED, __bundle_register, __bundle_modules)
do
local GUIDReferenceApi = {}
local function getGuidHandler()
return getObjectFromGUID("123456")
end
---@param owner string Parent object for this search
---@param type string Type of object to search for
---@return any: Object reference to the matching object
GUIDReferenceApi.getObjectByOwnerAndType = function(owner, type)
return getGuidHandler().call("getObjectByOwnerAndType", { owner = owner, type = type })
end
-- returns all matching objects as a table with references
---@param type string Type of object to search for
---@return table: List of object references to matching objects
GUIDReferenceApi.getObjectsByType = function(type)
return getGuidHandler().call("getObjectsByType", type)
end
-- returns all matching objects as a table with references
---@param owner string Parent object for this search
---@return table: List of object references to matching objects
GUIDReferenceApi.getObjectsByOwner = function(owner)
return getGuidHandler().call("getObjectsByOwner", owner)
end
-- sends new information to the reference handler to edit the main index
---@param owner string Parent of the object
---@param type string Type of the object
---@param guid string GUID of the object
GUIDReferenceApi.editIndex = function(owner, type, guid)
return getGuidHandler().call("editIndex", {
owner = owner,
type = type,
guid = guid
})
end
return GUIDReferenceApi
end
end)
__bundle_register("core/MythosAreaApi", function(require, _LOADED, __bundle_register, __bundle_modules)
do
local MythosAreaApi = {}
local guidReferenceApi = require("core/GUIDReferenceApi")
local function getMythosArea()
return guidReferenceApi.getObjectByOwnerAndType("Mythos", "MythosArea")
end
---@return any: Table of chaos token metadata (if provided through scenario reference card)
MythosAreaApi.returnTokenData = function()
return getMythosArea().call("returnTokenData")
end
---@return any: Object reference to the encounter deck
MythosAreaApi.getEncounterDeck = function()
return getMythosArea().call("getEncounterDeck")
end
-- draw an encounter card for the requesting mat
---@param mat tts__Object Playermat that triggered this
---@param alwaysFaceUp boolean Whether the card should be drawn face-up
MythosAreaApi.drawEncounterCard = function(mat, alwaysFaceUp)
getMythosArea().call("drawEncounterCard", {mat = mat, alwaysFaceUp = alwaysFaceUp})
end
-- reshuffle the encounter deck
MythosAreaApi.reshuffleEncounterDeck = function()
getMythosArea().call("reshuffleEncounterDeck")
end
return MythosAreaApi
end
end)
return __bundle_require("__root")