3

I am attempting to replicate realistic vegetation placement on a 2d grid. To accomplish this I am using poisson disc sampling (Bridson algorithm) vegetation placement and perlin noise to determine density of vegetation per area.

When I exclude perlin noise and keep a constant minimum distance, I achieve desirable results. However, when I vary the minimum distance via perlin noise, the results do not make sense.

What am I doing incorrectly?

Python 3.4.4. I attempted looking at psuedo-code from here, i've looked around StackOverflow, even here. I also copied the code from [github] (https://github.com/emulbreh/bridson) and altered it slightly.

But I cannot seem to grasp my error.

main.py

import subprocess as sp

import matplotlib.pyplot as plt
import numpy as np
from scipy.misc import toimage


import noise

from Poisson import poisson_disc_samples


def generate_perlin_poisson(width, height):

    # Perlin Noise
    print('Perlin Noise')
    shape = (height, width)
    scale = 100.0
    octaves = 6
    persistence = 0.5
    lacunarity = 2.0

    world = np.zeros(shape)
    for i in range(shape[0]):
        for j in range(shape[1]):
            world[i][j] = noise.pnoise2(i / scale,
                                        j / scale,
                                        octaves=octaves,
                                        persistence=persistence,
                                        lacunarity=lacunarity,
                                        repeatx=shape[0],
                                        repeaty=shape[1],
                                        base=0)
    toimage(world).show()

    min_rad = 1
    max_rad = 5
    z = np.interp(world, (np.amin(world), np.amax(world)), (min_rad, max_rad))

    # # Notepad PrintOut
    # fileName = 'perlin_world.txt'
    # programName = "notepad.exe"
    # with open(fileName, 'w') as f:
    #     for row in range(z.shape[0]):
    #         # print(row, z[row])
    #         f.write(str(z[row].tolist()) + '\n')
    #
    # sp.Popen([programName, fileName])

    # Bridson Poisson Disc Sampling
    print('Bridson Poisson Disc Sampling')
    plt.scatter(*zip(*poisson_disc_samples(width=height, height=width, r_max=max_rad, r_min=min_rad, r_array=z)), c='g', alpha=0.6, lw=0)
    plt.show()

    print('Completed.')


if __name__ == '__main__':
    width, height = 256, 256
    generate_perlin_poisson(width, height)

Poisson.py

from random import random
from math import cos, sin, floor, sqrt, pi, ceil


def euclidean_distance(a, b):
    dx = a[0] - b[0]
    dy = a[1] - b[1]
    return sqrt(dx * dx + dy * dy)


def poisson_disc_samples(width, height, r_max, r_min, k=3, r_array=[], distance=euclidean_distance, random=random):
    tau = 2 * pi
    cellsize = r_max / sqrt(2)

    grid_width = int(ceil(width / cellsize))
    grid_height = int(ceil(height / cellsize))
    grid = [None] * (grid_width * grid_height)

    def grid_coords(p):
        return int(floor(p[0] / cellsize)), int(floor(p[1] / cellsize))

    def fits(p, gx, gy, r):
        yrange = list(range(max(gy - 2, 0), min(gy + 3, grid_height)))
        for x in range(max(gx - 2, 0), min(gx + 3, grid_width)):
            for y in yrange:
                g = grid[x + y * grid_width]
                if g is None:
                    continue

                r = r_array[int(floor(g[0]))][int(floor(g[1]))]
                if distance(p, g) <= r:  # too close
                    return False
        return True

    p = width * random(), height * random()
    queue = [p]
    grid_x, grid_y = grid_coords(p)
    grid[grid_x + grid_y * grid_width] = p

    z_max = width * height * 8
    z = 0

    while queue:
        qindex = int(random() * len(queue))  # select random point from queue
        qx, qy = queue.pop(qindex)
        r = r_array[int(floor(qx))][int(floor(qy))]
        # print('min_dist:', r)

        z += 1
        if z > z_max:
            print('max iteration exceeded')
            break

        for _ in range(k):
            alpha = tau * random()
            d = r * sqrt(3 * random() + 1)
            px = qx + d * cos(alpha)
            py = qy + d * sin(alpha)

            if not (0 <= px < width and 0 <= py < height):
                continue

            p = (px, py)
            grid_x, grid_y = grid_coords(p)
            if not fits(p, grid_x, grid_y, r):
                continue
            queue.append(p)
            grid[grid_x + grid_y * grid_width] = p
    return [p for p in grid if p is not None]

I expected results like this:

image taken from https://imgur.com/LKOsjh2

where I can almost visualize the perlin noise map. Btw this is from the 1st link up above.

But I get outputs like this:

image taken from https://imgur.com/j4W6Hup

The gray scale map is the associated generated perlin noise.

I am aware there are more efficient ways of doing things. I plan to stick to Python however.

questionasker
  • 2,536
  • 12
  • 55
  • 119
Kevin Alvarez
  • 311
  • 2
  • 15

1 Answers1

0

One issue I see is that k=3. If you look at Bridson's original article, he recommends k=30. If k is too low, you are not testing enough to see if a candidate point is close to an existing point. That could easily lead to unexpected clumping, as you see in your output. Another problem is that the generic Bridson algorithm assumes a static value for r, but the clumping you get with Perlin is because you are varying r with the noise value. The Bridson algorithm has to be modified pretty substantially, since r drives the cell size.