Exemplo n.º 1
1
def sweep_perlin(shape, **params):
    """ Generate a 2 dimensional matrix with perlin noise normalized between -1 and 1 
    Available parameters

    octaves -- specifies the number of passes, defaults to 1 (simple noise).
    
    persistence -- specifies the amplitude of each successive octave relative
    to the one below it. Defaults to 0.5 (each higher octave's amplitude
    is halved). Note the amplitude of the first pass is always 1.0.
    
    lacunarity -- specifies the frequency of each successive octave relative
    to the one below it, similar to persistence. Defaults to 2.0.
    
    repeatx, repeaty -- specifies the interval along each axis when 
    the noise values repeat. This can be used as the tile size for creating 
    tileable textures
    
    base -- specifies a fixed offset for the noise coordinates. Useful for
    generating different noise textures with the same repeat interval
    """
    print repr(params)
    target = numpy.zeros(shape)
    print "weight matrix " + str(target.shape)
    for i in range(shape[0]):
        for j in range(shape[1]):
            target[i, j] = noise.pnoise2(i / shape[0], j / shape[1], **params)

    # target -= target.min()
    # target /= target.max()
    # target = target*2-1

    return target
Exemplo n.º 2
0
def make_donut(shape = (100,100), b=1):
  world = np.zeros(shape)
  radius1 = 0.2
  radius2=0.4
  alpha = b+1
  for i in range(shape[0]):
      for j in range(shape[1]):
        ii = (i-shape[0]/2)/shape[0]
        jj = (j-shape[1]/2)/shape[1]
        angle = math.atan2(ii,jj)
        cos = math.cos
        sin = math.sin
        r2 = radius2+ noise.pnoise2(cos(angle),sin(angle),base=alpha)/10
        r1 = radius1+ noise.pnoise2(cos(angle),sin(angle),base=100+1+alpha)/10

        rho = math.sqrt(ii*ii+jj*jj)

        if rho < r2 and rho > r1:
          #world[i][j] = 1
          middle_rho = (r2+r1)/2
          max_dist = max(abs(r2-middle_rho), abs(r1-middle_rho))
          temp = 1-abs(rho-middle_rho)/max_dist
          if temp < 0:
            temp = 0
          world[i][j] = temp
  return world
Exemplo n.º 3
0
def update_noise_map(noise_map, row_index, true_index, offset_x, offset_y):
    # Needs to replace a row with the correct offset.
    # To do this, we need the row / column.
    shape = noise_map.shape
    size = (shape[0] // 2, shape[1] // 2)

    if row_index == size[0]:
        # Update whole lower matrix.
        for i in range(size[0], size[0] * 2):
            i1 = (i + true_index) / 10 + offset_x
            for j in range(size[1], size[1] * 2):
                j1 = (j + true_index) / 10 + offset_y
                noise_map[i][j] = pnoise2(i1, j1)

        np.abs(noise_map[size[0]:size[0] * 2, size[1]:size[1] * 2],
               out=noise_map[size[0]:size[0] * 2, size[1]:size[1] * 2])

        return true_index + size[0]
    else:
        y = (row_index + true_index) / 10 + offset_y
        for j in range(row_index, size[0] + row_index):
            x = (j + true_index) / 10 + offset_x
            noise_map[j][row_index] = pnoise2(x, y)
        x = (row_index + true_index) / 10 + offset_x
        for j in range(row_index, size[0] + row_index):
            y = (j + true_index) / 10 + offset_y
            noise_map[row_index][j] = pnoise2(x, y)

        np.abs(noise_map[row_index, row_index:size[0] + row_index],
               out=noise_map[row_index, row_index:size[0] + row_index])
        np.abs(noise_map[row_index:size[0] + row_index, row_index],
               out=noise_map[row_index:size[0] + row_index, row_index])
        return true_index
Exemplo n.º 4
0
def create_bands_texture(bands=14.0,
                         stretch=2.0,
                         turbulence=18.0,
                         color1=(1.0, 0.8, 0.6),
                         color2=(0.1, -0.3, -0.4)):
    coords = range(TEXTURE_SIZE)
    texel = (ctypes.c_ubyte * (3 * TEXTURE_SIZE**2))()
    for y in coords:
        for x in coords:
            p = pnoise2(x * 15.0 / TEXTURE_SIZE,
                        y * 15.0 / TEXTURE_SIZE,
                        octaves=5,
                        repeatx=15.0,
                        repeaty=15.0) * math.pi * 2.0
            px = (x + math.sin(p) * turbulence)
            py = (y + math.cos(p) * turbulence)
            v = pnoise2(px / stretch / TEXTURE_SIZE,
                        py * bands / TEXTURE_SIZE,
                        octaves=4,
                        repeaty=bands,
                        repeatx=1.0 / stretch)
            r, g, b = blend((v + 1.0) / 2.0, color1, color2,
                            1.75 + (p**5) * 0.003)
            texel[(x + (y * TEXTURE_SIZE)) * 3] = max(min(int(r * 255.0), 255),
                                                      0)
            texel[(x + (y * TEXTURE_SIZE)) * 3 + 1] = max(
                min(int(g * 255.0), 255), 0)
            texel[(x + (y * TEXTURE_SIZE)) * 3 + 2] = max(
                min(int(b * 255.0), 255), 0)
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, TEXTURE_SIZE, TEXTURE_SIZE, 0,
                 GL_RGB, GL_UNSIGNED_BYTE, ctypes.byref(texel))
    return texel
Exemplo n.º 5
0
    def terrain_type_for_square(self, col, row):
        terrain_type = PLAINS

        frequency = 1.0/5
        forest_value = noise.pnoise2(col*frequency, row*frequency, 20)
        if forest_value < -0.05:
            terrain_type = FOREST

        frequency_x = 1.0/30
        frequency_y = 1.0/40
        mountain_value = noise.pnoise2(col*frequency, row*frequency, 1)
        if mountain_value > 0.2:
            terrain_type = MOUNTAINS

        frequency_x = 1.0/60
        frequency_y = 1.0/45
        river_value = noise.pnoise2(col*frequency_x, row*frequency_y, 10, -0.3)
        if river_value < 0.04 and river_value > -0.04:
            terrain_type = WATER

        frequency = 1.0/30
        lake_value = noise.pnoise2(col*frequency, row*frequency, 6)
        if lake_value < -0.2:
            terrain_type = WATER

        return terrain_type
Exemplo n.º 6
0
def update_matrix_funky(noise_map, row_index, true_index, offset_x, offset_y):
    # Needs to replace a row with the correct offset.
    # To do this, we need the row / column.
    if row_index == noise_map.shape[0] // 2:
        # Update whole lower matrix.
        for i in range(size[0], size[0] * 2):
            i1 = i / 10 + offset_x
            for j in range(size[1], size[1] * 2):
                j1 = j / 10 + offset_y
                noise_map[i][j] = pnoise2(i1, j1)
        np.abs(noise_map[size[0]:size[0] * 2, size[1]:size[1] * 2],
               out=noise_map[size[0]:size[0] * 2, size[1]:size[1] * 2])
    else:
        for j in range(row_index, size[0] + row_index):
            x = j / 10 + offset_x
            noise_map[j][row_index] = pnoise2(x, offset_y)
        np.abs(noise_map[j, row_index:size[0] + row_index],
               out=noise_map[j, row_index:size[0] + row_index])
        for j in range(row_index, size[0] + row_index):
            y = j / 10 + offset_y
            noise_map[row_index][j] = pnoise2(offset_x, y)
        np.abs(noise_map[row_index:size[0] + row_index, j],
               out=noise_map[row_index:size[0] + row_index, j])

    return true_index + 1
Exemplo n.º 7
0
    def terrain_type_for_square(self, col, row):
        terrain_type = PLAINS

        frequency = 1.0 / 5
        forest_value = noise.pnoise2(col * frequency, row * frequency, 20)
        if forest_value < -0.05:
            terrain_type = FOREST

        frequency_x = 1.0 / 30
        frequency_y = 1.0 / 40
        mountain_value = noise.pnoise2(col * frequency, row * frequency, 1)
        if mountain_value > 0.2:
            terrain_type = MOUNTAINS

        frequency_x = 1.0 / 60
        frequency_y = 1.0 / 45
        river_value = noise.pnoise2(col * frequency_x, row * frequency_y, 10,
                                    -0.3)
        if river_value < 0.04 and river_value > -0.04:
            terrain_type = WATER

        frequency = 1.0 / 30
        lake_value = noise.pnoise2(col * frequency, row * frequency, 6)
        if lake_value < -0.2:
            terrain_type = WATER

        return terrain_type
Exemplo n.º 8
0
def terrain_type_for_square(col, row):
    terrain_type = 'plains'

    frequency = 1.0/5
    forest_value = noise.pnoise2(col*frequency, row*frequency, 20)
    if forest_value < -0.05:
        terrain_type = 'forest'

    frequency_x = 1.0/30
    frequency_y = 1.0/40
    mountain_value = noise.pnoise2(col*frequency, row*frequency, 1)
    if mountain_value > 0.2:
        terrain_type = 'mountains'

    frequency_x = 1.0/60
    frequency_y = 1.0/45
    river_value = noise.pnoise2(col*frequency_x, row*frequency_y, 10, -0.3)
    if river_value < 0.04 and river_value > -0.04:
        terrain_type = 'water'

    frequency = 1.0/30
    lake_value = noise.pnoise2(col*frequency, row*frequency, 6)
    if lake_value < -0.2:
        terrain_type = 'water'

    return terrain_type
Exemplo n.º 9
0
def weighted_sum_tensor_field(tss, dominant_types, \
    target_i, target_j, num_row, num_col, decay_const):
    dominant_type_org = dominant_types[target_i][target_j]
    major_evec = np.array([0., 0.])
    minor_evec = np.array([0., 0.])
    if dominant_type_org != -1:
        for m in xrange(num_row):
            for n in xrange(num_col):
                dominant_type = dominant_types[m][n]
                [major,
                 minor] = tss[dominant_type].tensor_field(target_j, target_i)
                # XXX major or minor eigenvector? which to use?
                # a = math.pow(math.e,-1.*decay_const*(abs(m-target_i)*abs(m-target_i)+abs(n-target_j)*target_j(n-target_j)))
                # if a>math.pow(10.,-3):
                # print a

                major_evec[0] += major[0]*math.pow(math.e,\
                        -1.*decay_const*(abs(m-target_i)*abs(m-target_i)+abs(n-target_j)*abs(n-target_j)))
                major_evec[1] += major[1]*math.pow(math.e,\
                        -1.*decay_const*(abs(m-target_i)*abs(m-target_i)+abs(n-target_j)*abs(n-target_j)))
                minor_evec[0] += minor[0]*math.pow(math.e,\
                        -1.*decay_const*(abs(m-target_i)*abs(m-target_i)+abs(n-target_j)*abs(n-target_j)))
                minor_evec[1] += minor[1]*math.pow(math.e,\
                        -1.*decay_const*(abs(m-target_i)*abs(m-target_i)+abs(n-target_j)*abs(n-target_j)))

        # (2) normalize tensor vector
        major_evec = [major_evec[0]/np.linalg.norm(major_evec),\
                major_evec[1]/np.linalg.norm(major_evec)]
        minor_evec = [minor_evec[0]/np.linalg.norm(minor_evec),\
                minor_evec[1]/np.linalg.norm(minor_evec)]

        # (3) add rotational field (use Perlin noise to generate the angle)
        # https://github.com/caseman/noise
        # http://nullege.com/codes/search/noise.pnoise2
        # Perlin noise is not actually "random"
        # there are lots of easily discernible patterns
        # http://stackoverflow.com/questions/12473434/whats-the-randomness-quality-of-the-perlin-simplex-noise-algorithms

        R1_major = pnoise2(major_evec[0],
                           major_evec[1]) * math.pi - math.pi / 2.
        R1_minor = -1. * R1_major
        major_evec = np.dot(np.array([major_evec[0],major_evec[1]]),\
                np.array([[math.cos(R1_major),-math.sin(R1_major)],\
                [math.sin(R1_major),math.cos(R1_major)]]))
        minor_evec = np.dot(np.array([minor_evec[0],minor_evec[1]]),\
                np.array([[math.cos(R1_minor),-math.sin(R1_minor)],\
                [math.sin(R1_minor),math.cos(R1_minor)]]))

        R2 = pnoise2(major_evec[0], major_evec[1]) * math.pi - math.pi / 2.
        major_evec = np.dot(np.array([major_evec[0],major_evec[1]]),\
                np.array([[math.cos(R2),-math.sin(R2)],\
                [math.sin(R2),math.cos(R2)]]))
        R3 = pnoise2(major_evec[0], major_evec[1]) * math.pi - math.pi / 2.
        minor_evec = np.dot(np.array([minor_evec[0],minor_evec[1]]),\
                np.array([[math.cos(R3),-math.sin(R3)],\
                [math.sin(R3),math.cos(R3)]]))

        # TODO: (4) Laplacian smoothing
    return major_evec, minor_evec
Exemplo n.º 10
0
def noise_xy(points, scale=0.1, frequency=0.5, octaves=3, seed=None):
    """
    Generate a number of x,y points using Perlin noise.
    """
    seed = get_noise_seed(seed)
    tn = np.linspace(seed, seed + frequency, points)
    x = [pnoise2(0, float(t), octaves) * scale for t in tn]
    y = [pnoise2(1, float(t), octaves) * scale for t in tn]
    return x, y
Exemplo n.º 11
0
def animate(i):
    angle = np.linspace(0, 2 * np.pi, 1000)
    x = np.cos(angle) + noise.pnoise2(np.cos(i / frames * 2 * np.pi),
                                      np.sin(i / frames * 2 * np.pi))
    y = np.sin(angle) + noise.pnoise2(
        np.cos(i / frames * 2 * np.pi) + 1000,
        np.sin(i / frames * 2 * np.pi) + 1000)
    line.set_data(x, y)
    return line,
Exemplo n.º 12
0
def move_perlin(index, step):
    action = {}
    mag = (pnoise2(index, step * 0.01) + 1) * 200
    theta = (pnoise2(index, step * 0.01) + 1) * tau
    action["x"] = mag * cos(theta)
    action["y"] = mag * sin(theta)

    action["fire"] = random.random() > 0.999
    action["split"] = random.random() > 0.999
    return action
