Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --# Main
- -- Use this function to perform your initial setup
- function setup()
- noSmooth()
- noFill()
- strokeWidth(1)
- -- set quadtree depth (number of subdivisions)
- depth = 4
- size = 512
- map = Quadtree(0, 0, size, size, depth)
- ratio = WIDTH/size
- touches = {}
- fill(255, 255, 255, 255)
- print("Quadtree loaded...")
- end
- -- This function gets called once every frame
- function draw()
- background(0, 0, 0, 255)
- text("Touch anywhere on screen", WIDTH/2, HEIGHT-10)
- -- scale to screen width
- scale(ratio)
- -- draw for every touch
- for k,touch in pairs(touches) do
- map:draw(touch.x/ratio, touch.y/ratio, depth)
- end
- end
- function touched(touch)
- if touch.state == ENDED then
- touches[touch.id] = nil
- else
- touches[touch.id] = touch
- end
- end
- --# Quadtree
- Quadtree = class()
- function Quadtree:init(xmin, ymin, xmax, ymax, d)
- self.xmin = xmin
- self.xmax = xmax
- self.ymin = ymin
- self.ymax = ymax
- self.children = {}
- self.chunk = mesh()
- -- generate texture
- local w = self.xmax - self.xmin
- local h = self.ymax - self.ymin
- local x = self.xmin + w/2
- local y = self.ymin + w/2
- local t = image(w, h)
- setContext(t)
- stroke(255, 255, 255, 255)
- rect(0, 0, w, h)
- self.chunk.texture = t
- self.chunk:addRect(x, y, w, h)
- -- Subdivide until desired depth is reached
- if d > 0 then
- d = d - 1
- self.chunk:setColors(255, 0, 0, 255)
- local xmoy = (xmin + xmax)/2
- local ymoy = (ymin + ymax)/2
- self.children[1] = Quadtree(xmin, ymin, xmoy, ymoy, d)
- self.children[2] = Quadtree(xmin, ymoy, xmoy, ymax, d)
- self.children[3] = Quadtree(xmoy, ymoy, xmax, ymax, d)
- self.children[4] = Quadtree(xmoy, ymin, xmax, ymoy, d)
- else
- self.chunk:setColors(0, 0, 255, 255)
- end
- end
- function Quadtree:draw(x, y, d)
- -- Draw child if the "touch" is inside its bounds
- if x>=self.xmin and x<=self.xmax and y>=self.ymin and y<=self.ymax then
- if d > 0 then
- self.chunk:draw()
- d = d - 1
- self.children[1]:draw(x, y, d)
- self.children[2]:draw(x, y, d)
- self.children[3]:draw(x, y, d)
- self.children[4]:draw(x, y, d)
- else
- self.chunk:draw()
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement