Julia Set

Julia set, the dusts of mandelbrot, rendered with GLSL shaders.

July 19, 2021 · 5 mins read

Julia set with GLSL shaders and P5JS

drawing


Pseudocode - Wikipedia


Link: Julia Set on wiki

    R = escape radius  # choose R > 0 such that R**2 - R >= sqrt(cx**2 + cy**2)

    for each pixel (x, y) on the screen, do:
    {
        zx = scaled x coordinate of pixel # (scale to be between -R and R)
           # zx represents the real part of z.
        zy = scaled y coordinate of pixel # (scale to be between -R and R)
           # zy represents the imaginary part of z.

        iteration = 0
        max_iteration = 1000

        while (zx * zx + zy * zy < R**2  AND  iteration < max_iteration)
        {
            xtemp = zx * zx - zy * zy
            zy = 2 * zx * zy  + cy
            zx = xtemp + cx

            iteration = iteration + 1
        }

        if (iteration == max_iteration)
            return black;
        else
            return iteration;
    }

Vertex Shader

    #ifdef GL_ES
    precision highp float;
    #endif

    attribute vec3 aPosition;
    varying vec2 vPos;
    // Always include this to get the position of the pixel and map the shader correctly onto the shape

    void main(){

    // Send the vertex information on to the fragment shader
    gl_Position=vec4(aPosition,1.);

    vPos=gl_Position.xy;
    }

Fragment Shader

    #ifdef GL_ES
    precision highp float;
    #endif

    uniform vec2 canvasResolution;
    uniform float minI;
    uniform float maxI;
    uniform float minR;
    uniform float maxR;
    varying vec2 vPos;

    // Thsse are passed in as a uniform from the sketch.js file
    uniform vec2 p;
    uniform float r;
    uniform float angle;
    const int I = 500;
    const float offset = -0.25;

    void main(){

        // fractal code
        vec2 vPos = vec2(
            gl_FragCoord.x * (maxR - minR) / canvasResolution.x + minR,
            gl_FragCoord.y * (maxI - minI) / canvasResolution.y + minI
        );
        vec2 c = p - (vPos) * r, z = c;
        float n = 0.0;

        for (int i = I; i > 0; i --) {
        if(z.x*z.x+z.y*z.y > 4. ) {
            n = float(i)/float(I);
            break;
        }
        z = vec2((z.x*z.x-z.y*z.y)+(0.7885 * cos(angle)), (2.0*z.x*z.y)-(sin(angle)));
        }
        gl_FragColor=vec4(0.5-cos(n*75.0)/2.0,0.5-cos(n* 120.0)/2.0,0.5-cos(n*165.0)/2.0,1.0);
    }

How to


  • Clone the repository.
  • Start a local live server.
  • Open the index.html file from the live server.
  • Main code for is in script.js file for reference or editing.
  • The code for shaders in assets/ folder. These shaders do the mathematical computations.

Source code
High-res render on youtube