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 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 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 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 update(): noise = OpenSimplex() loff = 0 self.ox_off += 0.05 for linha in range(self.n_linhas): coff = 0 for coluna in range(self.n_colunas): self.OxMatrix[linha][coluna] = noise.noise3d(x=coff, y=loff, z=self.ox_off) coff += 0.2 loff += 0.2
class OpenSimplexWrapper(NoiseLibWrapper): def __init__(self, seed=0): super().__init__(seed) self.corelib = OpenSimplex(seed) def eval2d(self, x, y): return self.corelib.noise2d(x, y) def eval3d(self, x, y, z): return self.corelib.noise3d(x, y, z) def eval4d(self, x, y, z, w): return self.corelib.noise4d(x, y, z, w)
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
def prob_worker(vals): t = time.time() # get values passed in x, y, z, seed = vals # seed simplex generator simplex = OpenSimplex(seed) # initialize data chunk chunk = np.zeros(chunk_size).astype(float) # iterate over chunk for i in range(chunk_size[0]): for j in range(chunk_size[1]): for k in range(chunk_size[2]): # generate data chunk[i,j,k] = simplex.noise3d(((x*chunk_size[0]) + i) / feature_size[0], ((y*chunk_size[1]) + j) / feature_size[1], ((z*chunk_size[2]) + k) / feature_size[2]) return x, y, z, chunk
def show_cloud(point_displayer): from opensimplex import OpenSimplex import math 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) y = random.randint(0, 1000) z = random.randint(0, 1000) d = math.sqrt((x - 500)**2 + (y - 500)**2 + (z - 500)**2) / 500.0 r1 = 0.0009765625 * (simplex_g.noise3d(x=x, y=y, z=z)) r2 = 0.001953125 * (simplex_r.noise3d(x=x / 2.0, y=y / 2.0, z=z / 2.0)) r3 = 0.00390625 * (simplex_b.noise3d(x=x / 4.0, y=y / 4.0, z=z / 4.0)) r4 = 0.0078125 * (simplex_g.noise3d(x=x / 8.0, y=y / 8.0, z=z / 8.0)) r5 = 0.015625 * (simplex_r.noise3d(x=x / 16.0, y=y / 16.0, z=z / 16.0)) r6 = 0.03125 * (simplex_b.noise3d(x=x / 32.0, y=y / 32.0, z=z / 32.0)) r7 = 0.0625 * (simplex_g.noise3d(x=x / 64.0, y=y / 64.0, z=z / 64.0)) r8 = 0.125 * (simplex_r.noise3d(x=x / 128.0, y=y / 128.0, z=z / 128.0)) r9 = 0.25 * (simplex_b.noise3d(x=x / 256.0, y=y / 256.0, z=z / 256.0)) r10 = 0.5 * (simplex_g.noise3d(x=x / 512.0, y=y / 512.0, z=z / 512.0)) r11 = simplex_r.noise3d(x=x / 1024.0, y=y / 1024.0, z=z / 1024.0) val = (r1 + r2 + r3 + r4 + r5 + r6 + r7 + r8 + r9) / 2.0 if val > 0: p = 1.0 else: p = -1.0 # use ^d for cumulus clouds, # use distance from a certain height for a sky of clouds # use constant power <1 for endless 3d field of clouds # use distance from sets of points or lines for other shapes norm_val = (abs(val)**d) * p pos_val = (norm_val + 1.0) / 2.0 r = int(pos_val * 254.0) # r5 = int((r5)*255.0/2.0) # lim octaves->inf gives 1/2^x sum (=1) if r > 160: point_displayer.callback_instance.add_points([[x, y, z]], [[r, r, r]])
density_slider = pygame_gui.elements.UIHorizontalSlider( pygame.Rect((WIDTH - 210, HEIGHT - 45), (200, 20)), 8, (0.1, 24), manager) intensity_slider = pygame_gui.elements.UIHorizontalSlider( pygame.Rect((WIDTH - 210, HEIGHT - 20), (200, 20)), 5, (0, 12), manager) ui_text = pygame_gui.elements.UILabel( pygame.Rect((5, HEIGHT - 30), (310, 30)), "U - Hide/Show UI | S - Freeze Circle", manager) manager.process_events(event) theta = 0.0 points.clear() while theta <= math.tau: xoff = (math.cos(theta) + 1) / 2 * noiseDensity yoff = (math.sin(theta) + 1) / 2 * noiseDensity r = min(HEIGHT, WIDTH) / 4 + noise.noise3d(xoff, yoff, zoff) * noiseScalar * 10 x = r * math.cos(theta) y = r * math.sin(theta) pos = (x + WIDTH / 2, y + HEIGHT / 2) points.append(pos) theta += 0.005 pygame.draw.polygon(screen, (255, 255, 255), points, 1 * (not fillShape)) zoff += noiseSpeed * delta * (not isStatic) # Update manager and screen if drawUI: manager.update(delta) manager.draw_ui(screen) pygame.display.update()
if b_map[b][0] <= value <= b_map[b][1]: return b return (0, 0, 0) window = pygame.display.set_mode((600, 600)) engine = Engine(window) sphere = Sphere([300, 300, 0], 200, 50) generator = OpenSimplex() off = [uniform(0, 1024), uniform(0, 1024), uniform(0, 1024)] for p in range(len(sphere.points)): v = sphere.points[p].copy() v -= sphere.center n = generator.noise3d(sphere.points[p][0] / 100 + off[0], sphere.points[p][1] / 100 + off[1], sphere.points[p][2] / 100 + off[2]) * 100 v.setLength(n) sphere.points[p] += v sCol = [] for s in sphere.surfaces: v = Vector() for i in s: v += sphere.points[i] v /= len(s) v -= sphere.center c = (v.length() - 100) / 200 * 2 - 1 sCol.append(getColor(c)) sphere.surface_set(*sCol)
class animationDisplay(PGWindow): def __init__(self): super().__init__() # Load the tensorflow model self.model = loadDecoder() # All the necessary initializations self.reset() def handleEvent(self, event: pg.event) -> None: pass def reset(self): # Pixel matrices self.latentSpaceArray = np.zeros((16, 16)) self.pixelArray = np.zeros((512, 512 * 2, 3)) # simplex noise generator self.seed = 600613 # Google <3 self.noiseGenerator = OpenSimplex(self.seed) self.NoiseX = self.seed / 7919 # Noise-Space coordinates, need any non-integer value self.NoiseY = self.seed / 7919 # Dividing by a large prime number to minimize chance of getting integer values self.NoiseZ = self.seed / 7919 # Not sure that this is necessary in OpenSimplex but it is so for Perlin Noise self.NoisePhase = 0 self.deltaNoise = 0.01 self.animSpeed = 10 def generateLatentNoise(self): self.latentSpaceArray = np.zeros((16, 16)) # Sadly the open simplex library does not offer matrix generation, we have to loop over ours for x in range(16): for y in range(16): self.latentSpaceArray[x, y] = self.noiseGenerator.noise3d( self.NoiseX + x / 16, self.NoiseY + y / 16, self.NoiseZ + cos(self.NoisePhase)) self.NoisePhase = self.NoisePhase + self.deltaNoise * self.animSpeed if self.NoisePhase > 2 * pi: self.NoisePhase = 0 self.NoiseX += self.deltaNoise self.NoiseY += self.deltaNoise self.latentSpaceArray = np.maximum( np.minimum(self.latentSpaceArray, 1), 0) def handleInputs(self): # Handle Keyboard input key = pg.key.get_pressed() if key[pg.K_r]: # Reset draw board when R is pressed self.reset() def draw(self): self.generateLatentNoise() # Prepare draw board to be fed to the tf model predictArray = self.latentSpaceArray.reshape((1, 16, 16, 1)) # Get a reconstruction from the model and reshape it to a 2D matrix reconstructPixelArray = (self.model.predict(predictArray).reshape( (256, 256)) * 255).astype(np.uint8) # Scale the output to 512x512 reconstructPixelArray = np.repeat(np.repeat(reconstructPixelArray, 2, axis=0), 2, axis=1) # Scale the latent space to 512x512 latentSpacePixelArray = np.repeat( np.repeat(self.latentSpaceArray, 32, axis=0), 32, axis=1) * 255 # Put the draw board and the reconstruction next to each other pixelArray = np.concatenate( (latentSpacePixelArray, reconstructPixelArray)) # 'expand' each pixel from grayscale to rgb (by replicating each pixel 3 times) pixelArray = np.dstack((pixelArray, pixelArray, pixelArray)) # Draw array to screen pg.surfarray.blit_array(self.screen, pixelArray)
#f = lambda x: math.cos(x) #g = lambda x: math.sin(x) # tabIndice = {} nbFigures = 1000 for j in range(nbFigures): c.delete(id) p = .05 a, b = 0, 2 * math.pi # x = a listePoints = [] for t in range(int(1 + (b - a) / p)): X, Y = f(x), g(x) r = 1 + .5 * tmp.noise3d(X, Y, math.cos(2 * math.pi * j / 50)) listePoints += [r * f(x)] + [r * g(x)] x += p x, y = listePoints[0:2] listePoints += [x, y] # it = iter(listePoints) tabIndice[j] = [] for x in it: l = c.drawPoint(x, next(it), fill="red") tabIndice[j].append(l) # id = c.drawLine(listePoints, fill="white", width=3, smooth=1,
class chunkGenerator: def __init__(self, seed=None): """Initializes the noise generator Args: seed (int, optional): The seed of the noise generator. Defaults to None. """ # self.simp = OpenSimplex() # self.voronoi = Voronoi() # self.ridgedMulti = RidgedMulti() self.simp = OpenSimplex() def frontVal(self, x, y): """Returns value of (x,y) at front-plane Args: x (float): The x-coordinate of the noise plane y (float): The y-coordinate of the noise plane Returns: float: Value on the noise plane at (x,y), normalized between 0 and 100 """ #return (self.simp[x, y, 0.1] * 50) return (self.simp.noise3d(x, y, 0.1) + 1) * 50 def backVal(self, x, y): """Returns value of (x,y) at back-plane Args: x (float): The x-coordinate of the noise plane y (float): The y-coordinate of the noise plane Returns: float: Value on the noise plane at (x,y), normalized between 0 and 100 """ #return (self.simp[x, y, -0.1] * 50) return (self.simp.noise3d(x, y, -0.1) + 1) * 50 def getLowerBedrockWastes(self, x, y): if (y == 0): return tiles.bedrock, tiles.bedrock else: front = self.frontVal(x * BEDROCK_LOWER_X, y * BEDROCK_LOWER_Y) back = self.backVal(x * BEDROCK_LOWER_X, y * BEDROCK_LOWER_Y) bedrockProbability = 50 front = tiles.obsidian if (front <= bedrockProbability): front = tiles.bedrock back = tiles.obsidian if (back <= bedrockProbability): back = tiles.bedrock return front, back def getUpperBedrockWastes(self, x, y): front = self.frontVal(x * BEDROCK_UPPER_X, y * BEDROCK_UPPER_Y) back = self.backVal(x * BEDROCK_UPPER_X, y * BEDROCK_UPPER_Y) obsidianProbability = 70 stoneProbability = 20 + obsidianProbability hellStoneProbability = 12.5 + stoneProbability if (front <= obsidianProbability): front = tiles.obsidian elif (front <= stoneProbability): front = tiles.greystone else: front = tiles.hellstone if (back <= obsidianProbability): back = tiles.obsidian else: back = tiles.greystone return front, back def getLowerCaves(self, x, y): front = self.frontVal(x * CAVE_X, y * CAVE_Y) back = self.backVal(x * CAVE_X, y * CAVE_Y) obsidianProbability = 20 stoneProbability = obsidianProbability + 20 graniteProbability = stoneProbability + 20 limestoneProbability = graniteProbability + 20 unobtaniumProbability = limestoneProbability + 10 diamondProbability = unobtaniumProbability + 7.5 platinumProbability = diamondProbability + 7.5 if (front <= obsidianProbability): front = tiles.obsidian elif (front <= stoneProbability): front = tiles.greystone elif (front <= graniteProbability): front = tiles.granite elif (front <= limestoneProbability): front = tiles.limestone elif (front <= unobtaniumProbability): front = tiles.unobtaniumOre elif (front <= diamondProbability): front = tiles.diamondOre else: front = tiles.platinumOre return front, back def getMiddleCaves(self, x, y): front = self.frontVal(x * CAVE_X, y * CAVE_Y) back = self.backVal(x * CAVE_X, y * CAVE_Y) stoneProbability = 30 graniteProbability = 20 + stoneProbability quartzProbability = 20 + graniteProbability unobtaniumProbability = 10 + quartzProbability diamondProbability = 10 + unobtaniumProbability platinumProbability = 10 + diamondProbability if (front <= stoneProbability): front = tiles.greystone elif (front <= graniteProbability): front = tiles.granite elif (front <= quartzProbability): front = tiles.quartz elif (front <= unobtaniumProbability): front = tiles.unobtaniumOre elif (front <= diamondProbability): front = tiles.diamondOre elif (front <= platinumProbability): front = tiles.platinumOre if (back <= stoneProbability): back = tiles.greystone elif (back <= graniteProbability): back = tiles.granite elif (back <= quartzProbability): back = tiles.quartz else: back = tiles.greystone return front, back def getUpperCaves(self, x, y): front = self.frontVal(x * CAVE_X, y * CAVE_Y) back = self.backVal(x * CAVE_X, y * CAVE_Y) stoneProbability = 75 ironProbability = 12.5 + stoneProbability goldProbability = 12.5 + ironProbability back = tiles.greystone if (front <= stoneProbability): front = tiles.greystone elif (front <= ironProbability): front = tiles.ironOre elif (front <= goldProbability): front = tiles.goldOre return front, back def getLowerUnderground(self, x, y): front = self.frontVal(x * UNDERGROUND_X, y * UNDERGROUND_Y) back = self.backVal(x * UNDERGROUND_X, y * UNDERGROUND_Y) gravelProbability = 20 dirtProbability = 20 + gravelProbability redclayProbability = 20 + dirtProbability coalProbability = 20 + redclayProbability copperProbability = 20 + coalProbability if (front <= gravelProbability): front = tiles.gravel elif (front <= dirtProbability): front = tiles.browndirt elif (front <= redclayProbability): front = tiles.redClay elif (front <= coalProbability): front = tiles.coke elif (front <= copperProbability): front = tiles.copperOre if (back <= gravelProbability): back = tiles.gravel elif (back <= dirtProbability): back = tiles.browndirt else: back = redclayProbability return front, back def getUpperUnderground(self, x, y): front = self.frontVal(x * UNDERGROUND_X, y * UNDERGROUND_Y) back = self.backVal(x * UNDERGROUND_X, y * UNDERGROUND_Y) gravelProbability = 20 dirtProbability = 20 + gravelProbability redclayProbability = 20 + dirtProbability coalProbability = 20 + redclayProbability copperProbability = 20 + coalProbability if (front <= gravelProbability): front = tiles.gravel elif (front <= dirtProbability): front = tiles.browndirt elif (front <= redclayProbability): front = tiles.redClay elif (front <= coalProbability): front = tiles.coke elif (front <= copperProbability): front = tiles.copperOre if (back <= gravelProbability): back = tiles.gravel elif (back <= dirtProbability): back = tiles.browndirt else: back = redclayProbability return front, back
clock = pygame.time.Clock() tmp = OpenSimplex() z_off = 0 running = True while running: t1 = time.perf_counter() for event in pygame.event.get(): if (event.type == pygame.QUIT or event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): running = False grid = [[ scale(tmp.noise3d(x=j * xy_off, y=i * xy_off, z=z_off)) for j in range(size[0] // square_size + 1) ] for i in range(size[1] // square_size + 1)] z_off += 0.01 screen.fill(GREY) if corners: for row_i, row in enumerate(grid): for col_i, cell in enumerate(row): pygame.draw.circle(screen, WHITE if cell == 1 else BLACK, (col_i * square_size, row_i * square_size), weight * 2) for i in range(len(grid) - 1):
class NoiseWrapper(): def __init__(self, **kwargs): self.noise = OpenSimplex(**kwargs) self.fast_noise = fns.Noise() # self.fast_noise.frequency = 0.05 def polar_noise(self, theta, phi, rho): """Generates noise at the given polar coordinates Args: theta: inclination (north-south) phi: rotation around center (east-west) rho: The radius (altitude) Returns: """ # calculate cartesian coordinates x = rho * m.sin(theta) * m.cos(phi) y = rho * m.sin(theta) * m.sin(phi) z = rho * m.cos(theta) return self.noise.noise3d(x, y, z) def polar_fast_noise(self, h, w, o): numCoords = h * w coords = fns.emptyCoords(numCoords) for y in range(h): for x in range(w): theta = (y + .5) / (w / 2) * m.pi phi = x / h * m.pi xv = o * m.sin(theta) * m.cos(phi) yv = o * m.sin(theta) * m.sin(phi) zv = o * m.cos(theta) index = y * w + x coords[0][index] = xv coords[1][index] = yv coords[2][index] = zv result = self.fast_noise.genFromCoords(coords) return result.reshape((h, w)) def noise(self, nx, ny): # Rescale from -1.0:+1.0 to 0.0:1.0 return self.noise.noise2d(nx, ny) / 2.0 + 0.5 def get_normalized_world(self, h, w, octaves): map = np.zeros((h, w)) for y in range(h): for x in range(w): for e in range(octaves): theta = y / (w / 2) * m.pi phi = x / w * m.pi v = 2**e map[y][x] += self.polar_noise(theta, phi, v) * 1 / v return normalize_map(map) def get_normalized_world_fast(self, h, w, octaves, offset: int = 6): map = np.zeros((h, w)) for e in range(offset, octaves + offset): v = 2**e print(v) map += self.polar_fast_noise(h, w, v) / v # self.fast_noise = fns.Noise() return normalize_map(map)
def __init__(self, window: pyglet.window.Window, width, height, xoff, yoff, depth=1): """Initialize the board.""" assert depth > 0, "Attempted to created empty board." # ****** Board Attributes ****** self.window = window self.width = width self.height = height self.depth = depth self.level = 0 self.offset = Offset(xoff, yoff) # ****** Initialize Board ****** self.batch = pyglet.graphics.Batch() self.blocks: List[List[List[Block]]] = [[[None] * height for _1 in range(width)] for _2 in range(depth)] self.skirt: List[pyglet.sprite.Sprite] = [None] * width self.miners: List[Miner] = [] # self.lighting = LightingSystem( # window.width, window.height, # xoff, yoff, (width, height, depth), # batch=self.batch # ) # breaks if the size is decreased too much. # needs to be converted to a callback loader. self.seed = int.from_bytes(urandom(16), byteorder, signed=False) noise = OpenSimplex(seed=self.seed) for d in range(depth): # generate in 16x16 squares # 3 for-loops but only n squared. for chunk in range(int(ceil(width / 16) * ceil(height / 16))): m, n = map(lambda x: x * 16, divmod(chunk, int(ceil(width / 16)))) for i in range(n, n + 16): for j in range(m, m + 16): if not 0 <= i < width or not 0 <= j < height: continue pos = i * size + xoff, j * size + yoff block = Block(self, self.batch, pos, (i, j), d, (width, height, depth)) if d != self.level: block.disable_rendering() self.set_block(block, i, j, d) # range of OpenSimplex is -1 to 1. To retrieve a # value between 0 and 1 the equation is (x + 1) / 2 nval = (noise.noise3d(i / self.VEIN_SIZE, j / self.VEIN_SIZE, d / self.VEIN_SIZE) + 1) / 2 # nval = random() if nval < self.ORE_CHANCE: block = self.blocks[d][i][j] block.type = 'coal' # disabled for now. Looks kind of weird. # self.skirt[i] = pyglet.sprite.Sprite( # texture_map["skirt"], i * size + xoff, # yoff - size * 2, batch=self.batch, group=floors # ) num_miners = 5 for i in range(num_miners): k, m, d = randrange(width), randrange(height), randrange(depth) pos = k * size + xoff, m * size + yoff miner = Miner(i, self, self.batch, pos, (k, m), d, (width, height, depth)) if d != self.level: miner.disable_rendering() self.miners.append(miner) block = self.get_block(k, m, d) block.change_type("air") # self.lighting.add_air(k, m, d) for p, q in nearby_cells(k, m, 3): if not 0 <= p < width or not 0 <= q < height: continue block = self.get_block(p, q, d) block.visible = True for block_row in self.blocks: for block_col in block_row: for block in block_col: block.update()
def show_cloud(point_displayer): from opensimplex import OpenSimplex import math import randomSample simp_r = OpenSimplex(seed=364) simp_g = OpenSimplex(seed=535) simp_b = OpenSimplex(seed=656) for i in xrange(100000): x = randomSample.randInt(0, 1000, 4237842 + i) y = randomSample.randInt(0, 1000, 5437474 + i) z = randomSample.randInt(0, 1000, 6345876 + i) d = math.sqrt((x - 500)**2 + (y - 500)**2 + (z - 500)**2) / 500.0 r1 = .0009765625 * (simp_g.noise3d(x=x, y=y, z=z)) r2 = .001953125 * (simp_r.noise3d(x=x / 2.0, y=y / 2.0, z=z / 2.0)) r3 = .00390625 * (simp_b.noise3d(x=x / 4.0, y=y / 4.0, z=z / 4.0)) r4 = .0078125 * (simp_g.noise3d(x=x / 8.0, y=y / 8.0, z=z / 8.0)) r5 = .015625 * (simp_r.noise3d(x=x / 16.0, y=y / 16.0, z=z / 16.0)) r6 = .03125 * (simp_b.noise3d(x=x / 32.0, y=y / 32.0, z=z / 32.0)) r7 = .0625 * (simp_g.noise3d(x=x / 64.0, y=y / 64.0, z=z / 64.0)) r8 = .125 * (simp_r.noise3d(x=x / 128.0, y=y / 128.0, z=z / 128.0)) r9 = .25 * (simp_b.noise3d(x=x / 256.0, y=y / 256.0, z=z / 256.0)) r10 = .5 * (simp_g.noise3d(x=x / 512.0, y=y / 512.0, z=z / 512.0)) r11 = (simp_r.noise3d(x=x / 1024.0, y=y / 1024.0, z=z / 1024.0)) normalization_factor = .5 val = ((r1 + r2 + r3 + r4 + r5 + r6 + r7 + r8 + r9) / 2.0) if val > 0: p = 1.0 else: p = -1.0 # use ^d for cumulus clouds, # use distance from a certain height for a sky of clouds # use constant power <1 for endless 3d field of clouds # use distance from sets of points or lines for other shapes norm_val = (abs(val)**d) * p pos_val = (norm_val + 1.0) / 2.0 r = int(pos_val * 254.0) # r5 = int((r5)*255.0/2.0) # lim octaves->inf gives 1/2^x sum (=1) if r > 160: point_displayer.add_point([x, y, z], [r, r, r])
class Game: def __init__(self, players): self.current_round = 0 self.total_rounds = settings.TOTAL_ROUNDS self.map_size = settings.MAP_SIZE self.map = settings.MAP self.bike_length = settings.BIKE_LENGTH self.players = players self.items_map = [[[] for _ in range(settings.MAP_SIZE[1])] for _ in range(settings.MAP_SIZE[0])] self.new_items = None self._incoming_items = None self.heatmap = [[0 for _ in range(self.map_size[1])] for _ in range(self.map_size[0])] self.bike_cost = settings.BIKE_COST self.portal_gun_cost = settings.PORTAL_GUN_COST self.bike_turns = settings.BIKE_TURNS self.portal_gun_turns = settings.PORTAL_GUN_TURNS self.all_items = [Item1, Item2, Item3] self.noise_gen = OpenSimplex() self.random_spawn() def cell_available(self, row, col): return 0 <= row < self.map_size[0] and 0 <= col < self.map_size[1] and self.map[row][col] != '#' def path_available(self, p1, p2, max_dist): q = [(p1, 0)] seen = [p1] dx = [0, 1, 0, -1] dy = [1, 0, -1, 0] while len(q) > 0: front, dist = q[0] if dist >= max_dist: return False q = q[1:] for d in range(4): new_p = (front[0] + dx[d], front[1] + dy[d]) if new_p not in seen and self.cell_available(*new_p): if new_p == p2: return True seen.append(new_p) q.append((new_p, dist + 1)) def random_spawn(self): spawn_locations = [] for row in range(self.map_size[0]): for col in range(self.map_size[1]): if self.map[row][col] in ['S', 's']: spawn_locations.append((row, col)) while len(spawn_locations) < len(self.players): row, col = (random.randint(0, self.map_size[i] - 1) for i in range(2)) while not self.cell_available(row, col) or (row, col) in spawn_locations: row, col = (random.randint(0, self.map_size[i] - 1) for i in range(2)) spawn_locations.append((row, col)) random_bool = random.randint(0, 1) if random_bool == 1: spawn_locations[0], spawn_locations[1] = spawn_locations[1], spawn_locations[0] for i in range(2): self.players[i].location = spawn_locations[i] def deploy_items(self): """ Generate new items and update items_map and new_items accordingly if no new item -> self.new_items = None if new items -> add to self.new_items """ # Do nothing outside of the spawning tick. if self.current_round % settings.ITEM_SPAWN_PERIOD != 0: return if self._incoming_items is not None: # Time to spawn some items. self.new_items = self._incoming_items for x in range(settings.MAP_SIZE[0]): for y in range(settings.MAP_SIZE[1]): if settings.OVERLAP_ITEMS: self.items_map[x][y].extend(self.new_items[x][y]) else: if self.new_items[x][y]: self.items_map[x][y] = self.new_items[x][y] # Set the new incoming items. grid_noise = [[-1 for __ in range(settings.MAP_SIZE[1])] for _ in range(settings.MAP_SIZE[0])] self._incoming_items = [[[] for __ in range(settings.MAP_SIZE[1])] for _ in range(settings.MAP_SIZE[0])] for item in self.all_items: z = random.random() * 10000 for x in range(settings.MAP_SIZE[0]): for y in range(settings.MAP_SIZE[1]): if not self.cell_available(x, y): continue grid_noise[x][y] = self.noise_gen.noise3d(x * item.NOISE_MULT, y * item.NOISE_MULT, z) for a, b in [(x+1, y), (x-1, y), (x, y+1), (x, y-1)]: if grid_noise[x][y] < self.noise_gen.noise3d(a * item.NOISE_MULT, b * item.NOISE_MULT, z) + item.SPAWN_DIFF: break else: if settings.OVERLAP_ITEMS: self._incoming_items[x][y].append(item()) else: self._incoming_items[x][y] = [item()] def items_score_map(self): res = [[0 for _ in range(self.map_size[1])] for __ in range(self.map_size[0])] for row in range(self.map_size[0]): for col in range(self.map_size[1]): for item in self.items_map[row][col]: res[row][col] += item.points return res def update_heatmap(self): """ Return a 2d list with the shape of the game map for heatmap """ self.heatmap = [[0 for __ in range(settings.MAP_SIZE[1])] for _ in range(settings.MAP_SIZE[0])] target_distance = 1 + ((settings.ITEM_SPAWN_PERIOD - 1 - self.current_round % settings.ITEM_SPAWN_PERIOD) * settings.HEATMAP_LARGEST_DISTANCE) // settings.ITEM_SPAWN_PERIOD # Target distance will start off as HEATMAP_LARGEST_DISTANCE, then taper off to 1. for x in range(settings.MAP_SIZE[0]): for y in range(settings.MAP_SIZE[1]): if not self.cell_available(x, y): continue for a in range(settings.MAP_SIZE[0]): for b in range(settings.MAP_SIZE[1]): dist = abs(x-a) + abs(y-b) if dist < target_distance: self.heatmap[x][y] += (sum(item.points for item in self._incoming_items[a][b]) / (pow(dist + 1, 3))) self.heatmap[x][y] = float("{:.2f}".format(self.heatmap[x][y])) def transport_random(self, player): row, col = random.randint(0, self.map_size[0] - 1), random.randint(0, self.map_size[1] - 1) while not self.cell_available(row, col): row, col = random.randint(0, self.map_size[0] - 1), random.randint(0, self.map_size[1] - 1) player.update_location(row, col) def finish_turn(self, wagers_obj=None): if self.current_round >= 2: import aiarena21.server.network as network network.TIMEOUT_TIME = 2 recap = { 'type': 'tick', 'heatmap': self.heatmap, 'positions': [{ 'new_pos': self.players[i].location, 'delta': self.players[i].last_move } for i in range(2)], 'items': [[[y.short_name for y in position] for position in sublist] for sublist in self.items_map], 'bike': [ self.players[i].using_bike for i in range(2) ], 'teleport': [ self.players[i].using_portal_gun for i in range(2) ], 'scores': [ self.players[i].score for i in range(2) ], 'remaining_rounds': self.total_rounds - self.current_round } if wagers_obj is not None: recap.update({ 'wagers': wagers_obj['wagers'], 'positions': [{ 'new_pos': wagers_obj['before_positions'][i], 'delta': self.players[i].last_move } for i in range(2)], 'wager_positions': [self.players[i].location for i in range(2)] }) replay(recap) self.current_round += 1
from Engine3D import Engine from GeometricShapes import UniformSphere from data.vector import Vector window = pygame.display.set_mode((500, 500)) engine = Engine(window) sp = UniformSphere([250, 250, 0], 100, 2000) sp.point_set(1, '', [100, 100, 100], [0, 0, 255]) gen = OpenSimplex() for i in range(len(sp.points)): a = sp.points[i].copy() a -= sp.center a.setLength((gen.noise3d(sp.points[i][0] / 25, sp.points[i][1] / 25, sp.points[i][2] / 25) + 1) * 20) sp.points[i] += a while True: for event in pygame.event.get(): if event.type == pygame.QUIT: quit() window.fill((0, 0, 0)) sp.rotate_mode() engine.addToDraw([sp, True, False, False]) engine.draw()
n_linhas = 10 n_cols = 10 screen_size = (width, height) = 360, 640 FPS = 60 run = True matrix = [[0 for x in range(n_cols)] for y in range(n_linhas)] zoff = 0 loff = 0 for linha in range(n_linhas): coff = 0 for coluna in range(n_cols): matrix[linha][coluna] = noise.noise3d(x = coff, y = loff, z = zoff) coff += 0.2 loff += 0.2 r_width = ceil(width/n_cols) r_height = ceil(height/n_linhas) screen = pygame.display.set_mode(screen_size) clock = pygame.time.Clock() pygame.display.set_caption("Yo") while run: for event in pygame.event.get(): if(event.type == pygame.QUIT): run = False
yT = (y / shape[1]) - 0.5 lat = xT * Math.pi * 2 lon = yT * Math.pi pX = Math.cos(lon) * Math.cos(lat) * scale pY = Math.cos(lon) * Math.sin(lat) * scale pZ = Math.sin(lon) * scale val = 0 weightSum = np.sum(weights) for i in range(0, len(freqs)): freq = freqs[i] weight = weights[i] / weightSum val = val + noise3.noise3d(pX * freq, pY * freq, pZ * freq) * weight val *= 8 / 5 mapV[x, y] = float(val) SCALE = 0 THRESH = 1 mode = SCALE c = None if mode == SCALE: #c = int(255 * (1+val)/2) #c = int(255 * (1+transform(val))/2) c = getScale(transform(val), cRGB)
if __name__ == "__main__": WIDTH = 600 HEIGHT = 400 RESO = 10 N_WIDTH = WIDTH // RESO + RESO N_HEIGHT = HEIGHT // RESO + RESO FEATURE_SIZE = 10 ops = OpenSimplex() z_inc = 0 while True: img = np.full((HEIGHT, WIDTH), 127, dtype=np.uint8) grid = np.array([[(ops.noise3d(i / FEATURE_SIZE, j / FEATURE_SIZE, z_inc)) for i in range(N_WIDTH)] for j in range(N_HEIGHT)]) grid = scale(grid) img = draw_corners(img, grid) img = draw_lines(img, grid) cv.imshow("im", img) # cv.imshow("g",grid) key = cv.waitKey(1) if key == ord('q') & 0xFF: break z_inc += 0.1
def main(): global SEALEVEL global FEATURE_SIZE global WATER_LEVEL global SIZE global pathx global pathz MIN = 500 MAX = 0 CNT = 0 TOT = 0 pathx = [] pathz = [] if (len(sys.argv) > 1): if (sys.argv[1]): SIZE = int(sys.argv[1]) else: SIZE = 1000 if (sys.argv[2]): SEED = int(sys.argv[2]) else: SEED = 0 if (sys.argv[3]): WATER_LEVEL = float(sys.argv[3]) else: WATER_LEVEL = 15.0 if (sys.argv[4]): FEATURE_SIZE = float(sys.argv[4]) else: FEATURE_SIZE = 24.0 else: SIZE = 1000 SEED = 0 WATER_LEVEL = 15.0 FEATURE_SIZE = 24.0 print("Generating world of size " + str(SIZE) + " by " + str(SIZE) + "...") print("Seed " + str(SEED) + " Water Percentage " + str(WATER_LEVEL) + " Land Feature Variant " + str(FEATURE_SIZE) + ".") global MAXX MAXX = SIZE global MAXZ MAXZ = SIZE global Y Y = [[0 for x in range(MAXX)] for z in range(MAXZ)] global MOVE_NW MOVE_NW = [[0 for x in range(MAXX)] for z in range(MAXZ)] global MOVE_N MOVE_N = [[0 for x in range(MAXX)] for z in range(MAXZ)] global MOVE_NE MOVE_NE = [[0 for x in range(MAXX)] for z in range(MAXZ)] global MOVE_E MOVE_E = [[0 for x in range(MAXX)] for z in range(MAXZ)] global MOVE_SE MOVE_SE = [[0 for x in range(MAXX)] for z in range(MAXZ)] global MOVE_S MOVE_S = [[0 for x in range(MAXX)] for z in range(MAXZ)] global MOVE_SW MOVE_SW = [[0 for x in range(MAXX)] for z in range(MAXZ)] global MOVE_W MOVE_W = [[0 for x in range(MAXX)] for z in range(MAXZ)] global SEEDS SEEDS = [[random.randint(0, SIZE) for x in range(MAXX)] for z in range(MAXZ)] simplex = OpenSimplex(seed=SEED) for z in range(0, MAXX): for x in range(0, MAXZ): value = simplex.noise3d(x / FEATURE_SIZE, z / FEATURE_SIZE, 0.0) y = int((value + 1) * 128) if (y > MAX): MAX = y if (y < MIN): MIN = y Y[x][z] = y SEALEVEL = int((MAX - MIN) * (WATER_LEVEL / 100)) + MIN print("Make water level " + str(SEALEVEL) + " or below..") # waterify W by displaying everything below SEALEVEL+1 as ~ # calculate movement costs in all direction for W but only above SEALEVEL for Z in range(MAXZ): for X in range(MAXX): if (Y[X][Z] > SEALEVEL): # process movement # MOVE_NW[X][Z] = calmove(X,Z,1) # MOVE_N[X][Z] = calmove(X,Z,2) # MOVE_NE[X][Z] = calmove(X,Z,3) # MOVE_E[X][Z] = calmove(X,,Z,4) # MOVE_SE[X][Z] = calmove(X,Z,5) # MOVE_S[X][Z] = calmove(X,Z,6) # MOVE_SW[X][Z] = calmove(X,Z,7) # MOVE_W[X][Z] = calmove(X,Z,8) # special cases, corners and X=MAXX, Z=MAXZ if (X == 0): # process N, NE, E, SE, S if (Z == 0): # process E, SE, S MOVE_NW[X][Z] = MOVE_N[X][Z] = MOVE_NE[X][Z] = MOVE_W[ X][Z] = MOVE_SW[X][Z] = False MOVE_E[X][Z] = calmove(X, Z, 4) MOVE_SE[X][Z] = calmove(X, Z, 5) MOVE_S[X][Z] = calmove(X, Z, 6) continue if (Z == MAXZ): # BOTTOM LEFT CORNER, no process S, SW, W MOVE_W[X][Z] = MOVE_NW[X][Z] = MOVE_SE[X][Z] = MOVE_S[ X][Z] = MOVE_SW[X][Z] = False MOVE_NE[X][Z] = calmove(X, Z, 3) MOVE_N[X][Z] = calmove(X, Z, 2) MOVE_E[X][Z] = calmove(X, Z, 4) continue # X is 0 moving down left edge of world, no NW, SW, W MOVE_NW[X][Z] = False MOVE_N[X][Z] = calmove(X, Z, 2) MOVE_NE[X][Z] = calmove(X, Z, 3) MOVE_E[X][Z] = calmove(X, Z, 4) MOVE_SE[X][Z] = calmove(X, Z, 5) MOVE_S[X][Z] = calmove(X, Z, 6) MOVE_SW[X][Z] = MOVE_W[X][Z] = False if (X == MAXX): if (Z == 0): # TOP RIGHT CORNER, no NW, N, NE, E, SE MOVE_NW[X][Z] = MOVE_N[X][Z] = MOVE_NE[X][Z] = MOVE_E[ X][Z] = MOVE_SE[X][Z] = False MOVE_S[X][Z] = calmove(X, Z, 6) MOVE_SW[X][Z] = calmove(X, Z, 7) MOVE_W[X][Z] = calmove(X, Z, 8) continue if (Z == MAXZ): # BOTTOM RIGHT CORNER, no NE, E, SE, S, SW MOVE_NW[X][Z] = calmove(X, Z, 1) MOVE_N[X][Z] = calmove(X, Z, 2) MOVE_NE[X][Z] = MOVE_E[X][Z] = MOVE_SE[X][Z] = MOVE_S[ X][Z] = MOVE_SW[X][Z] = False MOVE_W[X][Z] = calmove(X, Z, 8) continue # X is MAXX moving down right edge of world, no NE, E, SE MOVE_NW[X][Z] = calmove(X, Z, 1) MOVE_N[X][Z] = calmove(X, Z, 2) MOVE_NE[X][Z] = MOVE_E[X][Z] = MOVE_SE[X][Z] = False MOVE_S[X][Z] = calmove(X, Z, 6) MOVE_SW[X][Z] = calmove(X, Z, 7) MOVE_W[X][Z] = calmove(X, Z, 8) continue if (Z == 0): # moving across the top, no NW, N, NE MOVE_NW[X][Z] = MOVE_N[X][Z] = MOVE_NE[X][Z] = False MOVE_E[X][Z] = calmove(X, Z, 4) MOVE_SE[X][Z] = calmove(X, Z, 5) MOVE_S[X][Z] = calmove(X, Z, 6) MOVE_SW[X][Z] = calmove(X, Z, 7) MOVE_W[X][Z] = calmove(X, Z, 8) continue if (Z == MAXZ): # moving across the bottom, no SE, S, SW MOVE_NW[X][Z] = calmove(X, Z, 1) MOVE_N[X][Z] = calmove(X, Z, 2) MOVE_NE[X][Z] = calmove(X, Z, 3) MOVE_E[X][Z] = calmove(X, Z, 4) MOVE_SE[X][Z] = MOVE_S[X][Z] = MOVE_SW[X][Z] = False MOVE_W[X][Z] = calmove(X, Z, 8) continue # Special cases done, not near an edge MOVE_NW[X][Z] = calmove(X, Z, 1) MOVE_N[X][Z] = calmove(X, Z, 2) MOVE_NE[X][Z] = calmove(X, Z, 3) MOVE_E[X][Z] = calmove(X, Z, 4) MOVE_SE[X][Z] = calmove(X, Z, 5) MOVE_S[X][Z] = calmove(X, Z, 6) MOVE_SW[X][Z] = calmove(X, Z, 7) MOVE_W[X][Z] = calmove(X, Z, 8) addrivers(SEED) print('Generated. Normalizing...') # normalize W for Z in range(MAXZ): for X in range(MAXX): Y[X][Z] = normalize_around(X, Z) V = Y[X][Z] if (MIN > V): MIN = V if (MAX < V): MAX = V CNT = CNT + 1 TOT = TOT + V AVG = TOT / CNT print("Normalize results: MAX " + str(MAX) + " MIN " + str(MIN) + " CNT " + str(CNT) + " AVG " + str(AVG)) display_cell(84, 73, SEALEVEL) print("Creating map representations:") print("PGM world.pgm [", end='') createfilepgm("data/world.pgm", MAX) print("DONE]") print("PPM world.ppm [", end='') createfileppm("data/world.ppm") print("DONE]") print("TEXT world.txt [", end='') createfiletext("data/world.txt") print("DONE]") print("Saving generated world to files.") write_Y() write_D() write_M()