Exemplo n.º 13
0
    def generate(self, chunkx, chunky):

        GRASS = "grass"
        MOUNTAIN = "mountain"
        EMPTY = "void"

        oct = 1

        floor_void_diff = 0.3
        mountain = floor_void_diff + 0.2

        floor = {}
        items = {}
        chunk = (chunkx, chunky)

        if chunk not in self.chunks:

            # print("Generating chunk at {}".format(chunk))
            for y in range(chunky * CHUNKSIZE, chunky * CHUNKSIZE + CHUNKSIZE):
                for x in range(chunkx * CHUNKSIZE,
                               chunkx * CHUNKSIZE + CHUNKSIZE):
                    try:
                        i = round(
                            noise.pnoise2(x / 15,
                                          y / 15,
                                          octaves=oct,
                                          base=int(self.seed)), 5)
                    except Exception:
                        i = round(
                            noise.pnoise2(x / 15,
                                          y / 15,
                                          octaves=oct,
                                          base=seedgen), 5)
                    if i >= floor_void_diff:
                        if i > mountain:
                            floor.update({(x, y): MOUNTAIN})
                        else:
                            floor.update({(x, y): GRASS})
                        spawner = random.randint(0, ITEM_SPAWN_RATIO)

                        if spawner == 0:
                            items.update({(x, y): "i"})
                        elif spawner == 1:
                            items.update({(x, y): "A"})

                    elif i < floor_void_diff:
                        floor.update({(x, y): EMPTY})
                    else:
                        floor.update({(x, y): EMPTY})

            self.chunks.update({chunk: {"floor": floor, "items": items}})
            self.unsaved += 1
Exemplo n.º 14
0
 def raise_point(self, point):
     new_elevation = 0
     #print("add1: " + str(3 * (noise.pnoise2(point.getX() / 10, point.getY() / 10, 1, .5, 2) + 1)))
     new_elevation += (4 * (noise.pnoise2(point.getX() / 10,
                                          point.getY() / 10, 1, .5, 2) + 1))
     #print("add2: " + str(3 * (noise.pnoise2(point.getX() / 100, point.getY() / 100, 1, .5, 2) + 1)))
     new_elevation += (4 *
                       (noise.pnoise2(point.getX() / 100,
                                      point.getY() / 100, 1, .5, 2) + 1))
     point.set_elevation(new_elevation)
     point.set_biome('coast')
     #print("raised: " + str(point))
     return point
Exemplo n.º 15
0
    def _initialize(self):
        """ Initialize the world by placing all the blocks.

        """
        n = int(SECTOR_SIZE * mapSize / 2)  # 1/2 width and height of world
        s = 1  # step size
        y = 0  # initial y height
        for x in xrange(-n, n + 1, s):
            for z in xrange(-n, n + 1, s):
                # create a layer stone an grass everywhere.

                self.add_block((x, y - 1, z), BEDROCK, immediate=False)
                # 0 for earthlike, 1 for alien,  2 for moon, 3 for mars, etc
                if planet_type == 2:
                    terrainHeight = noise.pnoise2((noiseOffsetX + x) / scale,
                                                  (noiseOffsetY + z) / scale,
                                                  octaves=octaves,
                                                  persistence=persistence,
                                                  lacunarity=lacunarity,
                                                  repeatx=1024,
                                                  repeaty=1024,
                                                  base=0) * 10 + 10
                elif planet_type == 3:
                    terrainHeight = noise.pnoise2((noiseOffsetX + x) / scale,
                                                  (noiseOffsetY + z) / scale,
                                                  octaves=octaves,
                                                  persistence=persistence,
                                                  lacunarity=lacunarity,
                                                  repeatx=1024,
                                                  repeaty=1024,
                                                  base=0) * 17 + 10
                else:
                    terrainHeight = noise.pnoise2((noiseOffsetX + x) / scale,
                                                  (noiseOffsetY + z) / scale,
                                                  octaves=octaves,
                                                  persistence=persistence,
                                                  lacunarity=lacunarity,
                                                  repeatx=1024,
                                                  repeaty=1024,
                                                  base=0) * 25 + 8
                for y in range(int(terrainHeight) - 5):
                    #self.world[(x,y,x)] = STONE
                    self.add_block((x, y, z), STONE, immediate=False)
                for y in range(5):
                    #self.world[(x,y,x)] = STONE
                    self.add_block((x, int(terrainHeight) - 5 + y, z),
                                   DIRT,
                                   immediate=False)
                self.add_block((x, int(terrainHeight), z),
                               GRASS,
                               immediate=False)
Exemplo n.º 16
0
def move_smarter(index, step, client):
    """
    Bot is moved using perlin noise.
    """
    action = {"x": 0, "y": 0, "fire": False, "split": False}

    best_food = None
    best_food_dist = inf
    for f_id in client.food:
        f = client.food[f_id]
        dist = (f["x"] - client.playerCoords["x"])**2 + (
            f["y"] - client.playerCoords["y"])**2
        if dist < best_food_dist:
            best_food_dist = dist
            best_food = f

    best_smaller_cell = None
    best_cell_dist = inf
    for c in client.cells:
        if c["mass"] < client.playerMass and c["playerID"] != client.playerID:
            dist = (c["x"] - client.playerCoords["x"])**2 + (
                c["y"] - client.playerCoords["y"])**2
            if dist < best_cell_dist:
                best_cell_dist = dist
                best_smaller_cell = c

    if best_food != None and best_smaller_cell != None:
        if best_food_dist * 10 < best_cell_dist:
            action["x"] = best_food["x"] - client.playerCoords["x"]
            action["y"] = best_food["y"] - client.playerCoords["y"]
        else:
            action["x"] = best_smaller_cell["x"] - client.playerCoords["x"]
            action["y"] = best_smaller_cell["y"] - client.playerCoords["y"]
    else:
        if best_food != None:
            action["x"] = best_food["x"] - client.playerCoords["x"]
            action["y"] = best_food["y"] - client.playerCoords["y"]
        elif best_smaller_cell != None:
            action["x"] = best_smaller_cell["x"] - client.playerCoords["x"]
            action["y"] = best_smaller_cell["y"] - client.playerCoords["y"]

    action["x"] *= 2
    action["y"] *= 2

    action["x"] += pnoise2(index * 10, step * 0.01) * 4 * client.playerMass
    action["y"] += pnoise2(index * 10, -step * 0.01) * 4 * client.playerMass

    action["fire"] = random() > 0.95
    action["split"] = random() > 0.95

    return action
Exemplo n.º 17
0
 def riged(x, y):
     e0 = 1.00 * abs(
         noise.pnoise2(
             1 * x / self.rows * parameters["shape"]["scale"] * 8,
             1 * y / self.cols * parameters["shape"]["scale"] * 8)) * 1
     e1 = 0.50 * abs(
         noise.pnoise2(
             2 * x / self.rows * parameters["shape"]["scale"] * 8,
             2 * y / self.cols * parameters["shape"]["scale"] * 8)) * e0
     e2 = 0.25 * abs(
         noise.pnoise2(
             4 * x / self.rows * parameters["shape"]["scale"] * 8,
             4 * y / self.cols * parameters["shape"]["scale"] *
             8)) * (e0 + e1)
     return e0 + e1 + e2
Exemplo n.º 18
0
def apply_perlin_3D(triangle_strip, transformation, noise_space=0):

	for line in triangle_strip:
		for node in line:
			# change node position
			x, y, z = node.position
			z += noise_space
			node.position[1] = noise.pnoise2(x, z) * transformation

			# change node.connections position
			for connection in node.connections:
				if connection.position:
					x, y, z = connection.position
					z += noise_space
					connection.position[1] = noise.pnoise2(x, z) * transformation
