Skip to content

Instantly share code, notes, and snippets.

@illarion
Last active August 1, 2018 15:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save illarion/30bf155e4eddc066945b78632dd1c276 to your computer and use it in GitHub Desktop.
Save illarion/30bf155e4eddc066945b78632dd1c276 to your computer and use it in GitHub Desktop.
Mandelbrot set golang implementation
package main
import (
"image"
"image/color"
"image/draw"
"image/png"
"os"
)
type pixel struct {
x, y int
color color.RGBA64
}
type window struct {
image.Rectangle
kx, ky float64
minReal float64
minImag float64
}
func newWindow(bounds image.Rectangle, minReal, maxReal, minImag, maxImag float64) window {
return window{
Rectangle: bounds,
kx: float64(bounds.Max.X-bounds.Min.X) / (maxReal - minReal),
ky: float64(bounds.Max.Y-bounds.Min.Y) / (maxImag - minImag),
minReal: minReal,
minImag: minImag,
}
}
func (w window) toComplex(x, y int) complex128 {
return complex(float64(x-w.Min.X)/w.kx+w.minReal, float64(y-w.Min.X)/w.ky+w.minImag)
}
func mandel(w window, iterations int, result chan pixel) {
maxuint16 := ^uint16(0)
colorK := maxuint16 / uint16(iterations)
for x := w.Min.X; x < w.Max.X; x++ {
for y := w.Min.Y; y <= w.Max.Y; y++ {
c := w.toComplex(x, y)
z := complex(0, 0)
for i := 0; i < iterations; i++ {
z = z*z + c
if real(z)*real(z)+imag(z)*imag(z) > 4 {
clr := uint16(i) * colorK
result <- pixel{
x: x,
y: y,
color: color.RGBA64{
R: clr / 3,
G: clr / 2,
B: clr,
A: maxuint16,
},
}
break
}
}
}
}
close(result)
}
func main() {
bounds := image.Rectangle{
Max: image.Point{
300,
300,
},
}
img := image.NewRGBA64(bounds)
draw.Draw(img, img.Bounds(), &image.Uniform{color.Black}, img.Bounds().Min, draw.Over)
w := newWindow(bounds, -2.0, 1, -1.5, 1.5)
result := make(chan pixel)
iters := 30
go mandel(w, iters, result)
for p := range result {
img.Set(p.x, p.y, p.color)
}
png.Encode(os.Stdout, img)
}
@illarion
Copy link
Author

illarion commented Apr 8, 2017

out

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment