def generate_tile(x, y, zoom=8, seed=0): tile_entity = '{0};{1}'.format(x, y) tile = {'entity': tile_entity} # # TODO: make these cached and configurable m_lower_min = 0.8 m_lower_max = 1.2 m_upper_min = 0.0 m_upper_max = 0.0 t_lower_min = 0.2 t_lower_max = 1.0 t_upper_min = 0.0 t_upper_max = 0.2 # # terrain type # TODO: cache OpenSimplex() objects instead of re-creating for each tile call elevation = _norm(os.OpenSimplex(seed + 1).noise2d(x / zoom, y / zoom)) moisture = _norm(os.OpenSimplex(seed + 2).noise2d(x / zoom, y / zoom)) m_lower = _scale(moisture, m_lower_min, m_lower_max) m_upper = _scale(moisture, m_upper_min, m_upper_max) moisture = _scale(moisture, m_lower, m_upper) temperature = _norm(os.OpenSimplex(seed + 3).noise2d(x / zoom, y / zoom)) t_lower = _scale(temperature, t_lower_min, t_lower_max) t_upper = _scale(temperature, t_upper_min, t_upper_max) temperature = _scale(temperature, t_lower, t_upper) tile['elevation'] = elevation tile['moisture'] = moisture tile['temperature'] = temperature tile['biome'] = _biome(moisture, temperature) # TODO: dynamically load plant definitions from elsewhere and loop through them or something plants = [] if 0.2 < temperature < 0.6 and 0.2 < moisture < 0.8: plants.append({ 'entity': tile_entity + ';apple tree', 'growth_rate': 10, 'growth': 100, 'plant': 'apple tree', 'fruit': 'apples', 'fruit_growth': 100, 'fruit_growth_rate': 4, 'fruit_count': 8 }) if 0.5 < temperature < 1.0 and 0.0 < moisture < 0.5: plants.append({ 'entity': tile_entity + ';fire berry bush', 'growth_rate': 4, 'growth': 100, 'max_quantity': 25, 'plant': 'fire berry bush', 'fruit': 'fire berries', 'fruit_growth': 100, 'fruit_growth_rate': 5, 'fruit_count': 46 }) tile['plants'] = [x['plant'] for x in plants] return tile, plants
def setSeed(newSeed): #Newseed should be a string global seed, localElevationNoise, largeElevationNoise numSeed = 0 for char in newSeed: numSeed += ord(char) seed = numSeed random.seed(seed) localElevationNoise = opensimplex.OpenSimplex(randInt()) largeElevationNoise = opensimplex.OpenSimplex(randInt())
def __init__(self, size, seed=None, frequency=None): self.seed = seed or random.randrange(2**32) self.freq = frequency or random.randrange(5, 10) self.size = self.width, self.height = size noise = self.gen_noise(simp.OpenSimplex(self.seed), self.freq) self.terrain = self.gen_map(noise) print(self)
class DefaultTemperatureLayer(Layer): noise = opensimplex.OpenSimplex(seed=random.randint(-10000, 10000)) @staticmethod def normalize_config(config: LayerConfig): if not hasattr(config, "min"): config.min = -0.5 if not hasattr(config, "max"): config.max = 2. if not hasattr(config, "size"): config.size = 2 NAME = "temperaturemap" @staticmethod def add_generate_functions_to_chunk(config: LayerConfig, chunk): chunk.chunkgenerationtasks.append([ DefaultTemperatureLayer.generate_temperature, [chunk, config], {} ]) @staticmethod def generate_temperature(chunk, config): cx, cz = chunk.position temperaturemap = chunk.get_value("temperaturemap") factor = 10**config.size r = [config.min, config.max] for x in range(cx * 16, cx * 16 + 16): for z in range(cz * 16, cz * 16 + 16): v = DefaultTemperatureLayer.noise.noise2d( x / factor, z / factor) v = v / 2. + .5 v *= abs(r[0] - r[1]) v += r[0] temperaturemap[(x, z)] = v
class DefaultBiomeMapLayer(Layer): noise = opensimplex.OpenSimplex(seed=random.randint(-10000, 10000)) @staticmethod def normalize_config(config: LayerConfig): if not hasattr(config, "size"): config.size = 1.5 NAME = "biomemap_default" @staticmethod def add_generate_functions_to_chunk(config: LayerConfig, chunk): chunk.chunkgenerationtasks.append([DefaultBiomeMapLayer.generate_biomemap, [chunk, config], {}]) @staticmethod def generate_biomemap(chunk, config): cx, cz = chunk.position biomemap = chunk.get_value("biomemap") landmap = chunk.get_value("landmassmap") temperaturemap = chunk.get_value("temperaturemap") factor = 10**config.size for x in range(cx*16, cx*16+16): for z in range(cz*16, cz*16+16): landmass = landmap[(x, z)] v = DefaultBiomeMapLayer.noise.noise3d(x/factor, z/factor, x*z/factor**2) * 0.5 + 0.5 biomemap[(x, z)] = G.biomehandler.get_biome_at(landmass, config.dimension, v, temperaturemap[(x, z)]) chunk.set_value("biomemap", biomemap, authcode)
def rand_im(width, height, num_channels, num_ims, scales): ims = np.zeros((width, height, num_channels, num_ims)) tmp = opensimplex.OpenSimplex() for x in range(width): for y in range(height): for c in range(num_channels): for i in range(num_ims): ims[x, y, c, i] = tmp.noise4d(x / scales[0], y / scales[1], c / scales[2], i) return ims
def __init__(self, average=0, min=None, max=None, roughness=0.2, amplitude=0.05, seed=None): self.field = opensimplex.OpenSimplex() self.start_time = time.time() self.average = average self.min = min self.max = max self.roughness = roughness self.amplitude = amplitude if seed is None: self.seed = 0 else: self.seed = seed
def generate(self, ore_data: dict) -> None: # Generate Heightmap and Grass print("Generating Heightmap") noise = opensimplex.OpenSimplex(self.seed) for x in range(self.width): render.print_and_back(f"x = {x}") y = int(noise.noise2d(x / 10, 1) * 5) + self.height // 2 while y < self.height - 1: self.set_tile(x, y, 1) y += 1 # Generate Caves print("Generating Caves") noise = opensimplex.OpenSimplex(self.seed + 1) for x in range(self.width): render.print_and_back(f"x = {x}") for y in range(0, self.height): if noise.noise2d(x / 10, y / 10) > 0.5: if self.get_tile_index(x, y) == 1: self.set_tile(x, y, 2) # Generate Ores print("Generating Ores") noise = opensimplex.OpenSimplex(self.seed + 2) for x in range(self.width): render.print_and_back(f"x = {x}") for y in range(self.width): if noise.noise2d(x / 10, y / 10) > 0.7: if self.get_tile_index(x, y) == 1: self.set_tile(x, y, 3) # Generate Grass random.seed = self.seed - 1 for x in range(self.width): if random.randint(1, 100) > 50: y = 0 while self.get_tile_index(x, y + 1) == 0: y += 1 if self.get_tile_index(x, y + 1) == 1: self.set_tile(x, y, 5)
def __init__(self, name, width, height, seed): self.name = name self.width = width self.height = height self.seed = seed self.random = random.Random(self.seed) self.noise = opensimplex.OpenSimplex(self.seed) self.stroke_width = None self.stroke_color = None self.fill_color = None self.log_file = "{}.log".format(self.name) self.log("canvas = {}({}, {}, {})".format(self.__class__.__name__, repr(name), repr(width), repr(height)))
def getSimplexNoise(t,y=0): """ return a nicely moving noise in [-1 /+1]. - t: a running time or simulated one, same t return same value. called with passing second should give a nice result. - y: optionnal offset to give another type of value the sum of all noise tend to zero """ # min and max seems to be limited from -0.864 to 0.864 maxval = 0.865 import opensimplex #~ gen = opensimplex.OpenSimplex(sizegrid=sizegrid) global global_gen if global_gen == None: global_gen = opensimplex.OpenSimplex() gen = global_gen v = gen.noise2d(x=t,y=y,bUseCache=False) #~ v = abs(v*255) v = v/maxval return v
def generateImageSimplex(w,h,rZoom=1,sizegrid=256,offsetx=0,offsety=0): """ sizegrid: change in the library to get more details (but not concluant) nice with a zoom around 200 """ # min and max seems to be limited from -0.864 to 0.864 maxval = 0.865 import opensimplex #~ gen = opensimplex.OpenSimplex(sizegrid=sizegrid) global global_gen if global_gen == None: global_gen = opensimplex.OpenSimplex() gen = global_gen #~ for i in range(3): #~ print(gen.noise2d(10,10)) min = +100000 max = -100000 random.seed(0) # for the random case im = np.zeros((h,w),dtype=np.uint8) for j in range(h): for i in range(w): if 1: v = gen.noise2d(x=(i-w/2+offsetx)/rZoom, y=(j-h/2+offsety)/rZoom,bUseCache=True) #~ v = abs(v*255) v = int( ( (v+maxval)/(2*maxval) )* 255 ) else: v = int(random.random()* 255) im[j,i] = v #~ print("%5.1f => %s" % (v, im[j,i]) ) if v > max: max = v if v < min: min = v print("zoom: %s, min: %5.3f, max: %5.3f" % (rZoom, min,max) ) return im
def simplex(size, scale=1, seed=None): """ Generates 3D simplex noise Parameters ---------- size : int size of the texture scale : int, optional scale of the noise, by default 1 seed : int, optional seed for the noise, by default None Returns ------- array [size, size, size] the texture """ # TODO add octaves, lacunarity and persistence? if seed is None: seed = int(np.random.default_rng().integers(2**10) * scale) volume = np.empty((size, size, size), dtype=np.float32) scale /= size sim_gen = opensimplex.OpenSimplex(seed=seed) # TODO optimize loops for x in range(size): for y in range(size): for z in range(size): volume[x, y, z] = sim_gen.noise3d(seed + x * scale, seed + y * scale, seed + z * scale) return volume
class DefaultHeightMapLayer(Layer): noise = opensimplex.OpenSimplex(seed=random.randint(-10000, 10000)) @staticmethod def normalize_config(config: LayerConfig): if not hasattr(config, "size"): config.size = 2 NAME = "heightmap_default" @staticmethod def add_generate_functions_to_chunk(config: LayerConfig, chunk): chunk.chunkgenerationtasks.append( [DefaultHeightMapLayer.generate_heightmap, [chunk, config], {}]) @classmethod def generate_heightmap(cls, chunk, config): heightmap = chunk.get_value("heightmap") cx, cz = chunk.position factor = 10**config.size for x in range(cx * 16, cx * 16 + 16): for z in range(cz * 16, cz * 16 + 16): heightmap[(x, z)] = cls.get_height_at(chunk, x, z, factor) # chunk.add_add_block_gen_task((x, heightmap[(x, z)][0][1], z), "minecraft:stone") @classmethod def get_height_at(cls, chunk, x, z, factor) -> list: v = DefaultHeightMapLayer.noise.noise2d(x / factor, z / factor) * 0.5 + 0.5 biomemap = chunk.get_value("biomemap") biome = G.biomehandler.biomes[biomemap[(x, z)]] r = biome.get_height_range() v *= r[1] - r[0] v += r[0] info = [(1, round(v))] return info
import numpy as np import opensimplex as px from pyprocessing import * # Configuration WIDTH = 1100 HEIGHT = 900 SCALE = 25 ROWS = round(HEIGHT / SCALE) COLS = round(WIDTH / SCALE) terrain = np.zeros((COLS, ROWS)) simplex = px.OpenSimplex() FLYING = 0 FLYING_STEP = 0.15 OFFSET_STEP = 0.2 def setup(): """Setup.""" size(600, 600) def draw(): """Draw.""" global FLYING stroke(255) background(0) noFill() FLYING -= FLYING_STEP
def reset(self): self._step = 0 self._episode += 1 self._terrain[:] = 0 center = self._area[0] // 2, self._area[1] // 2 self._simplex = opensimplex.OpenSimplex(seed=hash((self._seed, self._episode))) self._random = np.random.RandomState( seed=np.uint32(hash((self._seed, self._episode)))) simplex = self._noise uniform = self._random.uniform for x in range(self._area[0]): for y in range(self._area[1]): start = 4 - np.sqrt((x - center[0])**2 + (y - center[1])**2) start += 2 * simplex(x, y, 8, 3) start = 1 / (1 + np.exp(-start)) mountain = simplex(x, y, 0, {1: 15, 0.3: 5}) - 3 * start if start > 0.5: self._terrain[x, y] = MATERIAL_IDS['grass'] elif mountain > 0.15: if (simplex(x, y, 6, 7) > 0.15 and mountain > 0.3): # cave self._terrain[x, y] = MATERIAL_IDS['path'] elif simplex(2 * x, y / 5, 7, 3) > 0.4: # horizonal tunnle self._terrain[x, y] = MATERIAL_IDS['path'] elif simplex(x / 5, 2 * y, 7, 3) > 0.4: # vertical tunnle self._terrain[x, y] = MATERIAL_IDS['path'] elif simplex(x, y, 1, 8) > 0 and uniform() > 0.8: self._terrain[x, y] = MATERIAL_IDS['coal'] elif simplex(x, y, 2, 6) > 0.3 and uniform() > 0.6: self._terrain[x, y] = MATERIAL_IDS['iron'] elif mountain > 0.25 and uniform() > 0.99: self._terrain[x, y] = MATERIAL_IDS['diamond'] elif mountain > 0.3 and simplex(x, y, 6, 5) > 0.4: self._terrain[x, y] = MATERIAL_IDS['lava'] else: self._terrain[x, y] = MATERIAL_IDS['stone'] elif 0.25 < simplex(x, y, 3, 15) <= 0.35 and simplex( x, y, 4, 9) > -0.2: self._terrain[x, y] = MATERIAL_IDS['sand'] elif simplex(x, y, 3, 15) > 0.3: self._terrain[x, y] = MATERIAL_IDS['water'] else: # grass if simplex(x, y, 5, 7) > 0 and uniform() > 0.8: self._terrain[x, y] = MATERIAL_IDS['tree'] else: self._terrain[x, y] = MATERIAL_IDS['grass'] self._player = Player(center, self._health) self._achievements = self._player.achievements.copy() self._objects = [self._player] for x in range(self._area[0]): for y in range(self._area[1]): if self._terrain[x, y] in WALKABLE: if self._terrain[ x, y] == MATERIAL_IDS['grass'] and uniform() > 0.99: self._objects.append(Cow((x, y), self._random)) elif uniform() > 0.993: self._objects.append(Zombie((x, y), self._random)) return self._obs()
def __init__(self,area): Map.__init__(self,area) self.noise = opensimplex.OpenSimplex(area.seed) self.map = self.create_overworld()
noiseSeed = random.randrange(0, 1000) def randomWalls(i, j): """Generates walls randomly by the given chance.""" return random.random() < wallChance def perlinWalls(i, j): """Generates walls with the help of the perlin noise function.""" # The wallchance is 0:1, perlinnoise is -1:1 return noise.pnoise2(i/10.0, j/10.0, base=noiseSeed, repeatx=1_048_576, repeaty=1_048_576) < (wallChance*2-1) # The opensimplex generator that generates simplexnoise mySimplex = opensimplex.OpenSimplex(seed=noiseSeed) def simplexWalls(i, j): """Generates walls with the help of the simplexnoise function""" return mySimplex.noise2d(i/5.0, j/5.0) < (wallChance*2-1) done = False # Whether the program is finished and the window should be closed # Whether a valid path from the beginnning to the end has already been found pathFound = False # Whether a valid path from the beginning to the end has been drawn pathDrawn = False
def __init__(self): self.seed = random.randrange(2**32) freq = random.randrange(5, 10) noise = self.gen_noise(simp.OpenSimplex(self.seed), freq) self.terrain = self.gen_map(noise)
def __init__(self, pixel_max, factor): self.simplex = opensimplex.OpenSimplex( seed=random.randint(0, 2**32 - 1)) self.factor = factor self.pixel_max = pixel_max
sloped: bool cells: [(int, int)] origin_cells: [(int, int)] @dataclass class RiverLand: river: River cells: [(int, int)] def norm_noise_func(noise_func): return lambda x, y: np.interp(noise_func(x, y), [-1, 1], [0, 1]) relief_noise = norm_noise_func(opensimplex.OpenSimplex(0).noise2d) river_noise = norm_noise_func(opensimplex.OpenSimplex(1).noise2d) def sgn(val: int) -> int: return 1 if val >= 0 else -1 def gen_cells(x0: int, y0: int, x1: int, y1: int) -> [(int, int)]: return [(y, x) for y in range(y0, y1 + 1, sgn(y1 - y0)) for x in range(x0, x1 + 1, sgn(x1 - x0))] @dataclass class MainRiverParams: width: int
import sketcher import opensimplex import random canvas = sketcher.Canvas(600,600) noise_scale = 0.004 for c in [(137,143,167),(224,173,89),(209,192,181)]: noise = opensimplex.OpenSimplex(random.randint(0,9999)) ink = sketcher.Ink(color=c) for x in range(canvas.width): for y in range(canvas.width): ink.transparency = sketcher.mapped_noise(noise, (x*noise_scale, y*noise_scale), 0.4, 1) ink.point(canvas, (x,y)) canvas.save('grad{}.png'.format(random.randint(0,9999))) canvas.show()
nCptImageTotal = 0 timeBegin = time.time() t = 0 dt = 1/60. x = screenw // 2 y = screenh // 2 x2 = screenw // 2 + 100 y2 = screenh // 2 x3 = screenw // 2 - 100 y3 = screenh // 2 osx = opensimplex.OpenSimplex() screen.fill(WHITE) while bContinue: # --- Main event loop for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close bContinue = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: bContinue = False #logic dx = osx.noise2d(t,0)*0.2
def generate( parameters, width: int, height: int, seed: int ) -> object: #, octaves: int, persistence: float, lacunarity: float, initial_scale: float, **unused) -> object: """Generate a simple heightmap using the given parameters Parameters ========== width: int The heightmap width height: int The heightmap height seed: int The randomness seed octaves: int The number of octave in noise generation persistence: float The persistence of the noise lacunarity: float The lacunarity of the noise initial_scale: float The initial scale of the noise **unused Other unused arguments, hack to use **large_hash when calling this method Returns ======= numpy array The result of the generation""" # Retrieve parameters try: octaves = parameters.octaves persistence = parameters.persistence lacunarity = parameters.lacunarity initial_scale = parameters.initial_scale except AttributeError as e: logging.critical( "A required parameter is missing from the parameters : \n{err}". format(err=e)) # Initialize working variables heightmap = numpy.zeros((width, height), numpy.float64) prng = random.Random(seed) get_noise = opensimplex.OpenSimplex(seed).noise2d offsets = list( map(lambda o: (prng.randint(-1000, 1000), prng.randint(-1000, 1000)), [None] * octaves)) scale_clamp = float(min(width, height)) # Generating each value for x in range(width): for y in range(height): value = 0.0 scale = initial_scale weight = 1.0 for ox, oy in offsets: # Each octave have less impact than the previous value = value + (get_noise(ox + scale * x / scale_clamp, oy + scale * y / scale_clamp) + 1) * weight weight = weight * persistence scale = scale * lacunarity # Store height heightmap[x, y] = value # Correcting data to put them between -1.0 and 1.0 lowest = numpy.amin(heightmap) highest = numpy.amax(heightmap) if lowest != highest: delta = highest - lowest heightmap = numpy.array( list(map(lambda v: (v - lowest) / delta, heightmap)), numpy.float64) # Return the heightmap return heightmap
def generate(parameters, width: int, height: int, seed: int) -> object: """Generate a island heightmap using the given parameters Parameters ========== width: int The heightmap width height: int The heightmap height seed: int The randomness seed octaves: int The number of octave in noise generation persistence: float The persistence of the noise lacunarity: float The lacunarity of the noise initial_scale: float The initial scale of the noise radius_coef: float The island radius coef applied to the map width or height depending what's smaller center_radius_coef: float The island minimum radius in x coordinates, coef applied to map width or height depending what's smaller variation_initial_scale: float Radius variation noise initial scale variation_amplitude_coef: float Radius variation max amplitude, coef applied to width or height depending what's smaller ease_power: int Modify the steep overhal value **unused Other unused arguments, hack to use **large_hash when calling this method Returns ======= numpy 2d array The result of the generation""" # Retrieve parameters try: octaves = parameters.octaves persistence = parameters.persistence lacunarity = parameters.lacunarity initial_scale = parameters.initial_scale radius_coef = parameters.radius_coef center_radius_coef = parameters.center_radius_coef variation_initial_scale = parameters.variation_initial_scale variation_amplitude_coef = parameters.variation_amplitude_coef ease_power = parameters.ease_power except AttributeError as e: logging.critical( "A required parameter is missing from the parameters : \n{err}". format(err=e)) # Initialize working variables heightmap = numpy.zeros((width, height), numpy.float32) prng = random.Random(seed) get_noise = opensimplex.OpenSimplex(seed).noise2d offsets = list( map(lambda o: (prng.randint(-1000, 1000), prng.randint(-1000, 1000)), [None] * octaves)) scale_clamp = float(min(width, height)) radius = radius_coef * scale_clamp / 2 radius_center = center_radius_coef * scale_clamp / 2 variation_amplitude = variation_amplitude_coef * scale_clamp / 2 center_x = int(width / 2) center_y = int(height / 2) # Some optimization of function calling math_sqrt = math.sqrt math_asin = math.asin math_acos = math.acos radius_ease_power = radius**ease_power # Generating each value for x in range(width): for y in range(height): # Center exclusion if x == center_x and y == center_y: continue # Init and calculate distance value = 0.0 distance = math_sqrt((center_x - x) * (center_x - x) + (center_y - y) * (center_y - y)) if distance <= radius: # Calculate variation of the circle radius angle = math_asin((y - center_y) / distance) * \ math_acos((x - center_x) / distance) angle_noise = (get_noise(angle, 0) + 1) / 2 variation = variation_amplitude * angle_noise if distance <= radius - variation: # Emerged lands = calculate height # Calculate ease coefficient coef_ease = 1 - (distance ** ease_power) / \ radius_ease_power # Radius variation coefficient if distance <= radius_center: coef_variation = 1 else: coef_variation = 1 - \ (distance - radius_center) / \ (radius - variation - radius_center) # Actual height calculation based on noise scale = initial_scale weight = 1.0 for ox, oy in offsets: # Each octave have less impact than the previous value += (get_noise(ox + scale * x / scale_clamp, oy + scale * y / scale_clamp) + 1) * weight weight *= persistence scale *= lacunarity # Apply island ease to sea coefficients value = value * coef_ease * coef_variation # Store height heightmap[x, y] = value # Set the center value to the average of 4 neightbour heightmap[center_x, center_y] = (heightmap[center_x, center_y - 1] + heightmap[center_x, center_y + 1] + heightmap[center_x - 1, center_y] + heightmap[center_x + 1, center_y]) / 4 # Correcting data to put them between -1.0 and 1.0 lowest = numpy.amin(heightmap) highest = numpy.amax(heightmap) if lowest != highest: delta = highest - lowest heightmap = numpy.array( list(map(lambda v: (v - lowest) / delta, heightmap)), numpy.float64) # Return the heightmap return heightmap
import opensimplex import math from matplotlib import pyplot as plt values = [] width = 200 height = 200 scale = 10 noise = opensimplex.OpenSimplex() for y in range(height): values.append([]) for x in range(width): values[y].append( math.floor(5 * math.cos(2 + noise.noise2d(x / width * scale, y / height * scale)))) plt.pcolor(values, cmap="plasma") plt.show()