This project is an interactive Mandelbrot set explorer able to zoom in and out of twelve classic fractal locations featuring a multi-resolution renderer, title screens, sound, and nine selectable color cycling patterns ranging from soothing to psychedelic, all in only 10 lines of Atari BASIC.
I was inspired by the Hackaday article Basic In 10 Lines Or Less which led me to the annual Basic 10 Liner Contest page (English rules start halfway down the page). There you can see current and previous entries spanning many years. The basic idea is to write the best game, application, or demo in 10 lines or less of BASIC on your favorite platform. There are three game categories distinguished by maximum line length and one “SCHAU” or “Look” category for “a demo, a tool or an application program” into which this project will be entered.
What is the Mandelbrot set?
You’re probably familiar with the lightning enshrouded circle and cardioid fractal images that resemble colorful spirals and paisley when examined more closely.
From Wikipedia: The Mandelbrot set (/ˈmændəlbrɒt/) is the set of complex numbers c for which the function does not diverge when iterated from z = 0 , i.e., for which the sequence , etc., remains bounded in absolute value. Its definition is credited to Adrien Douady who named it in tribute to the mathematician Benoit Mandelbrot, a pioneer of fractal geometry.
The colors in these images represent the number of times the Mandelbrot function is iterated before it diverges. Central areas (typically black) are areas that either do not diverge (infinite iterations) or are beyond the number of iterations the program is capable of performing. This program is configured to perform 81 iterations. There are YouTube “Mandelbrot Set Zoom ” videos that reach magnifications requiring hundreds of millions of iterations (like this one).
The Mandelbrot set has an unknown but bound area probably just under 1.5065 yet the perimeter is infinitely long and complex. The more you zoom in on the edge, the more twists and convolutions are revealed. There are several “mini” Mandelbrot sets all around the main form and they are all connected.
This Program’s Mandelbrot Set Locations
There are many well known locations around the Mandelbrot set that have unique features and appearances that give them their colloquial names including: Seahorse Valley, Elephant Valley, Sceptre Valley, and The Needle.
Below are the locations featured in this program.
Download and install Atari emulator
This section describes how to download, install, configure and use the Atari800Win-PLus emulator. If you do not need to install and configure this emulator you may skip this section.
Atari DOS Mandelbrot disk image containing MANDELBRO.BAS and MANDELBRO.LST:
Mandelbrot Set Explorer – 10 lines Atari BASIC.atr
Set the machine type to OS-B
Make sure your ROM images are loaded.
If they are missing you can download them from Github here:
Set your video system to NTSC
You can set it to PAL but he color cycling and possibly rendering will be 1/6 slower. Otherwise it should make no difference on a PC Emulator.
“Insert” the Mandelbrot Set Explorer – 10 lines Atari BASIC.atr disk image in D1:
Atari menu, Disk Drives option or Alt-D
Alternately, you can drag and drop the file onto the running emulator. (you may need to re-enable the BASIC cartridge after drag and drop)
Configure input, you will need to emulate joystick 0 and its button.
I use the default:
Arrows +RCTRL as fire
Check Allow using keyset keys also as regular keys
In Misc menu Preferences uncheck Stop when inactive
This will allow you to let the emulator render in the background while the window does not have focus.
In the View menu select Graphics options… (Alt+G)
The smaller window will render faster, but larger sizes are acceptable.
In View menu set Artifacting… to GTIA
In View menu set Stretching to Scan lines
(my personal preference)
- F7 Toggle Unlimited speed
(to render more quickly, ~30x-50x, I highly recommend using this when rendering)
- F10 Capture image
- F11 Enable fast disk IO
(Turn this on and forget it)
Loading, listing, and running the program
Configure Atari as indicated above, make sure BASIC cartridge is enabled, and Mandelbrot Set Explorer – 10 lines Atari BASIC.atr is inserted in D1: then boot or reset the Atari.
To load the Atari Basic program, at the READY prompt enter:
Alternately you may enter the listing by entering: (they are the same)
If you would like to see the program (optional) listing enter:
Note: All of the abbreviations will be automatically expanded, and if you try to edit the lines on the Atari they will be too long. See How I developed this program below for information about how to edit this program.
To run the program enter:
After a few seconds of initialization you should see the title screen for the first area – Mandelbrot Set at (0,0).
Remember: F7 toggles normal and full speed (muted) which is very useful to speed the rendering.
Joystick (typically arrow keys in emulator)
- Up – Zoom in (enlarge image to double its size)
- Down – Zoom out (shrink image to half its size)
- Right – Move to the next of 12 locations and reset zoom level to default for location
- Left – Move to previous of 12 locations and reset zoom level to default for location
Joystick Button (typically Right CTRL in emulator)
- Title screen: Exits title screen to renderer
- While rendering: Cycles through color cycling modes
Due to potentially lengthy computations, input may be slightly delayed. Sounds confirm will confirm inputs to the user (Note: when running AtariWin800-PLus at full speed using F7, the emulator does not emit sound)
A title screen is displayed whenever moving to a new preset location or changing zoom level and it displays the following information:
- Nickname of location (“MANDELBROT SET”)
- Center coordinates X,Y
- Zoom Z (magnification level, screen x extends from -1 to 1 at zoom 1)
Numbers may be expressed in scientific notation.
For example 2.5e-5 means 2.5 * 10-5 or 2.5 * 0.00001 which equals 0.000025.
These coordinates are compatible with all other Mandelbrot set exploration tools.
Press the joystick button to exit the title screen and begin rendering the Mandelbrot Set!
It takes time to perform the many calculations needed to populate the 15,360 pixel display. Rather than slowly raster fill the display (left to right, top to bottom) this program uses a progressive multi-resolution rendering technique. It starts by filling the 80 column display with three evenly spaced rows stretched vertically 64x to fill the entire 192 line display. Then successive passes twice as many rows (after the second pass), half as tall as the previous pass until the last pass fills in every other row of the display.
Each pixel is calculated exactly once, each 80 pixel row is still calculated from left to right, each row takes roughly the same amount of time to render regardless of its height, and each pass doubles the resolution as the previous pass (as a consequence it also takes about twice as long).
This approach takes the same amount of time to fully draw a screen but a low resolution image is rendered quickly providing a preview that is continuously refined until complete. This quick preview is helpful when zooming and switching locations.
Multi-resolution rendering passes:
While rendering, a single pixel tall cursor is displayed to let the user more easily locate the current rendering location.
Tip: Rendering a single image at normal Atari speeds can take 16 hours or more depending on the complexity, press F7 to toggle “Run Atari as fast as possible” and they can be rendered in 15 ~ 30 minutes.
Color cycling is technically moving color values from color register to color register, instantly changing the colors on the screen without having to change pixels. Rather than cycling 8 values through the 8 color registers to repeat a short pattern, this program cycles 7 colors then adds a constant to the value in the 8th register to cycle through interesting color sequences from 8 to 128 colors in length.
Color cycling is performed continuously when the image is fully rendered and with each pixel calculation while rendering.
Pressing the joystick button will cycle through the 9 color cycling modes above (with a beep).
Detailed description of each of the 9 modes (pictured in left to right top to bottom order above):
- Decreasing intensities then decreasing hues (brightest color first)
- Increasing intensities then increasing hues (darkest color first, reverse of 1)
- Eight increasing hues through eight color registers at constant intensity for continuous hue cycling.
- Increasing hues while descending in intensities (brightest color first)
- Increasing hues while increasing intensities (darkest color first)
- Increasing hues of constant intensity (since there are only 8 color registers and 16 hues, only half the hues will be visible in a sliding window fashion)
- Decreasing hues while descending in intensities (brightest color first)
- Decreasing hues while increasing intensities (darkest color first)
- Decreasing hues of constant intensity (since there are only 8 color registers and 16 hues, only half the hues will be visible in a sliding window fashion)
Interesting notes about the color cycling modes:
- Modes in the left column all cycle with the brightest color first
- Modes in the second column cycle darkest color first
- Modes in the right column only change hue and not brightness (excellent for seeing the boundary of the Mandelbrot Set)
- The first two columns in the first row cycle through intensity then hue
- The first two columns of the last two rows cycle through intensity and hue in each step
Detailed Program Description
10 lines less than 256 characters long
Maximum line length for the contest is 256 characters. The image below shows the longest line (3) is 216 characters long.
Note: Spaces needed to be added after comas in DATA statements below to permit WordPress to wrap lines.
Line by line functional description
1LS=10:MC=81:DI.N$(192),Q(159):F.I=0TOLS-1:F.J=0TO7:Q(78+I*8+J)=8-J:N.J:N.I:F.I=0TO77:REA.X:Q(I)=X:N.I:Z=Q(24):N$="mandelbrot set ":L=0:T=L:Q(158)=L:DC=T
Line 1 is a one time program initialization.
LS=10LS is the number of color cycles in the solution.
MC is the maximum Mandelbrot Calculations depth which is 8*LS+1. The 8 is the number of colors in the screen palette which will be repeated LS times, and the extra one is for the black interior of the unreachable Mandelbrot calculations (see
DI.N$(192),Q(159)Dimension N$, and data array Q. N$ holds the 12 name streams for each location, each 16 characters long (12 * 16 = 192). Q is an array that holds program constants and precalculated data. See Managing program lookup tables and constants below.
Nested I and J loops to precalculate color cycling data in array Q to be used in rendering.
F.I=0TOLS-1The I FOR loop counts through all LS color cycles
F.J=0TO7The J FOR loop counts through 8 colors.
Q(78+I*8+J)=8-Jstored the color value to use for index 0 to 80 (I * 8 + J) which repeatedly counts down from 9 to 1 (8 – J)
FOR I loop reads 78 program constants from DATA statements and places them in the master data array Q for random access later. See Managing program lookup tables and constants below.
Z=Q(24)Zoom factor Z is loaded from the first location of 12 Zoom elements in the constants array.
N$="mandelbrot set "N$ is the area name array, it is temporarily initialized with the first level’s name.
L=0Location index L is initialized to zero.
T=LThe top T of multi-resolution pixels is set to zero by copying L (smaller tokenized line length).
Q(158)=LQ(158) is the last color in the color cycle table and is set to border color zero which is black, again by setting equal to L. This color will be used for all of the pixels with unreachable complexity meaning the function does not diverge to infinity in the 81 iterations (defined by Mandelbrot Calculations variable MC) – these are the black areas of the Mandelbrot images.
DC=TDelta Color index DC is set to zero by copying T. DC is used as an index to lookup the actual delta value that will be added to the color value to achieve the 9 color cycling modes.
2CX=Q(L):CY=Q(L+12):D=64:D2=D*2:H=D-1:GR.18:I=L*16+1:?#6;N$(I,I+15),,,"x";CX,"y";CY,"z";Z:?#6,,,,"press JOY BUTTON":F.I=0TO1:I=1-STRIG(0):POK.77,0:N.I:GR.10
Line 2 is entry to the title screen, main loop point for level select, and sets the graphics mode for rendering after leaving the title screen.
CX=Q(L):CY=Q(L+12)The center of the Mandelbrot rendering CX, CY are read from 12 element portions of the constants array Q offset by the Location index L. These are the center coordinates for each preset location. (The Zoom parameter is read elsewhere)
D=64Delta top D is set to 64 which will start the multi-resolution renderer rendering 64 pixel rows 64 pixels apart in the y (vertical) direction.
D2=D*2D2 is set equal to D so the distance between rows is the same as the pixel height for the first pass, filling the screen.
H=D-1Pixel height H is set to D-1 to account for drawing counting from zero. Drawing from 0 to 63 will draw 64 pixels, any more and we will get errors for trying to draw off the screen.
GR.18is Graphics mode 2+16. Mode 2 is large text, and the +16 means fill the screen with text (do not include a 4 line window of normal Graphics mode 0 characters).
=L*16+1Calculate substring index I based on integer location index L. N$ will be filled with 16 character names, and Atari BASIC strings index from 1. L*16+1. The first time line 2 is executed L is guaranteed to be zero.
?#6 means print to device number 6 which is how to display text in graphics mode 2. Semicolons print strings back to back and commas insert tabs up to 10 spaces (two commas fill a 20 character mode 2 line). The 16 character location name sub-string is printed from N$ at index I followed by a comma to complete the line and two more commas to add a blank line. Then “x” and CX, then a comma (tab), “y” and CY, another comma (tab) and “z” and z. The lengths of these numbers are not controllable so we allow line is allowed to end Z after z.
?#6,,,,"press JOY BUTTON"
The next print includes four commas to skip two lines then prints the mixed case
"press JOY BUTTON". In mode 2 all characters are printed in uppercase, printing mixed upper and lower case prints in different colors. Numbers and punctuation are printed in the same color as upper case.
Wait for the user to press the joystick button while resetting the Atari attract mode timer to prevent color cycling.
STRIG(0)is the trigger of the first joystick. It is 0 when pressed and 1 when not pressed.
This will loop until I is 1 but
1-STRIG(0)will only be 1 when
STRIG(0)is zero when the button is pressed.
POK.77,0will reset the Atari computer attract mode timer preventing the automatic attract mode color cycling intended to protect CRTs in Televisions from image burn in.
GR.10Sets the GTIA graphics mode 10, 80 x 192 pixels capable of 9 colors. Color 0 is set to black and is used for the border and pixels requiring more than the 81 Mandelbrot Calculations this program is capable of.
3N$="mandelbrot set lightning seahorse valley spirals needle (mini) lightning (mini)scepter valley elephant valley needle hairs thorny lightningtails on tails @spine blossom ":IF D<=1 THEN G.6
Line 3 sets all the location names in N$ and skips rendering if the image is completely rendered. Line 3 is executed right after title screens, with each iteration of the multi-resolution renderer, and when the image is fully rendered with each iteration of color cycling.
N$="mandelbrot set lightning seahorse valley spirals needle (mini) lightning (mini)scepter valley elephant valley needle hairs thorny lightningtails on tails @spine blossom "Sets N$ to the full 192 character string containing the 16 character names of the 12 locations in order. This could not be done earlier due to line length limitations.
IF D<=1 THEN G.6
D is delta Y for each line in the multi-resolution renderer. The last pass will render every odd line with a D of 2 (even lines were rendered in previous passes). Each iteration D is divided by 2, when it reaches 1 rendering is done so rendering is skipped, GOTO 6 jumps to color cycling.
Line 4 is the main part of the renderer setting up the nested pixel location loops for Y then X, plotting the cursor, and performing the iterative Mandelbrot calculation
F.Y=T TO191STEPDLoop over all the scan lines in the image starting at top T to the last line 191 stepping delta D which starts at 64 and is halved in each rendering pass
B=CY+(Y-96)/4*ZTransform screen pixel coordinate Y to imaginary (Y) coordinate in Mandelbrot coordinate system B. (A,B are used for real and imaginary coordinates because R and I are used elsewhere)
CYis the y coordinate of the center of the location in Mandelbrot space (on the imaginary y axis)
Y-96centers y on the 192 pixel tall screen (range from -96 to 95)
/4The divide by 4 is to correct for the wide 4:1 aspect ratio of Graphics 10 pixels (80×192 on a 4:3 aspect display)
*Zscales the Y range from -96 to 95 down to the desired zoom level. Small Z values effectively shrink the viewport which magnifies the apparent shape
F.X=0TO79Loop over all 80 columns on a line. All lines in an area of an image take approximately the same time to render based on the complexity of the Mandelbrot calculations.
A=CX+(X-40)*ZTransform screen pixel coordinate X to real (X) coordinate in Mandelbrot coordinate system A. (A,B are used for real and imaginary coordinates because R and I are used elsewhere)
CXis the x coordinate of the center of the location in Mandelbrot space (on the real x axis)
X-40centers X on the 80 pixel wide screen (range from -40 to 39)
*Zscales the X range from -40 to 39 down to the desired zoom level. Small Z values effectively shrink the viewport which magnifies the apparent shape
C.1:PL.X,YDraw the cursor Color 1 plot X,Y. This gives the user an idea of where calculation is being performed and how long until the image may be fully rendered.
R=0:I=R:R2=R:I2=RSet real, imaginary, real squared, and imaginary squared variables to zero. Setting R to zero and other variables to R is an Atari BASIC optimization to fit more on a line.
F.C1=0TOMC-1Calculation count C1 loop from 0 to MC-1, or loop Mandelbrot Calculations (MC) times.
J=R2-I2+A:I=(2*RI)+B:R=J:Perform Mandelbrot calculation
- The Mandelbrot calculation is Zn+1 =Zn2+C in the complex plane.
- Z and C are complex numbers
(x, y*i) where i is the square root of -1
- Z starts as 0 (
- C is the location (A, B*i) derived from the viewport coordinates centered on CX, CY with a viewport scaled by Z (small values magnify)
- Each iteration performs the complex calculation Zn+1 =Zn2+C
J=R2-I2+ACalculate the real portion ZRn+1 = ZRn2 – ZIn2+CR
R2 is precalculated ZRn2 from previous loop
I2 is precalculated ZIn2 from previous loop
A is CR
J is a temporary variable needed so we can complete the imaginary portion of the calculation
I=(2*R*I)+BCalculate the imaginary portion 2*ZRn* ZIn+CI
R is ZRn
I is ZIn
B is CI
R=JAssigns the calculated real portion to R from the temporary variable J
R2=R*R:I2=I*ICalculate ZRn2 and ZIn2
C=C1Save C1 into C for color cycling. At the end of the for loop C1 will be 1 more than the max value, which will cause us out of bounds headaches so we will use the last value saved here in C.
IF(R2+I2)<4THENN.C1Test for divergence
The colored shapes of the Mandelbrot plots you’re familiar with represent the how many iteration it takes before the calculation is divergent (it heads off to infinity). The central areas (typically black) either are not divergent, or require more calculations to resolve the infinite complexity of the boundary of the Mandelbrot set.
It’s proven that Z will be divergent if the magnitude of Z is ever greater than 2. The magnitude of a complex number is calculated as the square root of the sum of the squared real and squared imaginary coefficients: sqrt(ZR2 + ZI2)
Here we calculate the square of the magnitude and test if it is greater than the square of two; it is an optimization to remove a costly square root calculation.
If the function is not yet divergent ( (ZR2 + ZI2)<4 )continue to loop with
5C.Q(C+78):PL.X,Y:DR.X,Y+H:D.0, -0.170337, -0.745107298, -.462160300, -1.6487359367, -0.17485, -1.287769, .3150751, -1.9990959, -1.192101, -0.747227, -1.457758
Line 5 Set the color based on the calculated complexity, plot the top of the pixel, and draws a vertical line to fill the multi-resolution line. The rest of the line is filled with data.
C.Q(C+78)Set color based on complexity C which is the loop iteration count. from line 4 used to index precalculated color cycling table stored in Q in line 1
PL.X,Y:DR.X,Y+HPlot the top of the pixel X,Y and draw a line to the bottom of the pixel X,Y+H
D.0, -0.170337, -0.745107298, -.462160300, -1.6487359367, -0.17485, -1.287769, .3150751, -1.9990959, -1.192101, -0.747227, -1.457758
This data is the X (or real) coordinates of the 12 preset locations.
6F.I=1TO8:POK.704+I,PEEK(705+I):N.I:C=PEEK(713)+Q(36+DC):C=C-INT(C/256)*256:POK.713,C:POK.77,0:S=STICK(0)-5:IF S=10 THEN G.8
Line 6 Performs color cycling, resets attract mode timer, checks for stick input, skipping line 7 if there is none.
F.I=1TO8:POK.704+I,PEEK(705+I):N.Icopy 7 colors “down one” by looping through color locations 1 to 8 (counting from memory location 704 which is the base for all colors in memory). and setting them with data from locations 2 to 9 respectively.
Colors for GTIA graphics modes, including mode 10 must be read and set by peek and poke. Atari BASIC was written to support the earlier CTIA graphics chip and does not provide commands to set or read more than 4 colors. (See “Graphics 10” on GTIA: An Illustrated Overview)
C=PEEK(713)+Q(36+DC):C=C-INT(C/256)*256:POK.713,CPerform color cycling on color 9 in memory location 713 (704+9).
C=PEEK(713)+Q(36+DC)Read color byte from color memory location and add a constant to it to implement color cycling.
DC is the index to the type of color cycling which is determined by the constant that is added to the color register each iteration.
The 9 value color cycling constants table starts at index 36 in Q
Atari computers are capable of displaying 128 colors which are encoded into a bite as follows:
The upper 4 bits represent the 16 possible hues
Even values of the the lower 16 bits represent 8 intensities.
C=C-INT(C/256)*256Atari BASIC lacks modulo and boolean operations. This calculation is equivalent to modulo 256 and this pattern is used frequently in my BASIC programs. See Modulo below for a description of how it works.
POK.713,CStore the adjusted color value back in color 9 in memory location 713 (704+9)
POK.77,0Reset attract mode timer to prevent unwanted color cycling
S=STICK(0)-5:IF S=10 THEN G.8Read Joystick 0 value and skip joystick processing if the stick is in the unmoved centered position.
Tha Atari joysticks return the following values when pushed in the respective directions (15 center):
14 10 6 11 15 7 Atari Joystick values 9 5 13
By subtracting 5 we get these values which are smaller indices for table lookups later. Notice that the center value is 10, so if
S=10 then we skip joystick processing by
9 5 1 6 10 2 Atari Joystick values -5 4 0 8
Line 7 The joystick moved either changing a location or a zoom level. Make a cute joystick acknowledgement chime sound, adjust location, adjust zoom level, partially reset multi-resolution renderer, pop out of X and Y loops and go to Title screen
F.I=24TO0STEP-1:SO.0,I*.4+24,10,I*.75:N.IMake chime sound by looping from 24 to zero and performing a sound statement with the following parameters:
0voice 0 (first of 4 voices)
I*.4+24Pitch range from 33 to 24 (increasing pitch)
10Distortion, 10 is pure square wave
I*.75Volume 18 to 0, decreasing from full volume to silence.
L=L+Q(45+S):L=L-INT(L/12)*12Add delta level to L from constants starting at the 45th element of Q indexed by joystick direction S which is stick direction -5 (and remember
S=10skips this line). Here are the table values.
Indices 0,1,2 all move the stick to the right to the delta level is 1
Indices 4,5,6 all move the stick to the left so the delta level is 11. The
L=L-INT(L/12)*12modulo 12 operation only works on positive values so in order to “decrement” the level 11 (12-1) is added and then the modulus operator works.
Indices 8 and 9 move the stick up and down which are zoom functions that do not impact level so delta level is 0
Set Zoom level. This operates similarly to the level select using table lookups but must be able to reset Z when a new level is selected (left or right on the joystick) or half or double Z when zoom is adjusted (up or down on the joystick)
Atari BASIC lacks ELSE and ENDIF so each IF THEN statement completes a source code line requiring new approaches to solve basic problems when line count is limited. HERE we use the numeric method of choosing coefficients based on stick direction to solve this problem in one equation and table presets.
Q(L+24)Is the initial Z value for the level L, 12 initial Z values are stored in Q starting at index 24
Q(56+S)Is the coefficient for the existing Z value
Notice these are 2 in all downward direction indices, .5 in all upward direction indices, and zero for left and right
Q(67+S)Is the coefficient for the default Z value for the current level L
Notice these are 1 in all left and right direction indices and 0 in up and down
The result is that pushing up, down, left, or right results in one side of the plus sign in the equation being zero and the other having a meaningful value
T=0Reset the top of the multi-resolution pixel to 0
DC=TReset color cycling type to 0
POP:POP:G.2Pop out of X and Y loops and goto line 2 to display the Title screen for the current location and zoom level.
8IF STRIG(0)=0 THEN SO.1,20,10,15:SO.1,20,10,0:F.I=0 TO 1:I=STRIG(0):POK.77,0:NEXT I: POK.713,11:DC=DC+1:DC=DC-INT(DC/9)*9
Line 8 reads the joystick button while rendering and if pressed acknowledges with a chirp and cycles through the 9 color cycling modes.
IF STRIG(0)=0 THENTests to see if the button is pressed,
STRIG(0)is 0 when pressed
SO.1,20,10,15:SO.1,20,10,0Emits a chirp on voice 1, frequency 20, distortion 10 (pure square wave), volume 15 then immediately 0 in the second command
F.I=0 TO 1:I=STRIG(0):POK.77,0:NEXT ILoop similar to one used in line 2, but this one waits for the button to be released (
POKE 77,0again in the loop to reset attract mode timer.
POK.713,11Set color value to a known value so cycling is deterministic (not dependent on the value in the color register when button is hit)
DC=DC+1:DC=DC-INT(DC/9)*9Increment color cycling type index DC and perform modulo 9 on the value.
9IF D>1 AND S=10 THEN N.X:N.Y:D2=D2/2:D=D2:T=D/2:H=T-1:D.0, -1.06506, -0.15020534, -.5823998, 0, -1.071623, .063761, .02918, -0.000000063, 0.3061769, 0.105766, -0.001353
Line 9 if renderer is active then continue looping through all pixels on the screen, then adjust the multi-resolution renderer for the next pass. Line contains data statement with Y values for 12 preset locations.
IF D>1 AND S=10 THENIf delta line D is two or greater and the stick is not pushed in any direction then the renderer is still active so…
Finish looping through pixels in the current pass of the renderer then (still in the
- Reset multi-resolution renderer for next pass
D2=D2/2Divide D2 by 2
D=D2Set D to D2
T=D/2Set the top of the next pixel to half the delta D (fills bottom half of previous row)
H=T-1Set row height to be the top index (halfway down previous row) -1. The minus 1 is to account for starting drawing at pixel offset 0, so 0 to T-1 actually covers T pixels exactly. (without it there would be draw out of bounds error.
D.0, -1.06506, -0.15020534, -.5823998, 0, -1.071623, .063761, .02918, -0.000000063, 0.3061769, 0.105766, -0.001353
Data statement containing Y values for 12 preset locations.
DATAstatement is not impacted by the
10.G.3:D.0.05, .000001, .000002, .0001, .000001, 0.000045, .000004, .0004, .00000003, .00001, 0.000147, 0.00002, 254, 2, 32, 14, 18, 16, 238, 242, 240, 1, 1, 1, 0, 11, 11, 11, 0, 0, 0, 0, 2, .5, 0, 0, 2, .5, 0, 0, 2, .5, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0
Line 10 is the final loop statement for the renderer and the data statement containing the remainder of the preset constants needed by the program
G.3Forever loop that contains the multi-resolution renderer, color cycling, and user input.
D.0.05, .000001, .000002, .0001, .000001, 0.000045, .000004, .0004, .00000003, .00001, 0.000147, 0.00002, 254, 2, 32, 14, 18, 16, 238, 242, 240, 1, 1, 1, 0, 11, 11, 11, 0, 0, 0, 0, 2, .5, 0, 0, 2, .5, 0, 0, 2, .5, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0
Data statement containing:
- Zoom levels for 12 preset locations (12)
- Color cycling deltas for 9 color cycling modes (9)
- Z multipliers for joystick direction lookup (11)
- Level default Z multipliers for direction lookup (11)
Special features of this program
GTIA Graphics 10
Atari computers originally shipped with the CTIA chip only capable of displaying a background and up to three foreground colors from a 128 color palette (16 hues each with 8 intensities)
The GTIA chip released shortly after the Atari 400/800 were released offered three new graphics modes:
- Graphics 9 provides 16 intensities of any hue
- Graphics 10 used by this program uses all of the background (1), foreground (3), player (4), and missile (1) color registers to provide 9 color bitmapped graphics with programmable color registers
- Graphics 11 provides 16 hues at any singleintensity
- For more information see GTIA: An Illustrated Overview
Memory locations (PEEK/POKE)
704-712 Color registers
- High 4 bits 16 hues, lower 4 bits 8 intensities (low bit is ignored, see image above for 128 color palette of Atari computers).
- Atari BASIC has no command to read a color and SETCOLOR is only able to set the background and 3 foreground colors.
- The only way to read and write GTIA Graphics mode 10 colors is by using PEEK and POKE respectively to access locations 704 to 712.
77 attract mode timer
- The Atari computers have a built in “Attract Mode” that automatically begin cycling colors of the display. The term “Attract Mode” refers to attracting people to interact with the computer in a store, the theory being that the color changing would get peoples attention more than a static display. The Attract Mode was also needed to prevent CRT burn in. When a television displays the same image for a long period of time the phosphor in the display can be permanently marked. The color cycling in the attract mode prevents this both for in-store and home TV’s.
- An interactive Atari BASIC application can disable the automatic Attract Mode by frequently resetting the internal Attract Mode timer to 0 with a
- For more technical details see location 77 in Atari Computer Memory Map
No ELSE, no ENDIF
Atari BASIC has IF <expr> THEN <expr>:<expr>…
But is has no ELSE, nor ENDIF statements. This means that the remainder of any line after an IF THEN statement will be committed to the conditional statement; all statements after THEN will only be executed if the expression is true.
This is especially limiting in this kind of contest where the program may only have 10 lines. Here are strategies I used to work around this limitation:
- Use lookup tables indexed by joystick input to selectively change levels or zoom.
L=L+Q(45+S)in line 7
S is an index derived from joystick 0 direction, some values in the Q data table are 0 which will not change the level (joystick center, up, down), some are +1 (joystick right) to increment the level, and some are +11 (joystick left) which when used with the modulo function below effectively decrement the level.
- Use algebraic strategies to weight calculations based on data lookup rather than perform IF THEN conditional statements. This strategy calculates the answer for multiple conditions and then multiplies each result by coefficients of 0 or 1 and sums the results. (A strategy I’ve also used in graphics shaders, and vector processing)
Z=Z*Q(56+S)+Q(L+24)*Q(67+S)in line 7
- Use Modulo function (see below) to clamp integer values to ranges
- 256 for color cycling values
C=C-INT(C/256)*256in line 6
- 12 locations
L=L-INT(L/12)*12in line 7
- 9 color cycling modes
DC=DC-INT(DC/9)*9in line 8
- 256 for color cycling values
- Use GOTO at the end of IF THEN to skip over lines, effectively an ELSE. See lines 3 and 6.
- Fill ends of conditional statements with DATA which is not impacted by flow control statements like IF THEN or GOTO.
A modulo or modulus function returns the remainder of a division operation. For example MOD(A,B) would return the remainder of A/B, so for A=10, and B=5 would return 0, for A=10 and B=3 would return 1. (limiting to integers for simplicity here)
The example most often used to illustrate modulus math is a clock. You can keep adding hours to a clock and eventually as the hour hand passes midnight it will reset to 0. No matter how many hours you add to a clock, when you read it the hour hand it will always display a value between 0 and 12 hours, which represents the modulus of the total number of hours and 12 which is the same as remainder of the total number of hours divided by 12.
A modulo operator is really handy when programmatically cycling through a limited number of values (like menu options) or performing a math operation and bounding the output value (like a color register) because if the inputs are positive integers then the output will be an integer between 0 and the numerator minus 1.
Atari BASIC lacks binary logic operations AND, OR, XOR, and a modulo function. Binary logic operations can perform fast modulo operations on numbers that are a power of 2 by masking bits out of range. For example, MOD(8,B) is the same as B AND (8-1). The explanation is beyond the scope of this article but it is FAST and really handy.
I’ve always used this technique in Atari BASIC to calculate a modulo operation on positive integers.
Let’s break it down from the inside out.
A/B will be < 1 if B<A
A/B will >=1 if B>=A
INT is the integer operator with in Atari BASIC always rounds down to the nearest integer less than the value provided
INT(A/B) will be 0 if B<A
INT(A/B) will be a positive integer if B>A. That integer is the number of times B can be subtracted from A
INT(A/B)*B will be 0 if B<A
INT(A/B)*B will be a positive integer if B>A. This integer is the greatest multiple of B less than A.
So, A-INT(A/B)*B will subtract from A the portion of A that is from multiples of B, leaving the remainder of A/B
This modulo calculation is used in the program to wrap three values:
- The number of locations to 12:
in line 7
- the number of color cycling modes to 9:
DC=DC-INT(DC/9)*9in line 8
- and the color register to 256 (the size of a byte):
C=C-INT(C/256)*256in line 6
Since this approach works for positive integers, how does the program decrement values? It adds the number of elements minus 1.
Using a clock as an example: If it is 5 o’clock:
- If we add 1 hour it will display 6 o’clock
- If we add 12 hours the hand will spin all the way around and it will display 5 o’clock: adding the modulus is the same as adding 0
- If we add 11 hours the hands will spin almost all the way around but will be short by 1 hour and it will display 4 o’clock: subtracting values are the same as adding the modulus the value, in this case 12-1.
This program uses the third point, subtracting a value is equivalent to adding modulus minus that value in order to implement wrapping adds in location selection, color cycling mode selection, and color cycling itself.
Managing program lookup tables and constants
This program uses a lot of data that needs to be indexed like tables, some is precomputed at initialization and some is predefined. To keep the program as short and simple as possible all the constants are stored in a single array called Q. Line 1 initializes Q by performing precomputation of color table values and READing predefined data from DATA statements. The DATA statements are spread throughout the program but are read in order.
The data is accessed many places in the program by referencing Q(base_index+offset). For example in line 2
CY=Q(L+12) is loading the center y coordinate
CY from the
Q array at index
12 plus the current location
L. If you look in the contents below you will find the offset to the center Y location table is at offset 12 and the table contains 12 elements.
Data array Q contents:
0 (12 elements) Center X coordinates for 12 program locations
12 (12 elements) Center Y coordinates for 12 program locations
24 (12 elements) Default Zoom for 12 program locations
36 (9 elements) Delta Color for each of the 9 color cycling modes
45 (11 elements) Delta Level indexed by joystick 0 direction
56 (11 elements) Z multiplier (0.5,2) indexed by joystick 0 direction
67 (11 elements) Initialization (0,1) Z multiplier indexed by joystick 0 direction
78 (81 elements) Color to plot indexed by number of Mandelbrot calculations
How I developed this program
Atari BASIC automatically expands abbreviations and artificially short line lengths are enforced by the built in editor. The way to work around this limitation is to edit the program externally as a text file and use the
ENTER command to read the text file into the interpreter (as opposed to
LOAD which create and read an Atari BASIC tokenized file). The Atari800Win-PLus emulator allows you to map a folder on the host as device H: (Atari menu, Settings option, Enable H: patch for hard disk access).
The next challenge is that Atari uses 155 (0x9B) as a line terminator and fails to read text files with conventional carriage return (CR, 13, 0x0D) or linefeed (LF, 10, 0x0A) line terminators. To discover this I used the HxD hexadecimal editor to inspect program listings I made in Atari BASIC.
To develop the program, I edited a conventional text version of the program in Notepad++. To test the program I copied the text to MANDELBR.LST, replaced the line endings, saved the file, and used
ENTER"H:MANDELBR.LST" in the emulator to load the program. This process was iterated (a lot!).
When the program was complete I took the following steps to create the contest disk image:
- Booted the emulator with a blank Atari DOS 2.0S image called Mandelbrot Set Explorer – 10 lines Atari BASIC.atr
- From DOS used option C COPY FILE to copy H:MANDELBR.LST to D1:MANDELBR.LST
- From DOS used option B RUN CARTRIDGE to exit to BASIC
ENTER"D1:MANDELBR.LST"to load the program
RUNto verify that it works, then Break to stop program execution
SAVE"D1:MANDELBR.BAS"to save an Atari BASIC format file
References for programming Atari Computers
- Atari BASIC Reference Manual
- Atari BASIC abbreviations
- Graphics Modes And Color Registers
- GTIA: An Illustrated Overview
- Atari Computer Memory Map
- Strings in Atari BASIC
Mandelbrot Set Projects New And Old
I’m working on a followup project composing deep dive videos from 297 color cycling images generated by this program. Atari Chiptune artist Adam Sporka has generously agreed to to provide all the music for these videos. They are turning out awesome, even though they are composited with modern software on modern computers, it’s amazing to see and hear every pixel and sound that was originally generated on Atari computers.
It’s done! The videos, playlists, and details are all here: Atari 8 Bit Mandelbrot Set Zoom Videos
Other Mandelbrot Set related projects…
I’ve explored the Mandelbrot Set in a couple previous projects. The Python ASCII Mandelbrot project …
and VT100 terminal Mandelbrot project…
The source code is included in the YouTube video descriptions. I also wrote a Python VT100 Mandelbrot set explorer (not pictured here) that was configured to match the capabilities of this Atari BASIC program and used to pinpoint the 12 preset locations.
I’d like to give a shout out to my local makerspace Workshop 88, a like minded talented creative community active in the Chicago suburbs and accessible throughout the world. Be sure to check out the rest of this blog, our YouTube Maker Meeting videos, an all our socials (Facebook, Twitter, MeetUp…). You can join (or support) our community from anywhere in the world on Patreon.
I’d like to like to recognize and thank my father Dennis Williamson, and uncles Don Bahr, Henry Bahr, and Tom Mammoser for fostering my early interest in computers, electronics, and Atari as well as my grandparents Herbert and Virginia Williamson for my first Atari 400 computer and unlimited love, support, and encouragement.
I had a lot of fun writing this program, writing this article, and on the upcoming Atari Mandelbrot Set deep dive video project. In writing the detailed description of the code I discovered a few minor bugs, see if you can find them!