#!/usr/bin/env python

import numpy as np
import scipy.ndimage


def noise2d(width, height, smooth=1.8, filter_mode='wrap', falloff=0.02,
            power=3):
    rng = np.random.default_rng()
    x = np.zeros((1, 1))  # Zero mean
    iterations = int(np.ceil(np.log(max(width, height)) / np.log(power)))
    falloff *= smooth
    contribution = 1
    for i in range(iterations):
        upscaled = np.zeros((x.shape[0] * power, x.shape[1] * power))
        upscaled[power // 2::power, power // 2::power] = x
        x = scipy.ndimage.gaussian_filter(upscaled, smooth, mode=filter_mode)
        x += rng.normal(scale=contribution, size=x.shape)
        contribution *= falloff

    return x[:width, :height]
