King's dream fractal with generativepy


Martin McBride, 2021-06-07
Tags kings dream fractal
Categories generativepy generative art

The king's dream fractal works in a similar way to the tinkerbell fractal. It is worth reading the tinkerbell fractal article, and the article on colorising tinkerbell before tackling the king's dream fractal in this article.

Kings dream formula

The fractal equations for king's dream are:

xnext = math.sin(A*x)+B*math.sin(A*y)
ynext = math.sin(C*x)+D*math.sin(C*y)

Where:

A = 2.879879
B = -0.765145
C = -0.966918
D = 0.744728

Here is the image it creates:

The code

Here is the full code for the image above:

from generativepy.bitmap import Scaler
from generativepy.nparray import make_nparray_data, save_nparray, load_nparray, make_npcolormap, apply_npcolormap, save_nparray_image
from generativepy.color import Color
import math
import numpy as np

MAX_COUNT = 10000000
A = 2.879879
B = -0.765145
C = -0.966918
D = 0.744728


def paint(image, pixel_width, pixel_height, frame_no, frame_count):
    scaler = Scaler(pixel_width, pixel_height, width=4, startx=-2, starty=-2)

    x = 2
    y = 2
    for i in range(MAX_COUNT):
        x, y = math.sin(A*x)+B*math.sin(A*y), math.sin(C*x)+D*math.sin(C*y)
        px, py = scaler.user_to_device(x, y)
        image[py, px] += 1


def colorise(counts):
    counts = np.reshape(counts, (counts.shape[0], counts.shape[1]))
    power_counts = np.power(counts, 0.25)
    maxcount = np.max(power_counts)
    normalised_counts = (power_counts * 1023 / max(maxcount, 1)).astype(np.uint32)

    colormap = make_npcolormap(1024, [Color('black'), Color('red'), Color('orange'), Color('yellow'), Color('white')])

    outarray = np.zeros((counts.shape[0], counts.shape[1], 3), dtype=np.uint8)
    apply_npcolormap(outarray, normalised_counts, colormap)
    return outarray


data = make_nparray_data(paint, 600, 600, channels=1)

save_nparray("/tmp/temp.dat", data)
data = load_nparray("/tmp/temp.dat")

frame = colorise(data)

save_nparray_image('kings-dream.png', frame)

Variants

You can try different values of the constants. A and B need to be in the range -3 tp +3, while C and D need to be in the range -1.5 to +1.5, otherwise the values wil fly off to infinity rather than creating a pattern.

Be aware that most numbers you choose will not create pleasing patterns. You will need to experiment to find something that looks nice, and then do even more fine tuning to get something really nice.

You can also try varying the function. You can replace sin with cos in some or all of the equations. This will give different but similar patterns.

See the fractals article for a list of other fractal examples.

If you found this article useful, you might be interested in the book Computer Graphics in Python or other books by the same author.

Prev

Popular tags

2d arrays abstract data type alignment and animation arc array arrays bezier curve built-in function callable object circle classes close closure cmyk colour comparison operator comprehension context context manager conversion creational pattern data types design pattern device space dictionary drawing duck typing efficiency else encryption enumerate fill filter font font style for loop function function composition function plot functools game development generativepy tutorial generator geometry gif gradient greyscale higher order function hsl html image image processing imagesurface immutable object index inner function input installing iter iterable iterator itertools l system lambda function len line linspace list list comprehension logical operator lru_cache magic method mandelbrot mandelbrot set map monad mutability named parameter numeric python numpy object open operator optional parameter or partial application path polygon positional parameter print pure function pycairo radial gradient range recipes rectangle recursion reduce rgb rotation scaling sector segment sequence singleton slice slicing sound spirograph sprite square str stream string stroke subpath symmetric encryption template text text metrics tinkerbell fractal transform translation transparency tuple turtle unpacking user space vectorisation webserver website while loop zip