Skip to content

Instantly share code, notes, and snippets.

@ikr7
Last active October 17, 2021 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ikr7/195a8ebd18333987d51960808fae3ce8 to your computer and use it in GitHub Desktop.
Save ikr7/195a8ebd18333987d51960808fae3ce8 to your computer and use it in GitHub Desktop.
Draws mandelbrot fractal on sixel-enabled terminal. Worked on @ayosec 's fork of alacritty ( https://github.com/ayosec/alacritty/tree/graphics )
"""
usage:
$ python sixel-mandelbrot.py
or
$ python sixel-mandelbrot.py 300
"""
import sys
import fcntl, termios, struct
ESC = '\x1b'
_, _, canvas_width, canvas_height = struct.unpack(
'HHHH',
fcntl.ioctl(0, termios.TIOCGWINSZ, struct.pack('HHHH', 0, 0, 0, 0))
)
canvas_width = int(sys.argv[1]) if len(sys.argv) > 1 else canvas_width
def calculate_color(x, y):
z = 0 + 0j
c = complex(x, y)
for _ in range(40):
z = z * z + c
if abs(z) > 2:
return 0
return 1
delta = 3 / canvas_width
sys.stdout.write(ESC + 'Pq')
sys.stdout.write(
'#0;2;100;100;100'
'#1;2;0;0;0'
)
code = ord('?')
for sy in range(int(canvas_width / 1.5 / 6)):
y = -1 + sy * delta * 6
line = '#1'
for sx in range(canvas_width):
x = -2 + sx * delta
colors = [ calculate_color(x, y + delta * sub_y) for sub_y in range(6) ]
offset = 0
for bit in reversed(colors):
offset = (offset << 1) | bit
line += chr(code + offset)
sys.stdout.write(line + '-')
sys.stdout.write(ESC + '\\')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment