
\ ------------------------------------------------------------------------------
\  A few timing critical routines need to be copied to RAM for speed
\ ------------------------------------------------------------------------------

: isqrt      [ ' isqrt      inline, ] ;
: *          [ ' *          inline, ] ;
: putpixel   [ ' putpixel   inline, ] ;
: clrscr     [ ' clrscr     inline, ] ;
: flipbuffer [ ' flipbuffer inline, ] ;

\ ------------------------------------------------------------------------------
\  Julia set drawing, using single-cell fixpoint numbers
\ ------------------------------------------------------------------------------

10 constant FIXPOINT \ Number of fractional bits
\ 1 FIXPOINT lshift constant ONE \ Integer "ONE" in fixpoint notation

0 variable zreal
0 variable zimag

0,345 1 FIXPOINT lshift s>f f* f>s  variable creal
0,432 1 FIXPOINT lshift s>f f* f>s  variable cimag

0 variable re
0 variable im
\ 0 variable mag

: julia ( -- )

  clrscr

  0 zreal !
  0 zimag !

  256 0 do \ There is memory for up to 512 pixels, but animation would be too slow then
    zreal @ creal @ - re !
    zimag @ cimag @ - im !

    re @ dup *
    im @ dup *
    + isqrt \ mag !

    dup ( mag @ ) re @ +
  \ 2/ FIXPOINT lshift
    FIXPOINT 1- lshift
    isqrt zreal !

        ( mag @ ) re @ -
  \ 2/ FIXPOINT lshift
    FIXPOINT 1- lshift
    isqrt zimag !

    im @ 0< if zimag @ negate zimag ! then

  \ random 1 and
    $10010 @ 1024 and
    if
      zreal @ negate zreal !
      zimag @ negate zimag !
    then

    zreal @ 3 arshift 640 2/ +
    zimag @ 3 arshift 480 2/ +

    re @ 7 and
    dup 0 = if drop 7 then \ Black --> White
    putpixel

  loop

  flipbuffer
;

\ ------------------------------------------------------------------------------

: animation ( -- )
  \ cr
  begin
    \ cycles
    julia
    \ cycles swap -
    \ s>f 25000000,0 f/ 3 f.n cr

    \ Minsky circle algorithm to rotate (creal, cimag)

    creal @ 5 arshift negate cimag +!
    cimag @ 5 arshift        creal +!

  key? until
;

\ ------------------------------------------------------------------------------

animation
