SCED/src/util/ConnectionDrawingTool.ttslua
2024-05-21 11:35:07 +02:00

99 lines
2.4 KiB
Plaintext

local connections = {}
function onSave()
return JSON.encode({ connections = connections })
end
function onLoad(savedData)
if savedData and savedData ~= "" then
local loadedData = JSON.decode(savedData) or {}
connections = loadedData.connections
processLines()
end
addHotkey("Drawing Tool: Reset", function() connections = {} processLines() end)
addHotkey("Drawing Tool: Redraw", processLines)
end
function onScriptingButtonDown(index, playerColor)
if index ~= 10 then return end
Timer.create {
identifier = playerColor .. "_draw_from",
function_name = "draw_from",
parameters = { player = Player[playerColor] },
delay = 1
}
end
function draw_from(params)
local source = params.player.getHoverObject()
if not source then return end
for _, item in ipairs(params.player.getSelectedObjects()) do
if item ~= source then
if item.getGUID() > source.getGUID() then
addPair(item, source)
else
addPair(source, item)
end
end
end
processLines()
end
function onScriptingButtonUp(index, playerColor)
if index ~= 10 then return end
-- returns true only if there is a timer to cancel. If this is false then we've waited longer than a second.
if not Timer.destroy(playerColor .. "_draw_from") then return end
local items = Player[playerColor].getSelectedObjects()
if #items < 2 then return end
table.sort(items, function(a, b) return a.getGUID() > b.getGUID() end)
for i = 1, #items do
local first = items[i]
for j = i, #items do
local second = items[j]
addPair(first, second)
end
end
processLines()
end
function addPair(first, second)
local first_guid = first.getGUID()
local second_guid = second.getGUID()
if not connections[first_guid] then connections[first_guid] = {} end
connections[first_guid][second_guid] = not connections[first_guid][second_guid]
end
function processLines()
local lines = {}
for source_guid, target_guids in pairs(connections) do
local source = getObjectFromGUID(source_guid)
for target_guid, exists in pairs(target_guids) do
if exists then
local target = getObjectFromGUID(target_guid)
if source and target then
table.insert(lines, {
points = { source.getPosition(), target.getPosition() },
color = Color.White
})
end
end
end
end
Global.setVectorLines(lines)
end