Why isn't this shadertoy displaying correctly in glsl? - glsl

I'm working on porting this shader from shadertoy into glsl for a GPUImage based iOS platform.
https://www.shadertoy.com/view/4s2yW1
technically, it's running on the device effectively. However, it's only displaying the background, and not the circles, which is the whole point.
I'm wondering if someone can give me some clue as to why this isn't showing up properly. For whatever reason I'm getting the same results when using shaderfrog.
Here's the shaderfrog link:
http://shaderfrog.com/app/view/1463
and the code itself:
#define PI 3.14159265359
NSString *const kGPUImageBokehFragmentShaderString = SHADER_STRING
(
precision highp float;
varying highp vec2 textureCoordinate;
uniform sampler2D inputImageTexture;
uniform highp float time;
void Rotate( vec2 p, float a )
{
p = cos( a ) * p + sin( a ) * vec2( p.y, -p.x );
}
float Circle( vec2 p, float r )
{
return ( length( p / r ) - 1.0 ) * r;
}
float Rand( vec2 c )
{
return fract( sin( dot( c.xy, vec2( 12.9898, 78.233 ) ) ) * 43758.5453 );
}
float saturate( float x )
{
return clamp( x, 0.0, 1.0 );
}
void BokehLayer(vec3 color, vec2 p, vec3 c )
{
float wrap = 450.0;
if ( mod( floor( p.y / wrap + 0.5 ), 2.0 ) == 0.0 )
{
p.x += wrap * 0.5;
}
vec2 p2 = mod( p + 0.5 * wrap, wrap ) - 0.5 * wrap;
vec2 cell = floor( p / wrap + 0.5 );
float cellR = Rand( cell );
c *= fract( cellR * 3.33 + 3.33 );
float radius = mix( 30.0, 70.0, fract( cellR * 7.77 + 7.77 ) );
p2.x *= mix( 0.9, 1.1, fract( cellR * 11.13 + 11.13 ) );
p2.y *= mix( 0.9, 1.1, fract( cellR * 17.17 + 17.17 ) );
float sdf = Circle( p2, radius );
float circle = 1.0 - smoothstep( 0.0, 1.0, sdf * 0.04 );
float glow = exp( -sdf * 0.025 ) * 0.3 * ( 1.0 - circle );
color += c * ( circle + glow );
}
void main()
{
vec2 iResolution = vec2(1., 1.);
vec2 uv = textureCoordinate.xy/iResolution.xy;
vec2 p = ( 2.0 * textureCoordinate - iResolution.xy) / iResolution.x * 1000.0;
// background
vec3 color = mix( vec3( 0.3, 0.1, 0.3 ), vec3( 0.1, 0.4, 0.5 ), dot( uv, vec2( 0.2, 0.7 ) ) );
float timeElapsed = time - 15.0;
Rotate( p, 0.2 + timeElapsed * 0.03 );
BokehLayer( color, p + vec2( -50.0 * timeElapsed + 0.0, 0.0 ), 3.0 * vec3( 0.4, 0.1, 0.2 ) );
Rotate( p, 0.3 - timeElapsed * 0.05 );
BokehLayer( color, p + vec2( -70.0 * timeElapsed + 33.0, -33.0 ), 3.5 * vec3( 0.6, 0.4, 0.2 ) );
Rotate( p, 0.5 + timeElapsed * 0.07 );
BokehLayer( color, p + vec2( -60.0 * timeElapsed + 55.0, 55.0 ), 3.0 * vec3( 0.4, 0.3, 0.2 ) );
Rotate( p, 0.9 - timeElapsed * 0.03 );
BokehLayer( color, p + vec2( -25.0 * timeElapsed + 77.0, 77.0 ), 3.0 * vec3( 0.4, 0.2, 0.1 ) );
Rotate( p, 0.0 + timeElapsed * 0.05 );
BokehLayer( color, p + vec2( -15.0 * timeElapsed + 99.0, 99.0 ), 3.0 * vec3( 0.2, 0.0, 0.4 ) );
vec4 bokehColor = vec4( color, 1.0 );
gl_FragColor = bokehColor;
} );
Anything you can tell me about this would be greatly appreciated. Thanks!

The problem is you don't have color marked as inout
void BokehLayer(vec3 color, vec2 p, vec3 c ) // bad
void BokehLayer(inout vec3 color, vec2 p, vec3 c ) // good
BokehLayer wants to modify color but without the inout keyword it's just a parameter to the function. With inout it's a reference original variable.

Related

Problem going from Shadershop functions to glsl functions

It's a bit related to how to convert shadershop formula into glsl .
Only the above answer does not provide any explanation.
What I try is:
Where SineV is:
and SineH is:
This is what I have so far:
#ifdef GL_ES
precision mediump float;
#endif
float scale = 5.0;
uniform vec2 u_resolution;
float sineV(float x) {
x *= scale;
return (sin( x / 0.18 ) + sin( (x - -1.0) / 0.35 ) + 0.25);
}
float sineH(float x) {
x *= scale;
return (sin( (x - 0.18) / 0.37 ) + sin( ((x - 0.18) - -0.31) / 0.45 ) + -0.59) * 0.75 + 0.1;
}
mat2 inverse(mat2 m) {
float det_m = m[0][0]*m[1][1] - m[0][1]*m[1][0];
mat2 inv_m = mat2(m[1][1], -m[0][1], -m[1][0], m[0][0]) / det_m;
return inv_m;
}
void main() {
mat2 m = mat2(0.0, -1.0,
1.0, 0.0);
vec2 st = gl_FragCoord.xy / u_resolution.xy;
float x1 = st.x;
float x2 = st.y;
vec2 x1x2 = inverse(m) * vec2(x1, x2);
vec2 tmp = m * x1x2;
float x = sineV(x1x2.x - x1x2.y) + sineH(tmp.x - tmp.y);
vec3 color = vec3( x, x, abs(x) );
gl_FragColor = vec4(color, 1.0);
}
But I reached a point where it is just guessing and trial and error.
Hope someone can help.
The matrix in shadershop transforms the input tuple (x1, x2) to (u, v) coordinates.
The fragment shader is executed for each fragment, each fragment is associated to different (u, v) coordinates. You've to calculate the x1 and x2 corresponding to the actual (u, v) coordinate of the fragment. So you've to use the inverse matrix:
(u, v) = m * (x1, x2)
(x1, x2 = inverse(m) * (u, v)
The shader has to sum up result of the f(x1) and the result of the f(x2):
x = f(x1) + f(x2)
The corresponding glsl code is:
vec2 x1x2 = inverse(m) * st.xy;
float x = sineH(x1x2.x) + sineV(x1x2.y);
The mapping of x to the white, blue and black color can be achieved by the empirical formula (I found this out by trial and error):
vec3 color = vec3(x, x, abs(x));
For the full shader code see the example (note, the result is stretched to the canvas):
(function loadscene() {
var canvas, gl, vp_size, prog, bufObj = {};
function initScene() {
canvas = document.getElementById( "ogl-canvas");
gl = canvas.getContext( "experimental-webgl" );
if ( !gl )
return;
progDraw = gl.createProgram();
for (let i = 0; i < 2; ++i) {
let source = document.getElementById(i==0 ? "draw-shader-vs" : "draw-shader-fs").text;
let shaderObj = gl.createShader(i==0 ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
gl.shaderSource(shaderObj, source);
gl.compileShader(shaderObj);
let status = gl.getShaderParameter(shaderObj, gl.COMPILE_STATUS);
if (!status) alert(gl.getShaderInfoLog(shaderObj));
gl.attachShader(progDraw, shaderObj);
gl.linkProgram(progDraw);
}
status = gl.getProgramParameter(progDraw, gl.LINK_STATUS);
if ( !status ) alert(gl.getProgramInfoLog(progDraw));
progDraw.inPos = gl.getAttribLocation(progDraw, "inPos");
progDraw.u_resolution = gl.getUniformLocation(progDraw, "u_resolution");
gl.useProgram(progDraw);
var pos = [ -1, -1, 1, -1, 1, 1, -1, 1 ];
var inx = [ 0, 1, 2, 0, 2, 3 ];
bufObj.pos = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, bufObj.pos );
gl.bufferData( gl.ARRAY_BUFFER, new Float32Array( pos ), gl.STATIC_DRAW );
bufObj.inx = gl.createBuffer();
bufObj.inx.len = inx.length;
gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, bufObj.inx );
gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, new Uint16Array( inx ), gl.STATIC_DRAW );
gl.enableVertexAttribArray( progDraw.inPos );
gl.vertexAttribPointer( progDraw.inPos, 2, gl.FLOAT, false, 0, 0 );
gl.enable( gl.DEPTH_TEST );
gl.clearColor( 0.0, 0.0, 0.0, 1.0 );
window.onresize = resize;
resize();
requestAnimationFrame(render);
}
function resize() {
vp_size = [window.innerWidth, window.innerHeight];
//vp_size = [256, 256]
canvas.width = vp_size[0];
canvas.height = vp_size[1];
}
function render(deltaMS) {
gl.viewport( 0, 0, canvas.width, canvas.height );
gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT );
gl.uniform2f(progDraw.u_resolution, canvas.width, canvas.height);
gl.drawElements( gl.TRIANGLES, bufObj.inx.len, gl.UNSIGNED_SHORT, 0 );
requestAnimationFrame(render);
}
initScene();
})();
<script id="draw-shader-vs" type="x-shader/x-vertex">
precision mediump float;
attribute vec2 inPos;
varying vec2 ndcPos;
void main()
{
gl_Position = vec4( inPos.xy, 0.0, 1.0 );
}
</script>
<script id="draw-shader-fs" type="x-shader/x-fragment">
precision mediump float;
uniform vec2 u_resolution;
float scale = 5.0;
float sineV(float x) {
x *= scale;
return (sin( x / 0.18 ) + sin( (x - -1.0) / 0.35 ) + 0.25);
}
float sineH(float x) {
x *= scale;
return (sin( (x - 0.18) / 0.37 ) + sin( ((x - 0.18) - -0.31) / 0.45 ) + -0.59) * 0.75 + 0.1;
}
mat2 inverse(mat2 m) {
float det_m = m[0][0]*m[1][1] - m[0][1]*m[1][0];
mat2 inv_m = mat2(m[1][1], -m[0][1], -m[1][0], m[0][0]) / det_m;
return inv_m;
}
void main()
{
vec2 st = 2.0 * gl_FragCoord.xy / u_resolution.xy - 1.0;
mat2 m = mat2(0.0, -1.0, 1.0, 0.0);
vec2 x1x2 = inverse(m) * st.xy;
float x = sineH(x1x2.x) + sineV(x1x2.y);
vec3 color = vec3(x, x, abs(x));
gl_FragColor = vec4(color, 1.0);
}
</script>
<canvas id="ogl-canvas" style="border: none"></canvas>

