Sulunia wrote: ↑Wed Nov 01, 2017 10:42 pm
How can I get the color of a given pixel in a texture sent to the shader?
Suppose I send a drawn canvas to the shader. How can I get the color of a certain pixel on this canvas?
The Texel function fetches pixels from textures. Texel() expects texture coordinates though, so to address a certain pixel, you have to divide the pixel coordinates by the size of the canvas.
Code: Select all
extern Image canvas;
extern vec2 certainPixel;
vec4 effect(...) {
vec4 pixel = Texel(canvas, certainPixel);
...
}
On the Lua side, you send the required values to the shader:
Code: Select all
shader:send("canvas", canvas)
shader:send("certainPixel", { pixelX / canvas:getWidth(), pixelY / canvas:getHeight() })
For accurate results, you need to specify coordinates at the center of a pixel instead of the upper left corner. To accurately sample the pixel at 100, 100 you have to send 100.5, 100.5 to the shader.
Is there any way to see values that are calculated inside the shader code?
That's a funny question, because seeing the values that a shader calculated is
kind of the point of using a shader in the first place. So yes, there is way to see the values: you enable the shader and draw something on the screen. Like, a rectangle.
Example code that fills the screen with the color from a pixel on a canvas:
Code: Select all
local canvas = love.graphics.newCanvas(128, 128)
local certainPixel = { 32.5, 32.5 }
canvas:renderTo(function()
love.graphics.setColor(255, 0, 0)
love.graphics.points(certainPixel)
end)
local shader = love.graphics.newShader([[
extern Image canvas;
extern vec2 certainPixel;
vec4 effect(vec4 color, Image texture, vec2 uv, vec2 fc) {
return Texel(canvas, certainPixel);
}
]])
shader:send("canvas", canvas)
shader:send("certainPixel", { certainPixel[1] / canvas:getWidth(), certainPixel[2] / canvas:getHeight() })
love.graphics.setShader(shader)
function love.draw()
love.graphics.setColor(255, 255, 255)
love.graphics.rectangle("fill", 0, 0, love.graphics.getDimensions())
end