Exemplo n.º 19
0
    def terrainLoop(self):
        global flying
        xoff, yoff = 0,0
        for y in range(rows):
            terrainz.append(list())
            for x in range(cols):
                terrainz[y].append(noise.pnoise2(xoff,yoff))

        while True:
            flying-=.15
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()

            self.screen.fill((0,0,0))

            yoff = flying
            for y in range(rows):
                xoff = 0
                for x in range(cols):
                    terrainz[y][x]=35*noise.pnoise2(xoff,yoff)
                    xoff+=.15
                yoff+=.15

            for y in range(rows-1):
                x = 0
                points = list()
                for x in range(cols-1):
                    tempV = np.dot(rotation_matrix([1,0,0],1.8*math.pi/3), [x*scl-centerX,-(y*scl-centerY),terrainz[y][x]])
                    tempV[0]*=(1.5-(tempV[2]/600))
                    tempV[1]*=(2-(tempV[2]/600))
                    points.append([int(tempV[0]+centerX+translateX),int(tempV[1]+centerY)+translateY/2])

                    tempV = np.dot(rotation_matrix([1,0,0],1.8*math.pi/3), [x*scl-centerX,-((y+1)*scl-centerY),terrainz[y+1][x]])
                    tempV[0]*=(1.5-(tempV[2]/600))
                    tempV[1]*=(2-(tempV[2]/600))
                    points.append([int(tempV[0]+centerX+translateX),int(tempV[1]+centerY)+translateY/2])

                    tempV = np.dot(rotation_matrix([1,0,0],1.8*math.pi/3), [(x+1)*scl-centerX,-(y*scl-centerY),terrainz[y][x+1]])
                    tempV[0]*=(1.5-(tempV[2]/600))
                    tempV[1]*=(2-(tempV[2]/600))
                    points.append([int(tempV[0]+centerX+translateX),int(tempV[1]+centerY)+translateY/2])
                    pygame.draw.lines(self.screen,(255,255,255),True,points,1)
                    points = list()
                # pygame.draw.rect(self.screen,(255,255,255),[0,y*scl,self.width,1],1)
                # pygame.draw.line(self.screen,(255,255,255),rotateX([0,y*scl],self.centerX,self.centerY,.25),rotateX([self.width,y*scl],self.centerX,self.centerY,.25))

            pygame.display.flip()
Exemplo n.º 20
0
 def addNoise(self, octaves):
     freq = 16.0 * octaves
     for x in range(self.width):
         for y in range(self.height):
             self.heightmap[x][y] += \
                     int(pnoise2(x / freq, y / freq, octaves)\
                     * 127.0 + 128.0)
Exemplo n.º 21
0
	def draw(self, context, pa, pb):
		n = self.n

		dx = pb.x - pa.x
		dy = pb.y - pa.y
		m = dy / dx

		di = dx / float(n)

		r = self.r
		f = self.f
		dj = 0.0

		pts = []
		for i in range(n + 1):
			x = di*i
			pts.append(Pt(
				pa.x + x,
				pa.y + x*m + r*noise.pnoise2(i/f, (pa.y + x*m)/f, 1)))

		context.set_line_width(1.0)
		context.move_to(pa.x, pa.y)
		for i in range(1, len(pts)):
			a = pts[i - 1]
			b = pts[i]
			context.curve_to(
				a.x + di/2.0, a.y,
				b.x - di/2.0, b.y,
				b.x, b.y)
		context.stroke()
Exemplo n.º 22
0
def get_noise(size, freq, octaves, persistence):
	offset = np.random.randint(size)
	perlin = np.zeros((size, size), dtype=np.uint8)
	for i in range(size):
		for j in range(size):
			perlin[i, j] = pnoise2(offset + j * freq / size, offset + i * freq / size, octaves, persistence) * 127.0 + 128
	return perlin
Exemplo n.º 23
0
Arquivo: gen.py Projeto: stevesan/dero
def test_polygonate_perlin():
    L = 400
    G = Grid2(L, L, 0)
    S = 10.0/L

    minval = 999999.0
    maxval = -999999
    for (u,_) in G.piter():
        x = u.x * S
        y = u.y * S
        val = noise.pnoise2(x, y)
        G.pset(u, val)

    polys = polygonate(G, lambda x : x > -0.1 and x < 0.2, False, None)

    for i in range(len(polys)):
        polys[i] = linear_simplify_poly(polys[i])

    draw_polys(polys)
    marx = G.W*0.1
    mary = G.H*0.1
    pylab.xlim([-marx, G.W+marx])
    pylab.ylim([-mary, G.H+mary])
    pylab.grid(True)
    pylab.show()
Exemplo n.º 24
0
 def generate(self, space, block_x, block_y, random):
     
     if space.getBlockLayer(block_x, block_y) is not 2:
         return
     
     thisPlanetKey = str(block_x) + "," + str(block_y)
     if thisPlanetKey not in space.planets:
         space.setBlockLayer(block_x, block_y, 3)
         return
     thisPlanet = space.planets[thisPlanetKey]
     
     planetsAroundCount = 0
     for dx in range(-1, 1):
         for dy in range(-1, 1):
             thatPlanetKey = str(block_x+dx)+","+str(block_y+dy)
             if thatPlanetKey in space.planets:
                 planetsAroundCount += 1
     
     planetsAroundFactor = (planetsAroundCount + 1)/2
     
     thisPlanet.height = []
     for i in range(0, self.HEIGHT_RESOLUTION):
         
         a = math.pi * 2 * (float(i) / self.HEIGHT_RESOLUTION)
         hx = self.PLANET_HEIGHT_RADIUS * thisPlanet.size * math.sin(a)
         hy = self.PLANET_HEIGHT_RADIUS * thisPlanet.size * math.cos(a)
         h = pnoise2(thisPlanet.position[0] + hx, thisPlanet.position[1] + hy, self.PLANET_HEIGHT_OCTAVES)
         
         thisPlanet.height.append(1.0 + self.MAX_HEIGHT + h * self.MAX_HEIGHT * planetsAroundFactor)
     
     space.setBlockLayer(block_x, block_y, 3)
Exemplo n.º 25
0
 def terrain(self):
     pixels = self.pixels
     center = (self.size[0]/2, self.size[1]/2)
     def dist(c):
         dx = center[0] - c[0]
         dy = center[1] - c[1]
         mag = math.sqrt(dx * dx + dy * dy)
         return mag
     ox = random.random() * 1
     oy = random.random() * 1
     for y in range(self.size[1]):
         for x in range(self.size[0]):
             freq = 90.5
             octaves = 6
             perlin = pnoise2(ox + x / freq, oy + y / freq, octaves) + 0.5
             mag = dist((x, y)) / 300.0
             height = perlin * (1 - mag) * 1.0
             self.heights[x, y] = height
             if height < 0:
                 height = 0
             for t in TERRAINS:
                 if height < t.threshold:
                     rgb = t.color
                     if t.name == "Snow":
                         self.tips.append((x, y))
                     break
             pixels[x, y] = tuple([int(c * 255.0) for c in rgb])
     return self
