def __init__(self, freq=8, width=32):
		"""Generate the 3D noise texture.

		freq -- frequency of generated noise over the width of the 
		texture.

		width -- Width of the texture in texels. The texture is cubic,
		thus all sides are the same width. Must be a power of two.
		Using a larger width can reduce artifacts caused by linear
		interpolation of the noise texture, at the cost of video
		memory, and possibly slower texture access.
		"""
		self.freq = freq
		self.width = width
		scale = float(freq) / width
		width2 = width**2
		texel = (ctypes.c_ushort * (2 * width**3))()
		for z in range(width):
			for y in range(width):
				for x in range(width):
					texel[(x + (y * width) + (z * width2)) * 2] = int((pnoise3(
						x * scale, y * scale, z * scale, 
						repeatx=freq, repeaty=freq, repeatz=freq) + 1.0) * 32767)
					texel[(x + (y * width) + (z * width2)) * 2 + 1] = int((pnoise3(
						x * scale, y * scale, z * scale, 
						repeatx=freq, repeaty=freq, repeatz=freq, base=freq + 1) + 1.0) * 32767)
		self.data = texel
示例#2
0
文件: sample.py 项目: dribnet/discgen
def anchors_noise_offsets(anchors, offsets, rows, cols, spacing, z_step, x_indices_str, y_indices_str, x_minscale, y_minscale, x_maxscale, y_maxscale):
    from noise import pnoise3
    from plat.interpolate import lerp

    only_anchor = None
    if len(anchors) == 1:
        only_anchor = anchors[0]

    dim = len(anchors[0])
    x_offset = offset_from_string(x_indices_str, offsets, dim)
    y_offset = offset_from_string(y_indices_str, offsets, dim)

    num_row_anchors = (rows + spacing - 1) / spacing
    num_col_anchors = (cols + spacing - 1) / spacing

    newanchors = []
    cur_anchor_index = 0
    for j in range(num_row_anchors):
        y_frac = float(j) / num_row_anchors
        for i in range(num_col_anchors):
            if only_anchor is None:
                cur_anchor = anchors[cur_anchor_index]
                cur_anchor_index += 1
            else:
                cur_anchor = only_anchor
            x_frac = float(i) / num_col_anchors
            n1 = 0.5 * (1.0 + pnoise3(x_frac, y_frac, z_step, octaves=4, repeatz=2))
            n2 = 0.5 * (1.0 + pnoise3(100+x_frac, 100+y_frac, z_step, octaves=4, repeatz=2))
            x_scale = lerp(n1, x_minscale, x_maxscale)
            y_scale = lerp(n2, y_minscale, y_maxscale)
            # print("{}, {} produced {} -> {}, {} = {}".format(i,j,n1,x_minscale, x_maxscale,x_scale))
            newanchors.append(cur_anchor + x_scale * x_offset + y_scale * y_offset)
    return np.array(newanchors)
示例#3
0
def generate_wind(nodes, cells, prevailing_wind_bearing=270, average_wind_speed=7.0):
    import noise
    import math
    import numpy as np
    for n in nodes:
        wind_bearing = (int(round(180.0 * noise.pnoise3(n.x, n.y, n.z))) + 360) % 360  # in degrees
        wind_strength = (8 * noise.pnoise3(n.x, n.y, n.z)) + 16.0  # kmph

        # move the generated random wind bearing towards the prevailing wind a little
        wind_vector = np.add(np.array([wind_strength * math.cos(math.radians(90 - wind_bearing)),
                                       wind_strength * math.cos(math.radians(wind_bearing))]),
                             np.array([average_wind_speed * math.cos(math.radians(90 - prevailing_wind_bearing)),
                                       average_wind_speed * math.cos(math.radians(prevailing_wind_bearing))]))

        wind_strength = math.sqrt(math.pow(wind_vector[0], 2) + math.pow(wind_vector[1], 2)) #  sqrt((x2-x1)^2 + (y2-y1)^2) = vector magnitude
        wind_bearing = int(round(math.degrees(math.atan(wind_vector[1]/wind_vector[0])))) # tan-1((y2-y1)/x2-x1)) = vector bearing

        n.set_feature(['wind', 'bearing'], wind_bearing)
        n.set_feature(['wind', 'strength'], wind_strength)
        n.set_feature(['wind', 'vector', 'x'], wind_vector[0])
        n.set_feature(['wind', 'vector', 'y'], wind_vector[1])
        n.wind = Wind(wind_bearing, wind_strength, wind_vector)
    for c in cells:
        wind_vector = np.sum(np.array([n.wind.vector for n in c.nodes]), axis=0)
        wind_strength = math.sqrt(math.pow(wind_vector[0], 2) + math.pow(wind_vector[1], 2))  #  sqrt((x2-x1)^2 + (y2-y1)^2) = vector magnitude
        wind_bearing = int(round(math.degrees(math.atan(wind_vector[1]/wind_vector[0]))))  # tan-1((y2-y1)/x2-x1)) = vector bearing

        c.wind = Wind(wind_bearing, wind_strength, wind_vector)
示例#4
0
def make_terrain():
    terrain=[[1-int(abs(noise.pnoise3(i*0.4+0.5,j*0.1+0.5,0.5))*2)
              for i in range(500)] 
             for j in range(5000)]

    for x in range(5000):
        for y in range(50):
            terrain[x][y]=3
        terrain[x][50]=2

    for x in range(100):
        for y in range(500):
            terrain[-x][y]=4
            terrain[x][y]=4

    for x in range(5000):
        for y in range(50,100):
            ri=random.random()
            if terrain[x][y]==0 and terrain[x][y+1]==1:
                if ri<0.05:
                    terrain[x][y]=9
            if terrain[x][y]==0 and terrain[x][y+1]==1:
                if ri<0.2:
                    terrain[x][y]=6
            if terrain[x][y]==1:
                if ri<0.007:
                    terrain[x][y]=8
        for y in range(110,200):
            ri=random.random()
            if terrain[x][y]==1:
                if ri<0.002:
                    terrain[x][y]=10
    return terrain
示例#5
0
def main2():
    logging.info("(this might take a while...)")
    samples = 50
    t = time.time()
    # from stl import mesh
    diameter = 10
    radius = diameter / 2
    half = radius / 2

    # X, Y, Z = np.mgrid[:diameter, :diameter, :diameter]
    # print "X"
    # print X
    # print "Y"
    # print Y
    # print "Z"
    # print Z
    # u = (X-50)**2 + (Y-50)**2 + (Z-50)**2 - 25**2 + pnoise3(X,Y,Z,octaves=3)*3
    # u = (X-radius)**2 + (Y-radius)**2 + (Z-radius)**2 - half**2 #+ pnoise3(X,Y,Z,octaves=3)*3
    # u = [[[(X)**2 + (Y)**2 + (Z)**2 - 25**2 + pnoise3(X,Y,Z,octaves=3)*3 for X in range(-100,100)] for Y in range(-100,100)] for Z in range(-100,100)]
    u = np.ndarray((200, 200, 200))
    for X in range(-100, 100):
        for Y in range(-100, 100):
            for Z in range(-100, 100):
                # print v
                u[X + 100, Y + 100, Z + 100] = ((X) ** 2 + (Y) ** 2 + (Z) ** 2) + pnoise3(X * 0.05, Y * 0.05, Z * 0.05,
                                                                                          octaves=3) * 30
    # print u
    # Extract the 0-isosurface

    logging.debug("u")
    logging.debug(u)
    vertices, triangles = mcubes.marching_cubes(u, 60)
    logging.info("mesh completed in %f seconds" % (time.time() - t))

    meshexport.export(vertices, triangles)
示例#6
0
def create_3d_texture(width, scale):
	"""Create a grayscale 3d texture map with the specified 
	pixel width on each side and load it into the current texture
	unit. The luminace of each texel is derived using the input 
	function as:

	v = func(x * scale, y * scale, z * scale)

	where x, y, z = 0 in the center texel of the texture.
	func(x, y, z) is assumed to always return a value in the 
	range [-1, 1].
	"""
	coords = range(width)
	texel = (ctypes.c_byte * width**3)()
	half = 0 #width * scale / 2.0 

	for z in coords:
		for y in coords:
			for x in coords:
				v = pnoise3(x * scale - half, y * scale - half, z * scale - half, 4)
				texel[x + (y * width) + (z * width**2)] = int(v * 127.0)
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
	glTexImage3D(GL_TEXTURE_3D, 0, GL_LUMINANCE, width, width, width, 0, 
		GL_LUMINANCE, GL_BYTE, ctypes.byref(texel))
	return texel
示例#7
0
    def render(self, model, params, frame):
        # Noise spatial scale, in number of noise datapoints at the fundamental frequency
        # visible along the length of the sculpture. Larger numbers "zoom out".
        # For perlin noise, we have multiple octaves of detail, so staying zoomed in lets
        # us have a lot of detail from the higher octaves while still having gradual overall
        # changes from the lower-frequency noise.

        s = self.zoom # defaults to 0.6

        # Time-varying vertical offset. "Flow" upwards, slowly. To keep the parameters to
        # pnoise3() in a reasonable range where conversion to single-precision float within
        # the module won't be a problem, we need to wrap the coordinates at the point where
        # the noise function seamlessly tiles. By default, this is at 1024 units in the
        # coordinate space used by pnoise3().

        z0 = math.fmod(params.time * self.time_const, 1024.0)

        for i, rgb in enumerate(frame):
            # Normalized XYZ in the range [0,1]
            x, y, z = model.edgeCenters[i]

            # Perlin noise with some brightness scaling
            level = 1.2 * (0.35 + noise.pnoise3(x*s, y*s, z*s + z0, octaves=3))

            for w,v in enumerate(self.color):
                rgb[w] += v * level
示例#8
0
 def test_perlin_3d_range(self):
     from noise import pnoise3
     for i in range(-10000, 10000):
         x = -i * 0.49
         y = i * 0.67
         z = -i * 0.727
         n = pnoise3(x, y, z)
         self.assertTrue(-1.0 <= n <= 1.0, (x, y, z, n))
def create_noise(width=240, scale=1.0/48):
	coords = range(width)
	v = np.zeros((width, width, width))
	for z in coords:
		for y in coords:
			for x in coords:
				v[x][y][z] = (pnoise3(x * scale, y * scale , z * scale, octaves=8, persistence=.25) + 1.0)/2.0
	return v
示例#10
0
 def test_perlin_3d_octaves_range(self):
     from noise import pnoise3
     for i in range(-1000, 1000):
         x = i * 0.22
         y = -i * 0.77
         z = -i * 0.17
         for o in range(10):
             n = pnoise3(x, y, z, octaves=o + 1)
             self.assertTrue(-1.0 <= n <= 1.0, (x, y, z, n))
    def step(self, amt):
        octaves = 1
        freq = 16.0
        data = []
        for y in range(self.height):
            for x in range(self.width):
                v = int(pnoise3(x / self._freq, y / self._freq, self._step / self._freq, octaves=self._octaves) * 127.0 + 128.0)
                c = colors.hue2rgb_rainbow(v)
                self._led.set(x,y, c)

        self._step += amt
	def create_noise(self):
		matrix_size = self.matrix_size
		scale = self.noise_scale
		coords = range(matrix_size)

		v = np.zeros((matrix_size, matrix_size, matrix_size))
		for z in coords:
			for y in coords:
				for x in coords:
					v[x][y][z] = (pnoise3(x * scale, y * scale , z * scale, octaves=8, persistence=.25) + 1.0)/2.0
		return v
示例#13
0
def generatePerlinNoise(width,height,octaves=16,persistance=0.7,lacunarity=3.0,repeatx=10024,repeaty=10024,base=0):
	base = random.randint(0,1024)
	print (base)
	big_number = float(max(width,height) + 2)
	from noise import pnoise3
	my_noise = [[r for r in range(width)] for i in range(height)]
	_r = random.random()
	for i in range(0,height):
		for j in range(0,width):
			#my_noise[i][j] = (1.0 + pnoise3(float(i)/big_number, float(j)/big_number, _r, octaves,persistance,lacunarity,repeatx,repeaty,base)) / 2.0
			my_noise[i][j] = (1.0 + pnoise3(float(i)/big_number, float(j)/big_number, _r,octaves,persistance, lacunarity,repeatx,repeaty,base)) / 2.0
	return my_noise		
    def create_noise(self):
        """If a noise file was not found, this will create a noise file using pnoise3"""

        matrix_size = self.matrix_size
        scale = self.noise_scale
        coords = range(matrix_size)

        v = np.zeros((matrix_size, matrix_size, matrix_size))
        for z in coords:
            for y in coords:
                for x in coords:
                    v[x][y][z] = (pnoise3(x * scale, y * scale , z * scale, octaves=8, persistence=.25) + 1.0)/2.0
        return v
示例#15
0
    def octant(x_offset, y_offset, z_offset):
        array = np.ndarray((samples, samples, samples))
        for x in range(samples):
            for y in range(samples):
                for z in range(samples):
                    x2, y2, z2 = x + x_offset, y + y_offset, z + z_offset
                    noise = AMPLITUDE * pnoise3(x2 * FREQUENCY, y2 * FREQUENCY, z2 * FREQUENCY, octaves=2)
                    array[x, y, z] = x2 ** 2 + y2 ** 2 +  z2 ** 2 - half ** 2 + noise

        logging.debug("array")
        logging.debug(array)
        # Extract the 0-isosurface
        return mcubes.marching_cubes(array, 0)
示例#16
0
文件: planet.py 项目: tps12/Dorftris
    def sample(self, latitude, longitude):
        lat, lon = [v*pi/180 for v in latitude, longitude]
        c = cos(lat)
        x, y, z = c * cos(lon), c * sin(lon), sin(lat)

        octaves = 12
        persist = 0.7

        b = 1 if pnoise3(x+self.seeds[0],
                         y+self.seeds[1],
                         z+self.seeds[2], 4, persist) > -0.125 else -1
        value = pnoise3(x+self.seeds[3],
                        y+self.seeds[4],
                        z+self.seeds[5], octaves, persist)
        if value > 0.25:
            value *= 1.25 * b
        elif value > 0:
            value *= b
        else:
            value *= 3

        scale = 7000
        return scale * value
示例#17
0
def generate_uniform_altitudes(nodes, max_height=1000.0, min_height=-1000.0, target_wateriness=0.5):
    import noise
    noise_offset = (1.0 - 2.0*target_wateriness)
    noise_max = 1.0 + noise_offset
    noise_min = -1.0 + noise_offset
    half_range = (max_height - min_height) / 2.0
    for n in nodes:
        noise_point = noise.pnoise3(n.x, n.y, n.z, octaves=2) + noise_offset
        # noise_point = noise.pnoise2(n.longitude, n.latitude, repeatx=360.0, repeaty=180.0, octaves=2) + noise_offset
        # noise_point = noise.snoise3(n.x, n.y, n.z) + noise_offset
        try:
            if noise_point < 0:
                n.altitude = (min_height * noise_point) / noise_min
            elif noise_point > 0:
                n.altitude = (max_height * noise_point) / noise_max
            else:
                n.altitude = 0.0
        except ZeroDivisionError:
            n.altitude = 0.0
示例#18
0
def main2():
    logging.info("(this might take a while...)")
    samples = 50
    t = time.time()
    #from stl import mesh
    diameter = 10
    radius = diameter / 2
    half= radius / 2
    
    u = np.ndarray((200,200,200))
    for X in range(-100,100):
        for Y in range(-100,100):
            for Z in range(-100,100):
                u[X+100,Y+100,Z+100] = ((X)**2 + (Y)**2 + (Z)**2) + pnoise3(X*0.05,Y*0.05,Z*0.05,octaves=3)*30
    
    logging.debug("u")
    logging.debug(u)
    vertices, triangles = gts.marching_cubes(u, 60)
    logging.info("mesh completed in %f seconds" % (time.time() - t))

    meshexport.export(vertices, triangles)
示例#19
0
def octant_array(samples, isosurface, x_offset, y_offset, z_offset, spherefactor=1):
    """

    :param samples: the number of samples per dimension per octant,
     the full model would have samples**3 * 8 samples
    :param isosurface:
    :param x_offset: controls which octant
    :param y_offset:
    :param z_offset:
    :param spherefactor: power to apply to the spherical component. use 0.5 for a linear sphere.
    :return: a numpy.ndarray
    """
    array = np.ndarray((samples, samples, samples))
    isosurface **= 2
    for x in range(samples):
        for y in range(samples):
            for z in range(samples):
                x2, y2, z2 = x + x_offset, y + y_offset, z + z_offset
                noise = AMPLITUDE * pnoise3(x2 * FREQUENCY, y2 * FREQUENCY, z2 * FREQUENCY, octaves=2)
                array[x, y, z] = isosurface - pow(x2 ** 2 + y2 ** 2 + z2 ** 2,spherefactor) - noise
    return array
示例#20
0
def main3():
    logging.info("(this might take a while...)")
    t = time.time()
    # from stl import mesh
    samples = 50
    radius = samples / 2.0
    half = radius / 2.0

    array = np.ndarray((samples, samples, samples))
    for x in range(samples):
        for y in range(samples):
            for z in range(samples):
                noise = AMPLITUDE * pnoise3(x * FREQUENCY, y * FREQUENCY, z * FREQUENCY, octaves=2)
                array[x, y, z] = x ** 2 + y ** 2 + z ** 2 - half ** 2 + noise

    logging.debug("array")
    logging.debug(array)
    # Extract the 0-isosurface
    vertices, triangles = mcubes.marching_cubes(array, 0)
    logging.info("mesh completed in %f seconds" % (time.time() - t))

    meshexport.export(vertices, triangles)
示例#21
0
def draw_dots():
    global z,z2,mmin,mmax
    clear_grid()

    for x in range(WIDTH):
        for y in range(HEIGHT):
            c = noise.pnoise3(x * scale, y * scale, z * scale, octave, repeatx=WIDTH, repeaty=HEIGHT)

            if c > mmax: mmax = c
            if c < mmin: mmin = c
        
            c = c + math.fabs(mmin)
            c = c / (mmax + math.fabs(mmin))
            if mode == 1:
                c = (c + 0.2) % 1
                grid[x][y] = [c,1,1]
            elif mode == 2:
                c = (c + z2) % 1
                grid[x][y] = [c,1,1]
            else:
                grid[x][y] = [z2%1,1,c]

    z += .1
    z2 += .005
示例#22
0
def execute(mesh_file,
            output_to,
            gas_emission_base,
            gas_emission_scale,
            pnoise_scale,
            pnoise_offset,
            octaves,
            persistence,
            m_gas,
            T_gas,
            logger,
            chance_to_strong_jets=0.05,
            jets_scale=3.0,
            render_mode=False):

    N_a = 6.02214086  # Avogadro number [Si unit, mol dropped]
    k_b = 1.38064852  # Boltzman constant [Si unit, mol dropped]

    #Root-Mean-Square velocities of gas particles
    v_th = np.sqrt(3 * (k_b * N_a) * T_gas / m_gas) * 0.001  #velocity [km/s]

    logger.info("Start gas source generation")
    obj = mw.MeshObject(mesh_file, logger=logger)
    faces, areas, centroids = obj.get_face_information(t_float)
    data = np.zeros((centroids.shape[0], 2), t_float)
    indx = 0
    max_value = 0
    for centroid in centroids:
        x = centroid[0]
        y = centroid[1]
        z = centroid[2]
        v = pnoise3(x * pnoise_scale,
                    y * pnoise_scale,
                    z * pnoise_scale,
                    octaves=octaves,
                    persistence=persistence)
        max_value = max(max_value, v)
        if (np.random.uniform() < chance_to_strong_jets):
            v = v * (1 + np.random.normal() * jets_scale)
        data[indx, 0] = v
        indx = indx + 1

    min_value = np.amin(data[:, 0])
    data[:, 0] = (data[:, 0] + np.abs(min_value))
    data[:,
         0] = data[:,
                   0] / max_value * gas_emission_scale + gas_emission_base  # surface gas emission rates [mol/(s*km^2)]
    data[:, 1] = v_th  # gas source initial velocity [km/s]
    np.savetxt(output_to, data)  # save output
    logger.info("Finished, data saved to: {}".format(output_to))
    # Visualization
    if (render_mode):
        max_color = np.amax(data[:, 0])
        obj.change_to_face_color()
        colors = np.zeros((centroids.shape[0], 3), np.uint8)
        colors[:, 0] = data[:, 0] / max_color * 255
        colors[:, 1] = data[:, 0] / max_color * 255
        colors[:, 2] = data[:, 0] / max_color * 255

        obj.mesh.visual.face_colors = colors
        render(obj)
示例#23
0
    def createMap(self):

        #indirection for a few variables that will be used frequently
        rows = self.rows
        cols = self.cols
        borderBuffer = self.borderBuffer

        #First Create the elevation map using (perlin) noise
        #######################################################################

        print("Carving Land...")

        #setup initial values
        offset = self.perlinOffset
        i_offset = 0.0
        j_offset = 0.0

        #create the elevation map
        for i in range(rows):
            i_offset = i * offset
            for j in range(cols):
                j_offset = j * offset

                #get noisy value between -1 and 1
                pnoise = noise.pnoise3(i_offset, j_offset, self.elevationSeed,
                                       self.perlinOctaves,
                                       self.perlinPersistence)

                #set current tile's elevation to between -255 and +255
                self.tilemap[i][j].elevation = int(pnoise * 255)

        #Reduce the elevation of tiles as they approach the border of the map
        #######################################################################

        print("Shifting Techtonic plates...")

        #for each tile
        for i in range(0, rows):
            for j in range(0, cols):

                #if the tile is less than borderBuffer(128) tiles away from the edge,
                #then reduce its elevation
                distance = self.getDistance2(i, j, rows / 2, cols / 2)
                if (distance >= (rows / 2 - borderBuffer)):
                    self.tilemap[i][j].elevation += int(
                        float(rows) / 2.0 - borderBuffer - float(distance))

                #if the elevation is less than -255, then set it equal to -255
                self.tilemap[i][j].elevation = self.tilemap[i][
                    j].elevation if self.tilemap[i][
                        j].elevation >= -255 else -255

        #TODO--Smooth the coastlines

        #Create rivers
        #######################################################################

        print("Melting Glaciers...")

        #for each tile
        for i in range(1, rows - 1):
            for j in range(1, cols - 1):
                if (self.tilemap[i][j].elevation == 0):
                    if (random.random() > 0.999):
                        self.extend_river(i, j)

        #Identify ocean and lake tiles, set baseline humidity, and disperse humidity values
        #######################################################################

        ocean_identified = False
        fanned = False
        count = 0

        print("Flooding... (takes a sec)")

        #this will continue cycling through every tile until
        #all of the oceans tiles and lake tiles are identified
        #it will also keep going until the humidity map is complete
        while (not ocean_identified and not fanned):

            #reset flags
            ocean_identified = True
            fanned = True
            count += 1

            #the for-loops toggle between going from
            #left->right;top->bottom and left->right;bottom->top
            #(this helps areas like bays that only have land tiles above them)
            if (count % 2 == 1):
                startrow = 0
                startcol = 0
                endrow = rows
                endcol = cols
                direction = 1
            else:
                startrow = rows - 1
                startcol = cols - 1
                endrow = 0
                endcol = 0
                direction = -1

            #for each tile
            for i in range(startrow, endrow, direction):
                for j in range(startcol, endcol, direction):

                    #if the tile is along the edge, then it's ocean
                    if ((i == 0 or j == 0 or i == rows - 1 or j == cols - 1)
                            and self.tilemap[i][j].subtype == ""):
                        self.tilemap[i][j].type = "water"
                        self.tilemap[i][j].subtype = "ocean"
                        self.tilemap[i][j].humidity = 100

                    #if it's not along the edges...
                    else:

                        #if it's land, mark it and forget about it
                        if (self.tilemap[i][j].elevation > 0
                                and self.tilemap[i][j].type == ""):
                            self.tilemap[i][j].type = "land"

                        #if it's water and it hasn't been labelled yet...
                        elif (self.tilemap[i][j].elevation <= 0
                              and self.tilemap[i][j].subtype == ""):

                            #set the initial humidity to 75
                            #(lake tiles should be the only ones with 75 after this loop)
                            self.tilemap[i][j].type = "water"
                            self.tilemap[i][j].humidity = 75.0

                            #if any of the adjacent tiles are ocean, then this one is too.
                            if self.tilemap[i - 1][
                                    j].subtype == "ocean" or self.tilemap[i][
                                        j -
                                        1].subtype == "ocean" or self.tilemap[
                                            i +
                                            1][j].subtype == "ocean" or self.tilemap[
                                                i][j + 1].subtype == "ocean":
                                self.tilemap[i][j].subtype = "ocean"
                                self.tilemap[i][j].humidity = 100.0

                                #set the flag so we know that not all the ocean tiles
                                #have been identified yet
                                ocean_identified = False

                    #if the current tile is land, then distribute the humidity
                    if (self.tilemap[i][j].elevation > 0):

                        #initial max humidity set to current tile
                        max_humidity = self.tilemap[i][j].humidity

                        #max humidity is set to the highest humidity of all the adjacent tiles
                        if (self.tilemap[i - 1][j].humidity - 1 >
                                max_humidity):
                            max_humidity = self.tilemap[i - 1][j].humidity - .5
                        if (self.tilemap[i][j - 1].humidity - 1 >
                                max_humidity):
                            max_humidity = self.tilemap[i][j - 1].humidity - .5
                        if (self.tilemap[i + 1][j].humidity - 1 >
                                max_humidity):
                            max_humidity = self.tilemap[i + 1][j].humidity - .5
                        if (self.tilemap[i][j + 1].humidity - 1 >
                                max_humidity):
                            max_humidity = self.tilemap[i][j + 1].humidity - .5

                        if (self.tilemap[i - 1][j - 1].humidity - 1 >
                                max_humidity):
                            max_humidity = self.tilemap[i - 1][
                                j - 1].humidity - math.sqrt(2.0 * (.5**2))
                        if (self.tilemap[i + 1][j - 1].humidity - 1 >
                                max_humidity):
                            max_humidity = self.tilemap[i + 1][
                                j - 1].humidity - math.sqrt(2.0 * (.5**2))
                        if (self.tilemap[i + 1][j + 1].humidity - 1 >
                                max_humidity):
                            max_humidity = self.tilemap[i + 1][
                                j + 1].humidity - math.sqrt(2.0 * (.5**2))
                        if (self.tilemap[i - 1][j + 1].humidity - 1 >
                                max_humidity):
                            max_humidity = self.tilemap[i - 1][
                                j + 1].humidity - math.sqrt(2.0 * (.5**2))

                        #if an adjacent tile has a higher humidity than the current tile,
                        #recalculate humidity and set the flag
                        if (max_humidity > self.tilemap[i][j].humidity):
                            fanned = False
                            self.tilemap[i][j].humidity = max_humidity

        #Add additional humidity for increased elevations and rivers
        #######################################################################
        print("Misting...")
        for i in range(rows):
            for j in range(cols):

                if (self.tilemap[i][j].type == "water"
                        and self.tilemap[i][j].humidity == 75):
                    self.tilemap[i][j].subtype = "lake"

                #rivers add 25 humidity to what was already there
                if (self.tilemap[i][j].subtype == "river"):
                    self.tilemap[i][j].humidity += 25.0

                #higher elevations add humidity too
                if (self.tilemap[i][j].elevation >= 1):
                    self.tilemap[i][j].humidity += (
                        self.tilemap[i][j].elevation / 3.0)

        #Fan it a second time to disperse the additional humidity
        #######################################################################
        print("Evaporating...")
        while (not fanned):

            #reset flags
            fanned = True
            count += 1

            #the for-loops toggle between going from
            #left->right;top->bottom and left->right;bottom->top
            #(this helps areas like bays that only have land tiles above them)
            if (count % 2 == 1):
                startrow = 0
                startcol = 0
                endrow = rows
                endcol = cols
                direction = 1
            else:
                startrow = rows - 1
                startcol = cols - 1
                endrow = 0
                endcol = 0
                direction = -1

            #for each tile
            for i in range(startrow, endrow, direction):
                for j in range(startcol, endcol, direction):
                    #if the current tile is land, then distribute the humidity
                    if (self.tilemap[i][j].elevation > 0):

                        #initial max humidity set to current tile
                        max_humidity = self.tilemap[i][j].humidity

                        #max humidity is set to the highest humidity of all the adjacent tiles
                        if (self.tilemap[i - 1][j].humidity - 1 >
                                max_humidity):
                            max_humidity = self.tilemap[i - 1][j].humidity - .5
                        if (self.tilemap[i][j - 1].humidity - 1 >
                                max_humidity):
                            max_humidity = self.tilemap[i][j - 1].humidity - .5
                        if (self.tilemap[i + 1][j].humidity - 1 >
                                max_humidity):
                            max_humidity = self.tilemap[i + 1][j].humidity - .5
                        if (self.tilemap[i][j + 1].humidity - 1 >
                                max_humidity):
                            max_humidity = self.tilemap[i][j + 1].humidity - .5

                        if (self.tilemap[i - 1][j - 1].humidity - 1 >
                                max_humidity):
                            max_humidity = self.tilemap[i - 1][
                                j - 1].humidity - math.sqrt(2.0 * (.5**2))
                        if (self.tilemap[i + 1][j - 1].humidity - 1 >
                                max_humidity):
                            max_humidity = self.tilemap[i + 1][
                                j - 1].humidity - math.sqrt(2.0 * (.5**2))
                        if (self.tilemap[i + 1][j + 1].humidity - 1 >
                                max_humidity):
                            max_humidity = self.tilemap[i + 1][
                                j + 1].humidity - math.sqrt(2.0 * (.5**2))
                        if (self.tilemap[i - 1][j + 1].humidity - 1 >
                                max_humidity):
                            max_humidity = self.tilemap[i - 1][
                                j + 1].humidity - math.sqrt(2.0 * (.5**2))

                        #if an adjacent tile has a higher humidity than the current tile,
                        #recalculate humidity and set the flag
                        if (max_humidity > self.tilemap[i][j].humidity):
                            fanned = False
                            self.tilemap[i][j].humidity = max_humidity

        #Use Humidity and elevation values to Identify the biomes
        #######################################################################
        print("Climatizing...")
        for i in range(0, rows):
            for j in range(0, cols):

                #separate the map into 4 or 5 different elevation zones
                if (self.tilemap[i][j].elevation < 5):
                    elevation_zone = -1
                elif (self.tilemap[i][j].elevation >= 100):
                    elevation_zone = 4
                elif (self.tilemap[i][j].elevation < 100
                      and self.tilemap[i][j].elevation >= 75):
                    elevation_zone = 3
                elif (self.tilemap[i][j].elevation < 75
                      and self.tilemap[i][j].elevation >= 50):
                    elevation_zone = 2
                elif (self.tilemap[i][j].elevation < 50
                      and self.tilemap[i][j].elevation >= 25):
                    elevation_zone = 1
                else:
                    elevation_zone = 0

                #separate the map into 7 different moisture zones
                if (self.tilemap[i][j].humidity >= 95):
                    moisture_zone = 6
                elif (self.tilemap[i][j].humidity < 95
                      and self.tilemap[i][j].humidity >= 80):
                    moisture_zone = 5
                elif (self.tilemap[i][j].humidity < 80
                      and self.tilemap[i][j].humidity >= 65):
                    moisture_zone = 4
                elif (self.tilemap[i][j].humidity < 65
                      and self.tilemap[i][j].humidity >= 50):
                    moisture_zone = 3
                elif (self.tilemap[i][j].humidity < 50
                      and self.tilemap[i][j].humidity >= 35):
                    moisture_zone = 2
                elif (self.tilemap[i][j].humidity < 35
                      and self.tilemap[i][j].humidity >= 15):
                    moisture_zone = 1
                elif (self.tilemap[i][j].humidity < 15):
                    moisture_zone = 0

                if (elevation_zone == -1 and moisture_zone == 6):
                    self.tilemap[i][j].biome = "beach"
                elif (elevation_zone <= 3 and moisture_zone == 0):
                    self.tilemap[i][j].biome = "desert"
                elif (elevation_zone == 4 and moisture_zone == 0):
                    self.tilemap[i][j].biome = "scorched"
                elif ((elevation_zone <= 2 and moisture_zone == 1)
                      or (moisture_zone == 2 and elevation_zone == 2)):
                    self.tilemap[i][j].biome = "grassland"
                elif (elevation_zone == 3 and moisture_zone == 1):
                    self.tilemap[i][j].biome = "desert"
                elif (elevation_zone == 4 and moisture_zone == 1):
                    self.tilemap[i][j].biome = "bare"
                elif (elevation_zone <= 1
                      and (moisture_zone == 2 or moisture_zone == 3)):
                    self.tilemap[i][j].biome = "seasonal_forest"
                elif (elevation_zone == 3
                      and (moisture_zone == 2 or moisture_zone == 3)):
                    self.tilemap[i][j].biome = "shrubland"
                elif (elevation_zone == 4 and moisture_zone == 2):
                    self.tilemap[i][j].biome = "tundra"
                elif (elevation_zone == 4 and moisture_zone >= 3):
                    self.tilemap[i][j].biome = "snow"
                elif (elevation_zone == 3 and moisture_zone >= 4):
                    self.tilemap[i][j].biome = "taiga"
                elif (elevation_zone == 2
                      and (moisture_zone == 3 or moisture_zone == 4)):
                    self.tilemap[i][j].biome = "temperate_forest"
                elif (elevation_zone == 2 and moisture_zone == 5):
                    self.tilemap[i][j].biome = "temperate_rainforest"
                else:
                    self.tilemap[i][j].biome = "tropical_rainforest"

        #TODO--Create populated areas
        #TODO--Generate zones where trees are clustered (and plant individual trees within those clusters)

        return self.tilemap
