summaryrefslogtreecommitdiffstats
path: root/mandelbrot.go
blob: 686625bcf6d5a24e145e2ea58f4a6c2b1385b126 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package main

import (
	"fmt"
	"os"
	"syscall"
	"unsafe"
)

func terminalSize() (cols int, lines int, err error) {
	const tiocgwinsz uintptr = 21523

	ts := new(struct {
		wsRow, wsCol, wsXPixel, wsYPixel uint16
	})
	if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, 1, tiocgwinsz, uintptr(unsafe.Pointer(ts))); err != 0 {
		return 0, 0, err
	}
	return int(ts.wsCol), int(ts.wsRow), nil
}

func mandelbrot(x0, y0 float64) int {
	var x, y, x2, y2 float64
	for i := 0; i < 1000; i++ {
		if x2+y2 > 4 {
			return (i-1)%6 + 1
		}
		y = (x+x)*y + y0
		x = x2 - y2 + x0
		x2 = x * x
		y2 = y * y
	}
	return 0
}

func main() {
	const (
		xMin   = -2.
		xRange = 2.47
		yMin   = -1.12
		yRange = 2.24
	)

	width, height, err := terminalSize()
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

	xStep := xRange / float64(width)
	yStep := yRange / float64(height)

	y := yMin
	for i := 0; i < height; i++ {
		x := xMin
		for j := 0; j < width; j++ {
			fmt.Printf("\033[4%dm ", mandelbrot(x, y))
			x += xStep
		}
		fmt.Println("\033[49m")
		y += yStep
	}
}