Implementing RayPicking in a Fragment Shader

I am having trouble implementing RayPicking in a Fragment-Shader, I understand I must start from my mouse coordinates, but I am not sure what to multiply my origin with.
I have tried creating a 3 component vector, with x and y as my mouse coordinates divided by my resolution, and in z I have tried using my p(for point in space, calculated as rayOrigin + rayDirection * t) with no luck.
Here is a Shadertoy that tries what I am looking for.
float ray( vec3 ro, vec3 rd, out float d )
{
float t = 0.0; d = 0.0;
for( int i = 0; i < STEPS; ++i )
{
vec3 p = ro + rd * t;
d = map( p );
if( d < EPS || t > FAR ) break;
t += d;
}
return t;
}
vec3 shad( vec3 ro, vec3 rd, vec2 uv )
{
float t = 0.0, d = 0.0;
t = ray( ro, rd, d );
float x = ( 2.0 * iMouse.x ) / iResolution.x - 1.0;
float y = 1.0 - ( 2.0 * iMouse.y ) / iResolution.y;
float z = 1.0;
vec3 p = ro + rd * t;
vec3 n = nor( p );
vec3 lig = ( vec3( x, -y, z ) );
lig += ro + rd;
lig = normalize( lig );
vec3 ref = reflect( rd, n );
float amb = 0.5 + 0.5 * n.y;
float dif = max( 0.0, dot( n, lig ) );
float spe = pow( clamp( dot( ref, lig ), 0.0, 1.0 ), 16.0 );
vec3 col = vec3( 0 );
col += 0.1 * amb;
col += 0.2 * dif;
col += spe;
return col;
}
I expect to get a light that moves as if I was shooting a ray from my mouse coordinates to the SDF.
This is the correct code:
// Our sphere-tracing algorithm.
float ray( vec3 ro, vec3 rd, out float d )
{
float t = 0.0; d = 0.0;
for( int i = 0; i < STEPS; ++i )
{
vec3 p = ro + rd * t;
d = map( p );
if( d < EPS || t > FAR ) break;
t += d;
}
return t;
}
// Here we compute all our lighting calculations.
vec3 shad( vec3 ro, vec3 rd, vec2 uv )
{
float t = 0.0, d = 0.0;
t = ray( ro, rd, d );
vec3 p = ro + rd * t;
vec3 n = nor( p );
// The values of the variable lig are not random they are in the same position as our rayOrigin for our sphere tracing algo, that goes in main's body.
vec3 lig = ( vec3( 0, 0, 2 ) );
// Here is where we "shoot" our ray from the mouse position. Our ray's origin.
vec2 uvl = ( -iResolution.xy + 2.0 * iMouse.xy ) / iResolution.y;
// This is our ray's direction.
vec3 lir = normalize( vec3( uvl, -1 ) );
// Here we get our SDF(dO) and our incrementing value(tO).
float dO = 0.0, tO = ray( lig, lir, dO );
// Now we update our vector with the direction and incrementing steps.
lig += lir * tO;
// We must normalize lights as they are just a direction, the magnitude screws the lighting calculations.
lig = normalize( lig );
vec3 ref = reflect( rd, n );
float amb = 0.5 + 0.5 * n.y;
float dif = max( 0.0, dot( n, lig ) );
float spe = pow( clamp( dot( ref, lig ), 0.0, 1.0 ), 16.0 );
vec3 col = vec3( 0 );
col += 0.1 * amb;
col += 0.2 * dif;
col += spe;
return col;
}
// Last step, here we create the origin and direction of our rays that we shoot against the SDF.
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
//Normalize the coordinates.
vec2 uv = ( -iResolution.xy + 2.0 * fragCoord.xy ) / iResolution.y;
// This is our ray's origin. We must use the same values for our lig's origin.
vec3 ro = vec3( 0, 0, 2 );
// This is our ray's direction.
vec3 rd = normalize( vec3( uv, -1 ) );
// Our SDF(d) and our incrementing steps(t), we only need our SDF(d) to bail the shading calculations according to our epsilon(EPS).
float t = 0.0, d = 0.0;
t = ray( ro, rd, d );
vec3 col = d < EPS ? shad( ro, rd, uv ) : vec3( 0 );
fragColor = vec4( col, 1 );
}

What causes this sort of tearing at the edges?

What causes this kind of tearing in GLSL? I noticed the same kind of thing going on at the teamLab art exhibit in Tokyo. Notice the imperfections in the edges.
Here is my fragment shader:
#version 300 es
precision highp float;
precision highp int;
uniform float time;
in vec2 v_pos;
out vec4 FragColor;
vec4 measureFloat(float measure_number_float){
return vec4(
float( mod ( measure_number_float, 60.0 ) ) / 60.0,
float( mod ( measure_number_float, 3600.0 ) ) / (60.0 * 60.0),
float( mod ( measure_number_float, 216000.0 ) ) / (60.0 * 60.0 * 60.0),
1.0
);
}
vec4 measureInt( int measure_number_int ){
return vec4(
float( measure_number_int % 60 ) / 60.0,
float( measure_number_int % 3600 ) / (60.0 * 60.0),
float( measure_number_int % 216000 ) / (60.0 * 60.0 * 60.0),
1.0
);
}
vec4 sampleColor(){
int x_coord_i, y_coord_i = 0;
float x_coord_f, y_coord_f = 0.0;
float res_mul_x_f = 20.0; // mul = multiplier
float res_mul_y_f = 20.0; // mul = multiplier
x_coord_i = int(v_pos.x * res_mul_x_f);
y_coord_i = int(v_pos.y * res_mul_y_f);
// return back to float:
x_coord_f = float(x_coord_i) / res_mul_x_f;
y_coord_f = float(y_coord_i) / res_mul_y_f;
int cell_number = y_coord_i * int(res_mul_x_f) + x_coord_i;
// return measureInt(cell_number);
return measureFloat(float(cell_number));
}
void main(void) {
FragColor = sampleColor();
}
This bug was present in both Chrome and Firefox, using both the measureInt function and the measureFloat function. I also don't know what to call this, so if there is a technical name for it, please do inform.

GLSL - Gaussian Blur Artifact Issue

First of all, due to requirements constraints, I am working in OpenGL v. 2.1, and GLSL 120. I have implemented a simple fragment shader that applies a two pass (horizontal & vertical) Gaussian blur with n-kernel weights obtained from Pascal's Triangle. For the image below, I have decided to use a kernel size of 32, just for funsies:
As observed, the edges of the filtered blob seems to have some strange artifacts, as well as a ringing effect on its edges. For reference, here's how I am applying the blur:
if(isHorizontal)
{
result += texture2D(tex, vec2( curFrag.x - 14.0 * xOff, curFrag.y )).rgba * 0.000000115484001;
result += texture2D(tex, vec2( curFrag.x - 13.0 * xOff, curFrag.y )).rgba * 0.00000115484001;
result += texture2D(tex, vec2( curFrag.x - 12.0 * xOff, curFrag.y )).rgba * 0.000008372590071;
result += texture2D(tex, vec2( curFrag.x - 11.0 * xOff, curFrag.y )).rgba * 0.0000468865044;
result += texture2D(tex, vec2( curFrag.x - 10.0 * xOff, curFrag.y )).rgba * 0.0002109892698;
result += texture2D(tex, vec2( curFrag.x - 9.0 * xOff, curFrag.y )).rgba * 0.0007836744306;
result += texture2D(tex, vec2( curFrag.x - 8.0 * xOff, curFrag.y )).rgba * 0.002448982596;
result += texture2D(tex, vec2( curFrag.x - 7.0 * xOff, curFrag.y )).rgba * 0.006530620255;
result += texture2D(tex, vec2( curFrag.x - 6.0 * xOff, curFrag.y )).rgba * 0.01502042659;
result += texture2D(tex, vec2( curFrag.x - 5.0 * xOff, curFrag.y )).rgba * 0.03004085317;
result += texture2D(tex, vec2( curFrag.x - 4.0 * xOff, curFrag.y )).rgba * 0.05257149305;
result += texture2D(tex, vec2( curFrag.x - 3.0 * xOff, curFrag.y )).rgba * 0.08087922008;
result += texture2D(tex, vec2( curFrag.x - 2.0 * xOff, curFrag.y )).rgba * 0.1097646558;
result += texture2D(tex, vec2( curFrag.x - 1.0 * xOff, curFrag.y )).rgba * 0.131717587;
result += texture2D(tex, curFrag).rgba * 0.1399499362;
result += texture2D(tex, vec2( curFrag.x + 1.0 * xOff, curFrag.y )).rgba * 0.131717587;
result += texture2D(tex, vec2( curFrag.x + 2.0 * xOff, curFrag.y )).rgba * 0.1097646558;
result += texture2D(tex, vec2( curFrag.x + 3.0 * xOff, curFrag.y )).rgba * 0.08087922008;
result += texture2D(tex, vec2( curFrag.x + 4.0 * xOff, curFrag.y )).rgba * 0.05257149305;
result += texture2D(tex, vec2( curFrag.x + 5.0 * xOff, curFrag.y )).rgba * 0.03004085317;
result += texture2D(tex, vec2( curFrag.x + 6.0 * xOff, curFrag.y )).rgba * 0.01502042659;
result += texture2D(tex, vec2( curFrag.x + 7.0 * xOff, curFrag.y )).rgba * 0.006530620255;
result += texture2D(tex, vec2( curFrag.x + 8.0 * xOff, curFrag.y )).rgba * 0.002448982596;
result += texture2D(tex, vec2( curFrag.x + 9.0 * xOff, curFrag.y )).rgba * 0.0007836744306;
result += texture2D(tex, vec2( curFrag.x + 10.0 * xOff, curFrag.y )).rgba * 0.0002109892698;
result += texture2D(tex, vec2( curFrag.x + 11.0 * xOff, curFrag.y )).rgba * 0.0000468865044;
result += texture2D(tex, vec2( curFrag.x + 12.0 * xOff, curFrag.y )).rgba * 0.000008372590071;
result += texture2D(tex, vec2( curFrag.x + 13.0 * xOff, curFrag.y )).rgba * 0.00000115484001;
result += texture2D(tex, vec2( curFrag.x + 14.0 * xOff, curFrag.y )).rgba * 0.000000115484001;
}
else
{
result += texture2D(tex, vec2( curFrag.x, curFrag.y - 14.0 * yOff )).rgba * 0.000000115484001;
result += texture2D(tex, vec2( curFrag.x, curFrag.y - 13.0 * yOff )).rgba * 0.00000115484001;
result += texture2D(tex, vec2( curFrag.x, curFrag.y - 12.0 * yOff )).rgba * 0.000008372590071;
result += texture2D(tex, vec2( curFrag.x, curFrag.y - 11.0 * yOff )).rgba * 0.0000468865044;
result += texture2D(tex, vec2( curFrag.x, curFrag.y - 10.0 * yOff )).rgba * 0.0002109892698;
result += texture2D(tex, vec2( curFrag.x, curFrag.y - 9.0 * yOff )).rgba * 0.0007836744306;
result += texture2D(tex, vec2( curFrag.x, curFrag.y - 8.0 * yOff )).rgba * 0.002448982596;
result += texture2D(tex, vec2( curFrag.x, curFrag.y - 7.0 * yOff )).rgba * 0.006530620255;
result += texture2D(tex, vec2( curFrag.x, curFrag.y - 6.0 * yOff )).rgba * 0.01502042659;
result += texture2D(tex, vec2( curFrag.x, curFrag.y - 5.0 * yOff )).rgba * 0.03004085317;
result += texture2D(tex, vec2( curFrag.x, curFrag.y - 4.0 * yOff )).rgba * 0.05257149305;
result += texture2D(tex, vec2( curFrag.x, curFrag.y - 3.0 * yOff )).rgba * 0.08087922008;
result += texture2D(tex, vec2( curFrag.x, curFrag.y - 2.0 * yOff )).rgba * 0.1097646558;
result += texture2D(tex, vec2( curFrag.x, curFrag.y - 1.0 * yOff )).rgba * 0.131717587;
result += texture2D(tex, curFrag).rgba * 0.1399499362;
result += texture2D(tex, vec2( curFrag.x, curFrag.y + 1.0 * yOff )).rgba * 0.131717587;
result += texture2D(tex, vec2( curFrag.x, curFrag.y + 2.0 * yOff )).rgba * 0.1097646558;
result += texture2D(tex, vec2( curFrag.x, curFrag.y + 3.0 * yOff )).rgba * 0.08087922008;
result += texture2D(tex, vec2( curFrag.x, curFrag.y + 4.0 * yOff )).rgba * 0.05257149305;
result += texture2D(tex, vec2( curFrag.x, curFrag.y + 5.0 * yOff )).rgba * 0.03004085317;
result += texture2D(tex, vec2( curFrag.x, curFrag.y + 6.0 * yOff )).rgba * 0.01502042659;
result += texture2D(tex, vec2( curFrag.x, curFrag.y + 7.0 * yOff )).rgba * 0.006530620255;
result += texture2D(tex, vec2( curFrag.x, curFrag.y + 8.0 * yOff )).rgba * 0.002448982596;
result += texture2D(tex, vec2( curFrag.x, curFrag.y + 9.0 * yOff )).rgba * 0.0007836744306;
result += texture2D(tex, vec2( curFrag.x, curFrag.y + 10.0 * yOff )).rgba * 0.0002109892698;
result += texture2D(tex, vec2( curFrag.x, curFrag.y + 11.0 * yOff )).rgba * 0.0000468865044;
result += texture2D(tex, vec2( curFrag.x, curFrag.y + 12.0 * yOff )).rgba * 0.000008372590071;
result += texture2D(tex, vec2( curFrag.x, curFrag.y + 13.0 * yOff )).rgba * 0.00000115484001;
result += texture2D(tex, vec2( curFrag.x, curFrag.y + 14.0 * yOff )).rgba * 0.000000115484001;
}
Furthermore, I am using two framebuffers. First, I draw the white blob onto a texture bound to the first framebuffer, then I apply my blur shader onto the second framebuffer for a horizontal pass, then back to the first one for a vertical pass. I have implemented a slider that repeats this process as well, see snippet below:
glUseProgram(gauss_blur_frag);
glUniform1f(glGetUniformLocation(gauss_blur_frag, "offset"), (float)radius);
glUniform2f(glGetUniformLocation(gauss_blur_frag, "resolution"), (float)fboWidth, (float)fboHeight);
for(int i = 1; i < smoothAmount; i++)
{
glUniform1i(glGetUniformLocation(gauss_blur_frag, "isHorizontal"), true);
drawTexOnFBO(secondFBO, firstFBO->texId, bounds);
glUniform1i(glGetUniformLocation(gauss_blur_frag, "isHorizontal"), false);
drawTexOnFBO(firstFBO, secondFBO->texId, bounds);
}
The banding/ringing/artifacts get more pronounced as I increase the offset/radius of my blur, as well as increase the number of times the for-loop runs. The aim for this exercise is to simply apply a 'softening' effect on the edges of the blob, without the kernels being visible while being able to manipulate the offset. Can anyone shed some light on this issue? Thank you.
The banding/ringing/artifacts get more pronounced as I increase the offset/radius of my blur.
Of course. If you increase the radius, the you increase the distance between the sample points, but you don't increase the number of sample points itself.
This causes that there is a gap between to texels when you lookup the 32 samples and you don't consider the whole information of the source texture.
Note, for a large radius, 2 adjacent points in the target texture uses completely different texels from the source texture when be processed. This causes the banding and artefacts.
In common this effect can be decreased by using bilinear texture filtering (GL_LINEAR).
For a completely smooth and free of artefact blur effect, you have to increase the number of samples. But this will decrease the performance rapidly.
See also Fast Gaussian blur at pause.
See the example, where the effect can be reproduced with decreasing blur factor and increasing radius:
var readInput = true;
function changeEventHandler(event){
readInput = true;
}
(function loadscene() {
var resize, gl, progDraw, progBlur, vp_size, blurFB;
var bufCube = {};
var bufQuad = {};
var shininess = 10.0;
var glow = 10.0;
var sigma = 0.8;
var radius = 1.0;
function render(delteMS){
if ( readInput ) {
//readInput = false;
var sliderScale = 100;
sigma = document.getElementById( "sigma" ).value / sliderScale;
radius = document.getElementById( "radius" ).value / sliderScale;
}
Camera.create();
Camera.vp = vp_size;
gl.enable( gl.DEPTH_TEST );
gl.clearColor( 0.0, 0.0, 0.0, 1.0 );
gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT );
// set up framebuffer
gl.bindFramebuffer( gl.FRAMEBUFFER, blurFB[0] );
gl.viewport( 0, 0, blurFB[0].width, blurFB[0].height );
gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT );
// set up draw shader
ShaderProgram.Use( progDraw.prog );
ShaderProgram.SetUniformM44( progDraw.prog, "u_projectionMat44", Camera.Perspective() );
var viewMat = Camera.LookAt();
//viewMat = RotateAxis( viewMat, CalcAng( delteMS, 13.0 ), 0 );
//viewMat = RotateAxis( viewMat, CalcAng( delteMS, 17.0 ), 1 );
ShaderProgram.SetUniformM44( progDraw.prog, "u_modelViewMat44", viewMat );
ShaderProgram.SetUniformF1( progDraw.prog, "u_shininess", shininess );
// draw scene
VertexBuffer.Draw( bufCube );
// set blur-X framebuffer and bind frambuffer texture
gl.bindFramebuffer( gl.FRAMEBUFFER, blurFB[1] );
gl.viewport( 0, 0, blurFB[1].width, blurFB[1].height );
gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT );
var texUnit = 1;
gl.activeTexture( gl.TEXTURE0 + texUnit );
gl.bindTexture( gl.TEXTURE_2D, blurFB[0].color0_texture );
// set up blur-X shader
ShaderProgram.Use( progBlur.prog );
ShaderProgram.SetUniformI1( progBlur.prog, "u_texture", texUnit )
ShaderProgram.SetUniformF2( progBlur.prog, "u_textureSize", vp_size );
ShaderProgram.SetUniformF1( progBlur.prog, "u_sigma", sigma )
ShaderProgram.SetUniformF1( progBlur.prog, "u_radius", radius )
ShaderProgram.SetUniformF2( progBlur.prog, "u_dir", [1.0, 0.0] )
// draw full screen space
gl.enableVertexAttribArray( progBlur.inPos );
gl.bindBuffer( gl.ARRAY_BUFFER, bufQuad.pos );
gl.vertexAttribPointer( progBlur.inPos, 2, gl.FLOAT, false, 0, 0 );
gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, bufQuad.inx );
gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
gl.disableVertexAttribArray( progBlur.inPos );
// reset framebuffer and bind frambuffer texture
gl.bindFramebuffer( gl.FRAMEBUFFER, null );
gl.viewport( 0, 0, vp_size[0], vp_size[1] );
gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT );
texUnit = 2;
gl.activeTexture( gl.TEXTURE0 + texUnit );
gl.bindTexture( gl.TEXTURE_2D, blurFB[1].color0_texture );
// set up pst process shader
ShaderProgram.SetUniformI1( progBlur.prog, "u_texture", texUnit )
ShaderProgram.SetUniformF2( progBlur.prog, "u_dir", [0.0, 1.0] )
// draw full screen space
gl.enableVertexAttribArray( progBlur.inPos );
gl.bindBuffer( gl.ARRAY_BUFFER, bufQuad.pos );
gl.vertexAttribPointer( progBlur.inPos, 2, gl.FLOAT, false, 0, 0 );
gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, bufQuad.inx );
gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
gl.disableVertexAttribArray( progBlur.inPos );
requestAnimationFrame(render);
}
function resize() {
//vp_size = [gl.drawingBufferWidth, gl.drawingBufferHeight];
vp_size = [window.innerWidth, window.innerHeight]
//vp_size = [256, 256]
canvas.width = vp_size[0];
canvas.height = vp_size[1];
var fbsize = Math.max(vp_size[0], vp_size[1]);
fbsize = 1 << 31 - Math.clz32(fbsize); // nearest power of 2
blurFB = [];
for ( var i = 0; i < 2; ++ i ) {
fb = gl.createFramebuffer();
fb.width = fbsize;
fb.height = fbsize;
gl.bindFramebuffer( gl.FRAMEBUFFER, fb );
fb.color0_texture = gl.createTexture();
gl.bindTexture( gl.TEXTURE_2D, fb.color0_texture );
gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, fb.width, fb.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
fb.renderbuffer = gl.createRenderbuffer();
gl.bindRenderbuffer( gl.RENDERBUFFER, fb.renderbuffer );
gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, fb.width, fb.height );
gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, fb.color0_texture, 0 );
gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, fb.renderbuffer );
gl.bindTexture( gl.TEXTURE_2D, null );
gl.bindRenderbuffer( gl.RENDERBUFFER, null );
gl.bindFramebuffer( gl.FRAMEBUFFER, null );
blurFB.push( fb );
}
}
function initScene() {
canvas = document.getElementById( "canvas");
gl = canvas.getContext( "experimental-webgl" );
if ( !gl )
return null;
progDraw = {}
progDraw.prog = ShaderProgram.Create(
[ { source : "draw-shader-vs", stage : gl.VERTEX_SHADER },
{ source : "draw-shader-fs", stage : gl.FRAGMENT_SHADER }
] );
if ( !progDraw.prog )
return null;
progDraw.inPos = gl.getAttribLocation( progDraw.prog, "inPos" );
progDraw.inNV = gl.getAttribLocation( progDraw.prog, "inNV" );
progDraw.inCol = gl.getAttribLocation( progDraw.prog, "inCol" );
progBlur = {}
progBlur.prog = ShaderProgram.Create(
[ { source : "post-shader-vs", stage : gl.VERTEX_SHADER },
{ source : "blur-shader-fs", stage : gl.FRAGMENT_SHADER }
] );
progBlur.inPos = gl.getAttribLocation( progBlur.prog, "inPos" );
if ( !progBlur.prog )
return;
// create cube
var cubePos = [
-1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0,
-1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, -1.0, 1.0, -1.0 ];
var cubeCol = [ 1.0, 0.0, 0.0, 1.0, 0.5, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 ];
var cubeHlpInx = [ 0, 1, 2, 3, 1, 5, 6, 2, 5, 4, 7, 6, 4, 0, 3, 7, 3, 2, 6, 7, 1, 0, 4, 5 ];
var cubePosData = [];
for ( var i = 0; i < cubeHlpInx.length; ++ i ) {
cubePosData.push( cubePos[cubeHlpInx[i]*3], cubePos[cubeHlpInx[i]*3+1], cubePos[cubeHlpInx[i]*3+2] );
}
var cubeNVData = [];
for ( var i1 = 0; i1 < cubeHlpInx.length; i1 += 4 ) {
var nv = [0, 0, 0];
for ( i2 = 0; i2 < 4; ++ i2 ) {
var i = i1 + i2;
nv[0] += cubePosData[i*3]; nv[1] += cubePosData[i*3+1]; nv[2] += cubePosData[i*3+2];
}
for ( i2 = 0; i2 < 4; ++ i2 )
cubeNVData.push( nv[0], nv[1], nv[2] );
}
var cubeColData = [];
for ( var is = 0; is < 6; ++ is ) {
for ( var ip = 0; ip < 4; ++ ip ) {
cubeColData.push( cubeCol[is*3], cubeCol[is*3+1], cubeCol[is*3+2] );
}
}
var cubeInxData = [];
for ( var i = 0; i < cubeHlpInx.length; i += 4 ) {
cubeInxData.push( i, i+1, i+2, i, i+2, i+3 );
}
bufCube = VertexBuffer.Create(
[ { data : cubePosData, attrSize : 3, attrLoc : progDraw.inPos },
{ data : cubeNVData, attrSize : 3, attrLoc : progDraw.inNV },
{ data : cubeColData, attrSize : 3, attrLoc : progDraw.inCol } ],
cubeInxData );
bufQuad.pos = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, bufQuad.pos );
gl.bufferData( gl.ARRAY_BUFFER, new Float32Array( [ -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0 ] ), gl.STATIC_DRAW );
bufQuad.inx = gl.createBuffer();
gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, bufQuad.inx );
gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, new Uint16Array( [ 0, 1, 2, 0, 2, 3 ] ), gl.STATIC_DRAW );
window.onresize = resize;
resize();
requestAnimationFrame(render);
}
function Fract( val ) {
return val - Math.trunc( val );
}
function CalcAng( deltaTime, intervall ) {
return Fract( deltaTime / (1000*intervall) ) * 2.0 * Math.PI;
}
function CalcMove( deltaTime, intervall, range ) {
var pos = self.Fract( deltaTime / (1000*intervall) ) * 2.0
var pos = pos < 1.0 ? pos : (2.0-pos)
return range[0] + (range[1] - range[0]) * pos;
}
function EllipticalPosition( a, b, angRag ) {
var a_b = a * a - b * b
var ea = (a_b <= 0) ? 0 : Math.sqrt( a_b );
var eb = (a_b >= 0) ? 0 : Math.sqrt( -a_b );
return [ a * Math.sin( angRag ) - ea, b * Math.cos( angRag ) - eb, 0 ];
}
function IdentityMat44() {
return [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ];
};
function RotateAxis(matA, angRad, axis) {
var aMap = [ [1, 2], [2, 0], [0, 1] ];
var a0 = aMap[axis][0], a1 = aMap[axis][1];
var sinAng = Math.sin(angRad), cosAng = Math.cos(angRad);
var matB = matA.slice(0);
for ( var i = 0; i < 3; ++ i ) {
matB[a0*4+i] = matA[a0*4+i] * cosAng + matA[a1*4+i] * sinAng;
matB[a1*4+i] = matA[a0*4+i] * -sinAng + matA[a1*4+i] * cosAng;
}
return matB;
}
function Cross( a, b ) { return [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0], 0.0 ]; }
function Dot( a, b ) { return a[0]*b[0] + a[1]*b[1] + a[2]*b[2]; }
function Normalize( v ) {
var len = Math.sqrt( v[0] * v[0] + v[1] * v[1] + v[2] * v[2] );
return [ v[0] / len, v[1] / len, v[2] / len ];
}
var Camera = {};
Camera.create = function() {
this.pos = [0, 3, 0.0];
this.target = [0, 0, 0];
this.up = [0, 0, 1];
this.fov_y = 90;
this.vp = [800, 600];
this.near = 0.5;
this.far = 100.0;
}
Camera.Perspective = function() {
var fn = this.far + this.near;
var f_n = this.far - this.near;
var r = this.vp[0] / this.vp[1];
var t = 1 / Math.tan( Math.PI * this.fov_y / 360 );
var m = IdentityMat44();
m[0] = t/r; m[1] = 0; m[2] = 0; m[3] = 0;
m[4] = 0; m[5] = t; m[6] = 0; m[7] = 0;
m[8] = 0; m[9] = 0; m[10] = -fn / f_n; m[11] = -1;
m[12] = 0; m[13] = 0; m[14] = -2 * this.far * this.near / f_n; m[15] = 0;
return m;
}
Camera.LookAt = function() {
var mz = Normalize( [ this.pos[0]-this.target[0], this.pos[1]-this.target[1], this.pos[2]-this.target[2] ] );
var mx = Normalize( Cross( this.up, mz ) );
var my = Normalize( Cross( mz, mx ) );
var tx = Dot( mx, this.pos );
var ty = Dot( my, this.pos );
var tz = Dot( [-mz[0], -mz[1], -mz[2]], this.pos );
var m = IdentityMat44();
m[0] = mx[0]; m[1] = my[0]; m[2] = mz[0]; m[3] = 0;
m[4] = mx[1]; m[5] = my[1]; m[6] = mz[1]; m[7] = 0;
m[8] = mx[2]; m[9] = my[2]; m[10] = mz[2]; m[11] = 0;
m[12] = tx; m[13] = ty; m[14] = tz; m[15] = 1;
return m;
}
var ShaderProgram = {};
ShaderProgram.Create = function( shaderList ) {
var shaderObjs = [];
for ( var i_sh = 0; i_sh < shaderList.length; ++ i_sh ) {
var shderObj = this.CompileShader( shaderList[i_sh].source, shaderList[i_sh].stage );
if ( shderObj == 0 )
return 0;
shaderObjs.push( shderObj );
}
var progObj = this.LinkProgram( shaderObjs )
if ( progObj != 0 ) {
progObj.attribIndex = {};
var noOfAttributes = gl.getProgramParameter( progObj, gl.ACTIVE_ATTRIBUTES );
for ( var i_n = 0; i_n < noOfAttributes; ++ i_n ) {
var name = gl.getActiveAttrib( progObj, i_n ).name;
progObj.attribIndex[name] = gl.getAttribLocation( progObj, name );
}
progObj.unifomLocation = {};
var noOfUniforms = gl.getProgramParameter( progObj, gl.ACTIVE_UNIFORMS );
for ( var i_n = 0; i_n < noOfUniforms; ++ i_n ) {
var name = gl.getActiveUniform( progObj, i_n ).name;
progObj.unifomLocation[name] = gl.getUniformLocation( progObj, name );
}
}
return progObj;
}
ShaderProgram.AttributeIndex = function( progObj, name ) { return progObj.attribIndex[name]; }
ShaderProgram.UniformLocation = function( progObj, name ) { return progObj.unifomLocation[name]; }
ShaderProgram.Use = function( progObj ) { gl.useProgram( progObj ); }
ShaderProgram.SetUniformI1 = function( progObj, name, val ) { if(progObj.unifomLocation[name]) gl.uniform1i( progObj.unifomLocation[name], val ); }
ShaderProgram.SetUniformF1 = function( progObj, name, val ) { if(progObj.unifomLocation[name]) gl.uniform1f( progObj.unifomLocation[name], val ); }
ShaderProgram.SetUniformF2 = function( progObj, name, arr ) { if(progObj.unifomLocation[name]) gl.uniform2fv( progObj.unifomLocation[name], arr ); }
ShaderProgram.SetUniformF3 = function( progObj, name, arr ) { if(progObj.unifomLocation[name]) gl.uniform3fv( progObj.unifomLocation[name], arr ); }
ShaderProgram.SetUniformF4 = function( progObj, name, arr ) { if(progObj.unifomLocation[name]) gl.uniform4fv( progObj.unifomLocation[name], arr ); }
ShaderProgram.SetUniformM33 = function( progObj, name, mat ) { if(progObj.unifomLocation[name]) gl.uniformMatrix3fv( progObj.unifomLocation[name], false, mat ); }
ShaderProgram.SetUniformM44 = function( progObj, name, mat ) { if(progObj.unifomLocation[name]) gl.uniformMatrix4fv( progObj.unifomLocation[name], false, mat ); }
ShaderProgram.CompileShader = function( source, shaderStage ) {
var shaderScript = document.getElementById(source);
if (shaderScript)
source = shaderScript.text;
var shaderObj = gl.createShader( shaderStage );
gl.shaderSource( shaderObj, source );
gl.compileShader( shaderObj );
var status = gl.getShaderParameter( shaderObj, gl.COMPILE_STATUS );
if ( !status ) alert(gl.getShaderInfoLog(shaderObj));
return status ? shaderObj : null;
}
ShaderProgram.LinkProgram = function( shaderObjs ) {
var prog = gl.createProgram();
for ( var i_sh = 0; i_sh < shaderObjs.length; ++ i_sh )
gl.attachShader( prog, shaderObjs[i_sh] );
gl.linkProgram( prog );
status = gl.getProgramParameter( prog, gl.LINK_STATUS );
if ( !status ) alert("Could not initialise shaders");
gl.useProgram( null );
return status ? prog : null;
}
var VertexBuffer = {};
VertexBuffer.Create = function( attributes, indices ) {
var buffer = {};
buffer.buf = [];
buffer.attr = []
for ( var i = 0; i < attributes.length; ++ i ) {
buffer.buf.push( gl.createBuffer() );
buffer.attr.push( { size : attributes[i].attrSize, loc : attributes[i].attrLoc } );
gl.bindBuffer( gl.ARRAY_BUFFER, buffer.buf[i] );
gl.bufferData( gl.ARRAY_BUFFER, new Float32Array( attributes[i].data ), gl.STATIC_DRAW );
}
buffer.inx = gl.createBuffer();
gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, buffer.inx );
gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, new Uint16Array( indices ), gl.STATIC_DRAW );
buffer.inxLen = indices.length;
gl.bindBuffer( gl.ARRAY_BUFFER, null );
gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
return buffer;
}
VertexBuffer.Draw = function( bufObj ) {
for ( var i = 0; i < bufObj.buf.length; ++ i ) {
gl.bindBuffer( gl.ARRAY_BUFFER, bufObj.buf[i] );
gl.vertexAttribPointer( bufObj.attr[i].loc, bufObj.attr[i].size, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( bufObj.attr[i].loc );
}
gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, bufObj.inx );
gl.drawElements( gl.TRIANGLES, bufObj.inxLen, gl.UNSIGNED_SHORT, 0 );
for ( var i = 0; i < bufObj.buf.length; ++ i )
gl.disableVertexAttribArray( bufObj.attr[i].loc );
gl.bindBuffer( gl.ARRAY_BUFFER, null );
gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
}
initScene();
})();
html,body { margin: 0; overflow: hidden; }
#gui { position : absolute; top : 0; left : 0; }
<script id="draw-shader-vs" type="x-shader/x-vertex">
precision mediump float;
attribute vec3 inPos;
attribute vec3 inNV;
attribute vec3 inCol;
varying vec3 vertPos;
varying vec3 vertNV;
varying vec3 vertCol;
uniform mat4 u_projectionMat44;
uniform mat4 u_modelViewMat44;
void main()
{
vertNV = mat3( u_modelViewMat44 ) * normalize( inNV );
vertCol = inCol;
vec4 pos = u_modelViewMat44 * vec4( inPos, 1.0 );
vertPos = pos.xyz / pos.w;
gl_Position = u_projectionMat44 * pos;
}
</script>
<script id="draw-shader-fs" type="x-shader/x-fragment">
precision mediump float;
varying vec3 vertPos;
varying vec3 vertNV;
varying vec3 vertCol;
uniform float u_shininess;
void main()
{
vec3 color = vertCol;
vec3 normalV = normalize( vertNV );
vec3 eyeV = normalize( -vertPos );
vec3 halfV = normalize( eyeV + normalV );
float NdotH = max( 0.0, dot( normalV, halfV ) );
float shineFac = ( u_shininess + 2.0 ) * pow( NdotH, u_shininess ) / ( 2.0 * 3.14159265 );
gl_FragColor = vec4( color.rgb * (0.2 + NdotH), 1.0 );
}
</script>
<script id="post-shader-vs" type="x-shader/x-vertex">
precision mediump float;
attribute vec2 inPos;
varying vec2 pos;
void main()
{
pos = inPos;
gl_Position = vec4( inPos, 0.0, 1.0 );
}
</script>
<script id="blur-shader-fs" type="x-shader/x-fragment">
precision mediump float;
varying vec2 pos;
uniform sampler2D u_texture;
uniform vec2 u_textureSize;
uniform float u_sigma;
uniform float u_radius;
uniform vec2 u_dir;
float CalcGauss( float x, float sigma )
{
if ( sigma <= 0.0 )
return 0.0;
return exp( -(x*x) / (2.0 * sigma) ) / (2.0 * 3.14157 * sigma);
}
void main()
{
vec2 texC = pos.st * 0.5 + 0.5;
vec4 texCol = texture2D( u_texture, texC );
vec4 gaussCol = vec4( texCol.rgb, 1.0 );
vec2 step = u_dir / u_textureSize;
for ( int i = 1; i <= 32; ++ i )
{
float weight = CalcGauss( float(i) / 32.0, u_sigma * 0.5 );
if ( weight < 1.0/255.0 )
break;
texCol = texture2D( u_texture, texC + u_radius * step * float(i) );
gaussCol += vec4( texCol.rgb * weight, weight );
texCol = texture2D( u_texture, texC - u_radius * step * float(i) );
gaussCol += vec4( texCol.rgb * weight, weight );
}
gaussCol.rgb = clamp( gaussCol.rgb / gaussCol.w, 0.0, 1.0 );
gl_FragColor = vec4( gaussCol.rgb, 1.0 );
}
</script>
<div>
<form id="gui" name="inputs">
<table>
<tr> <td> <font color= #CCF>radius</font> </td>
<td> <input type="range" id="radius" min="1" max="1000" value="1000" onchange="changeEventHandler(event);"/></td> </tr>
<tr> <td> <font color= #CCF>blur</font> </td>
<td> <input type="range" id="sigma" min="1" max="100" value="5" onchange="changeEventHandler(event);"/></td> </tr>
</table>
</form>
</div>
<canvas id="canvas" style="border: none;"></canvas>

