'
' Fractal demonstration using GL and GLUT - learning 2D GL/GLUT programming.
'
' Ported from my own GTK demo http://www.basic-converter.org/fractal.bac.html
'
' October 2010, PvE - GPL
'
'--------------------------------------------------------------------------------------------

INCLUDE "glut.bac"
INCLUDE "gl.bac"

OPTION BASE 1

CONST XSize = 640
CONST YSize = 480
CONST MaxIters = 60
CONST Left = -2.0
CONST Right = 1.0
CONST Top = 1.0
CONST Bottom = -1.0
CONST message$ = "Drawing ready."

DECLARE PixelColR[17], PixelColG[17], PixelColB[17] TYPE float

DATA 128, 0, 0, 128, 0, 128, 128, 0, 255, 128, 128, 0, 128, 128, 128, 128, 128, 255, 128, 255, 0, 128, 255, 128
DATA 128, 255, 255, 255, 0, 0, 255, 0, 128, 255, 0, 255, 255, 128, 0, 255, 128, 128, 255, 128, 255, 255, 255, 0, 0, 0, 0

SUB draw

    LOCAL x, y, count, idx
    LOCAL zr, zi, cr, ci, rsquared, isquared TYPE FLOATING

    glMatrixMode (GL_PROJECTION)
    glLoadIdentity

    glOrtho(0, XSize, 0, YSize, 0, 1)
    glDisable(GL_DEPTH_TEST)
    glMatrixMode (GL_MODELVIEW)
    glLoadIdentity

    glClearColor(1, 1, 1, 0)
    glClear(GL_COLOR_BUFFER_BIT)

    FOR y = 0 TO YSize
        FOR x = 0 TO XSize

            zr = 0.0 : zi = 0.0

            cr = Left + x * (Right - Left) / XSize
            ci = Top + y * (Bottom - Top) / YSize

            rsquared = zr * zr
            isquared = zi * zi

            FOR count = 0 TO MaxIters
                zi = zr * zi * 2
                zi = zi + ci

                zr = rsquared - isquared
                zr = zr + cr

                rsquared = zr * zr
                isquared = zi * zi
            NEXT

            IF rsquared + isquared <= 4.0 THEN

                idx = INT((rsquared + isquared)*4)

                glColor3f(PixelColR[idx]/256, PixelColG[idx]/256, PixelColB[idx]/256)

                glBegin(GL_POINTS)
                    glVertex2i(x, y)
                glEnd
            END IF
        NEXT
    NEXT

    glutSwapBuffers

END SUB

SUB key (NUMBER k, NUMBER x, NUMBER y)

    END

END SUB

SUB mainprog

    glutInitDisplayMode (GLUT_RGB | GLUT_DOUBLE)
    glutInitWindowSize(XSize, YSize)
    glutCreateWindow ("Fractal demo")

    glutDisplayFunc (ADDRESS (draw))
    glutKeyboardFunc (ADDRESS(key))

    glutMainLoop

END SUB

FOR i = 1 TO 17
    READ PixelColR[i]
    READ PixelColG[i]
    READ PixelColB[i]
NEXT

mainprog