_James

Node Finder

May 12th, 2019
1,086
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.43 KB | None | 1 0
  1. local class = {}
  2. class.threshold = 200 -- Determines when the program decides to stop cutting tables in half.
  3. class.axis = { -- Me being lazy.
  4.     "X"; "Z"
  5. }
  6.  
  7. function class.new(list)
  8.     local self = {}
  9.     setmetatable(self, {__index = class})
  10.    
  11.     self.list = list
  12.    
  13.     return self
  14. end
  15.  
  16. function class:get_axis(depth)
  17.     return self.axis[depth%2+1]
  18. end
  19.  
  20. function class:bake()
  21.     -- Processes the map and breaks it down to be used by get_scope.
  22.     self.system = self:bisect(self.list, 1)
  23. end
  24.  
  25. function class:get_scope(coord)
  26.     local scope = self.system
  27.     repeat
  28.         if coord[scope.axis] > scope.center then
  29.             scope = scope[1]
  30.         else
  31.             scope = scope[2]
  32.         end
  33.     until not scope.axis
  34.     return scope
  35. end
  36.  
  37. function class:bisect(list, depth)
  38.     if #list <= self.threshold then
  39.         return list
  40.     end
  41.     local axis = self:get_axis(depth)
  42.     table.sort(list, function(a, b)
  43.         return a.Position[axis] > b.Position[axis]
  44.     end)
  45.    
  46.     local size = #list
  47.     local half = size / 2
  48.     local i1 = list[1].Position[axis]
  49.     local i2 = list[size].Position[axis]
  50.     local center = (i1 + i2) / 2
  51.    
  52.     local output = {}
  53.     output.axis = axis
  54.     output.center = center
  55.     output[1] = {}
  56.     output[2] = {}
  57.    
  58.     for i,node in ipairs(list)do
  59.         if i <= half then
  60.             table.insert(output[1], node)
  61.         else
  62.             table.insert(output[2], node)
  63.         end
  64.     end
  65.     output[1] = self:bisect(output[1], depth + 1)
  66.     output[2] = self:bisect(output[2], depth + 1)
  67.    
  68.     return output
  69. end
  70.  
  71. return class
Advertisement
Add Comment
Please, Sign In to add comment