Exemplo n.º 26
0
    def data(self):
        xlim = ylim = 100
        value = [[None for x in range(xlim)] for y in range(ylim)]
        
        data = self.source.data()
        noise = [[pnoise2(self.source.selection[1][0]+self.selection[1][0]+float(x)/xlim,
                          self.source.selection[0][0]+self.selection[0][0]+float(y)/ylim,
                          6, 0.65) * 1000
                  for x in range(xlim)]
                 for y in range(ylim)]

        hmin = hmax = 0
        for y in range(ylim):
            for x in range(xlim):
                yd = len(data)*(self.selection[1][0]/ylim+y/10.0/ylim)
                xd = len(data[0])*(self.selection[0][0]/xlim+x/10.0/xlim)

                h = self._height(data, yd, xd)
                n = noise[y][x]
                if h < 0:
                    h += -n if n > 0 else n
                else:
                    h += n if n > 0 else -n
                value[y][x] = h
        return value
Exemplo n.º 27
0
    def perlin_array(self) -> list:
        """
            The perlin_array method generates the actual perlin noise map.
            The noise map itself is array which will have to be converted to a PIL image later.

        Returns:
            list: The noise map is returend as a list represnting the values,
            this can be converted easyly to an image.
        """
        if not self.seed:

            seed = np.random.randint(0, 100)

        arr = np.zeros(self.shape)
        for i in range(self.shape[0]):
            for j in range(self.shape[1]):
                arr[i][j] = noise.pnoise2(i / self.scale,
                                          j / self.scale,
                                          octaves=self.octaves,
                                          persistence=self.persistence,
                                          lacunarity=self.lacunarity,
                                          repeatx=1024,
                                          repeaty=1024,
                                          base=seed)
        max_arr = np.max(arr)
        min_arr = np.min(arr)
        norm_me = lambda x: (x - min_arr) / (max_arr - min_arr)
        norm_me = np.vectorize(norm_me)
        arr = norm_me(arr)
        return arr
Exemplo n.º 28
0
def mapGenerator2(width, height):
    grid = []
    for i in range(width):
        fila = []
        for j in range(height):
            x = (i * 1.0) / width
            y = (j * 1.0) / height

            seed = random.random()
            seed2 = random.randint(10, 250)

            n = noise.pnoise2(seed2 * x + 10, 10 * y, 1, 0.5, 0.2, 1024, 1024, 0) * 1.5 + 0.6

            # if n == 0.0:
            #     fila.append('/')

            if n < 0.15:
                fila.append("~")
            elif n >= 0.15 and n < 0.6:
                fila.append(".")
            elif n >= 0.75:
                fila.append("#")

        grid.append(fila)
    return grid
Exemplo n.º 29
0
 def test_perlin_2d_range(self):
     from noise import pnoise2
     for i in range(-10000, 10000):
         x = i * 0.49
         y = -i * 0.67
         n = pnoise2(x, y)
         self.assertTrue(-1.0 <= n <= 1.0, (x, y, n))
Exemplo n.º 30
0
    def generate_input_data(self, land_percentage: float) -> np.array:
        if not self.validate_percentage(land_percentage):
            raise ValueError("The land_percentage argument is supposed to be a float number in range [0, 1]!")

        # creating perlin's noise array
        world = np.zeros(self._size)
        for i in range(self._size[0]):
            for j in range(self._size[1]):
                world[i][j] = noise.pnoise2(i / self._scale,
                                            j / self._scale,
                                            octaves=self._octaves,
                                            persistence=self._persistence,
                                            lacunarity=self._lacunarity,
                                            repeatx=self._size[0],
                                            repeaty=self._size[1],
                                            base=0)
        # standardizing created array
        world -= np.min(world)
        world *= 255
        world = world.astype(np.uint8)

        # adjusting land percentage
        world_height = np.sort(world.reshape(1, -1))
        threshold = world_height[0, int((1 - land_percentage) * world_height.size)]
        world[np.where(world < threshold)] = 0
        indexes = world.nonzero()
        min_nonzero = world[indexes].min()
        max_nonzero = world[indexes].max()
        factor = max_nonzero / (max_nonzero - min_nonzero - 1)
        world[indexes] = (world[indexes] - min_nonzero) * factor + 1
        # print(world.min(), world.max(), world[indexes].min())
        return world
Exemplo n.º 31
0
    def generate(self):
        """Generates islands as an n * n grid of pixels in a binary image representing land and water.

        Loops through every pixel in a grid while using Perlin noise (https://en.wikipedia.org/wiki/Perlin_noise) to
        calculate a value between -1 and 1 based on the seed and weathering. If the value plus sea level is greater than
        0.01 the pixel is land and if is less than 0.01 the pixel is water.
        """
        self.counted = False
        self.pixels = self.map.load()
        # Cache the calculations on constants to save calculations in the loops
        half_n = self.n / 2
        scale = self.n * 0.15
        max_distance = self.n * 0.60
        # Could be sped up with OpenCL https://documen.tician.de/pyopencl/algorithm.html#module-pyopencl.elementwise
        for x in range(self.n):
            for y in range(self.n):
                pixel_value = noise.pnoise2(
                    self.seed + x / scale,
                    self.seed + y / scale,
                    self.weathering,
                    self.PERSISTENCE,
                    self.LACUNARITY,
                    self.n,
                    self.n,
                    self.BASE
                )
                distance_to_center = math.sqrt(
                    math.pow((x - half_n), 2) +
                    math.pow((y - half_n), 2)
                )
                pixel_value -= math.pow(distance_to_center / max_distance, 4)
                self.pixels[x, y] = pixel_value > 0.01 + self.sea_level
Exemplo n.º 32
0
def perlin_mask(shape, scale, octaves, persistence, lacunarity, base):
    mask = np.zeros(shape)
    for i in range(shape[0]):
        for j in range(shape[1]):
            # Value is normalized between -1 and 1
            pixel = noise.pnoise2(i / scale,
                                  j / scale,
                                  octaves=octaves,
                                  persistence=persistence,
                                  lacunarity=lacunarity,
                                  repeatx=shape[0],
                                  repeaty=shape[1],
                                  base=base)
            # Denormalize between 0 and 255
            mask[i][j] = ((pixel + 1) / 2.0 * 255.0)
    # Make whites whiter and black blacker
    minValue = np.amin(mask)
    mask = mask - minValue
    maxValue = np.amax(mask)
    mask = (mask / maxValue) * 255.0
    # Cast array to uint8
    mask = mask.astype(np.uint8)
    # Converting to RGB
    mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2RGB)
    return mask
Exemplo n.º 33
0
    def generate(self, x, z):
        xOffset = random.randint(-4096, 4096)
        zOffset = random.randint(-4096, 4096)
        self.tiles = []
        for xLoop in range(x):
            for zLoop in range(z):
                y = noise.pnoise2(xLoop * .02 + xOffset,
                                  zLoop * .02 + zOffset,
                                  octaves=NOISE_OCTAVES)
                color = SEA_COLOR

                if y > -0.1:
                    color = SHORE_COLOR
                if y > 0.05:
                    color = SAND_COLOR
                if y > 0.1:
                    color = GRASS_COLOR
                if y > 0.2:
                    color = HILL_COLOR
                if y > 0.3:
                    color = MOUNTAIN_COLOR
                if y > 0.4:
                    color = SNOW_COLOR

                tileObject = Tile(xLoop, y, zLoop, color)
                self.tiles.append(tileObject)
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
Exemplo n.º 35
0
 def perlin(self, base=None):
     if base is None:
         base = np.random.randint(1000)
     return np.array([
         noise.pnoise2(x, y, lacunarity=1.7, octaves=3, base=base)
         for x, y in self.vxs
     ])
Exemplo n.º 36
0
    def __add_trees(self):
        vmapWidth = int(self.width / squ_width)
        vmapHeight = int(self.height / squ_width)

        noiseYOff = random.randint(0, 100000)
        noiseXOff = random.randint(0, 100000)

        for x in range(0, vmapWidth):
            for y in range(0, vmapHeight):
                value = noise.pnoise2(float((x + noiseXOff) / vmapWidth),
                                      float((y + noiseYOff) / vmapHeight), 4)
                value = math.sin(value) + 0.5
                if value < 0.0: value = 0.0
                if value > 1.0: value = 1.0

                if value > 0.4 and value < 0.7 and (self.__get_land_type(
                    (x, y)) == "grassland" or self.__get_land_type(
                        (x, y)) == "mountain_low") and random.randint(
                            0, 10000) > 9996:
                    entity = entities.Tree((x * squ_width, y * squ_width),
                                           random.randint(10, 50))
                    entities.add_entity(entity)  #this works janky
                    self.drawEntity(entity)
                elif value >= 0.7 and self.__get_land_type(
                    (x, y)) == "grassland" and random.randint(0, 10000) > 9990:
                    entity = entities.Tree((x * squ_width, y * squ_width),
                                           random.randint(20, 50))
                    entities.add_entity(entity)  #this works janky
                    self.drawEntity(entity)
Exemplo n.º 37
0
def perlin_array(shape: tuple = (200, 200),
                 scale: int = 100,
                 octaves: int = 6,
                 persistence: float = 0.5,
                 lacunarity: float = 2.0,
                 seed: int = None) -> list:

    if not seed:

        seed = np.random.randint(0, 100)
        print("seed was {}".format(seed))

    arr = np.zeros(shape)
    for i in range(shape[0]):
        for j in range(shape[1]):
            arr[i][j] = noise.pnoise2(i / scale,
                                      j / scale,
                                      octaves=octaves,
                                      persistence=persistence,
                                      lacunarity=lacunarity,
                                      repeatx=1024,
                                      repeaty=1024,
                                      base=seed)
    max_arr = np.max(arr)
    min_arr = np.min(arr)
    norm_me = lambda x: (x - min_arr) / (max_arr - min_arr)
    norm_me = np.vectorize(norm_me)
    arr = norm_me(arr)
    return arr
Exemplo n.º 38
0
    def gera_mapa(self, shape=(RAZAO[1], RAZAO[0]),  # gera um array de ruido 2d
                  scale=100, octaves=6,
                  persistence=0.5,
                  lacunarity=2.0,
                  seed=None):

        if not seed:
            seed = np.random.randint(0, 100)

        arr = np.zeros(shape)
        for i in range(shape[0]):
            for j in range(shape[1]):
                arr[i][j] = pnoise2(i / scale,
                                    j / scale,
                                    octaves=octaves,
                                    persistence=persistence,
                                    lacunarity=lacunarity,
                                    repeatx=1024,
                                    repeaty=1024,
                                    base=seed)
        max_arr = np.max(arr)
        min_arr = np.min(arr)
        norm_me = lambda x: (x - min_arr) / (max_arr - min_arr)
        norm_me = np.vectorize(norm_me)
        arr = norm_me(arr)
        return arr
Exemplo n.º 39
0
 def blot(self, blot_sizeX, blot_sizeY):
     centerX = blot_sizeX // 2
     centerY = blot_sizeY // 2
     middenKwadraat = min(centerX**2, centerY**2)
     canvas = np.zeros((blot_sizeX, blot_sizeY))
     for x in range(0, blot_sizeX):
         for y in range(0, blot_sizeY):
             noiseWaarde = noise.pnoise2(x / self.scaleX,
                                         y / self.scaleY,
                                         octaves=self.octaves,
                                         persistence=self.persistence,
                                         lacunarity=self.lacunarity,
                                         repeatx=blot_sizeX / self.scaleX,
                                         repeaty=blot_sizeY / self.scaleY,
                                         base=self.base)
             canvas[x, y] = noiseWaarde
     canvas = (canvas - np.amin(canvas)) / (np.amax(canvas) -
                                            np.amin(canvas))
     for x in range(0, blot_sizeX):
         for y in range(0, blot_sizeY):
             afstand_kwadraad = ((x - centerX)**2 + (y - centerY)**2)
             vermenigvuldinging = max(
                 0, 1 - (afstand_kwadraad / (middenKwadraat)))
             canvas[x, y] = canvas[x, y] * vermenigvuldinging
     # in plaats van opnieuw normaliseren passen we de grenswaarde aan die uitgaat
     # van range 0-1
     canvas = (canvas - np.amin(canvas)) / (np.amax(canvas) -
                                            np.amin(canvas))
     canvas = np.where(canvas > self.grenswaarde, 1, 0)
     self.base = self.base + np.random.randint(1, 2)
     return canvas
Exemplo n.º 40
0
    def ___insertNoiseTile(self, x, y, textureTab) -> None:
        """Method inserting into one tile (with the size of STEP_GENERATIONxSTEP_GENERATION) a
        perlin noise value and then a color"""

        textureTab[y][x] = noise.pnoise2(
            ((x * self.stepGeneration) - self.posOffset[0]) / self.scale,
            ((y * self.stepGeneration) - self.posOffset[1]) / self.scale,
            octaves=self.octaves,
            persistence=self.persistence,
            lacunarity=self.lacunarity,
            repeatx=self.Game.resolution,
            repeaty=self.Game.resolution,
            base=self.mapSeed,
        )

        # Inserting color

        # Taking care of the round map if enabled in the config object
        if self.circularMap and not self.CIRCULAR_MASK[y][x]:
            textureTab[y][x] = {"color": WATER}
        else:
            if textureTab[y][x] < -0.05:
                textureTab[y][x] = {"color": WATER}
            elif textureTab[y][x] < 0:
                textureTab[y][x] = {"color": BEACH}
            elif textureTab[y][x] < 0.2:
                textureTab[y][x] = {"color": GREEN}
            elif textureTab[y][x] < 0.35:
                textureTab[y][x] = {"color": MOUNTAIN}
            elif textureTab[y][x]:
                textureTab[y][x] = {"color": SNOW}

        # handling progress bar
        if self.id == 1 and self.showLoading:
            self.progressBar.update(1)
Exemplo n.º 41
0
def grille_perlin(n, p, seuil):
    depthmax = 5  #fct de n, ici si n = 200 les profondeurs varient
    g = np.zeros([n, n])
    depth = np.zeros([n, n])
    scale = n * 1 / 2  #zoom, fct croissante, 1/12 et 1/5 interessant (1/5 pour continent)
    b = int(100 * rd.random())
    for i in range(n):
        for j in range(n):
            pernoise = noise.pnoise2(
                i / scale,
                j / scale,
                octaves=10,
                persistence=
                .35,  #.5 de base, taille des blocs (fct croissante), .35 ?
                lacunarity=2,  #2 de base, nb de petits trous(plus si plus grand)
                repeatx=n,
                repeaty=n,
                base=b)
            g[i][j] = (.05 + pernoise - (1 - p) / 5 < 0) * seuil  #à bidouiller
            depth[i][j] = (.05 + pernoise - (1 - p) / 5 > 0) * pernoise
    depth = 1 - np.exp(-5 * depth)
    min = np.amin(depth)
    speed = np.zeros([n, n])
    for i in range(n):
        for j in range(n):
            if depth[i, j] != 0:
                speed[i, j] = np.sqrt((depth[i, j] - min) * depthmax * 9.81)
    return (g, speed)