示例#24
0
     random.randint(0, 100000)
 ]
 Seed2 = [
     random.randint(0, 100000),
     random.randint(0, 100000),
     random.randint(0, 100000)
 ]
 for i in range(xSize):
     iArray = []
     for j in range(zSize):
         jArray = []
         for k in range(ySize):
             if ColorMode == 1:
                 NoiseToColor = abs(
                     noise.pnoise3((i * PSize) + Seed[0],
                                   (j * PSize) + Seed[1],
                                   (k * PSize * 3) + Seed[2])) * 2
                 if NoiseToColor > 1:
                     NoiseToColor = 1.0
             elif ColorMode == 2:
                 NoiseToColor = abs(
                     noise.pnoise3(
                         (i * RandomNoiseColorSeed) + Seed2[0],
                         (j * RandomNoiseColorSeed) + Seed2[1],
                         (k * RandomNoiseColorSeed * 3) + Seed2[2])) * 2
                 if NoiseToColor > 1:
                     NoiseToColor = 1.0
             NoiseToColor = int(NoiseToColor * 14)
             jArray.append([
                 True if noise.pnoise3(
                     (i * PSize) + Seed[0], (j * PSize) + Seed[1],
示例#25
0
def ProcessPerlin3DOnePoint(vertex, amplitude, offset):
    return abs(amplitude * noise.pnoise3(vertex[0], vertex[1], vertex[2], 5, 1,
                                         2, 128, 128, 128, offset))
示例#26
0
def generation(seed, mode, x, y, flatdata=10):
    if mode == "flat":
        if y * bsInv - 6 >= flatdata:
            a = random.randint(0, 1000)
            z = False
            if a < 35 and a > 20:
                return 4
                z = True
            if not z and a < 20 and a > 10 and y * bsInv > flatdata + 10:
                return 9
                z = True
            if not z:
                return 1
        if y * bsInv - 2 >= flatdata:
            return 2
        if y * bsInv - 1 >= flatdata:
            return 3
        if y * bsInv - 4 < flatdata:
            return 0
    if mode == "empty":
        return 0

    if mode == "interstellar":
        r = seed * x * y
        if divis_get(r, 2):
            return (0)
        else:
            return (1)

    if mode == "normal":

        left_point = int(x * lh_DIVggs) * gs
        random.seed(seed)
        random.seed(
            int((left_point * 100.0) * bsInv * lh_DIVggs /
                random.randint(4, 30)))
        left_biom = BIOMS[random.randint(0, len(BIOMS) - 1)]

        right_point = (int(x * lh_DIVggs) * gs) + gs
        random.seed(seed)
        random.seed(
            int((right_point * 100.0) * bsInv * lh_DIVggs /
                random.randint(4, 30)))
        right_biom = BIOMS[random.randint(0, len(BIOMS) - 1)]

        if int(left_point * bsInv * bsInv) == 0:
            left_biom = PlainsB

        if int(right_point * bsInv * bsInv) == 0:
            right_biom = PlainsB

        #определение высот 2-х основных точек, левой и правой
        random.seed(seed * left_point * gs)
        left_point_H = int(
            random.randint(left_biom[1], left_biom[0]) * bsInv) * bs
        random.seed(seed * right_point * gs)
        right_point_H = int(
            random.randint(right_biom[1], right_biom[0]) * bsInv) * bs
        biom = PlainsB
        #если блок совподает с левой точкой
        if int(left_point * bsInv) * bs == int(x * bsInv) * bs:
            point_hight = left_point_H
            biom = left_biom
        #если блок совподает с правой точкой
        if int(right_point * bsInv) * bs == int(x * bsInv) * bs:
            point_hight = right_point_H
            biom = right_biom
        left_percent = float(float(x - left_point) * lh_DIVggs)
        right_percent = float(float(right_point - x) * lh_DIVggs)
        try:
            point_hight
        except NameError:
            rsn = 0
            point_hight = (left_point_H * right_percent) + (right_point_H *
                                                            left_percent)

            random.seed(seed + x + y + point_hight)
            if random.randint(-(int(left_point_H * left_percent * 100)),
                              int(right_point_H * right_percent * 100)) >= 0:
                biom = left_biom
            else:
                biom = right_biom

        if y > point_hight:
            if int(y * bsInv) == int(point_hight * bsInv):
                return 6
            if y - 6 * bs <= point_hight:
                return biom[2]
            else:
                random.seed(seed + x + y + seed - point_hight + biom[0] -
                            biom[1] * x * y * x**2)
                rand = random.randint(0, 20000)
                to_id = 1
                if rand < 250:
                    to_id = 4
                if rand < 40 and point_hight + (20 * bs) < y:
                    to_id = 9
                if rand < 5 and point_hight + (100 * bs) < y:
                    to_id = 6
                return to_id
        else:
            random.seed(seed + x)
            if biom[3] != 0:
                done_1 = False
                if random.randint(0, biom[3]) == 0:
                    if int(y * bsInv) == int(point_hight * bsInv):
                        return 7
                        done_1 = True
                    if int(y * bsInv) + 1 == int(point_hight * bsInv):
                        return 7
                        done_1 = True
                    if int(y * bsInv) + 2 == int(point_hight * bsInv):
                        return 7
                        done_1 = True
                    if int(y * bsInv) + 3 == int(point_hight * bsInv):
                        return 7
                        done_1 = True
                    if int(y * bsInv) + 4 == int(point_hight * bsInv):
                        return 7
                        done_1 = True
                    if int(y * bsInv) + 5 == int(point_hight * bsInv):
                        return 8
                    if int(y * bsInv) + 6 == int(point_hight * bsInv):
                        return 8
                        done_1 = True

                random.seed(seed + x + bs)
                if not done_1 and random.randint(0, biom[3]) == 0:
                    if int(y * bsInv) + 1 == int(point_hight * bsInv):
                        return 8
                        done_1 = True
                    if int(y * bsInv) + 2 == int(point_hight * bsInv):
                        return 8
                        done_1 = True
                    if int(y * bsInv) + 3 == int(point_hight * bsInv):
                        return 8
                        done_1 = True
                    if int(y * bsInv) + 4 == int(point_hight * bsInv):
                        return 8
                        done_1 = True
                random.seed(seed + x - bs)
                if not done_1 and random.randint(0, biom[3]) == 0:
                    if int(y * bsInv) + 1 == int(point_hight * bsInv):
                        return 8
                        done_1 = True
                    if int(y * bsInv) + 2 == int(point_hight * bsInv):
                        return 8
                        done_1 = True
                    if int(y * bsInv) + 3 == int(point_hight * bsInv):
                        return 8
                        done_1 = True
                    if int(y * bsInv) + 4 == int(point_hight * bsInv):
                        return 8
                        done_1 = True
                random.seed(seed + x + bs * 2)
                if not done_1 and random.randint(0, biom[3]) == 0:
                    if int(y * bsInv) + 2 == int(point_hight * bsInv):
                        return 8
                        done_1 = True
                    if int(y * bsInv) + 3 == int(point_hight * bsInv):
                        return 8
                        done_1 = True
                    if int(y * bsInv) + 4 == int(point_hight * bsInv):
                        return 8
                        done_1 = True
                random.seed(seed + x - bs * 2)
                if not done_1 and random.randint(0, biom[3]) == 0:
                    if int(y * bsInv) + 2 == int(point_hight * bsInv):
                        return 8
                        done_1 = True
                    if int(y * bsInv) + 3 == int(point_hight * bsInv):
                        return 8
                        done_1 = True
                    if int(y * bsInv) + 4 == int(point_hight * bsInv):
                        return 8
                        done_1 = True

            if int(y * bsInv) >= 251:
                return 11
        return 0
#		x_left_rasn = float(ogs/(x-left_point+0.1))

    if mode == "islands#beta":
        ggss = 5
        if True:
            sis = noise.pnoise3(float(x * bsInv * 0.1), float(y * bsInv * 0.1),
                                seed, 3)
            sis = float(float(sis) * 100)

            if True:
                sss = 5
                if sis > sss:
                    if sis > sss + 3:
                        if int(sis) == 39:
                            if int(sis) > 40:
                                return 11
                            return 6
                        return 1
                    elif sis > sss + 1:
                        return 3
                else:
                    sis2 = noise.pnoise3(float(x * bsInv * 0.07),
                                         float(y * bsInv * 0.07), seed, 1)
                    sis2 = float(float(sis2) * 100)
                    if sis2 > 30 and sis > sss - 10:
                        if sis2 > 45:
                            return 7
                        return 8
                    return 0
            return 0

    if mode == "new#normal#beta":
        global nbiom, bsInv
        nbiom1 = noise.pnoise2(x * 0.00002, seed, 2)
        nbiom = int(abs(nbiom1 * 40))

        def get_biom():
            global nbiom, bsInv
            if int(y * bsInv) < 80 + sis * 0.3:
                if int(y * bsInv) < 110 + sis * 0.3:
                    return 19

                if sis3 > 13 and int(y * bsInv) > sis + 200:
                    return 6
                if sis2 < -12:
                    return 9
                if sis2 > 10:
                    return 4
                return 1
            if nbiom == 0:
                return 5
            return 3

        seed = seed * 0.0006567568

        sism = noise.pnoise2(float(x * bsInv * 0.005), seed, 5)
        sism = float(float(sism) * 120) + 100

        sis2 = noise.pnoise3(float(x * bsInv * 0.2), float(y * bsInv * 0.2),
                             seed, 1)
        sis2 = float(float(sis2 * 18))

        sis3 = noise.pnoise3(float(x * bsInv * 0.1), float(y * bsInv * 0.1),
                             seed + 1, 1)
        sis3 = float(float(sis3 * 19))

        sis = noise.pnoise2(float(x * bsInv * 0.002), seed, 5)
        aaa = float(nbiom1)
        bbb = (float(float(sis) * 600) + 200)
        sis = ((bbb * 0.5 + ((bbb) * (aaa + 2)) * 0.9) * 0.35) + 20

        get_biom()

        ol = 270

        if int(y * bsInv) > sis:
            if int(y * bsInv) > sis + 10:
                if sis3 > 13 and int(y * bsInv) > sis + 250:
                    return 6
                if sis2 < -12:
                    return 9
                if sis2 > 10:
                    return 4
                return 1
            if int(y * bsInv) >= ol - int(sis / 29):
                return 5
            else:
                return get_biom()
        if int(y * bsInv) >= ol:
            return 11
        return 0

    if mode == "optim#normal":
        lh_DIVggs = 1.0 / float(gs)

        left_point = int(x * lh_DIVggs) * gs
        random.seed(seed)
        random.seed(
            int((left_point * 100.0) * bsInv * lh_DIVggs /
                random.randint(4, 30)))
        left_biom = BIOMS[random.randint(0, len(BIOMS) - 1)]

        right_point = (int(x * lh_DIVggs) * gs) + gs
        random.seed(seed)
        random.seed(
            int((right_point * 100.0) * bsInv * lh_DIVggs /
                random.randint(4, 30)))
        right_biom = BIOMS[random.randint(0, len(BIOMS) - 1)]

        if int(left_point * bsInv * bsInv) == 0:
            left_biom = PlainsB

        if int(right_point * bsInv * bsInv) == 0:
            right_biom = PlainsB

        #определение высот 2-х основных точек, левой и правой
        random.seed(seed * left_point * gs)
        left_point_H = int(
            random.randint(left_biom[1], left_biom[0]) * bsInv) * bs
        random.seed(seed * right_point * gs)
        right_point_H = int(
            random.randint(right_biom[1], right_biom[0]) * bsInv) * bs
        biom = PlainsB

        #если блок совподает с левой точкой
        if int(left_point * bsInv) * bs == int(x * bsInv) * bs:
            point_hight = left_point_H
            biom = left_biom

        #если блок совподает с правой точкой
        if int(right_point * bsInv) * bs == int(x * bsInv) * bs:
            point_hight = right_point_H
            biom = right_biom
        left_percent = float(x - left_point) * lh_DIVggs
        right_percent = float(right_point - x) * lh_DIVggs

        lpecented = left_point_H * right_percent
        rpercented = right_point_H * left_percent
        try:
            point_hight
        except NameError:
            rsn = 0
            point_hight = lpecented + rpercented

            random.seed(seed + x + y + point_hight)
            if random.randint(-(int(lpecented * 100)), int(
                    rpercented * 100)) >= 0:
                biom = left_biom
            else:
                biom = right_biom

        if y > point_hight:
            if int(y * bsInv) == int(point_hight * bsInv):
                return 6
            if y - 6 * bs <= point_hight:
                return biom[2]
            else:
                random.seed(seed + x + y + seed - point_hight + biom[0] -
                            biom[1] * x * y * x**2)
                rand = random.randint(0, 20000)
                to_id = 1
                if rand < 250:
                    to_id = 4
                if rand < 40 and point_hight + (20 * bs) < y:
                    to_id = 9
                if rand < 5 and point_hight + (100 * bs) < y:
                    to_id = 6
                return to_id
        else:
            if int(y * bsInv) >= 251:
                return 11
        return 0
示例#27
0
    def create_background(self, res):
        """
        Method to create a simple, random background
        
        Arguments:
            res : [int, int] - Current screen resolution
            
        Return values:
            bg_surf : pygame.Surface - The generated background image
        """

        # Create black surface to draw on
        bg_surf = pygame.Surface(res)
        bg_px_arr = pygame.PixelArray(bg_surf)
        bg_surf.fill((0, 0, 0))

        # Generate nebulae if it is set to generate nebulae in cfg file
        if self.game_instance.generate_nebulae:
            bg_surf_arr = pygame.PixelArray(bg_surf)

            # Create arrays of with the same number of entries as there are pixels on the screen
            nebula_mask = numpy.empty(res[0] * res[1])
            nebula_color = numpy.empty(res[0] * res[1])
            nebula_lightness = numpy.empty(res[0] * res[1])

            # Set random seeds for noise function
            maskseed = random.random()
            colorseed = random.random()
            lightnessseed = random.random()

            # Loop through all pixels of the background to fill noise arrays
            px_index = 0
            for i in range(res[0]):
                for j in range(res[1]):

                    # Set noise coordinates to normalized pixel coordinates
                    x_noise = (i * 4) / res[0]
                    y_noise = (j * 4) / res[1]

                    # Generate noise values for pixel
                    nebula_mask[px_index] = noise.pnoise3(
                        x_noise / 1.5, y_noise / 1.5, maskseed, 6)
                    nebula_color[px_index] = noise.pnoise3(
                        x_noise / 30, y_noise / 30, colorseed)
                    nebula_lightness[px_index] = noise.pnoise3(
                        x_noise / 20, y_noise / 20, lightnessseed)

                    px_index += 1

            # Normalize noise values between 0 and 1
            nebula_mask = (nebula_mask - nebula_mask.min()) / (
                nebula_mask.max() - nebula_mask.min())
            nebula_color = (nebula_color - nebula_color.min()) / (
                nebula_color.max() - nebula_color.min())
            nebula_lightness = (nebula_lightness - nebula_lightness.min()) / (
                nebula_lightness.max() - nebula_lightness.min())
            nebula_mask = nebula_mask**2

            # Loop through all pixels again for color processing
            px_index = 0
            for i in range(res[0]):
                for j in range(res[1]):

                    newcolor = pygame.Color(0, 0, 0)
                    h, s, l, a = newcolor.hsla

                    h = nebula_color[px_index] * 360
                    s = 50
                    l = nebula_lightness[px_index] * nebula_mask[px_index] * 40

                    newcolor.hsla = h, s, l, a

                    bg_surf_arr[i, j] = newcolor

                    px_index += 1

        # Generate white background stars (by coloring single, random pixels)
        for bgstars in range(1000):
            x = random.randint(0, res[0] - 1)
            y = random.randint(0, res[1] - 1)

            bg_px_arr[x, y] = (255, 255, 255)

        # Draw larger, colored stars
        for fgstars in range(100):
            color_index = random.randint(0, 255)

            # Determine random color, but just blue-ish and red-ish tints
            b = color_index
            if b > 200:
                r = int(b * 0.75)
                g = random.randint(int(0.75 * b), b)
            else:
                r = 255 - b
                g = random.randint(0, int(0.75 * r))

            # Select random screen coordinates to draw star at
            x = random.randint(0, res[0] - 1)
            y = random.randint(0, res[1] - 1)

            # Set star radius
            radius = random.randint(1, 5) // 2

            # Draw star
            pygame.draw.circle(bg_surf, (r, g, b), (x, y), radius)

        return bg_surf
示例#28
0
import pygame
import noise

width = 300
height = 300
WHITE = (255, 255, 255)
window = pygame.display.set_mode((width, height))

timer = pygame.time.Clock()
running = True
z = 0
scale = 50
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    pixels = pygame.PixelArray(window)
    for x in range(width):
        for y in range(height):
            n = noise.pnoise3(x / scale, y / scale, z, octaves=6)
            n = (n + 1) * 128
            pixels[x, y] = (n, n, n)
    z += 1 / scale
    del pixels
    pygame.display.update()
    timer.tick(30)
示例#29
0
def gen_room(path, loc, save):
    dist = ((loc[0])**2 + (loc[1])**2)**0.5
    print((loc[0]**2 + loc[1]**2)**0.5)
    blank = open("blank_room.txt", "r")
    blank = list(map(lambda s: s.strip(), blank))
    lines = []

    tiles = []
    for line in blank:
        tiles.append(line.split(","))

    doors = []
    banned_doors = []

    if (connect_door(loc, [loc[0] + 1, loc[1]], save)):
        doors.append(1)
    elif (banned_door(loc, [loc[0] + 1, loc[1]], save)):
        banned_doors.append(1)

    if (connect_door(loc, [loc[0] - 1, loc[1]], save)):
        doors.append(3)
    elif (banned_door(loc, [loc[0] - 1, loc[1]], save)):
        banned_doors.append(3)

    if (connect_door(loc, [loc[0], loc[1] + 1], save)):
        doors.append(0)
    elif (banned_door(loc, [loc[0], loc[1] + 1], save)):
        banned_doors.append(0)

    if (connect_door(loc, [loc[0], loc[1] - 1], save)):
        doors.append(2)
    elif (banned_door(loc, [loc[0], loc[1] - 1], save)):
        banned_doors.append(2)

    print(doors, banned_doors)

    c = random.randint(1, 100)
    if c < 10: c = 1
    elif c < 40: c = 2
    else: c = 3

    while len(doors) + len(banned_doors) < c:
        for c in range(4):
            if random.randint(1, 10) < 4:
                if not c in doors + banned_doors:
                    doors.append(c)

    #doors = [0,1,2,3]

    if not 0 in doors:
        tiles[0][5] = "tp"
        tiles[0][6] = "tp"
        tiles[1][5] = "ts"
        tiles[1][6] = "ts"
    if not 1 in doors:
        tiles[5][11] = "er"
        tiles[6][11] = "er"
    if not 2 in doors:
        tiles[11][5] = "bp"
        tiles[11][6] = "bp"
    if not 3 in doors:
        tiles[5][0] = "el"
        tiles[6][0] = "el"
        tiles[5][1] = "ls"
        tiles[6][1] = "ls"

    y = 0
    enemies = []
    for line in tiles:
        x = 0
        temp_line = ""
        for tile in line:
            t = random.randint(0, 8)
            if tile == "tp" and t < 3:
                tile = "tp" + str(t)
            if random.randint(1, 50) < 2 and not x in [
                    0, 1, 2, 11
            ] and not y in [0, 1, 11]:
                tile = "mc" + str(random.randint(0, 1))
            scale = 12
            n = 0.5 + noise.pnoise3(x / scale,
                                    y / scale,
                                    random.randint(1, 10000),
                                    octaves=2,
                                    persistence=1,
                                    lacunarity=1,
                                    repeatx=64,
                                    repeaty=64,
                                    base=2)
            if n > 0.7 and not y in [0, 1, 10, 11] and not x in [0, 1, 10, 11]:
                tile = "tt"
            elif (random.randint(1, 100) <
                  6) and not y in [0, 1, 10, 11] and not x in [0, 1, 10, 11]:
                if random.randint(1, 100) < 100 / ((dist**0.9) + 1):
                    enemies.append(
                        enemies_main.Begazun([x * 64, y * 64], 1.5, 3))
                else:
                    if random.randint(1, 100) < 80:
                        enemies.append(
                            enemies_main.Taghut([x * 64, y * 64], 2, 5))
                    else:
                        enemies.append(
                            enemies_main.Siyah([x * 64, y * 64], 3.5, 1))
            temp_line += tile
            if x + 1 < len(line): temp_line += ","
            x += 1
        lines.append(temp_line + "\n")
        y += 1
    lines.append(":ENDROOM:\n")

    for enemy in enemies:
        line = enemy.type + ":" + str(int(enemy.pos[0])) + "," + str(
            int(enemy.pos[1])) + ":" + str(enemy.speed) + ":" + str(
                enemy.health)
        lines.append(line + "\n")

    lines.append(":ENDMOB:\n")

    if 0 in doors:
        line = "320,-10,128,10:"
        line += str(loc[0]) + "," + str(loc[1] + 1) + ":352,704\n"
        lines.append(line)

    if 2 in doors:
        line = "320,768,128,10:"
        line += str(loc[0]) + "," + str(loc[1] - 1) + ":352,0\n"
        lines.append(line)

    if 3 in doors:
        line = "-10,320,10,128:"
        line += str(loc[0] - 1) + "," + str(loc[1]) + ":704,350\n"
        lines.append(line)

    if 1 in doors:
        line = "768,320,10,128:"
        line += str(loc[0] + 1) + "," + str(loc[1]) + ":0,350\n"
        lines.append(line)
    lines.append(":ENDACT:\n")

    lines.append(":ENDITEMS:\n")

    line = ""
    c = 1
    for i in doors:
        line += str(i)
        if c < len(doors):
            line += ","
        c += 1

    line += "\n"
    lines.append(line)

    file = open(path, "w")
    file.writelines(lines)
    file.close()
示例#30
0
def make_shadow_terrain():
    terrain=[[1-int(abs(noise.pnoise3(i*0.6+0.5,j*0.2+0.5,0.8))*5)
              for i in range(500)] 
             for j in range(5000)]

    return terrain
示例#31
0
HEIGHT = 256


def clamp(x, a, b):
    return min(max(float(x), float(a)), float(b))

def scaleVal(val, inlow, inhigh, outlow, outhigh):
    return ((val - float(inlow)) / (float(inhigh) - float(inlow))) * (float(outhigh) - float(outlow)) + float(outlow)
   
img = []
for y in range(HEIGHT):
    t = tuple()
    for x in range(WIDTH):
        nx = scaleVal(x, 0, WIDTH, -1.0, 1.0)
        ny = scaleVal(y, 0, HEIGHT, -1.0, 1.0)
        val = noise.pnoise3(nx, ny, 1, octaves=int(sys.argv[1]), persistence=int(sys.argv[2]), lacunarity=float(sys.argv[3]), repeatx=256, repeaty=256, base=int(sys.argv[4]))
        
        nval = int(scaleVal(val, -1.0, 1.0, 0, 255))
        
        #nval = clamp(nval, 155, 255)
       
        if nval < 140:
            nval = 10
        else:
            nval = 255

        t += (nval, nval, nval,)
    img.append(t)

if img:
    with open('random_map_pnoise.png', 'wb') as f:
示例#32
0
def test_fg_scores():
    logger.debug("Starting randomized fg test!")
    shape = [20, 20, 20]
    freq = 16
    frac = 0.2
    offset, scale = np.array([0, 0, 0]), np.array([1, 1, 1])

    fg_pred = np.ndarray(shape)
    for coord in product(*[range(d) for d in shape]):
        fg_pred[coord] = noise.pnoise3(*[c / freq for c in coord]) / 2 + 0.5

    assert fg_pred.min() > 0
    assert fg_pred.max() < 1

    gt_bin_mask = fg_pred > 0.5
    ref_tracings = skeletonize(gt_bin_mask, offset, scale)
    logger.warning(f"pred_cable_len: {cable_len(ref_tracings, 'location')}")

    recall, precision, (true_ref, total_ref, true_pred, total_pred) = score_foreground(
        gt_bin_mask,
        ref_tracings,
        offset,
        scale,
        2,
        "location",
        Metric.RECALL_PRECISION,
        details=True,
    )
    assert recall == 1, (true_ref, total_ref, true_pred, total_pred)
    assert precision == 1, (true_ref, total_ref, true_pred, total_pred)

    num_edges = len(ref_tracings.edges())
    k = int(np.ceil(num_edges * frac))
    to_remove = random.sample(list(ref_tracings.edges()), k=k)
    to_add = []
    temp = copy.deepcopy(ref_tracings)
    k = 0
    while len(to_add) < len(to_remove):
        k += 1
        if k > 1000:
            raise Exception(len(to_remove), len(to_add))
        a = random.choice(list(ref_tracings.nodes))
        b = random.choice(list(ref_tracings.nodes))
        # make sure line ab does not have the same slope as any neighbors of a or b
        a_loc = ref_tracings.nodes[a]["location"]
        b_loc = ref_tracings.nodes[b]["location"]
        slope = (a_loc - b_loc) / np.linalg.norm(a_loc - b_loc)
        fail = False
        for a_neighbor in ref_tracings.neighbors(a):
            if fail:
                break
            n_loc = ref_tracings.nodes[a_neighbor]["location"]
            n_slope = (a_loc - n_loc) / np.linalg.norm(a_loc - n_loc)
            if abs(np.dot(slope, n_slope)) < 1e-4:
                fail = True
                print(f"failed since ab share slope with ac")
        for b_neighbor in ref_tracings.neighbors(b):
            if fail:
                break
            n_loc = ref_tracings.nodes[b_neighbor]["location"]
            n_slope = (b_loc - n_loc) / np.linalg.norm(b_loc - n_loc)
            if abs(np.dot(slope, n_slope)) < 1e-4:
                fail = True
                print(f"failed since ab share slope with bc")

        temp.add_edge(a, b)
        to_add.append((a, b))

    current_total_ref = total_ref
    current_true_ref = true_ref
    current_total_pred = total_pred
    current_true_pred = true_pred

    for edge in to_remove:
        u_loc = ref_tracings.nodes[edge[0]]["location"]
        v_loc = ref_tracings.nodes[edge[1]]["location"]
        edge_len = np.linalg.norm(u_loc - v_loc)

        ref_tracings.remove_edge(*edge)
        logger.info(f"removed edge {edge}")

        (
            recall,
            precision,
            (true_ref, total_ref, true_pred, total_pred),
        ) = score_foreground(
            gt_bin_mask,
            ref_tracings,
            offset,
            scale,
            0.05,
            "location",
            Metric.RECALL_PRECISION,
            details=True,
        )

        assert np.isclose(total_ref, current_total_ref - edge_len)
        assert np.isclose(true_ref, current_true_ref - edge_len)
        assert np.isclose(total_pred, current_total_pred)
        assert np.isclose(true_pred, current_true_pred - edge_len)
        current_total_ref = total_ref
        current_true_ref = true_ref
        current_total_pred = total_pred
        current_true_pred = true_pred

    for edge in to_add:
        ref_tracings.add_edge(*edge)
        u_loc = ref_tracings.nodes[edge[0]]["location"]
        v_loc = ref_tracings.nodes[edge[1]]["location"]
        edge_len = np.linalg.norm(u_loc - v_loc)

        (
            recall,
            precision,
            (true_ref, total_ref, true_pred, total_pred),
        ) = score_foreground(
            gt_bin_mask,
            ref_tracings,
            offset,
            scale,
            0.05,
            "location",
            Metric.RECALL_PRECISION,
            details=True,
        )
        assert np.isclose(total_ref, current_total_ref + edge_len)
        assert np.isclose(true_ref, current_true_ref)
        assert np.isclose(total_pred, current_total_pred)
        assert np.isclose(true_pred, current_true_pred)
        current_total_ref = total_ref
        current_true_ref = true_ref
        current_total_pred = total_pred
        current_true_pred = true_pred
示例#33
0
from PIL import Image
import math
import noise

width, height = (640, 480)
seed = 3600
centerx, centery = (256, 256)
heightmultiplier = 2

data = []

for x in range(0, width):
    a = []
    for y in range(0, height):
        # Perlin noise data
        value = noise.pnoise3(x / width, y / height, seed, persistence=0.4, lacunarity=3, octaves=32) * heightmultiplier

        # Gradient mask
        mask = math.sqrt((centerx - x) ** 2 + (centery - y) ** 2) / width
        a.append(value - mask)

    data.append(a)

im = Image.new("RGB", (width, height))

for idx, x in enumerate(data):
    for idy, y in enumerate(x):
        # Elevation colors
        if y < 0.02:
            im.putpixel((idx, idy), (0, 0, 255))
        elif y < 0.05:
示例#34
0
from matplotlib import animation
from brownian import fast_brownian
import time

RES = 25
SIZE = 200
BROWNIAN = True

frames = 60
pixels = None

def animate(i):
    im = plt.imshow(pixels[:, :, i])

    return im

if __name__ == "__main__":
    pixels = np.zeros((SIZE, SIZE, frames))
    brownian_z_slice = fast_brownian(0, frames, 0.1, 0.25)
    print('generating slices...')
    for f in range(frames):
        for xp in range(SIZE):
            for yp in range(SIZE):
                pixels[xp, yp, f] = noise.pnoise3(xp / RES, yp / RES, brownian_z_slice[f] if BROWNIAN else f / RES)
    print('done')
    fig = plt.figure()
    ax = plt.axes()
    anim = animation.FuncAnimation(fig, animate, frames=frames)
    print('rendering...')
    anim.save('animation-{}.gif'.format(time.time()), writer='imagemagick', fps=60)
    print('done')
def noise(x, y, z, freq=30, level=1):
    return abs(_noise.pnoise3(x / freq, y / freq + level * G.seed, z / freq))
示例#36
0
def gen_planet(planet_res, planet_radius, planet_atm_thickness, roughness):
    """
    Function to generate a random planet texture
    
    Arguments:
        planet_res : [int, int] - Desired resolution of the planet image
        planet_radius: float - Planet radius [m]
        planet_atm_thickness: float - Planet atmosphere thickness [m]
        roughness : int - Roughness of the planet texture
        
    Return values:
        body_surface : pygame.Surface - Complete texture of the planet
    """

    # Create several helpful variables
    # Radius of the outmost part of the atmosphwere [m]
    atm_radius = planet_radius + planet_atm_thickness * 2

    # Planet radius in px on the screen
    planet_radius_px = int(planet_res / 2)

    # Atmosphere radius in pixels on the screen
    atm_radius_px = int(atm_radius / planet_radius * planet_res / 2)

    # Atmosphere thickness in pixels on the screen
    atm_thickness_px = int(planet_atm_thickness * 2 / planet_radius *
                           planet_res / 2)

    ### PLANET SURFACE GENERATION

    # Set step sized for elevation, temperature and humidity map; is a measure of how accurate and how smooth the color gradients will be
    n_elevation_steps = 25
    n_temperature_steps = 8
    n_humidity_steps = 3

    # Generate either earth-like planet with earth-like color scheme, or a randomly colored planet, may look like Mars or a gas planet, both options have 50% probability
    # Earth-like planet
    if random.random() < (1 / 2):
        # Set the base color to the colorspace default
        base_color = [-1, -1, -1]

        # Set the water color to the colorspace default
        water_color = [-1, -1, -1]

        # Set the water color to blue with a slightly green hue
        atm_color = [0, 96, 255]

        # Enable forest effect generation
        trees = 1

        # Randomize ice_transition temperature between 0 and 0.1, temperature at which land starts transitioning to arctic climate
        ice_temperature = random.random() * 0.1

        # Randomize fraction of the planet is covered with clouds between 0% and 50%
        cloud_amt = random.random() * 0.5

    # Randomly colored planet
    else:
        # Generate random planet color
        base_color = [
            random.randint(32, 255),
            random.randint(32, 255),
            random.randint(32, 255)
        ]

        # Vary water and atmosphere color slightly from base color
        bcolor = pygame.Color(base_color[0], base_color[1], base_color[2])
        h, s, l, a = bcolor.hsla
        h = 10
        h_water = (h + 15) % 360
        h_atm = (h + 30) % 360

        # Set water color
        bcolor.hsla = h_water, s, l, a
        water_color = [bcolor.r, bcolor.g, bcolor.b]

        # Set atmosphere color
        bcolor.hsla = h_atm, s, l, a
        atm_color = [bcolor.r, bcolor.g, bcolor.b]

        # Disable forestation effect (due to bad-looking results with randomized colors)
        trees = 0

        # Randomize if poles have ice caps or not, 50% chance for each case
        # No ice caps on poles
        if random.random() < 0.5:
            ice_temperature = 0

        # Ice caps on poles
        else:
            ice_temperature = random.random() * 0.1

        # Randomize fraction of the planet is covered with clouds between 0% and 80%
        cloud_amt = random.random() * 0.8

    # Water elevation, elevation at which the water-land transition happens, randomize between 0 and 1, 0 means no water, 1 means only water
    water_level = random.random()

    # Set elevation above which land transitions to mountainous, summit environment
    mountain_level = 0.8

    # Randomize threshold temperature after which desert colors may be present, values range from 0.4 to 0.7
    desert_temperature = 0.4 + 0.3 * random.random()

    # Create new (alpha-enabled) planet surface with the size of the planet radius [px] on the screen and create PixelArray for pixel-wise access
    planet_surface = pygame.Surface(
        [planet_radius_px * 2, planet_radius_px * 2], pygame.SRCALPHA)
    planet_pxarr = pygame.PixelArray(planet_surface)

    # Generate 3D colorspace that contains all used colors
    cspace = colorspace_3d_linear_interp(n_elevation_steps,
                                         n_temperature_steps, n_humidity_steps,
                                         base_color, water_color, water_level,
                                         ice_temperature, mountain_level,
                                         desert_temperature)

    # Display slice of 3D colorspace for debugging or color point set adjustments
    #show_grad(cspace, 0)

    # Generate different seeds for elevation, temperature, humidity, tree and cloud noise maps
    elevation_seed = random.randint(0, 1000)
    temperature_seed = random.randint(0, 1000)
    humidity_seed = random.randint(0, 1000)
    tree_seed = random.randint(0, 1000)
    cloud_seed = random.randint(0, 1000)

    # Declare noise map lists
    screen_coords_lst = []
    elevation_lst = []
    temperature_lst = []
    humidity_lst = []
    tree_lst = []
    cloud_lst = []

    # Loop through all pixels contained in planet
    for i in range(1, planet_res):  # X-axis
        for j in range(1, planet_res):  # Y-axis

            # Draw round shape, generate perlin noise only for pixels contained in planet shape
            d = ((planet_radius_px - i)**2 + (planet_radius_px - j)**2)**0.5
            if d < planet_radius_px:

                # Create normalized value for distance of current pixel from center of the planet, Value limits: 1 (Pixel is on the edge), 0 (Pixel is in the center)
                d_norm = d / planet_radius_px

                # Create gradient variable, taken from circle function x^2 + y^2 = z^2, but for unit circle
                grad = (1 - d_norm**2)**0.5

                # Set center coordinates for noise generation function
                noise_center_coord_x = (-2 * roughness +
                                        i * roughness / planet_res)
                noise_center_coord_y = (-2 * roughness +
                                        j * roughness / planet_res)

                # Generate elevation, temperature and humidity from 3D perlin-simplex noise. Only 2D needed, 3rd dimension used for randomization
                elevation = (
                    noise.pnoise3(noise_center_coord_x, noise_center_coord_y,
                                  elevation_seed, 20) + 1) / 2
                temperature = (
                    (noise.pnoise3(noise_center_coord_x, noise_center_coord_y,
                                   temperature_seed, 8) + 1) /
                    2) * (-math.cos(2 * math.pi * j / planet_res) + 1) / 2
                humidity = (
                    noise.pnoise3(noise_center_coord_x, noise_center_coord_y,
                                  humidity_seed, 20) + 1) / 2
                tree = (noise.pnoise3(noise_center_coord_x,
                                      noise_center_coord_y, tree_seed, 20) +
                        1) / 2
                cloud = (noise.pnoise3(noise_center_coord_x / 2,
                                       noise_center_coord_y * 2, cloud_seed,
                                       20) + 1) / 2

                # append noise map lists
                screen_coords_lst.append([i, j])
                elevation_lst.append(elevation)
                temperature_lst.append(temperature)
                humidity_lst.append(humidity)
                tree_lst.append(tree)
                cloud_lst.append(cloud)

    # Convert noise map lists to numpy arrays to enable batch processing of the data (needed for normalization of values)
    elevation_arr = np.array(elevation_lst)
    temperature_arr = np.array(temperature_lst)
    humidity_arr = np.array(humidity_lst)
    tree_arr = np.array(tree_lst)
    cloud_arr = np.array(cloud_lst)

    # Normalize perlin noise values, necessary since the noise output never really gets close to 0 and 1 but stays between around 0.3 and 0.7 if not normalized, 0.99999 added since perfectly normalized values caused errors that I did not have time to fix
    elevation_arr_norm = (elevation_arr - elevation_arr.min()) / (
        elevation_arr.max() - elevation_arr.min()) * 0.99999
    temperature_arr_norm = (temperature_arr - temperature_arr.min()) / (
        temperature_arr.max() - temperature_arr.min()) * 0.99999
    humidity_arr_norm = (humidity_arr - humidity_arr.min()) / (
        humidity_arr.max() - humidity_arr.min()) * 0.99999
    tree_arr_norm = (tree_arr - tree_arr.min()) / (tree_arr.max() -
                                                   tree_arr.min()) * 0.99999
    cloud_arr_norm = (cloud_arr - cloud_arr.min()) / (
        cloud_arr.max() - cloud_arr.min()) * 0.99999

    # Loop through all points in the noise map lists
    for point in range(len(screen_coords_lst)):

        # Get pixel color from 3D color space and create pygame color from it
        px_color = cspace[int(
            elevation_arr_norm[point] * n_elevation_steps)][int(
                temperature_arr_norm[point] * n_temperature_steps)][int(
                    humidity_arr_norm[point] * n_humidity_steps)]
        color = pygame.Color(px_color[0], px_color[1], px_color[2])

        # Get HSLA color values to make forestation effect generation easier
        h, s, l, a = color.hsla

        # COLOR POSTPROCESSING
        # Forestation effect, works through lowering lightness of a pixel if it meets several conditions
        if (trees and  # Forestation effect enabled?
                tree_arr_norm[point] > 0.5
                and  # Only generate forestation if tree noise map value is over 0.5
            (water_level + 0.02) < elevation_arr_norm[point] < mountain_level
                and  # Only generate forestation if elevation is between water and mountain level, with some margin
            (ice_temperature + 0.1) < temperature_arr_norm[point]
                and  # Only generate forestation if temperature is over the ice temperature, with some margin
                humidity_arr_norm[point] >
                0.5):  # Only generate forestation if humidity is over 0.5

            # Lower lightness to create forestation effect
            l = l / 2

            # Update color with new HSLA values
            color.hsla = h, s, l, a

        # Cloud generation
        # Generate clouds if cloud noise map value is lower than the cloud fraction that was randomized
        if cloud_arr_norm[point] < cloud_amt:
            # Get color rgb values from current pixel color
            r = color.r
            g = color.g
            b = color.b

            # Blend current pixel color with white to create cloud effect
            color_with_cloud = blend_to_white([r, g, b],
                                              1 - cloud_arr_norm[point])

            # Update color with new RGB values
            color.r = color_with_cloud[0]
            color.g = color_with_cloud[1]
            color.b = color_with_cloud[2]

        # Generate atmospheric glow from increasing view angles to the side of the planet
        # Get distance of pixel from center of planet
        d = ((planet_radius_px - screen_coords_lst[point][0])**2 +
             (planet_radius_px - screen_coords_lst[point][1])**2)**0.5

        # Produce normalized distance value
        d_norm = d / planet_radius_px

        # Create gradient variable that is 1 in the center and 0 at the edges of the planet
        grad = (1 - d_norm**2)**0.5

        # Apply atmospheric tint
        # Get RGB values from current pixel color
        r = color.r
        g = color.g
        b = color.b

        # Find atmosphere color at current pixel
        atm_color_curr_r = atm_color[0] + (255 - atm_color[0]) * grad
        atm_color_curr_g = atm_color[1] + (255 - atm_color[1]) * grad
        atm_color_curr_b = atm_color[2] + (255 - atm_color[2]) * grad

        # Blend atmosphere color with current pixel color using blend mode Multiply to create atmospheric glow effect
        color_with_atm = blend_multiply(
            [r, g, b], [atm_color_curr_r, atm_color_curr_g, atm_color_curr_b])

        # Update color with new RGB values
        color.r = color_with_atm[0]
        color.g = color_with_atm[1]
        color.b = color_with_atm[2]

        # Apply atmosphere glow on texture (to replicate bight light scattering when looking through the atmosphere at a shallow angle)
        h, s, l, a = color.hsla
        l = l + (100 - l) * (1 - grad)**1.5 * 0.75
        s = s * grad

        # Update color with new HSLA values
        color.hsla = h, s, l, a

        # Set pixel to new color
        planet_pxarr[screen_coords_lst[point][0],
                     screen_coords_lst[point][1]] = color

    # Close pixel array to enable blitting
    planet_pxarr.close()

    ### PLANET ATMOSPHERE GRADIENT GENERATION

    # Create new alpha-enabled surface to draw atmosphere layers and finall the planet texture on
    body_surface = pygame.Surface([atm_radius_px * 2, atm_radius_px * 2],
                                  pygame.SRCALPHA)

    # Specify number of layers out of which to draw the atmosphere
    n_atm_layers = 50

    # Draw each atmosphere layer
    for layer in range(n_atm_layers):

        # Set layer radius in pixels, smaller radius for ever layer draw to give effect of different atmosphere layers
        layer_radius = int(atm_radius_px - atm_thickness_px /
                           (n_atm_layers) * layer)

        # Grade color from white (innermost layer) to atm_color (at half drawn atmosphere thickness), outer half of the layer are atm_color, but alpha changes
        # Inner layers
        if layer > n_atm_layers / 2:
            red = atm_color[0] + (255 - atm_color[0]) / (
                n_atm_layers / 2 + 1) * (layer - n_atm_layers / 2)
            green = atm_color[1] + (255 - atm_color[1]) / (
                n_atm_layers / 2 + 1) * (layer - n_atm_layers / 2)
            blue = atm_color[2] + (255 - atm_color[2]) / (
                n_atm_layers / 2 + 1) * (layer - n_atm_layers / 2)

        # Outer layers
        else:
            red = atm_color[0]
            green = atm_color[1]
            blue = atm_color[2]

        # Use alpha values to create a smooth gradient
        alpha = 10 + (200 - 10) / (n_atm_layers - 1) * layer

        # Build new layer color from RGBA values
        layer_color = (red, green, blue, alpha)

        # Draw atmosphere layer
        pygame.draw.circle(body_surface, layer_color,
                           [atm_radius_px, atm_radius_px], layer_radius)

    # Blit atmosphere layer onto surface
    body_surface.blit(planet_surface, [atm_thickness_px, atm_thickness_px])

    # Return surface
    return body_surface
示例#37
0
 def test_perlin_3d_base(self):
     from noise import pnoise3
     x, y, z = 0.1, 0.7, 0.33
     self.assertEqual(pnoise3(x, y, z), pnoise3(x, y, z, base=0))
     self.assertNotEqual(pnoise3(x, y, z), pnoise3(x, y, z, base=5))
     self.assertNotEqual(pnoise3(x, y, z, base=5), pnoise3(x, y, z, base=1))
resolution = 720
aspect_ratio = 16 / 9
n_frames = 30 * 34
fps = 30
num_neurons = 32
num_layers = 8
jitter_factor = 0.5  # The lower the more jittery
noise_scale = 5  # The higher the more movement
plot = True

net = NN(num_neurons=num_neurons)
net.apply(init_normal)
perlin = [[[
    noise.pnoise3(i / (jitter_factor * n_frames),
                  j / num_neurons,
                  k / num_layers,
                  base=j,
                  repeatx=int(1 / jitter_factor),
                  octaves=2) * noise_scale for i in range(n_frames)
] for j in range(num_neurons)] for k in range(num_layers)]

for i in range(n_frames):
    start = time.time()
    print('frame {}/{}'.format(i + 1, n_frames))
    for j in range(len(perlin)):
        for k in range(2, num_layers):
            net.state_dict()['layers.{}.weight'.format(
                (k + 1) * 2)][0][j] = perlin[k][j][i]

    colors = run_net(net, resolution, int(aspect_ratio * resolution))

    colors[0][0] = 1
示例#39
0
	def generate_world(self):
		helpers.log('Generating map...')

		self.__world_height = np.zeros((self.__world_size['y'], self.__world_size['x']))
		self.__world_temp = np.zeros((self.__world_size['y'], self.__world_size['x']))
		self.__world_type_blocks = np.ones((self.__world_size['y'], self.__world_size['x'])) * -1

		helpers.log('\t-| Generating noise, placing blocks...')
		for y in range(self.__world_size['y']):
			for x in range(self.__world_size['x']):
				# gen noise
				height = noise.pnoise3(
					float(x) * self.__scale,
					float(y) * self.__scale,
					self.__seed_height,
					1
				)

				temp = noise.pnoise3(
					float(x) * self.__scale,
					float(y) * self.__scale,
					self.__seed_temp,
					1
				)

				# Just for test smoothing, but does not matter looks bad
				# if x / self.__world_size['x'] < 0.1:
				# 	temp = 0
				# elif x / self.__world_size['x'] > 0.9:
				# 	temp = 0
				# else:
				# 	temp = noise.pnoise3(
				# 		float(x) * self.__scale,
				# 		float(y) * self.__scale,
				# 		self.__seed_temp,
				# 		1
				# 	)

				self.__world_height[y][x] = height
				self.__world_temp[y][x] = temp

				# place water...
				if height < -0.15:
					if temp < -0.2:
						self.__world_type_blocks[y][x] = self.__color_pick.get_id_by_name('ICE')
						continue
					else:
						self.__world_type_blocks[y][x] = self.__color_pick.get_id_by_name('WATER')
						continue

				# place mountains...
				if height > 0.5:
					if temp < 0.45:
						self.__world_type_blocks[y][x] = self.__color_pick.get_id_by_name('SNOW_MOUNTAIN')
						continue
					else:
						self.__world_type_blocks[y][x] = self.__color_pick.get_id_by_name('MOUNTAIN')
						continue

				# place land, grass, snow, sand
				if temp > 0.5:
					self.__world_type_blocks[y][x] = self.__color_pick.get_id_by_name('SAND')
					continue
				elif temp < -0.15:
					self.__world_type_blocks[y][x] = self.__color_pick.get_id_by_name('SNOW')
					continue
				else:
					if temp > 0.1:
						self.__world_type_blocks[y][x] = self.__color_pick.get_id_by_name('GRASS')
						continue
					else:
						self.__world_type_blocks[y][x] = self.__color_pick.get_id_by_name('LAND')
						continue
示例#40
0
 def test_perlin_3d_base(self):
     from noise import pnoise3
     x, y, z = 0.1, 0.7, 0.33
     self.assertEqual(pnoise3(x, y, z), pnoise3(x, y, z, base=0))
     self.assertNotEqual(pnoise3(x, y, z), pnoise3(x, y, z, base=5))
     self.assertNotEqual(pnoise3(x, y, z, base=5), pnoise3(x, y, z, base=1))
示例#41
0
import noise
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D  # needed for 3d projection

RES = 5
SIZE = 20
voxels = np.zeros((SIZE, SIZE, SIZE), dtype=np.bool)

for xp in range(SIZE):
    for yp in range(SIZE):
        for zp in range(SIZE):
            voxels[xp, yp, zp] = True if abs(
                noise.pnoise3(xp / RES, yp / RES, zp / RES)) > .5 else False

colors = np.empty(voxels.shape, dtype=object)
colors[voxels] = 'green'

fig = plt.figure()
ax = fig.gca(projection='3d')
ax.voxels(voxels, facecolors=colors, edgecolor='k')
plt.show()