

Task
Produce a graphical or ASCII-art representation of a Sierpinski square curve of at least order 3.

--
-- demo\rosetta\Sierpinski_square_curve.exw
-- ========================================
--
-- My second atempt at a Lindenmayer system. The first 
--  is now saved in demo\rosetta\Penrose_tiling.exw
--
with javascript_semantics
include pGUI.e

Ihandle dlg, canvas
cdCanvas cddbuffer, cdcanvas

function redraw_cb(Ihandle /*canvas*/)
    string s = "F+F+XF+F+XF"
    for n=1 to 4 do
        string next = ""
        for i=1 to length(s) do
            integer ch = s[i]
            next &= iff(ch='X'?"XF-F+F-XF+F+XF-F+F-X":ch)
        end for
        s = next
    end for
 
    cdCanvasActivate(cddbuffer)
    cdCanvasBegin(cddbuffer, CD_CLOSED_LINES)
    atom x=0, y=0, theta=PI/4, r = 6
    for i=1 to length(s) do
        integer ch = s[i]
        switch ch do
            case 'F':   x += r*cos(theta)
                        y += r*sin(theta)
                        cdCanvasVertex(cddbuffer, x+270, y+270)
            case '+':   theta += PI/2
            case '-':   theta -= PI/2
        end switch
    end for
    cdCanvasEnd(cddbuffer)
    cdCanvasFlush(cddbuffer)
    return IUP_DEFAULT
end function

function map_cb(Ihandle canvas)
    cdcanvas = cdCreateCanvas(CD_IUP, canvas)
    cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
    cdCanvasSetBackground(cddbuffer, CD_WHITE)
    cdCanvasSetForeground(cddbuffer, CD_BLUE)
    return IUP_DEFAULT
end function

IupOpen()
canvas = IupCanvas("RASTERSIZE=290x295")
IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"),
                         "ACTION", Icallback("redraw_cb")})
dlg = IupDialog(canvas,`TITLE="Sierpinski square curve"`)
IupSetAttribute(dlg,`DIALOGFRAME`,`YES`)
IupShow(dlg)
if platform()!=JS then
    IupMainLoop()
    IupClose()
end if