Creating a Gradient Color in Fragment Shader

I'm trying to achieve making a gradient color as the design apps (Photoshop for example) does, but can't get the exact result i want.
My shader creates very nice 'gradients' but also contains other colors that are different from the colors I want to switch in.
It looks nice but, my aim is adding blending functions later and make a kind of color correction shader. but first of all I have to get the right colors.
Here is my fragment shader
http://player.thebookofshaders.com/?log=171119111216
uniform vec2 u_resolution;
void main() {
vec2 st = gl_FragCoord.xy/u_resolution.xy;
vec3 color1 = vec3(1.9,0.55,0);
vec3 color2 = vec3(0.226,0.000,0.615);
float mixValue = distance(st,vec2(0,1));
vec3 color = mix(color1,color2,mixValue);
gl_FragColor = vec4(color,mixValue);
}
And here is
Thanks in advance..
In response to just the title of your question you might also want to consider doing the mix in other color spaces. Your code is mixing in RGB space but you'll get different results in different spaces.
Example
const gl = document.createElement("canvas").getContext("webgl");
gl.canvas.width = 100;
gl.canvas.height = 100;
gl.viewport(0, 0, 100, 100);
const vsrc = `
void main() {
gl_PointSize = 100.0;
gl_Position = vec4(0, 0, 0, 1);
}
`;
const fRGB = `
precision mediump float;
uniform vec3 color1;
uniform vec3 color2;
void main() {
vec2 st = gl_PointCoord;
float mixValue = distance(st, vec2(0, 1));
vec3 color = mix(color1, color2, mixValue);
gl_FragColor = vec4(color, 1);
}
`;
const fHSV = `
precision mediump float;
uniform vec3 color1;
uniform vec3 color2;
// from: http://lolengine.net/blog/2013/07/27/rgb-to-hsv-in-glsl
vec3 rgb2hsv(vec3 c) {
vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));
vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));
float d = q.x - min(q.w, q.y);
float e = 1.0e-10;
return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);
}
vec3 hsv2rgb(vec3 c) {
c = vec3(c.x, clamp(c.yz, 0.0, 1.0));
vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
}
void main() {
vec2 st = gl_PointCoord;
float mixValue = distance(st, vec2(0, 1));
vec3 hsv1 = rgb2hsv(color1);
vec3 hsv2 = rgb2hsv(color2);
// mix hue in toward closest direction
float hue = (mod(mod((hsv2.x - hsv1.x), 1.) + 1.5, 1.) - 0.5) * mixValue + hsv1.x;
vec3 hsv = vec3(hue, mix(hsv1.yz, hsv2.yz, mixValue));
vec3 color = hsv2rgb(hsv);
gl_FragColor = vec4(color, 1);
}
`;
const fHSL = `
precision mediump float;
uniform vec3 color1;
uniform vec3 color2;
const float Epsilon = 1e-10;
vec3 rgb2hcv(in vec3 RGB)
{
// Based on work by Sam Hocevar and Emil Persson
vec4 P = lerp(vec4(RGB.bg, -1.0, 2.0/3.0), vec4(RGB.gb, 0.0, -1.0/3.0), step(RGB.b, RGB.g));
vec4 Q = mix(vec4(P.xyw, RGB.r), vec4(RGB.r, P.yzx), step(P.x, RGB.r));
float C = Q.x - min(Q.w, Q.y);
float H = abs((Q.w - Q.y) / (6. * C + Epsilon) + Q.z);
return vec3(H, C, Q.x);
}
vec3 rgb2hsl(in vec3 RGB)
{
vec3 HCV = rgb2hcv(RGB);
float L = HCV.z - HCV.y * 0.5;
float S = HCV.y / (1 - abs(L * 2. - 1.) + Epsilon);
return vec3(HCV.x, S, L);
}
vec3 hsl2rgb(vec3 c)
{
c = vec3(fract(c.x), clamp(c.yz, 0.0, 1.0));
vec3 rgb = clamp(abs(mod(c.x * 6.0 + vec3(0.0, 4.0, 2.0), 6.0) - 3.0) - 1.0, 0.0, 1.0);
return c.z + c.y * (rgb - 0.5) * (1.0 - abs(2.0 * c.z - 1.0));
}
void main() {
vec2 st = gl_PointCoord;
float mixValue = distance(st, vec2(0, 1));
vec3 hsl1 = rgb2hsl(color1);
vec3 hsl2 = rgb2hsl(color2);
// mix hue in toward closest direction
float hue = (mod(mod((hsl2.x - hsl1.x), 1.) + 1.5, 1.) - 0.5) * mixValue + hsl1.x;
vec3 hsl = vec3(hue, mix(hsl1.yz, hsl2.yz, mixValue));
vec3 color = hsl2rgb(hsv);
gl_FragColor = vec4(color, 1);
}
`;
const fLAB = `
precision mediump float;
uniform vec3 color1;
uniform vec3 color2;
// from: https://code.google.com/archive/p/flowabs/source
vec3 rgb2xyz( vec3 c ) {
vec3 tmp;
tmp.x = ( c.r > 0.04045 ) ? pow( ( c.r + 0.055 ) / 1.055, 2.4 ) : c.r / 12.92;
tmp.y = ( c.g > 0.04045 ) ? pow( ( c.g + 0.055 ) / 1.055, 2.4 ) : c.g / 12.92,
tmp.z = ( c.b > 0.04045 ) ? pow( ( c.b + 0.055 ) / 1.055, 2.4 ) : c.b / 12.92;
return 100.0 * tmp *
mat3( 0.4124, 0.3576, 0.1805,
0.2126, 0.7152, 0.0722,
0.0193, 0.1192, 0.9505 );
}
vec3 xyz2lab( vec3 c ) {
vec3 n = c / vec3( 95.047, 100, 108.883 );
vec3 v;
v.x = ( n.x > 0.008856 ) ? pow( n.x, 1.0 / 3.0 ) : ( 7.787 * n.x ) + ( 16.0 / 116.0 );
v.y = ( n.y > 0.008856 ) ? pow( n.y, 1.0 / 3.0 ) : ( 7.787 * n.y ) + ( 16.0 / 116.0 );
v.z = ( n.z > 0.008856 ) ? pow( n.z, 1.0 / 3.0 ) : ( 7.787 * n.z ) + ( 16.0 / 116.0 );
return vec3(( 116.0 * v.y ) - 16.0, 500.0 * ( v.x - v.y ), 200.0 * ( v.y - v.z ));
}
vec3 rgb2lab(vec3 c) {
vec3 lab = xyz2lab( rgb2xyz( c ) );
return vec3( lab.x / 100.0, 0.5 + 0.5 * ( lab.y / 127.0 ), 0.5 + 0.5 * ( lab.z / 127.0 ));
}
vec3 lab2xyz( vec3 c ) {
float fy = ( c.x + 16.0 ) / 116.0;
float fx = c.y / 500.0 + fy;
float fz = fy - c.z / 200.0;
return vec3(
95.047 * (( fx > 0.206897 ) ? fx * fx * fx : ( fx - 16.0 / 116.0 ) / 7.787),
100.000 * (( fy > 0.206897 ) ? fy * fy * fy : ( fy - 16.0 / 116.0 ) / 7.787),
108.883 * (( fz > 0.206897 ) ? fz * fz * fz : ( fz - 16.0 / 116.0 ) / 7.787)
);
}
vec3 xyz2rgb( vec3 c ) {
vec3 v = c / 100.0 * mat3(
3.2406, -1.5372, -0.4986,
-0.9689, 1.8758, 0.0415,
0.0557, -0.2040, 1.0570
);
vec3 r;
r.x = ( v.r > 0.0031308 ) ? (( 1.055 * pow( v.r, ( 1.0 / 2.4 ))) - 0.055 ) : 12.92 * v.r;
r.y = ( v.g > 0.0031308 ) ? (( 1.055 * pow( v.g, ( 1.0 / 2.4 ))) - 0.055 ) : 12.92 * v.g;
r.z = ( v.b > 0.0031308 ) ? (( 1.055 * pow( v.b, ( 1.0 / 2.4 ))) - 0.055 ) : 12.92 * v.b;
return r;
}
vec3 lab2rgb(vec3 c) {
return xyz2rgb( lab2xyz( vec3(100.0 * c.x, 2.0 * 127.0 * (c.y - 0.5), 2.0 * 127.0 * (c.z - 0.5)) ) );
}
void main() {
vec2 st = gl_PointCoord;
float mixValue = distance(st, vec2(0, 1));
vec3 lab1 = rgb2lab(color1);
vec3 lab2 = rgb2lab(color2);
vec3 lab = mix(lab1, lab2, mixValue);
vec3 color = lab2rgb(lab);
gl_FragColor = vec4(color, 1);
}
`;
function draw(gl, shaders, color1, color2, label) {
const programInfo = twgl.createProgramInfo(gl, shaders);
gl.useProgram(programInfo.program);
twgl.setUniforms(programInfo, {
color1: color1,
color2: color2,
});
gl.drawArrays(gl.POINTS, 0, 1);
const div = document.createElement("div");
const img = new Image();
img.src = gl.canvas.toDataURL();
div.appendChild(img);
const inner = document.createElement("span");
inner.textContent = label;
div.appendChild(inner);
document.body.appendChild(div);
}
const color1 = [1.0, 0.55, 0];
const color2 = [0.226, 0.000, 0.615];
draw(gl, [vsrc, fRGB], color1, color2, "rgb");
draw(gl, [vsrc, fHSV], color1, color2, "hsv");
draw(gl, [vsrc, fHSV], color1, color2, "hsl");
draw(gl, [vsrc, fLAB], color1, color2, "lab");
img { border: 1px solid black; margin: 2px; }
span { display: block; }
div { display: inline-block; text-align: center; }
<script src="https://twgljs.org/dist/4.x/twgl.min.js"></script>
I would also suggest passing your colors in in a ramp texture. An Nx1 texture and using
color = texture2D(
rampTexture,
vec2((mixValue * (rampWidth - 1.) + .5) / rampWidth, 0.5)).rgb;
Then you can easily blend across 2 colors, 3 colors, 20 colors. You can space out the colors as well by repeating colors etc..
Example:
const gl = document.createElement("canvas").getContext("webgl");
gl.canvas.width = 100;
gl.canvas.height = 100;
gl.viewport(0, 0, 100, 100);
const vsrc = `
void main() {
gl_PointSize = 100.0;
gl_Position = vec4(0, 0, 0, 1);
}
`;
const fsrc = `
precision mediump float;
uniform sampler2D rampTexture;
uniform float rampWidth;
void main() {
vec2 st = gl_PointCoord;
float mixValue = distance(st, vec2(0, 1));
vec3 color = texture2D(
rampTexture,
vec2((mixValue * (rampWidth - 1.) + .5) / rampWidth, 0.5)).rgb;
gl_FragColor = vec4(color, 1);
}
`;
const programInfo = twgl.createProgramInfo(gl, [vsrc, fsrc]);
gl.useProgram(programInfo.program);
const tex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
function draw(gl, ramp, label) {
const width = ramp.length;
gl.bindTexture(gl.TEXTURE_2D, tex);
const level = 0;
const internalFormat = gl.RGB;
const height = 1;
const border = 0;
const format = gl.RGB;
const type = gl.UNSIGNED_BYTE;
const rampData = new Uint8Array([].concat(...ramp).map(v => v * 255));
gl.texImage2D(gl.TEXTURE_2D, level, internalFormat, width, height, border,
format, type, rampData);
twgl.setUniforms(programInfo, {
rampTexture: tex,
rampWidth: width,
});
gl.drawArrays(gl.POINTS, 0, 1);
const div = document.createElement("div");
const img = new Image();
img.src = gl.canvas.toDataURL();
div.appendChild(img);
const inner = document.createElement("span");
inner.textContent = label;
div.appendChild(inner);
document.body.appendChild(div);
}
const color1 = [1.0, 0.55, 0];
const color2 = [0.226, 0.000, 0.615];
const r = [1, 0, 0];
const g = [0, 1, 0];
const b = [0, 0, 1];
const w = [1, 1, 1];
draw(gl, [color1, color2], "color1->color2");
draw(gl, [r, g], "red->green");
draw(gl, [r, g, b], "r->g->b");
draw(gl, [r, b, r, b, r], "r->b->r->b->r");
draw(gl, [g, b, b, b, g], "g->b->b->b->g");
img { border: 1px solid black; margin: 2px; }
span { display: block; }
div { display: inline-block; text-align: center; }
<script src="https://twgljs.org/dist/4.x/twgl.min.js"></script>
Note: a 1 dimensional 256x1 texture is how Chrome, Firefox, and Android render both linear and radial gradients. See src
Ther is a simple mistake when you set up the color value. You used 1.9 for the value of red color channel instead of 1.0, when you set up the orange color.
Change your code to:
vec3 color1 = vec3(1.0, 0.55, 0.0); // 1.0 insted of 1.9
Note, the final color channels are clamped to [0, 1], but since you use mix to interpolate the colors, a color channel above 1.0 raises the part of the color in the gradient.
Preview:
var ShaderProgram = {};
ShaderProgram.Create = function( shaderList ) {
var shaderObjs = [];
for ( var i_sh = 0; i_sh < shaderList.length; ++ i_sh ) {
var shderObj = this.CompileShader( shaderList[i_sh].source, shaderList[i_sh].stage );
if ( shderObj == 0 )
return 0;
shaderObjs.push( shderObj );
}
var progObj = this.LinkProgram( shaderObjs )
if ( progObj != 0 ) {
progObj.attribIndex = {};
var noOfAttributes = gl.getProgramParameter( progObj, gl.ACTIVE_ATTRIBUTES );
for ( var i_n = 0; i_n < noOfAttributes; ++ i_n ) {
var name = gl.getActiveAttrib( progObj, i_n ).name;
progObj.attribIndex[name] = gl.getAttribLocation( progObj, name );
}
progObj.unifomLocation = {};
var noOfUniforms = gl.getProgramParameter( progObj, gl.ACTIVE_UNIFORMS );
for ( var i_n = 0; i_n < noOfUniforms; ++ i_n ) {
var name = gl.getActiveUniform( progObj, i_n ).name;
progObj.unifomLocation[name] = gl.getUniformLocation( progObj, name );
}
}
return progObj;
}
ShaderProgram.AttributeIndex = function( progObj, name ) { return progObj.attribIndex[name]; }
ShaderProgram.UniformLocation = function( progObj, name ) { return progObj.unifomLocation[name]; }
ShaderProgram.Use = function( progObj ) { gl.useProgram( progObj ); }
ShaderProgram.SetUniformF2 = function( progObj, name, arr ) { if(progObj.unifomLocation[name]) gl.uniform2fv( progObj.unifomLocation[name], arr ); }
ShaderProgram.CompileShader = function( source, shaderStage ) {
var shaderScript = document.getElementById(source);
if (shaderScript) {
source = "";
var node = shaderScript.firstChild;
while (node) {
if (node.nodeType == 3) source += node.textContent;
node = node.nextSibling;
}
}
var shaderObj = gl.createShader( shaderStage );
gl.shaderSource( shaderObj, source );
gl.compileShader( shaderObj );
var status = gl.getShaderParameter( shaderObj, gl.COMPILE_STATUS );
if ( !status ) alert(gl.getShaderInfoLog(shaderObj));
return status ? shaderObj : 0;
}
ShaderProgram.LinkProgram = function( shaderObjs ) {
var prog = gl.createProgram();
for ( var i_sh = 0; i_sh < shaderObjs.length; ++ i_sh )
gl.attachShader( prog, shaderObjs[i_sh] );
gl.linkProgram( prog );
status = gl.getProgramParameter( prog, gl.LINK_STATUS );
if ( !status ) alert("Could not initialise shaders");
gl.useProgram( null );
return status ? prog : 0;
}
function drawScene(){
var canvas = document.getElementById( "ogl-canvas" );
var vp = [canvas.width, canvas.height];
gl.viewport( 0, 0, canvas.width, canvas.height );
gl.enable( gl.DEPTH_TEST );
gl.clearColor( 0.0, 0.0, 0.0, 1.0 );
gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT );
ShaderProgram.Use( progDraw );
ShaderProgram.SetUniformF2( progDraw, "u_resolution", vp )
gl.enableVertexAttribArray( progDraw.inPos );
gl.bindBuffer( gl.ARRAY_BUFFER, bufObj.pos );
gl.vertexAttribPointer( progDraw.inPos, 2, gl.FLOAT, false, 0, 0 );
gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, bufObj.inx );
gl.drawElements( gl.TRIANGLES, bufObj.inx.len, gl.UNSIGNED_SHORT, 0 );
gl.disableVertexAttribArray( progDraw.pos );
}
var gl;
var prog;
var bufObj = {};
function sceneStart() {
var canvas = document.getElementById( "ogl-canvas");
gl = canvas.getContext( "experimental-webgl", { premultipliedAlpha: true } );
if ( !gl )
return;
progDraw = ShaderProgram.Create(
[ { source : "draw-shader-vs", stage : gl.VERTEX_SHADER },
{ source : "draw-shader-fs", stage : gl.FRAGMENT_SHADER }
] );
progDraw.inPos = gl.getAttribLocation( progDraw, "inPos" );
if ( prog == 0 )
return;
var pos = [ -1, -1, 1, -1, 1, 1, -1, 1 ];
var inx = [ 0, 1, 2, 0, 2, 3 ];
bufObj.pos = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, bufObj.pos );
gl.bufferData( gl.ARRAY_BUFFER, new Float32Array( pos ), gl.STATIC_DRAW );
bufObj.inx = gl.createBuffer();
bufObj.inx.len = inx.length;
gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, bufObj.inx );
gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, new Uint16Array( inx ), gl.STATIC_DRAW );
setInterval(drawScene, 50);
}
<script id="draw-shader-vs" type="x-shader/x-vertex">
precision mediump float;
attribute vec2 inPos;
varying vec2 vertPos;
void main()
{
vertPos = inPos;
gl_Position = vec4( inPos.xy, 0.0, 1.0 );
}
</script>
<script id="draw-shader-fs" type="x-shader/x-fragment">
precision mediump float;
varying vec2 vertPos;
uniform vec2 u_resolution;
void main()
{
vec2 st = gl_FragCoord.xy/u_resolution.xy;
vec3 color1 = vec3(1.0,0.55,0);
vec3 color2 = vec3(0.226,0.000,0.615);
float mixValue = distance(st,vec2(0,1));
vec3 color = mix(color1,color2,mixValue);
gl_FragColor = vec4(color,1.0);
}
</script>
<body onload="sceneStart();">
<canvas id="ogl-canvas" style="border: none;" width="256" height="256"></canvas>
</body>