dcearth/locationQuery.lua

62 lines
1.3 KiB
Lua

--Shitty acceleration structure: get closest point in set.
--Assumed to be in world coordinates: ( -180, 180 ) x ( -100, 100 )
local t = {}
local hashes = {}
local math = math
local hash = function( x, y, debug )
local s = "h"..("%2d%2d"):format(math.floor( 0.5 + (180 + x) / 10 ), math.floor( 0.5 + (100 + y) / 10 ) )
return s
end
function t.getClosestPoint( points, x, y )
local closePoints = hashes[hash( x, y )]
if not closePoints then return end
local distance = math.huge
local px, py, point
for k, v in pairs(closePoints) do
px, py = v.x, v.y
local d = (x - px) * (x - px) + (y - py) * (y - py)
if d < distance then
distance = d
point = v
end
end
return point
end
function t.Edit( points, point, x, y )
local h = hashes[hash( point.x, point.y )]
if h then
for i, p in pairs(h) do
if p == point then
table.remove( h, i )
break
end
end
end
table.insert( hashes[ hash( x, y ) ], point )
point.x = x
point.y = y
end
function t.Add( points, x, y )
end
function t.New( points )
for i = 1, #points do
local x, y = points[i].x, points[i].y
local h = hash( x, y )
hashes[h] = hashes[h] or {}
hashes[h][#hashes[h] + 1] = points[i]
end
return setmetatable( points, {__index = t } )
end
return t