Skip to content

Instantly share code, notes, and snippets.

@nitori
Last active December 17, 2015 05:10
Show Gist options
  • Save nitori/157fb8d052cdb73085e8 to your computer and use it in GitHub Desktop.
Save nitori/157fb8d052cdb73085e8 to your computer and use it in GitHub Desktop.
from itertools import product
import random
from noise import snoise2
from PIL import Image
import numpy as np
size = (500, 500)
shape = (size[1], size[0])
im = Image.new('RGB', size)
terrain = np.zeros(shape, dtype='uint8')
mountains = np.zeros(shape, dtype='uint8')
forest = np.zeros(shape, dtype='uint8')
terrain_kw = dict(
octaves=10,
persistence=0.6,
repeatx=1000 + (random.random() * 100 - 50),
repeaty=1001 + (random.random() * 100 - 50),
base=0.0,
)
mountain_kw = dict(
octaves=10,
persistence=0.6,
repeatx=999 + (random.random() * 100 - 50),
repeaty=1002 + (random.random() * 100 - 50),
base=0.0,
)
forest_kw = dict(
octaves=10,
persistence=0.6,
repeatx=998 + (random.random() * 100 - 50),
repeaty=1003 + (random.random() * 100 - 50),
base=0.0,
)
mountain_th = 0.4
forest_th_lo = 0.2
forest_th_hi = mountain_th + 0.1
stretch_factor = 3
zoom = 16.0 * 32
for y, x in product(*(range(n) for n in size)):
terrain_z = snoise2(
x/zoom,
y/zoom,
**terrain_kw
)
terrain_z = min(1.0, max(-1.0, terrain_z * 2))
mountain_z = snoise2(
x/zoom,
y/zoom,
**mountain_kw
)
forest_z = snoise2(
x/zoom,
y/zoom,
**forest_kw
)
if terrain_z >= 0:
terrain[x,y] = 255
if terrain_z >= mountain_th and mountain_z >= 0.0:
mountains[x,y] = 255
if (forest_th_lo <= terrain_z <= forest_th_hi) and forest_z >= 0.0:
forest[x,y] = 255
def l_to_rgb(im, f):
w, h = im.shape
ret = np.empty((w, h, 3), dtype=np.uint8)
ret[:, :, 0] = im * f[0]
ret[:, :, 1] = im * f[1]
ret[:, :, 2] = im * f[2]
return ret
terrain_rgb = l_to_rgb(terrain, (0, 1, 0))
mountains_rgb = l_to_rgb(mountains, (0.5, 0.5, 0.5))
forest_rgb = l_to_rgb(forest, (0, 0.5, 0))
im.frombytes(terrain_rgb)
im = im.convert('RGB')
im2 = Image.new('RGB', size)
im2.frombytes(mountains_rgb)
im3 = Image.new('RGB', size)
im3.frombytes(forest_rgb)
mask2 = Image.new('L', size)
mask2.frombytes(mountains)
mask3 = Image.new('L', size)
mask3.frombytes(forest)
im.paste(im2, (0, 0), mask2)
im.paste(im3, (0, 0), mask3)
im.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment