Search code examples
androidlibgdx

drawing the Mandelbrot set with libGDX


I want to try rendering the mandelbrot set using libGDX on AIDE (I only have my phone to code with). So, I studied up on the algorithm and tried implementing it.

This function is called for every pixel on the screen-

public int calcFract(int x, int y, int maxiter)
{
    zx = zy = 0;
    cx = (x - width/2) / zoom;
    cy = (y - height/2) / zoom;

    while( zx * zx + zy * zy < 4.0 && iter < maxiter )
    {
        tmp = zx * zx - zy * zy + cx;
        zy = 2.0 * zx * zy + cy;
        zx = tmp;
        iter++;
    }

    return iter | iter << 8;
}

And here is the create() callback-

public void create()
{
    width = Gdx.graphics.getWidth();
    height = Gdx.graphics.getHeight();
    Gdx.input.setInputProcessor(this);
    fractal = new Pixmap(width, height, Pixmap.Format.RGB888);
    for (int i = 0; i < width; ++i)
        for (int j = 0; j < height; ++j)
        {
            int c = mandelbrot.calcFract(i, j, maxiter);
            fractal.drawPixel( i, j, Color.toIntBits(0xff, c, c, c));
        }

     fracTex = new Texture(fractal);
     batch = new SpriteBatch();
}

The app compiles without errors, but when I run it, it shows me this-

notice the left side of the screen

Here is the render() callback as well-

public void render()
{   
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    batch.begin();
    batch.draw(fracTex, 0, 0);
    batch.end();
}

Please tell me if there's anything wrong with my code. Thanks in advance!


Solution

  • I made a very nooby mistake.

    If you look at my code, you will notice that after rendering the first pixel of the pixmap, the algorithm stops working because iter gets stuck at maxiter forever because I forgot to reset iter for every pixel. The while loop is skipped since iter = maxiter for all pixels after the first one. This means that all pixels after the first one take on the same colour, ruining everything.

    I fixed it by setting iter to 0 before the while loop in calcFract().