Exemplo n.º 42
0
def scalar_field(size=1000, rng=None):
    """Produces a square scalar field

    :param size: Dimensions of field
    :param rng: Random number generator for the field
    :returns: A scalar field of noise, as a 2d array
    """
    if rng is None:
        rng = np.random.default_rng(seed=0)

    scale = size
    octaves = 4
    persistence = 0.5
    lacunarity = 2
    offset_x, offset_y = (rng.random(2) - 0.5) * 2e5

    field = np.zeros((size, size))
    for i in range(size):
        for j in range(size):
            field[i][j] = noise.pnoise2(
                offset_x + i / scale,
                offset_y + j / scale,
                octaves=octaves,
                persistence=persistence,
                lacunarity=lacunarity,
            )
    field /= np.max(np.abs(field))
    return field
Exemplo n.º 43
0
    def makebackground(self, surface):
        surface.fill((0,0,0))
        
        template = Surface(2*(min(self.zoom.width, self.zoom.height),))
        template.fill((0,0,0,255))
        width,height = template.get_size()

        ylim = surface.get_height()/height
        xlim = surface.get_width()/width

        data = self._data
        noise = [[pnoise2(self._selected[1][0]+x,
                          self._selected[0][0]+y,
                          4, 0.85) * 50
                  for x in range(xlim)]
                 for y in range(ylim)]

        hmin = hmax = 0
        for y in range(ylim):
            for x in range(xlim):
                yd = len(data)*float(y)/ylim
                xd = len(data[0])*float(x)/xlim

                h = self._height(data, yd, xd)
                n = noise[y][x]
                if h < 0:
                    h += -n if n > 0 else n
                else:
                    h += n if n > 0 else -n
                if h < hmin:
                    hmin = h
                if h > hmax:
                    hmax = h

        self.rects = []
        for y in range(ylim):
            for x in range(xlim):
                block = template.copy()
                yd = len(data)*float(y)/ylim
                xd = len(data[0])*float(x)/xlim

                h = self._height(data, yd, xd)
                n = noise[y][x]
                if h < 0:
                    h += -n if n > 0 else n
                else:
                    h += n if n > 0 else -n
                if h < 0:
                    color = 0, 0, int(255 * (1 - h/hmin))
                else:
                    color = 0, int(255 * h/hmax), 0
                block.fill(color)
                if self.selection:
                    if self.selection[0][0] <= yd <= self.selection[0][1]:
                        if self.selection[1][0] <= xd <= self.selection[1][1]:
                            block.fill((255,0,0,32),
                                       special_flags = BLEND_ADD)
                rect = Rect(x*width, y*height, width, height)
                surface.blit(block, rect.topleft)
                self.rects.append((rect, (yd, xd)))
Exemplo n.º 44
0
def perlin_array(shape,
                 scale=100,
                 octaves=6,
                 persistence=0.5,
                 lacunarity=2.0,
                 seed=None):
    if not seed:
        seed = random.randint(0, 100)
        arr = [[0 for a in range(shape[0])] for b in range(shape[1])]
    for i in range(shape[0]):
        for j in range(shape[1]):
            arr[i][j] = pnoise2(i / scale,
                                j / scale,
                                octaves=octaves,
                                persistence=persistence,
                                lacunarity=lacunarity,
                                repeatx=1024,
                                repeaty=1024,
                                base=seed)
    max_arr = max(map(max, arr))
    min_arr = min(map(min, arr))
    for i in range(shape[0]):
        for j in range(shape[1]):
            arr[i][j] = (arr[i][j] - min_arr) / (max_arr - min_arr)
    return arr
Exemplo n.º 45
0
def make_last_point(last_point, width, height, factor):
    """
    Generates a new last point in order to help with the route generation.
    It uses the following parameters:

    - last_point (the former last point)
    - width (the width of the window)
    - height (the height of the window)
    - factor (a user-chosen factor)
    """
    newx = \
	pnoise2(last_point.get_x() / width, last_point.get_y() / height)
    newy = \
	pnoise2(last_point.get_y() / height, last_point.get_x() / width)
    newx = CLAMP(last_point.get_x() + newx * factor, 0, width)
    newy = CLAMP(last_point.get_y() + newy * factor, 0, height)
    return Point(newx, newy)
 def applyPertubation(self, frequency=32.0, displacement=32.0):
     width = self.width*self.cPatchSize
     height = self.height*self.cPatchSize
     frequency = float(frequency) / float(width)
     
     tmp = numpy.zeros([width*self.cPatchSize+1,height*self.cPatchSize+1], dtype=float)
     
     for i in range(width):
         for j in range(height):
             u = i + int(pnoise2(j * frequency, i * frequency, 1) * displacement)
             v = j + int(pnoise2(j * frequency, i * frequency, 2) * displacement)
             if u < 0: u = 0
             if v < 0: v = 0
             if u >= width: u = width - 1
             if v >= height: v = height - 1
             tmp[i][j] = self.d_array[u][v]
     self.d_array = tmp
Exemplo n.º 47
0
 def test_perlin_2d_octaves_range(self):
     from noise import pnoise2
     for i in range(-1000, 1000):
         for o in range(10):
             x = -i * 0.49
             y = i * 0.67
             n = pnoise2(x, y, octaves=o + 1)
             self.assertTrue(-1.0 <= n <= 1.0, (x, n))
Exemplo n.º 48
0
 def glyph(cls, at):
     row, col = at.position
     col_prime = int(
         round(
             abs(
                 (time() * 0.1 + (col * 0.1) + pnoise2(row*0.1, col*0.1)) % 1
                 ) * (len(cls.glyphs) - 1)
             )
         )
     return cls.glyphs[col_prime]
Exemplo n.º 49
0
def draw_doodle_dah(context, x, y, vx, vy, r):
	v = (1 + noise.pnoise2(vx, vy, 1))/2.0
	a = 0.2+v*0.6
	context.set_source_rgba(*color_of(0xff0099, a=a))
	context.arc(x, y, r, 0, 2*math.pi)
	context.fill()

	context.set_source_rgb(*color_of(0x333333))
	context.arc(x, y, r, 0, 2*math.pi)
	context.stroke()
Exemplo n.º 50
0
def draw_empty_spot(context, x, y, vx, vy, r):
	v = (1 + noise.pnoise2(vx, vy, 1))/2.0
	a = v*0.3
	context.set_source_rgba(*color_of(0x333333, a=0.1))
	context.arc(x, y, r, 0, 2*math.pi)
	context.fill()

	context.set_line_width(1.0)
	context.set_source_rgba(*color_of(0x333333, a=0.3))
	context.arc(x, y, r, 0, 2*math.pi)
	context.stroke()
