Code: Select all
o = {} -- table with our buttons
-- fragment shader, only non-transparent pixels are allowed in the stencil
mask_effect = love.graphics.newShader [[ vec4 effect (vec4 color, Image texture, vec2 texture_coords, vec2 screen_coords) {if(Texel(texture, texture_coords).a == vec3(0.0)) discard; return vec4(1.0);} ]]
function love.load()
button = love.graphics.newImage("button.png") -- button image with transparency
-- creating several buttons, random coords, width & height equal to button image size
for i = 1, 5 do
o[i] = {}
o[i].x = love.math.random(100, 800)
o[i].y = love.math.random(100, 600)
o[i].image = button
o[i].w = o[i].image:getWidth()
o[i].h = o[i].image:getHeight()
end
-- preparing canvas (to getPixel(x,y) later)
offw, offh = love.window.getDesktopDimensions()
pickbuf = love.graphics.newCanvas(offw, offh)
end
-- stencil function, we must draw all our buttons in the loop
function stencil()
love.graphics.setShader(mask_effect)
love.graphics.setColor(255, 255, 255, 255)
love.graphics.setScissor(mx - 4, my - 4, 8, 8)
for k, v in ipairs(o) do
love.graphics.draw(v.image, v.x, v.y)
end
love.graphics.setScissor(0, 0, offw, offh)
love.graphics.setShader()
end
-- now we draw our buttons as a simple rectangles, setting next color in each iteration
-- from color(0,0,1) to (255,255,255)
function pickrender()
love.graphics.clear()
love.graphics.setStencil(stencil)
love.graphics.setScissor(mx - 4, my - 4, 8, 8)
for k, v in ipairs(o) do
love.graphics.setColor(math.floor(k / 2 ^ 16), math.floor(k / 2 ^ 8) % 2 ^ 8, k % 2 ^ 8, 255)
love.graphics.rectangle("fill", v.x, v.y, v.w, v.h)
end
love.graphics.setScissor(0, 0, offw, offh)
end
-- here we get pixel color under cursor and convert it into object's id
function pick()
mx, my = love.mouse.getPosition()
love.graphics.setScissor(mx - 4, my - 4, 8, 8)
pickbuf:renderTo(pickrender)
mr, mg, mb = pickbuf:getPixel(mx, my)
curr = mb + mg * 255 + mr * 65535
love.graphics.setScissor(0, 0, offw, offh)
end
function love.draw()
pick() -- do we have button under cursor?
love.graphics.setColor(255, 255, 255, 255)
-- draw buttons normally
for _, v in ipairs(o) do
love.graphics.draw(v.image, v.x, v.y)
end
-- here goes something if we have button under cursor
if curr ~= 0 then
love.graphics.setColor(128, 0, 0, 128)
love.graphics.draw(button, o[curr].x, o[curr].y)
end
end
function love.keypressed(key, isRepeat)
if key == "escape" then
love.event.quit()
end
end