' Koch Snowflake Fractal with Sierpinski Triangle, and Color
' Oxygen Basic, ConsoleG, OpenGL

'fixed CP 19/04/2026

#compact
%filename "t.exe"
'uses RTL64
% Title "Koch Snowflake Fractal with Sierpinski Triangle, and Color"

'% WindowStyle WS_OVERLAPPEDWINDOW
'% Animated
'% ScaleUp
% PlaceCentral
% AnchorCentral

% shaders

uses consoleG

BeginScript

procedure drawLine(float x1, float y1, float x2, float y2, float r, float g, float b) {
    color(r, g, b)
    thickness 2
    glBegin(GL_LINES)
    glVertex2f(x1, y1)
    glVertex2f(x2, y2)
    glEnd()
}

procedure koch(float x1, float y1, float x2, float y2, int level, float r, float g, float b) {
    if (level == 0) {
        drawLine(x1, y1, x2, y2, r, g, b)
        return
    }

    float dx = x2 - x1
    float dy = y2 - y1
    float le = sqrt(dx*dx + dy*dy) / 3.0
    float angle = atan(dy, dx)
    float pia=angle+pi()/3

    float x3 = x1 + le * cos(angle)
    float y3 = y1 + le * sin(angle)
    float x4 = x3 + le * cos(pia)
    float y4 = y3 + le * sin(pia)
    float x5 = x2 - le * cos(angle)
    float y5 = y2 - le * sin(angle)

    koch(x1, y1, x3, y3, level-1, r, g, b)
    koch(x3, y3, x4, y4, level-1, r, g, b)
    koch(x4, y4, x5, y5, level-1, r, g, b)
    koch(x5, y5, x2, y2, level-1, r, g, b)

    'if (level == 1) {
    '    drawLine(x3, y3, x4, y4, r, g, b)
    '    drawLine(x4, y4, x5, y5, r, g, b)
    '    drawLine(x5, y5, x3, y3, r, g, b)
    ''}

}

procedure sierpinski(float x1, float y1, float x2, float y2, float x3, float y3, int level, float r, float g, float b) {
    if (level == 0) {
        return;
    }
    drawLine(x1,y1, x2,y2, r,g,b)
    drawLine(x2,y2, x3,y3, r,g,b)
    drawLine(x3,y3, x1,y1, r,g,b)

    float midX1 = x1 + 0.5 * (x2 - x1)
    float midY1 = y1 + 0.5 * (y2 - y1)
    float midX2 = x2 + 0.5 * (x3 - x2)
    float midY2 = y2 + 0.5 * (y3 - y2)
    float midX3 = x3 + 0.5 * (x1 - x3)
    float midY3 = y3 + 0.5 * (y1 - y3)

    sierpinski(x1, y1, midX1, midY1, midX3, midY3, level-1, r,g,b)
    sierpinski(x2, y2, midX2, midY2, midX1, midY1, level-1, r,g,b)
    sierpinski(x3, y3, midX3, midY3, midX2, midY2, level-1, r,g,b)
}


procedure main() {
    cls 0.2, 0.2, 0.4
    'shading
    float x1 = -0.5
    float y1 = -0.5
    float x2 = 0.5
    float y2 = -0.5
    float x3 = 0.0
    float y3 = 0.5

    int level = 4
    pushstate
      move -8
      scale 20
      koch(x1, y1, x2, y2, level, 0.0, 1.0, 0.0)
      koch(x2, y2, x3, y3, level, 0.0, 1.0, 0.0)
      koch(x3, y3, x1, y1, level, 0.0, 1.0, 0.0)
    popstate

    pushstate
      move 8
      scale 20
      sierpinski(x1, y1, x2, y2, x3, y3, level, 1.0, 0.0, 0.0)
    popstate
}

EndScript