def main(): pil_image = Image.new('RGB', (origDimension, origDimension)) pixels = pil_image.load() tmp = OpenSimplex(seed=1) tmp2 = OpenSimplex(seed=3) for i in range(pil_image.size[0]): for j in range(pil_image.size[1]): pixels[i, j] = (0, 119, 190) for i in range(pil_image.size[0]): for j in range(pil_image.size[1]): pixel_value = (tmp.noise2d(x=i / 200.0, y=j / 200.0) + tmp2.noise2d(x=i / 200.0, y=j / 200.0)) / 2 #if (int(pixel_value * 100.0) == 90) or (int(pixel_value * 100.0) == 70) or (int(pixel_value * 100.0) == 40) or (int(pixel_value * 100.0) == 0): if (int(pixel_value * 100.0) == 15): pixels[i, j] = (0, 0, 0) elif (int(pixel_value * 100.0) > 15): pixels[i, j] = (107, 142, 35) elif (int(pixel_value * 100.0) > 0): pixels[i, j] = (214, 204, 169) pil_image.save('Generative-Space-Texture.png')
def run(args): MIN_LEN = 10 MAX_LEN = 70 dx_noise = OpenSimplex(42) dx_noise_mult = 0.010 dy_noise = OpenSimplex(211) dy_noise_mult = 0.010 img = cv2.imread(args.pic) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) H, W = gray.shape[:2] pos = np.random.randint(0, min(H, W), size=2).astype(np.float64) path = [pos.copy()] i = 0 ITER = 50000 pbar = tqdm.tqdm(total=ITER) while i < ITER: # direction = np.random.rand(2) - 0.5 dx = dx_noise.noise2d(x=pos[0] * dx_noise_mult, y=pos[1] * dx_noise_mult) dy = dy_noise.noise2d(x=pos[0] * dy_noise_mult, y=pos[1] * dy_noise_mult) direction = np.array([dy, dx]) direction /= np.linalg.norm(direction) try: value = gray[int(np.round(pos[0])), int(np.round(pos[1]))] except IndexError: value = 255 length = remap(value, 0, 255, MIN_LEN, MAX_LEN) length = MAX_LEN new_pos = pos + direction * length if np.any(new_pos < 0) or np.any(new_pos >= (H, W)): direction = np.array([H / 2, W / 2]) - pos direction /= np.linalg.norm(direction) pos += direction * length path.append(pos.copy()) i += 1 pbar.update() pbar.close() vis = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR) path = np.round(path).astype(np.int32) print('path.shape: {}'.format(path.shape)) # print('path: {}'.format(path)) for i in range(1, path.shape[0]): cv2.line(vis, tuple(path[i - 1, ::-1]), tuple(path[i, ::-1]), (0, 0, 255), 1) # cv2.imshow("cv: img", img) # cv2.imshow("cv: gray", gray) cv2.imshow("cv: vis", vis) while True: c = cv2.waitKey(0) if c == ord('q'): break return 0
def generate_heightmap(self, env_name): current_height = 0 if env_name == "flat" or env_name is None: hm = np.ones((self.config["env_length"], self.config["env_width"])) * current_height if env_name == "perlin": oSim = OpenSimplex(seed=int(time.time())) height = self.config["perlin_height"] M = math.ceil(self.config["env_width"]) N = math.ceil(self.config["env_length"]) hm = np.zeros((N, M), dtype=np.float32) scale_x = 15 scale_y = 15 octaves = 4 # np.random.randint(1, 5) persistence = 1 lacunarity = 2 for i in range(N): for j in range(M): for o in range(octaves): sx = scale_x * (1 / (lacunarity ** o)) sy = scale_y * (1 / (lacunarity ** o)) amp = persistence ** o hm[i][j] += oSim.noise2d(i / sx, j / sy) * amp wmin, wmax = hm.min(), hm.max() hm = (hm - wmin) / (wmax - wmin) * height hm += current_height if env_name == "obstacle": oSim = OpenSimplex(seed=int(time.time())) height = self.config["obstacle_height"] * self.config["training_difficulty"] # 30-40 M = math.ceil(self.config["env_width"]) N = math.ceil(self.config["env_length"]) hm = np.zeros((N, M), dtype=np.float32) scale_x = 15 scale_y = 15 octaves = 4 # np.random.randint(1, 5) persistence = 1 lacunarity = 2 for i in range(int(N/2) + 3, int(N/2) + 7): for j in range(M): for o in range(octaves): sx = scale_x * (1 / (lacunarity ** o)) sy = scale_y * (1 / (lacunarity ** o)) amp = persistence ** o hm[i][j] += abs(oSim.noise2d(i / sx, j / sy) * amp) wmin, wmax = hm.min(), hm.max() hm = (hm - wmin) / (wmax - wmin) * height hm += current_height return hm, current_height
class Benchmark: def __init__(self): self.simplex = OpenSimplex(seed=0) def run(self, number=100000): for i in _range(number): self.simplex.noise2d(0.1, 0.1) self.simplex.noise3d(0.1, 0.1, 0.1) self.simplex.noise4d(0.1, 0.1, 0.1, 0.1)
class ChunkGenerator: def setWorld(self, world): self.world = world self.genNoiseElev = OpenSimplex(world.seed * 5824389085730) self.genNoiseMoist = OpenSimplex(world.seed * 3674237955873) self.genNoiseTemp = OpenSimplex(world.seed * 8209480480238) def genChunk(self, chunk): biome = None for cX in range(Chunk.CHUNK_SIZE): rX = cX + chunk.x * Chunk.CHUNK_SIZE for cZ in range(Chunk.CHUNK_SIZE): rZ = cZ + chunk.z * Chunk.CHUNK_SIZE smX = rX / 120 smZ = rZ / 120 smX2 = rX / 200 smZ2 = rZ / 200 biome = self.getBiomeAt(smX, smZ) height = self.getHeightAt(smX2, smZ2) chunk.heightMap[cX][cZ] = height for y in range(height): chunk.setTileAt(self.getTileForDepth(y, height, biome), cX, y, cZ) chunk.biome = biome chunk.biome.generate(self.world, chunk) def getTileForDepth(self, cY, surface, biome): depth = surface - cY if (cY == 0): return Tiles.BEDROCK if (depth > 5): return Tiles.STONE elif (depth > 2): return Tiles.DIRT else: return biome.floorTile def getHeightAt(self, x, z): return int((self.genNoiseElev.noise2d(x, z) / 2.0 + 0.5) * 30) def getMoistAt(self, x, z): return self.genNoiseMoist.noise2d(x, z) / 2.0 + 0.5 def getTemperatureAt(self, x, z): return self.genNoiseTemp.noise2d(x, z) / 2.0 + 0.5 def getBiomeAt(self, x, z): moist = self.getMoistAt(x, z) temperature = self.getTemperatureAt(x, z) return Biomes.getBiomeForClimate(moist, temperature)
class Noise: def __init__(self, seed, scale = 0.007): self.scale = scale self.simplex = OpenSimplex(seed) def get(self, x, y): return self.simplex.noise2d(x * self.scale, y * self.scale) / 2 * 255 def height(self, x, y): return (self.simplex.noise2d(x * self.scale, y * self.scale) + 1) / 2 * 255
class WrappedNoise: def __init__(self, config): self.conf = config self.noise = OpenSimplex(int(time.time())) def noise_at_point(self, x, y): x = x + 1 y = y + 1 if x == 0 and y == 0: print(self.noise.noise2d(x, y)) output = 0.0 divisor = 0.0 octfac = 1.0 for i in range(0, int(self.conf.oc)): divisor += octfac output += octfac * \ self.noise.noise2d(self.conf.freq * pow(2,i) * x, self.conf.freq * pow(2,i)*y) octfac *= self.conf.persistence output = output / divisor flipper = 1 if output < 0: output *= -1 flipper = -1 output = pow(output, self.conf.exp) output *= flipper output *= self.conf.amplitude output = helper.linearConversion(output, self.conf.amplitude * -1, self.conf.amplitude, -1, 1) return output def transform_noise_list(self, input, new_mean, new_sd): """Calculates mean and standard deviation of the list given, then transforms the list to have new_mean and new_sd""" mean = statistics.mean(input) stdev = statistics.pstdev(input, mean) mean_scaled_input = [(x - mean) for x in input] st_dev_transformed = [x * (new_sd / stdev) for x in mean_scaled_input] mean_scaled_output = [x + new_mean for x in st_dev_transformed] #Found on stack exchange post about transforming mean and stdev of dataset return mean_scaled_output def produce_noise_list_percent(self, sizex, sizey): """Produces a list of floats between 0 to 100""" results = list() for y in range(0, sizey): row = list() for x in range(0, sizex): percent = self.noise_at_point(x, y) if percent > 1 or percent < -1: print("noise outside bounds") percent = helper.linearConversion(percent, -1, 1, 0, 100) results.append(percent) return results
def show_landscape(point_displayer): from opensimplex import OpenSimplex import random simplex_r = OpenSimplex(seed=364) simplex_g = OpenSimplex(seed=535) simplex_b = OpenSimplex(seed=656) for i in range(100000): x = random.randint(0, 1000, 4237842 + i) y = random.randint(0, 1000, 5437474 + i) r1 = 0.0009765625 * (simplex_g.noise2d(x=x, y=y)) r2 = 0.001953125 * (simplex_r.noise2d(x=x / 2.0, y=y / 2.0)) r3 = 0.00390625 * (simplex_b.noise2d(x=x / 4.0, y=y / 4.0)) r4 = 0.0078125 * (simplex_g.noise2d(x=x / 8.0, y=y / 8.0)) r5 = 0.015625 * (simplex_r.noise2d(x=x / 16.0, y=y / 16.0)) r6 = 0.03125 * (simplex_b.noise2d(x=x / 32.0, y=y / 32.0)) r7 = 0.0625 * (simplex_g.noise2d(x=x / 64.0, y=y / 64.0)) r8 = 0.125 * (simplex_r.noise2d(x=x / 128.0, y=y / 128.0)) r9 = 0.25 * (simplex_b.noise2d(x=x / 256.0, y=y / 256.0)) normalization_factor = 0.5 val = (r1 + r2 + r3 + r4 + r5 + r6 + r7 + r8 + r9) / 2.0 if val > 0: p = 1.0 else: p = -1.0 norm_val = (abs(val)**normalization_factor) * p pos_val = (norm_val + 1.0) / 2.0 z = pos_val * 254.0 point_displayer.add_point([x - 100, y - 100, z - 100], [160, int(z), 20])
def draw_layers(pixels, width, height, zoom): s1 = OpenSimplex(seed=int(time.time())) s2 = OpenSimplex(seed=int(time.time())) s3 = OpenSimplex(seed=int(time.time())) for x, y in [(x, y) for x in range(width) for y in range(height)]: nx, ny = x / width, y / height value = 1 * s1.noise2d(1 * nx * zoom, 1 * ny * zoom) \ + 0.5 * s2.noise2d(2 * nx * zoom, 2 * ny * zoom) \ + 0.25 * s3.noise2d(4 * nx * zoom, 4 * ny * zoom) pixels[y][x] = (value / (1 + 0.5 + 0.25) + 1) / 2
def apply_simplex_biomes(self, map): (octaves, persist, lacuna, scale, moist_mod, temp_mod, water_level) = SIMPLEX width, height = map.width, map.height equator = height / 2 altitude_mesh = OpenSimplex(seed=randint(1, 1000000)) rainfall_mesh = OpenSimplex(seed=randint(1, 1000000)) for j in range(height): tempdiff = abs(equator - j) / equator for i in range(width): amp = 1 freq = 1 altitude = 0 moist = 0 temp = 1 - tempdiff for k in range(octaves): octavex = i * scale * freq octavey = j * scale * freq altitude_value = altitude_mesh.noise2d(x=octavex, y=octavey) rainfall_value = rainfall_mesh.noise2d(x=octavex, y=octavey) altitude += altitude_value * amp moist += rainfall_value * amp amp *= persist freq *= lacuna altmod = (abs(altitude)) * .7 temp -= altmod moist -= altmod moist += moist_mod temp += temp_mod templist = [('very_hot', 5 / 6), ('hot', 4 / 6), ('warm', 3 / 6), ('cool', 2 / 6), ('cold', 1 / 6), ('very_cold', 0), ('polar', -10)] if altitude <= water_level: if altitude > 0: map.tiles[j][i].type = 'shallow' else: map.tiles[j][i].type = 'deep' self.get_biome_floor(map.tiles[j][i]) else: temp = self.temperature(templist, temp) moistlist = self.get_moistlist(temp) biome = self.moisture(moistlist, moist) map.tiles[j][i].type = biome self.get_biome_floor(map.tiles[j][i])
class Bot(): global directions def __init__(self): self.x = ((random.randint(-98, 98)*10)/8)/10 self.y = ((random.randint(-98, 98)*10)/8)/10 self.char = '()' self.movenum = 0 self.state = random.choice(states) self.frequency = random.randint(15, 20) self.seed = random.randint(0, 1000000) self.noise = OpenSimplex(seed=self.seed) self.health = 100 def move(self): self.movenum += 1 if self.state == 'walker': index = int((self.noise.noise2d(0, self.movenum * (1/self.frequency))+1)*8)%9 direction = directions[states.index(self.state)][index] elif self.state == 'idler': index = int((self.noise.noise2d(0, self.movenum * (1/self.frequency))+1)*5)%6 direction = directions[states.index(self.state)][index] elif self.state == 'average': index = int((self.noise.noise2d(0, self.movenum * (1/self.frequency))+1)*4)%5 direction = directions[states.index(self.state)][index] if direction == 'up': for bot in bots: if bot.y == self.y-1/8 and bot.x == self.x: return if self.y - 1/8 <= 100/8: return self.y -= 1/8 elif direction == 'down': for bot in bots: if bot.y == self.y+1/8 and bot.x == self.x: return if self.y + 1/8 >= 100/8: return self.y += 1/8 elif direction == 'left': for bot in bots: if bot.x == self.x-1/8 and bot.y == self.y: return if self.x - 1/8 <= 100/8: return self.x -= 1/8 elif direction == 'right': for bot in bots: if bot.x == self.x+1/8 and bot.y == self.y: return if self.x + 1/8 >= 100/8: return self.x += 1/8 self.movenum += 1
def wave(value, img): """ Waves the image according to a gradient noise generator Args: 1 - h or v 2 - frequency 3 - amplitude e.g. h;50;300 """ values = args_to_array(value, 3) frequency = int(values[1]) amplitude = int(values[2]) v = values[0] == 'v' print(img.size) # Start the noise s = OpenSimplex(seed=random.randint(0, 1000000)) # Make the waves start at 0 # so using multi with them creates horrifying results offset = s.noise2d(0, 1) * amplitude # We're either going to loop through the width or height of the image # depending on wether the wave is horizontal or vertical size = img.size[0] if v else img.size[1] # Convert the image to numpy array for rolling arr = np.array(img) for x in range(size): # Vertical Horizontal messing #1 a = arr[:, x] if v else arr[x] # Wave the pixels a = np.roll(a, int(s.noise2d(x / frequency, 1) * amplitude - offset), 0) # Vertical Horizontal messing #2 if v: arr[:, x] = a else: arr[x] = a return Image.fromarray(arr)
class Benchmark: def __init__(self): self.simplex = OpenSimplex(seed=0) # trigger compilation x = np.linspace(0, 1, 10) self.simplex.noise2d(x, x) self.simplex.noise3d(x, x, x) self.simplex.noise4d(x, x, x, x) def run(self, number=1000000): x = np.linspace(0, 1, number) self.simplex.noise2d(x, x) self.simplex.noise3d(x, x, x) self.simplex.noise4d(x, x, x, x)
def run(args): particles = circle((0, 0), 1, N=360) forces = [] x_noise = OpenSimplex(42) y_noise = OpenSimplex(211) np.random.seed(64) dist = lambda x: np.linalg.norm(x) forces.append(lambda x: 0.6*np.array( [x_noise.noise2d(x=x[0], y=x[1]), y_noise.noise2d(x=x[0], y=x[1])])) forces.append(lambda x: 0.05*gravity(x, np.array((2, 2)))) forces.append(lambda x: 0.05*gravity(x, np.array((1.5, 0)))) forces.append(lambda x: 0.05*gravity(x, np.array((1.5, 1.5)))) forces.append(lambda x: -x if dist(x) > 3 else np.array((0.0, 0.0))) to_draw = [] for p in tqdm.tqdm(particles): path = run_particle(p, forces, N_steps=np.random.randint(999, 1000), step_size=1) to_draw.append(path) x_margin_mm = 30 y_margin_mm = 30 H = 210 # A4 W = 297 # A4 to_draw = resize_and_center(to_draw, H, W, x_margin_mm, x_margin_mm, y_margin_mm, y_margin_mm) simplified = [] for p in to_draw: simplified.append(simplify_reumann_witkam(0.5, p)) to_draw = optimize(simplified) vis_drawing(to_draw, 'b-', lw=0.1) plt.axis('equal') plt.gca().invert_yaxis() plt.show() # return 1 with Plotter('/dev/ttyUSB0', 9600) as p: p.load_config('config.json') p.set_input_limits((0, 0), (W, 0), (0, H), (W, H)) p.draw_polylines(to_draw) return 0
class randomGenerator(object): def __init__(self, seed=False, scale=1.0): self.scale = scale self.reseed(seed) def reseed(self, seed=False): if seed: self.seed = seed self.oneDseed = seed * 1000000 else: self.seed = random.randint(1, 4294967296) self.oneDseed = random.randint(1, 4294967296) self.generator = OpenSimplex(seed=self.seed) self.previous_trace = set() def noise2d(self, y, x, scale=1): return self.generator.noise2d( float(y) / self.scale / scale, float(x) / self.scale / scale) def noise1d(self, y, scale=1): return self.generator.noise2d( float(y) / self.scale / scale, float(self.oneDseed) / self.scale / scale) def noise3d(self, y, x, t, time_scale=1, scale=1): return self.generator.noise3d( float(y) / self.scale / scale, float(x) / self.scale / scale, float(t) / time_scale) def get_closest_direction(self, y, x, retrace=False): closest_direction = (y + 1, x + 1) for i in [1, 0, -1]: for n in [1, 0, -1]: if not (i == 0 and n == 0): if self.noise2d(y + i, x + n) < self.noise2d( closest_direction[0], closest_direction[1]): if (y + i, x + n) not in self.previous_trace: closest_direction = (y + i, x + n) if closest_direction in self.previous_trace and not retrace: closest_direction = (y + random.randint(-1, 1), x + random.randint(-1, 1)) self.previous_trace.add(closest_direction) return closest_direction
class TerrainGenerator: def __init__(self, seed): self.seed = seed self.noise = OpenSimplex(self.seed) def getHeight(self, x): return round(self.noise.noise2d(x=x, y=1) / 2 * 3)
def generate_noise_map(self, flatness): self.map = np.zeros([self.height, self.width]) divisor = 0 for n in range(self.octaves): simplex = OpenSimplex(int(np.random.rand() * 1e5)) frequency = 2**n / 1e2 amplitude = 1 / frequency divisor += amplitude for i in range(self.height): for j in range(self.width): rand = simplex.noise2d(x=frequency * i, y=frequency * j) self.map[i, j] += ((rand + 1) / 2) * amplitude if self.show_components: self.layers[n].putpixel((j, i), int(255 * ((rand + 1) / 2))) if self.show_components: for x in self.layers: x.show() quit() self.map /= divisor self.map = self.map**flatness self.normalize()
def main(): simplex = OpenSimplex() print('Generating 2D image...') im = Image.new('L', (WIDTH, HEIGHT)) for y in range(0, HEIGHT): for x in range(0, WIDTH): value = simplex.noise2d(x / FEATURE_SIZE, y / FEATURE_SIZE) color = int((value + 1) * 128) im.putpixel((x, y), color) im.save('noise2d.png') print('Generating 2D slice of 3D...') im = Image.new('L', (WIDTH, HEIGHT)) for y in range(0, HEIGHT): for x in range(0, WIDTH): value = simplex.noise3d(x / FEATURE_SIZE, y / FEATURE_SIZE, 0.0) color = int((value + 1) * 128) im.putpixel((x, y), color) im.save('noise3d.png') print('Generating 2D slice of 4D...') im = Image.new('L', (WIDTH, HEIGHT)) for y in range(0, HEIGHT): for x in range(0, WIDTH): value = simplex.noise4d(x / FEATURE_SIZE, y / FEATURE_SIZE, 0.0, 0.0) color = int((value + 1) * 128) im.putpixel((x, y), color) im.save('noise4d.png')
def generate_map(map_config: GenerationConfig, x_offset: float, map_type: str) -> GenerationResult: if map_type == 'perlin': data = np.zeros(map_config.shape, dtype=np.float32) for i in range(map_config.shape[0]): for j in range(map_config.shape[1]): data[i][j] = noise.pnoise2(i / map_config.scale, (j + x_offset) / map_config.scale, octaves=map_config.octaves, persistence=map_config.persistence, lacunarity=map_config.lacunarity, repeatx=10, repeaty=10, base=0) * map_config.amplitude_scale result = GenerationResult(data.flatten()) elif map_type == 'simplex': gen = OpenSimplex(seed=1) data = np.zeros(map_config.shape, dtype=np.float32) for i in range(map_config.shape[0]): for j in range(map_config.shape[1]): data[i][j] = gen.noise2d(i / map_config.scale * map_config.simplex_step, (j + x_offset) / map_config.scale * map_config.simplex_step) \ * map_config.amplitude_scale result = GenerationResult(data.flatten()) else: raise Exception('Invalid type:' + map_type) return result
class Perlin(Default): """ Use perlin noise together with rgb mapping """ def __init__(self, **kwargs): super().__init__(**kwargs) self.pattern_name = "Perlin" self.x_div = Modifier('horizontal', 2**4, minimum=1, maximum=2**10) self.y_div = Modifier('vertical', 2**4, minimum=1, maximum=2**10) self.op = OpenSimplex() self.counter = 0 self.modifiers = dict( x_div=self.x_div, y_div=self.y_div, ) def fill(self): # reset counter if self.counter == sys.maxsize - 1: self.counter = 0 # color for idx in range(self.strip_length): val = self.op.noise2d(idx / self.x_div(), self.counter / self.y_div()) val = scale(val, 0, 3, -1, 1) self.pixels[idx]['color'] = num_to_rgb(val) + (self.color.a, ) # update counter self.counter += 1
class NoiseMap(Map): generator = None def __init__(self, parent=None, seed=0): Map.__init__(self, parent, seed) pass def refresh(self): Map.refresh(self) self.generator = OpenSimplex(self.seed) print("asdf") pass def get_noise(self, nx, ny): value = 1.0 / float(self.frequency) * self.generator.noise2d( self.frequency * nx, self.frequency * ny) / 2 + 0.5 return value #A value between 0.0 and 1.0 def get_z(self, nx, ny): value = self.get_noise(nx, ny) difference = (self.max_value + abs(self.min_value)) normal = difference * value - abs(self.min_value) return normal #return value between self.max_value and self.min_value def generate_noise_map(self): Map.generate_noise_map(self) for iy in range(self.y_axis): for ix in range(self.x_axis): nx = float(ix) / float(self.x_axis) + self.x_offset ny = float(iy) / float(self.y_axis) + self.y_offset z = self.get_noise(nx, ny) self.noise_map[iy][ix] = z pass
def StartMap(self): tmp = OpenSimplex(self.SEED) image = Image.new('RGB', (self.HEIGHT, self.WIDTH), 'White') if self.SCALE <= 0: self.SCALE = 0.0001 if self.WIDTH <= 0: self.WIDTH = 1 if self.HEIGHT <= 0: self.HEIGHT = 1 for y in range(0, self.HEIGHT): for x in range(0, self.WIDTH): AMPLITUDE = 1 FREQUENCY = 1 NOISEHEIGHT = 0 for i in range(self.OCTAVES): samplex = x / self.SCALE * FREQUENCY sampley = y / self.SCALE * FREQUENCY simplexvalue = tmp.noise2d(samplex, sampley) NOISEHEIGHT += simplexvalue * AMPLITUDE AMPLITUDE *= self.PERSISTANCE FREQUENCY *= self.LACUNARITY self.noisemap[x][y] = NOISEHEIGHT draw = ImageDraw.Draw(image) for y in range(0, self.HEIGHT): for x in range(0, self.WIDTH): color = self.noisemap[x][y] color = int((color * 128) + 128) draw.point((x, y), fill=(color, color, color, 255)) image.save("NoiseMap.png") return True
def generate_heightmap(self, env_name): current_height = 0 if env_name == "flat" or env_name is None: hm = np.ones((self.config["env_length"], self.config["env_width"])) * current_height if env_name == "stairs_up": hm = np.ones((self.config["env_length"], self.config["env_width"])) stair_height = 14 * self.config["training_difficulty"] stair_width = 3 initial_offset = self.config["env_length"] // 2 + 1 n_steps = min(math.floor(self.config["env_length"] / stair_width) - 1, 10) for i in range(n_steps): hm[initial_offset + i * stair_width: initial_offset + i * stair_width + stair_width, :] = current_height current_height += stair_height hm[n_steps * stair_width + initial_offset:, :] = current_height if env_name == "obstacle": oSim = OpenSimplex(seed=int(time.time())) height = self.config["obstacle_height"] * self.config["training_difficulty"] # 30-40 M = math.ceil(self.config["env_width"]) N = math.ceil(self.config["env_length"]) hm = np.zeros((N, M), dtype=np.float32) scale_x = 15 scale_y = 15 octaves = 4 # np.random.randint(1, 5) persistence = 1 lacunarity = 2 cutoff_scale = 8 rnd_dir = np.random.randint(0, 2) rnd_slope = np.random.rand() * 0.2 rnd_left_cutoff = np.random.randint(int(M / 2) - cutoff_scale, int(M / 2) - int(cutoff_scale/2)) rnd_right_cutoff = np.random.randint(int(M / 2) + int(cutoff_scale/2), int(M / 2) + cutoff_scale) init_offset = int(N/2) + 3 + - int(rnd_slope * 26) # np.random.randint(0,2) for i in range(init_offset, int(N/2) + 15): for j in range(M): if (i < j * rnd_slope + init_offset) * rnd_dir\ or (i < (M - j) * rnd_slope + init_offset) * (1 - rnd_dir)\ or j < rnd_left_cutoff \ or j > rnd_right_cutoff: continue for o in range(octaves): sx = scale_x * (1 / (lacunarity ** o)) sy = scale_y * (1 / (lacunarity ** o)) amp = persistence ** o hm[i][j] += abs(oSim.noise2d(i / sx, j / sy) * amp) wmin, wmax = hm.min(), hm.max() hm = (hm - wmin) / (wmax - wmin) * height hm = np.minimum(hm, self.config["obstacle_height"] - 10) hm += current_height return hm, current_height
class SimplexNoise(ActionNoise): """ A simplex action noise """ def __init__(self, dim): super().__init__() self.idx = 0 self.dim = dim self.noisefun = OpenSimplex(seed=int((time.time() % 1) * 10000000)) def __call__(self) -> np.ndarray: self.idx += 1 return np.array([(self.noisefun.noise2d(x=self.idx / 10, y=i*10) + self.noisefun.noise2d(x=self.idx / 50, y=i*10)) for i in range(self.dim)]) def __repr__(self) -> str: return 'Opensimplex Noise()'.format()
def Issou(height, width, coeffs, expo): """Crée l'image height*width avec coeffs comme coefficients des harmoniques et expo l'exposant correcteur.""" matrice = np.empty((width, height)) n = len(coeffs) simplex = OpenSimplex(seed=int(random() * (10**15))) mat = [] sum = 0 decX = int(random() * (10**5)) decY = int(random() * (10**5)) for i in range(n): sum += coeffs[i] #Calcule la somem des coeffs for y in range(0, height): for x in range(0, width): nx = x / width - 0.5 #Positions normalisées ny = y / width - 0.5 #entre -0.5 et +0.5 e = 0 for i in range(n): e += abs(coeffs[i] * simplex.noise2d((2**i) * nx + decX, (2**i) * ny + decY)) e = e / sum #Renormalise avec la somme des coeffs e = pow(e, expo) #Sert à plus ou moins accentuer les variations matrice[x, y] = e #os.system('cls') print("Bruit : " + str(int((y / width) * 100)) + "%") return matrice
def main(): simplex = OpenSimplex() print("Generating 2D image...") im = Image.new("L", (WIDTH, HEIGHT)) for y in range(0, HEIGHT): for x in range(0, WIDTH): value = simplex.noise2d(x / FEATURE_SIZE, y / FEATURE_SIZE) color = int((value + 1) * 128) im.putpixel((x, y), color) im.save("noise2d.png") print("Generating 2D slice of 3D...") im = Image.new("L", (WIDTH, HEIGHT)) for y in range(0, HEIGHT): for x in range(0, WIDTH): value = simplex.noise3d(x / FEATURE_SIZE, y / FEATURE_SIZE, 0.0) color = int((value + 1) * 128) im.putpixel((x, y), color) im.save("noise3d.png") print("Generating 2D slice of 4D...") im = Image.new("L", (WIDTH, HEIGHT)) for y in range(0, HEIGHT): for x in range(0, WIDTH): value = simplex.noise4d(x / FEATURE_SIZE, y / FEATURE_SIZE, 0.0, 0.0) color = int((value + 1) * 128) im.putpixel((x, y), color) im.save("noise4d.png")
def mapHeight_maker(self): self.raw_mapHeight = [] self.mapHeight = [] noise = OpenSimplex(seed=self.entity_variables.seed) #get raw noise data for x in range( 0, int(self.entity_variables.map_width / self.config_options.distance_between_raw + 2)): noise_ouput = noise.noise2d(x=x, y=1) noise_ouput = (noise_ouput + 1) / (2 / self.config_options.mountain_steepness) noise_ouput = int(noise_ouput) self.raw_mapHeight.append(noise_ouput) #edit raw noise data (extra distance between each point) for x in range( 0, int(self.entity_variables.map_width / self.config_options.distance_between_raw)): temp_value = 0 temp_difference_between_point = ( self.raw_mapHeight[x] - self.raw_mapHeight[x + 1] ) / self.config_options.distance_between_raw * -1 for y in range(0, self.config_options.distance_between_raw): value = temp_difference_between_point + temp_value temp_value = value self.mapHeight.append(int(value + self.raw_mapHeight[x]))
def IssouC(height, width, coeffs, expo): """Crée l'image height*width avec coeffs comme coefficients des harmoniques et expo l'exposant correcteur.""" n = len(coeffs) simplex = OpenSimplex(seed=int(random() * (10**15))) mat = [] min = 100 max = -1 sum = 0 for i in range(n): sum += coeffs[i] #Calcule la somem des coeffs for y in range(0, height): mat.append([]) for x in range(0, width): nx = x / width - 0.5 #Positions normalisées ny = y / width - 0.5 #entre -0.5 et +0.5 e = 0 for i in range(n): e += abs(coeffs[i] * simplex.noise2d((2**i) * nx, (2**i) * ny)) e = e / sum #Renormalise avec la somme des coeffs e = pow(e, expo) #Sert à plus ou moins accentuer les variations mat[y].append(e) if e < min: min = e elif e > max: max = e os.system('cls') print("Bruit : " + str(int((y / width) * 100)) + "%") return (mat, min, max)
class Generator(): complexity = 5 def __init__(self, seed): self.gen = OpenSimplex(seed) def generateHeightmap(self, size, featuresize, detail): self.width = size self.height = size self.featuresize = featuresize self.detail = detail print("Using {} cores".format(multiprocessing.cpu_count())) value = Parallel(n_jobs=multiprocessing.cpu_count())( delayed(self.doRow)(y) for y in range(self.height)) return value def doRow(self, y): val = [] for x in range(self.width): nx = x / self.width - 0.5 ny = y / self.height - 0.5 a = 0 b = 0 for t in range(-self.featuresize, self.detail - self.featuresize): n = 2**t b += 1 / n a += self.noise(n * nx, n * ny) / n val.append(a / b) return val def noise(self, nx, ny, scale=255): return int( (self.gen.noise2d(nx * self.complexity, ny * self.complexity) / 2.0 + 0.5) * scale)
def renderMap(x, y, width, height, seed, zoom=default_zoom, boundaries=[(-100, 100), (-100, 100)]): noise = OpenSimplex(seed=seed) screen = np.array([]) for i in np.arange(-height // 2, height // 2): newLine = np.array([]) for j in np.arange(-width // 2, width // 2): newLine = np.append( newLine, noise.noise2d(y + i * (1 / zoom), x + j * (1 / zoom))) screen = np.append(screen, newLine) output = np.reshape(screen, (height, width)) newOut = np.array([], dtype=str) for i in np.reshape(output, output.size): index = int((i + 1) * len(blocks) / 2) char = blocks[index] newOut = np.append(newOut, char) output = np.reshape(newOut, (height, width)) return output
def npIssou(height, width, coeffs, expo): """Tentative de vectorisation de la fonction Issou.""" n = len(coeffs) simplex = OpenSimplex(seed=int(random() * (10**15))) mat = [] min = 100 max = -1 sum = 0 for i in range(n): sum += coeffs[i] for y in range(0, height): mat.append([]) for x in range(0, width): nx = x / width - 0.5 ny = y / width - 0.5 e = 0 for i in range(n): e += abs(coeffs[i] * simplex.noise2d((2**i) * nx, (2**i) * ny)) e = e / sum e = pow(e, expo) mat[y].append(e) if e < min: min = e elif e > max: max = e return (mat, min, max)
class Game(object): def __init__(self): self.gen = OpenSimplex(random.randint(0, sys.maxint)) def noise(self, nx, ny): return self.gen.noise2d(nx, ny) / 2.0 + 0.5 def create_height_map(self, width, height): fwidth = float(width) fheight = float(height) result = array.array('B') for y in xrange(height): for x in xrange(width): nx = x / fwidth - 0.5 ny = y / fheight - 0.5 value = self.noise(10 * nx, 10 * ny) result.append(int(255 * value if value != 1.0 else 255)) return result