dcearth/travelNodes.lua

109 lines
2.8 KiB
Lua

--Manage the pathfinding nodes used by DEFCON.
--This is important for a mapping tool because the DEFCON client will not load a map unless
--the pathfinding nodes form a connected graph.
local bmp = require 'bmp'
local locationQuery = require 'locationQuery'
local lg = assert( love.graphics )
local t = setmetatable({}, {__index = locationQuery})
local isSailable
local function isConnected( startNode, endNode )
local ix, iy, fx, fy = startNode.x, startNode.y, endNode.x, endNode.y
if fx < -180 then fx = fx + 180 end
if fx > 180 then fx = fx - 180 end
local dx, dy = fx - ix, fy - iy
local mag = math.sqrt( dx * dx + dy * dy )
local n = 2 * math.floor( mag )
dx, dy = 0.5 * dx / mag, 0.5 * dy / mag
for i = 1, n do
ix, iy = ix + dx, iy + dy
if not( isSailable( ix, -iy ) ) then return nil end
end
return true
end
function t.selectNearest( nodes, x, y )
return (nodes.nodes):getClosestPoint( x, y )
end
local travelNode = {}
local mtTravelNode = { __index = travelNode }
function travelNode:formatDisplayInfo()
return ([[ TRAVEL NODE: %d
LONGITUDE: %3.2f
LATITUDE: %3.2f]]):format( self.idx, self.x, self.y )
end
function t.load( filename, sailable )
isSailable = sailable
local img, imgd = bmp.load( filename )
local nodes = { visible = true, nodes = {}, points = {}, connections = {}, img = img }
print( "=== Loading Nodes: ===" )
local n = 1
for x = 0, 799 do
for y = 0, 399 do
if imgd:getPixel( x, 399 - y ) > 0 then
local long = 360 * ( x - 800 ) / 800 - 360 / 2 + 360
local lat = 360 * ( 600 / 800 ) * ( 600 - y ) / 600 - 180
nodes.nodes[n] = setmetatable({x = long, y = -lat, idx = n}, mtTravelNode )
print( nodes.nodes[n]:formatDisplayInfo() )
nodes.points[ 2 * n - 1 ] = long
nodes.points[ 2 * n ] = lat
n = n + 1
end
end
end
for i, srcNode in ipairs( nodes.nodes ) do
local adjacent = {}
for j, destNode in ipairs( nodes.nodes ) do
adjacent[j] = isConnected( srcNode, destNode )
end
nodes.connections[i] = adjacent
end
print( "=== Nodes Loaded ===" )
nodes.nodes = locationQuery.New( nodes.nodes )
setmetatable( nodes, {__index = t} )
return nodes
end
--Determine if graph has more than one connected component.
function t.isConnected( nodes )
end
function t.draw( nodes )
lg.setPointSize( 8 )
lg.setColor( 1, 1, 1, 0.5 )
lg.points( nodes.points )
return t.drawConnections( nodes )
end
function t.drawConnections( nodes )
for i, connection in pairs( nodes.connections ) do
for j in pairs( connection ) do
local ix, iy, fx, fy = nodes.nodes[i].x, nodes.nodes[i].y, nodes.nodes[j].x, nodes.nodes[j].y
lg.line( ix, -iy, fx, -fy )
end
end
end
function t.save( nodes, filename )
end
return t