shader example

Here’s a shader example that’s based on some code in a discussion started by @ellie_ff1493. Slide your finger right or left to change the value that controls how the circles interact.

displayMode(FULLSCREEN)

function setup()
    value=.002
    vel={}
    circles={}
    for z=1,6 do
        table.insert(vel,vec2(math.random()/300,math.random()/200))
        table.insert(circles,vec2(math.random(),math.random()))
    end
    m=mesh()
    m.shader=shader(sh.v,sh.f)
    m:addRect(WIDTH/2,HEIGHT/2,WIDTH,HEIGHT)
end

function draw()
    background(0)
    m.shader.circles=circles
    m.shader.value=value
    m:draw()
    for a,b in pairs(circles) do
        b.x=b.x+vel[a].x
        b.y=b.y+vel[a].y
        if b.x>=1 or b.x<=0 then
            vel[a].x=vel[a].x*-1           
        end
        if b.y>=1 or b.y<=0 then
            vel[a].y=vel[a].y*-1           
        end
    end
    fill(255, 248, 0, 255)
    rect(WIDTH/2-40,HEIGHT-60,80,20)
    fill(255,0,0)
    text(string.format("%.4f",value),WIDTH/2,HEIGHT-50)
    text("Slide your finger right or left to change the value",WIDTH/2,HEIGHT-25)
end

function touched(t)
    value=value+t.deltaX/100000
    value=math.max(.002,math.min(.05,value))
end

sh ={   v=[[    
    uniform mat4 modelViewProjection;
    varying highp vec2 vTexCoord;
    attribute vec4 position;
    attribute vec2 texCoord;
    void main()
    {   vTexCoord = texCoord;
        gl_Position = modelViewProjection * position;
    }
    ]], 

    f=[[   
    precision highp float;
    uniform vec2 circles[6];
    uniform float value;
    varying highp vec2 vTexCoord;        
    void main()
    {   float col = 0.;
        for (int z=0; z<6; z++)
              col = col + .001 + value / distance(vTexCoord,circles[z]);
        if (col>.84)
            gl_FragColor=vec4(1,1,1,1);
        else if (col>.72) 
            gl_FragColor=vec4(1,1,0,1);
        else if (col>.60)
            gl_FragColor=vec4(1,0,1,1);
        else if (col>.48)
            gl_FragColor=vec4(1,0,0,1);
        else if (col>.36)
            gl_FragColor=vec4(0,1,1,1);
        else if (col>.24)
            gl_FragColor=vec4(0,1,0,1);
        else if (col>.12)
            gl_FragColor=vec4(0,0,1,1);
        else
            gl_FragColor=vec4(0,0,0,1);    
    }
    ]]
}

Very cool

That is so cool!

Forking grate.

I never did finish my project because of constant crashes.
Any tips on not writing code that crashes?

@ellie_ff1493 I normally write code in small chunks and keep increasing it’s size until I get what I want. I might not start with exactly what I’m after, but something similar just to get it working. If you post the code that crashes and what you’re trying to do, maybe we can get it working.