Exemplo n.º 51
0
def create_bands_texture(bands=14.0, stretch=2.0, turbulence=8.0, 
	color1=(1.0, 0.8, 0.6), color2=(0.1, -0.3, -0.4)):
	coords = range(TEXTURE_SIZE)
	texel = (ctypes.c_ubyte * (3 * TEXTURE_SIZE**2))()
	for y in coords:
		for x in coords:
			p = pnoise2(x * 15.0 / TEXTURE_SIZE, y * 15.0 / TEXTURE_SIZE, octaves=5, 
				repeatx=15.0, repeaty=15.0) * math.pi * 2.0
			px = (x + math.sin(p) * turbulence)
			py = (y + math.cos(p) * turbulence)
			v = pnoise2(
				px / stretch / TEXTURE_SIZE, py * bands / TEXTURE_SIZE, octaves=4,
				repeaty=bands, repeatx=1.0/stretch)
			r, g, b = blend((v + 1.0) / 2.0, color1, color2, 1.75 + (p**5)*0.003)
			texel[(x + (y * TEXTURE_SIZE))*3] = max(min(int(r * 255.0), 255), 0)
			texel[(x + (y * TEXTURE_SIZE))*3 + 1] = max(min(int(g * 255.0), 255), 0)
			texel[(x + (y * TEXTURE_SIZE))*3 + 2] = max(min(int(b * 255.0), 255), 0)
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, TEXTURE_SIZE, TEXTURE_SIZE, 0, 
		GL_RGB, GL_UNSIGNED_BYTE, ctypes.byref(texel))
	return texel
Exemplo n.º 52
0
def evaluate_noise(eval_info):
    """
    :param eval_info: Parameters describing the sample currently being evaluated.
    :return: The evaluated value at the supplied sample location.
    """
    octaves = eval_info.evaluate('octaves', eval_info.x, eval_info.y)
    frequency = eval_info.evaluate('frequency', eval_info.x, eval_info.y)
    frequency_x = frequency / eval_info.image_size[0] * octaves
    frequency_y = frequency / eval_info.image_size[0] * octaves
    pnoise = noise.pnoise2(eval_info.x / frequency_x, eval_info.y / frequency_y, octaves=octaves)
    pnoise = 0.5 + pnoise / 2.0
    return Color(pnoise, pnoise, pnoise, pnoise)
Exemplo n.º 53
0
def evaluate_turbulence(eval_info):
    """
    :param eval_info: EvalInfo object containing the sample being evaluated.
    :return: The evaluated value at the supplied sample location.
    """
    octaves = eval_info.evaluate('octaves', eval_info.x, eval_info.y)
    frequency = eval_info.evaluate('frequency', eval_info.x, eval_info.y)
    frequency_x = frequency / eval_info.image_size[0] * octaves
    frequency_y = frequency / eval_info.image_size[0] * octaves
    pnoise = noise.pnoise2(eval_info.x / frequency_x, eval_info.y / frequency_y, octaves=octaves)
    pnoise = math.fabs(pnoise)
    return Color(pnoise, pnoise, pnoise, pnoise)
Exemplo n.º 54
0
Arquivo: gol.py Projeto: Pranz/gsgpy
def initialize(self):
	self.con   = libtcod.console_new(main.SCREEN_WIDTH, main.SCREEN_HEIGHT)
	random.seed()
	noise_seed = random.randint(-10000,10000)
	scale      = 0.02
	self.noise = lambda x,y: noise.pnoise2(scale * (x + noise_seed), scale * (y + noise_seed),15,0.5,3)
	self.world = [[self.noise(x,y) > -0.1 for y in range(0,GOL_HEIGHT+2)] for x in range(0,GOL_WIDTH+2)]
	for x in range(0,GOL_WIDTH+2):
		self.world[x][0]            = False
		self.world[x][GOL_HEIGHT+1] = False
	for y in range(0,GOL_HEIGHT+2):
		self.world[0][y]            = False
		self.world[GOL_WIDTH+1][y]  = False
Exemplo n.º 55
0
 def glyph(cls, at):
     try:
         return cls.glyph_cache[at.position]
     except KeyError:
         row, col = at.position
         col_prime = int(
             round(
                 abs(
                     (pnoise2(row*0.1, col*0.1)) % 1
                     ) * (len(cls.glyphs) - 1)
                 )
             )
         g = cls.glyph_cache[at.position] = cls.glyphs[col_prime]
         return g
 def applyPerlinNoise(self, octaves=1, frequency=1, persistence=0.5, amplitude=100):
     """ TerrainGenerator.applyPerlinNoise(...)
         - applyPerlinNoise() method generates a heightmap with perlin noise and applies it on top of
         the current heightmap. If used to generate the initial heightmap, TerrainGenerator.initialize()
         must be called first.
     """
     width = self.width*self.cPatchSize
     height = self.height*self.cPatchSize
     frequency = float(frequency) / float(width)
     
     for y in range(height):
         for x in range(width):
             noise = pnoise2(x * frequency, y * frequency, octaves, persistence)
             self.d_array[x][y] += noise*amplitude
Exemplo n.º 57
0
    def generate(self, octaves, persistance, lacunarity):
        base_x = random.randint(0, 100)
        base_y = random.randint(0, 100)

        for x in range(self.screen_width):
            for y in range(self.screen_height):
                xoff = (x / self.screen_width * 7) + base_x
                yoff = (y / self.screen_height * 7) + base_y
                color = int(abs(noise.pnoise2(
                    xoff, yoff,
                    octaves,
                    persistance,
                    lacunarity) * 3333))
                self.image.set_at(
                    (x, y),
                    (color % 255, color % 255, color % 255))
Exemplo n.º 58
0
 def drawLand(self):
   if self.seed == None:
     seed = random.randint(1, 1000)
     self.seed = seed
   else:
     seed = self.seed
   noise = []
   for tile in self.getTiles():
     relX = float(tile.col / self.width)
     relY = float(tile.row / self.height)
     tile.noise = pnoise2(relX, relY, 13, 0.6, base = seed)
     noise.append(tile.noise)
   min_noise = min(noise)
   max_noise = max(noise)
   noise_range = float(max_noise - min_noise)
   for tile in self.getTiles():
     tile.elevation = (tile.noise + abs(min_noise)) / noise_range
Exemplo n.º 59
0
 def add_mountains(self):
     """
     instead of the add_blocks function which was to produce
     line shaped walls for blocking path finding agents, this
     function creates more natural looking blocking areas like
     mountains
     """
     from noise import pnoise2
     import random
     random.seed()
     octaves = (random.random() * 0.5) + 0.5
     freq = 17.0 * octaves  # 
     for y in range(self.grd.grid_height - 1):
         for x in range(self.grd.grid_width - 1):
             pixel = self.grd.get_tile(y,x)
             if pixel == 'X':     # denoise blocks of mountains
                 n = int(pnoise2(x/freq, y / freq, 1)*11+5)
                 if n < 1:
                     self.grd.set_tile(y, x, '#')
Exemplo n.º 60
0
def perlinNoise(wWidth, wHeight):
    """
    wrapper for 'noise' packages pnoise2 function
    """
    # create the map
    landscape = np.empty((wWidth, wHeight), dtype=np.float)
    landscape.fill(-1)
    

    max_height = 0.0
    denom = 16.0
    # generate the noise
    for x in range(len(landscape)):
        for y in range(len(landscape[0])):
            height = noise.pnoise2(x / denom, y / denom) * 10 + 10
            landscape[x][y] = height
            if height > max_height:
                max_height = height
    return (landscape, max_height)