def makeSlopeMap(self): self.slopeMap = PNMImage() if SAVED_SLOPE_MAPS: fileName = "maps/slope/" + self.name + ".png" if self.slopeMap.read(Filename(fileName)): logging.info("read slopemap from " + fileName) return self.slopeMap = PNMImage(self.terrain.heightMapSize, self.terrain.heightMapSize) self.slopeMap.makeGrayscale() self.slopeMap.setMaxval(65535) size = self.slopeMap.getYSize() getNormal = self.getNormal setGray = self.slopeMap.setGray for x in range(size): for y in range(size): #note getNormal works at the same resolution as the heightmap normal = getNormal(x, y) # feed pixel into image # why is it necessary to invert the y axis I wonder? #logging.info( normal) normal.z /= self.terrain.getSz() normal.normalize() slope = 1.0 - normal.dot(Vec3(0, 0, 1)) setGray(x, y, slope) if SAVED_SLOPE_MAPS: fileName = "maps/slope/" + self.name + ".png" logging.info("saving slopemap to " + fileName) self.slopeMap.write(Filename(fileName))
def loadFlatQuad(self, fullFilename): cm = CardMaker('cm-%s' % fullFilename) cm.setColor(1.0, 1.0, 1.0, 1.0) aspect = base.camLens.getAspectRatio() htmlWidth = 2.0 * aspect * WEB_WIDTH_PIXELS / float(WIN_WIDTH) htmlHeight = 2.0 * float(WEB_HEIGHT_PIXELS) / float(WIN_HEIGHT) cm.setFrame(-htmlWidth / 2.0, htmlWidth / 2.0, -htmlHeight / 2.0, htmlHeight / 2.0) bottomRightX = WEB_WIDTH_PIXELS / float(WEB_WIDTH + 1) bottomRightY = WEB_HEIGHT_PIXELS / float(WEB_HEIGHT + 1) cm.setUvRange(Point2(0, 1 - bottomRightY), Point2(bottomRightX, 1)) card = cm.generate() quad = NodePath(card) jpgFile = PNMImage(WEB_WIDTH, WEB_HEIGHT) smallerJpgFile = PNMImage() readFile = smallerJpgFile.read(Filename(fullFilename)) if readFile: jpgFile.copySubImage(smallerJpgFile, 0, 0) guiTex = Texture('guiTex') guiTex.setupTexture(Texture.TT2dTexture, WEB_WIDTH, WEB_HEIGHT, 1, Texture.TUnsignedByte, Texture.FRgba) guiTex.setMinfilter(Texture.FTLinear) guiTex.load(jpgFile) guiTex.setWrapU(Texture.WMClamp) guiTex.setWrapV(Texture.WMClamp) ts = TextureStage('webTS') quad.setTexture(ts, guiTex) quad.setTransparency(0) quad.setTwoSided(True) quad.setColor(1.0, 1.0, 1.0, 1.0) result = quad else: result = None Texture.setTexturesPower2(1) return result
def from_data(self, texture_data, palettes): from pandac.PandaModules import PNMImage, VBase4D from pandac.PandaModules import Texture as P3DTexture tex_pnm = PNMImage(17*256, 1024) tex_pnm.addAlpha() testpnm = PNMImage(256, 1024) palette = [(x, x, x, 1) for x in range(16)] colors = [] for color in palette: color_list = [c / 15.0 for c in color[:3]] color_list.append(0 if color == (0, 0, 0, 0) else 1) colors.append(VBase4D(*color_list)) for y in range(1024): row = texture_data.image[y] for x in range(256): testpnm.setXelA(x, y, colors[row[x]]) self.texture2 = P3DTexture() self.texture2.load(testpnm) self.texture2.setMagfilter(P3DTexture.FTNearest) self.texture2.setMinfilter(P3DTexture.FTLinear) self.update(tex_pnm, texture_data, palettes)
def loadFlatQuad(self, fullFilename): """Load the flat jpg into a quad.""" assert self.notify.debugStateCall(self) #Texture.setTexturesPower2(AutoTextureScale.ATSUp) #Texture.setTexturesPower2(2) cm = CardMaker('cm-%s'%fullFilename) cm.setColor(1.0, 1.0, 1.0, 1.0) aspect = base.camLens.getAspectRatio() htmlWidth = 2.0*aspect * WEB_WIDTH_PIXELS / float(WIN_WIDTH) htmlHeight = 2.0*float(WEB_HEIGHT_PIXELS) / float(WIN_HEIGHT) # the html area will be center aligned and vertically top aligned #cm.setFrame(-htmlWidth/2.0, htmlWidth/2.0, 1.0 - htmlHeight, 1.0) cm.setFrame(-htmlWidth/2.0, htmlWidth/2.0, - htmlHeight / 2.0, htmlHeight / 2.0) bottomRightX = (WEB_WIDTH_PIXELS) / float( WEB_WIDTH +1) bottomRightY = WEB_HEIGHT_PIXELS / float (WEB_HEIGHT+1) #cm.setUvRange(Point2(0,0), Point2(bottomRightX, bottomRightY)) cm.setUvRange(Point2(0,1-bottomRightY), Point2(bottomRightX,1)) card = cm.generate() quad = NodePath(card) #quad.reparentTo(self.parent) jpgFile = PNMImage(WEB_WIDTH, WEB_HEIGHT) smallerJpgFile = PNMImage() readFile = smallerJpgFile.read(Filename(fullFilename)) if readFile: jpgFile.copySubImage(smallerJpgFile, 0, 0) guiTex = Texture("guiTex") guiTex.setupTexture(Texture.TT2dTexture, WEB_WIDTH, WEB_HEIGHT, 1, Texture.TUnsignedByte, Texture.FRgba) guiTex.setMinfilter(Texture.FTLinear) guiTex.load(jpgFile) #guiTex.setKeepRamImage(True) #guiTex.makeRamImage() guiTex.setWrapU(Texture.WMClamp) guiTex.setWrapV(Texture.WMClamp) ts = TextureStage('webTS') quad.setTexture(ts, guiTex) #quad.setTexScale(ts, 1.0, -1.0) quad.setTransparency(0) quad.setTwoSided(True) quad.setColor(1.0, 1.0, 1.0, 1.0) result= quad else: # if we have an error loading the file, return None to signify an error result = None #Texture.setTexturesPower2(AutoTextureScale.ATSDown) Texture.setTexturesPower2(1) return result
def _createMapTextureCard(self): mapImage = PNMImage(MAP_RESOLUTION, MAP_RESOLUTION) mapImage.fill(*self._bgColor) fgColor = VBase4D(*self._fgColor) for x in range(self._mazeHeight): for y in range(self._mazeWidth): if self._mazeCollTable[y][x] == 1: ax = float(x) / self._mazeWidth * MAP_RESOLUTION invertedY = self._mazeHeight - 1 - y ay = float(invertedY) / self._mazeHeight * MAP_RESOLUTION self._drawSquare(mapImage, int(ax), int(ay), 10, fgColor) mapTexture = Texture('mapTexture') mapTexture.setupTexture(Texture.TT2dTexture, self._maskResolution, self._maskResolution, 1, Texture.TUnsignedByte, Texture.FRgba) mapTexture.setMinfilter(Texture.FTLinear) mapTexture.load(mapImage) mapTexture.setWrapU(Texture.WMClamp) mapTexture.setWrapV(Texture.WMClamp) mapImage.clear() del mapImage cm = CardMaker('map_cardMaker') cm.setFrame(-1.0, 1.0, -1.0, 1.0) map = self.attachNewNode(cm.generate()) map.setTexture(mapTexture, 1) return map
def make_blank(self): from pandac.PandaModules import PNMImage from pandac.PandaModules import Texture as P3DTexture tex_pnm = PNMImage(2, 2) tex_pnm.fill(1, 1, 1) self.texture = P3DTexture() self.texture.load(tex_pnm)
def _createMaskTextureCard(self): """ This will return a NodePath with a card textured with the map mask. It also creates several other members that re needed to change the mask. """ # create and fill empty mask image self._maskImage = PNMImage(self._maskResolution, self._maskResolution, 4) for x in range(self._maskResolution): for y in range(self._maskResolution): #maskImage.setXel(x,y,mapImage.getRed(x/13,y/10),mapImage.getGreen(x/13,y/10),mapImage.getBlue(x/13,y/10)) self._maskImage.setXelA(x,y,0,0,0,1) # create the texture for the mask self.maskTexture = Texture("maskTexture") self.maskTexture.setupTexture(Texture.TT2dTexture, self._maskResolution, self._maskResolution, 1, Texture.TUnsignedByte, Texture.FRgba) self.maskTexture.setMinfilter(Texture.FTLinear) self.maskTexture.setWrapU(Texture.WMClamp) self.maskTexture.setWrapV(Texture.WMClamp) self.maskTexture.load(self._maskImage) base.graphicsEngine.renderFrame() # put the mask texture on a card and return it cm = CardMaker("mask_cardMaker") cm.setFrame(-1.0,1.0,-1.0,1.0) mask = self.attachNewNode(cm.generate()) mask.setTexture(self.maskTexture, 1) mask.setTransparency(1) return mask
def getWaterSurface(manager, polycount=50000, size=(512, 512)): # Get cache directory... cacheDir = manager.get('paths').getConfig().find('cache').get('path') # Check if the data required already exists... cachedWaterSurface = "%s/plane-%dx%d-%dk.bam" % ( cacheDir, size[0], size[1], int(polycount / 1000)) try: return loader.loadModel(cachedWaterSurface) except: pass # Make cache directory if needed... if not os.path.isdir(cacheDir): os.mkdir(cacheDir) # Put in an image... img = PNMImage(*size) img.makeGrayscale() img.fill(0, 0, 0) img.write("%s/black-%dx%d.png" % (cacheDir, size[0], size[1])) # Put in a mesh... ht = HeightfieldTesselator("plane") assert ht.setHeightfield( Filename("%s/black-%dx%d.png" % (cacheDir, size[0], size[1]))) ht.setPolyCount(polycount) ht.setFocalPoint(size[0] * 0.5, size[1] * 0.5) node = ht.generate() node.setPos(-0.5 * size[0], 0.5 * size[1], 0) node.flattenLight() node.writeBamFile(cachedWaterSurface) return node
def calculateTextures(self, terrainTile): size = self.terrain.tileSize + 1 #getNormal = self.getNormal getSlope = terrainTile.slopeMap.getGray #slopeMult = self.terrain.maxHeight / self.terrain.horizontalScale getHeight = terrainTile.image.getGray maxHeight = self.terrain.maxHeight calculateFinalWeight = self.calculateFinalWeight textures = self.textures for tex in textures: tex.image = PNMImage(size, size, 3) for x in range(size): for y in range(size): slope = getSlope(x, y) height = getHeight(x, y) * maxHeight textureWeightTotal = 0.000001 for tex in textures: tex.weight = 0.0 for region in tex.regions: weight = calculateFinalWeight(height, slope, region) tex.weight += weight textureWeightTotal += weight #logging.info( tex.weight) for tex in textures: #logging.info( "setGray(", x, y, " tex.weight / textureWeightTotal =",tex.weight / textureWeightTotal) tex.image.setGray(x, y, tex.weight / textureWeightTotal)
def __init__(self, terrain, x, y): """Builds a Tile for the terrain at input coordinates. Important settings are used directly from the terrain. This allows for easier setting changes, and reduces memory overhead. x and y parameters give the appropriate world coordinates of this tile. """ self.terrain = terrain self.xOffset = x self.yOffset = y self.heightMapDetail = 1 # higher means greater detail self.name = "ID" + str(terrain.id) + "_X" + str(x) + "_Y" + str(y) GeoMipTerrain.__init__(self, name=self.name) self.image = PNMImage() #self.setAutoFlatten(GeoMipTerrain.AFMOff) self.setFocalPoint(self.terrain.focus) self.setAutoFlatten(GeoMipTerrain.AFMOff) self.getRoot().setPos(x, y, 0) if self.terrain.bruteForce: GeoMipTerrain.setBruteforce(self, True) GeoMipTerrain.setBlockSize( self, self.terrain.heightMapSize * self.heightMapDetail) else: GeoMipTerrain.setBlockSize(self, self.terrain.blockSize / 2) #self.setBorderStitching(1) self.setNear(self.terrain.near) self.setFar(self.terrain.far)
def grassTexture(imgSize=(256,256)): """Return a green, 'grassy' texture (PNMImage) of the given image size, produced using 2D Perlin noise.""" # Initialuse the PNMImage object img = PNMImage(*imgSize) # Initalise 4 PerlinNoise2 objects to produce noise at different scales noise1 = PerlinNoise2() noise1.setScale(2.0) noise2 = PerlinNoise2() noise2.setScale(5.0) noise3 = PerlinNoise2() noise3.setScale(0.25) noise4 = PerlinNoise2() noise4.setScale(0.125) # For each pixel in the image, set the red and blue values of the pixel to # constant values, and set the green value of the pixel using all 4 # PerlinNoise2 objects. red = 0.125 # Colour values in PNMImage are doubles in the range [0.0,1.0] blue = 0.0625 for x in xrange(imgSize[0]): for y in xrange(imgSize[1]): img.setRed(x,y,red) img.setBlue(x,y,blue) pos = Vec2(1.0/32*x, 1.0/32*y) img.setGreen(x,y,(0.5 + noise1(pos)*0.0625 + noise2(pos)*0.0625 + noise3(pos)*0.125 + noise4(pos)*0.0625)) return img
def get_heightmap_tex(self, size, filename=None): """Generate texture of map """ mod = self.world_size / size image = PNMImage(size, size) for x in xrange(size): for y in xrange(size): px = x * mod py = y * mod height = self[px, py] color = height / 50 r = 0 g = 0 b = 0 if color > 255: color = 255 if color < 0: color = abs(color) b = color else: g = color image.setPixel(x, y, (r, g, b)) if filename != None: image.write(filename) #for x in xrange(-1, 2): #for y in xrange(-1, 2): #image.setPixel(int(world.chunks_map.charX)+x, int(world.chunks_map.charY)+y, (255, 0, 0)) texture = Texture() texture.load(image) return texture
def export(self, file_name, texture_data): from pandac.PandaModules import PNMImage, VBase4D from pandac.PandaModules import Texture as P3DTexture pnm = PNMImage(256, 1024) self.texture2.store(pnm) pnm.write(file_name)
def _createMapTextureCard(self): """ This will return a NodePath with a card textured with the minimap. The minimap texture is dynamically created from the map data. """ # create and fill empty map image mapImage = PNMImage(MAP_RESOLUTION, MAP_RESOLUTION) blockFiles = [] for i in range(5): blockFiles.append(PNMImage()) #blockFiles[i].read(Filename("mapBlock%i.jpg"%(i+1))) # TODO:maze either reference a set of textures for each piece or fill with color blockFiles[i].read(Filename('phase_4/maps/male_sleeve4New.jpg')) mapImage.fill(0.8, 0.8, 0.8) # iterate through the map data and place a block in the map image where appropriate for x in range( len(self._mazeLayout[0]) ): for y in range( len(self._mazeLayout) ): if self._mazeLayout[y][x]: ax = float(x)/len(self._mazeLayout[0]) * MAP_RESOLUTION ay = float(y)/len(self._mazeLayout) * MAP_RESOLUTION #TODO:maze use different blocks for different wall types or items #mapImage.copySubImage(random.choice(blockFiles), int(ax), int(ay), 20, 20, 32, 32) #TODO:maze find the ideal block texture size for the map so we dont # have to do this strange offset #mapImage.copySubImage(blockFiles[0], int(ax), int(ay), 0, 0, 32, 32) self._drawSquare(mapImage, int(ax), int(ay), 10, VBase4D(0.5, 0.5, 0.5, 1.0)) # create a texture from the map image mapTexture = Texture("mapTexture") mapTexture.setupTexture(Texture.TT2dTexture, self._maskResolution, self._maskResolution, 1, Texture.TUnsignedByte, Texture.FRgba) mapTexture.setMinfilter(Texture.FTLinear) mapTexture.load(mapImage) mapTexture.setWrapU(Texture.WMClamp) mapTexture.setWrapV(Texture.WMClamp) mapImage.clear() del mapImage # put the texture on a card and return it cm = CardMaker("map_cardMaker") cm.setFrame(-1.0,1.0,-1.0,1.0) map = self.attachNewNode(cm.generate()) map.setTexture(mapTexture, 1) return map
def __init__(self, tex, terrain): self.tex = tex self.regions = [] self.terrain = terrain size = self.terrain.tileSize + 1 self.image = PNMImage() self.weight = 0.0
def __createBuffer(self): ''' create the buffer we render in the background into ''' print "I: TexturePainter.__createBuffer" # the window has been modified if WindowManager.activeWindow: # on window resize there seems to be never a active window win = WindowManager.activeWindow.win else: win = base.win # get the window size self.windowSizeX = win.getXSize() self.windowSizeY = win.getYSize() # create a buffer in which we render the model using a shader self.paintMap = Texture() # 1.5.4 cant handle non power of 2 buffers self.modelColorBuffer = createOffscreenBuffer( -3, TEXTUREPAINTER_BACKGROUND_BUFFER_RENDERSIZE[0], TEXTUREPAINTER_BACKGROUND_BUFFER_RENDERSIZE[1] ) #self.windowSizeX, self.windowSizeY) self.modelColorBuffer.addRenderTexture(self.paintMap, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor) self.modelColorCam = base.makeCamera(self.modelColorBuffer, lens=base.cam.node().getLens(), sort=1) # Create a small buffer for the shader program that will fetch the point from the texture made # by the self.modelColorBuffer self.colorPickerImage = PNMImage() self.colorPickerTex = Texture() self.colorPickerBuffer = base.win.makeTextureBuffer( "color picker buffer", 2, 2, self.colorPickerTex, True) self.colorPickerScene = NodePath('color picker scene') self.colorPickerCam = base.makeCamera(self.colorPickerBuffer, lens=base.cam.node().getLens(), sort=2) self.colorPickerCam.reparentTo(self.colorPickerScene) self.colorPickerCam.setY(-2) cm = CardMaker('color picker scene card') cm.setFrameFullscreenQuad() pickerCard = self.colorPickerScene.attachNewNode(cm.generate()) loadPicker = NodePath(PandaNode('pointnode')) loadPicker.setShader(Shader.make(COLOR_PICKER_SHADER), 10001) # Feed the paintmap from the paintBuffer to the shader and initial mouse positions self.colorPickerScene.setShaderInput('paintmap', self.paintMap) self.colorPickerScene.setShaderInput('mousepos', 0, 0, 0, 1) self.colorPickerCam.node().setInitialState(loadPicker.getState())
def fromImageFile(self, filename, tolerance=2, max_depth=5, debugOutput=False): # the source image img = PNMImage() if not img.read(Filename(filename)): self.log.error('Failed to read %s' % filename) return None
def to_data(self, texture): from pandac.PandaModules import PNMImage tex_pnm = PNMImage() texture.texture2.store(tex_pnm) image = [] for y in range(1024): row = [] for x in range(256): gray = tex_pnm.getXel(x, y) pal_i = int(gray[0] * 15.0) row.append(pal_i) image.append(row) return image
def get_map_3d_tex(self, size, filename=None, charPos=None): """Generate texture of map """ mod = self.world_size / size image = PNMImage(size, size) for x in xrange(size): for y in xrange(size): px = x * mod py = y * mod height = self[px, py] if height <= 0: color = (abs(height) / 50) + 50 if color > 255: color = 255 image.setPixel(x, y, (0, 0, 255 - color)) else: if height <= self.config.low_mount_level[1]: color = height / 20 r = 0 g = 50 + color b = 0 image.setPixel(x, y, (r, g, b)) elif height > self.config.low_mount_level[1]: color = height / 50 r = color g = color b = color if r > 255: r = 255 if g > 255: r = 255 if b > 255: b = 255 image.setPixel(x, y, (r, g, b)) if filename != None: image.write(filename) if charPos != None: charX, charY = charPos for x in xrange(-1, 2): for y in xrange(-1, 2): image.setPixel( int(charX / mod) + x, int(charY / mod) + y, (255, 0, 0)) texture = Texture() texture.load(image) return texture
def rotateHue(self, tex, value=0.1): ''' ''' img = PNMImage() tex.store(img) for y in range(img.getReadYSize()): for x in range(img.getReadXSize()): r, g, b = img.getXel(x, y) h, s, v = colorsys.rgb_to_hsv(r, g, b) h += value if h < 0: h += 360 r, g, b = colorsys.hsv_to_rgb(h, s, v) img.setXel(x, y, r, g, b) tex.load(img)
def __startEditor(self, editModel, editTexture, backgroundShader=MODEL_COLOR_SHADER): print "I: TexturePainter.__startEditor" # this is needed as on startup the editor may not have had a window etc. self.__windowEvent() if not editModel or not editTexture: print "W: TexturePainter.__startEditor: model or texture invalid", editModel, editTexture return False self.editModel = editModel self.editTexture = editTexture self.editImage = None self.backgroundShader = backgroundShader if type(self.editTexture) == Texture: # if the image to modify is a texture, create a pnmImage which we modify self.editImage = PNMImage() # copy the image from the texture to the working layer self.editTexture.store(self.editImage) else: self.editImage = self.editTexture # create the brush for painting self.painter = PNMPainter(self.editImage) self.setBrushSettings(*self.getBrushSettings()) self.__updateModel() # start edit messenger.send(EVENT_TEXTUREPAINTER_STARTEDIT) for startEvent in TEXTUREPAINTER_START_PAINT_EVENTS: self.accept(startEvent, self.__startPaint) for stopEvent in TEXTUREPAINTER_STOP_PAINT_EVENTS: self.accept(stopEvent, self.__stopPaint) self.modelColorCam.node().copyLens( WindowManager.activeWindow.camera.node().getLens()) taskMgr.add(self.__paintTask, 'paintTask') #modelModificator.toggleEditmode(False) self.isPainting = False
def createPickingImage(size): ''' create a picking image with uniq colors for each point in the image ''' image = PNMImage(*size) for x in xrange(size[0]): for y in xrange(size[1]): r = x % 256 g = y % 256 b = (x // 256) + (y // 256) * 16 image.setXelVal(x, y, r, g, b) # Reverse way is: # tx = r + ((b%16)*256) # ty = g + ((b//16)*256) imageFilename = 'data/textures/index-%i-%i.png' % (size[0], size[1]) image.write(Filename(imageFilename))
def get_map_2d_tex(self, map2d, factor=1): """Generate texture for map2d, factor - for size [size / factor] """ size = map2d.size / factor image = PNMImage(size, size) for x in xrange(size): for y in xrange(size): px = x * factor py = y * factor if map2d[(px, py)] <= map2d.water_z: image.setPixel(x, y, (0, 0, 100)) else: image.setPixel(x, y, (0, 100, 0)) texture = Texture() texture.load(image) return texture
def transparencyKey(filename): image = PNMImage(GAME+'/textures/effects/'+filename) image.addAlpha() backgroundColor = None for y in range(image.getYSize()): for x in range(image.getXSize()): if backgroundColor == None: backgroundColor = Color(image.getRedVal(x, y), image.getGreenVal(x, y), image.getGreenVal(x, y), 0) if image.getRedVal(x, y) == backgroundColor.R and \ image.getGreenVal(x, y) == backgroundColor.G and \ image.getGreenVal(x, y) == backgroundColor.B: # Transparent image.setAlpha(x, y, 0.0) else: # Opaque image.setAlpha(x, y, 1.0) return image
def _createMaskTextureCard(self): self._maskImage = PNMImage(self._maskResolution, self._maskResolution, 4) for x in range(self._maskResolution): for y in range(self._maskResolution): self._maskImage.setXelA(x, y, 0, 0, 0, 1) self.maskTexture = Texture('maskTexture') self.maskTexture.setupTexture(Texture.TT2dTexture, self._maskResolution, self._maskResolution, 1, Texture.TUnsignedByte, Texture.FRgba) self.maskTexture.setMinfilter(Texture.FTLinear) self.maskTexture.setWrapU(Texture.WMClamp) self.maskTexture.setWrapV(Texture.WMClamp) self.maskTexture.load(self._maskImage) base.graphicsEngine.renderFrame() cm = CardMaker('mask_cardMaker') cm.setFrame(-1.1, 1.1, -1.1, 1.1) mask = self.attachNewNode(cm.generate()) mask.setTexture(self.maskTexture, 1) mask.setTransparency(1) return mask
def load(self, container, name="New Region"): '''Loads a new region, usually from connecting to a server Or starting a new or previously saved region. ''' import base64 self.heightmap = PNMImage() imageString = base64.b64decode(container.heightmap) self.heightmap.read(StringStream(imageString)) self.region_size = (self.heightmap.getXSize() - 1, self.heightmap.getYSize() - 1) position = 0 tileid = 0 total_tiles = self.region_size[0] * self.region_size[1] ranges = [] tiles = [] for tile in container.tiles: tiles.append((tile.id, tile.cityid)) for n in range(len(tiles)): try: ranges.append((tiles[n][0], tiles[n + 1][0] - 1, tiles[n][1])) except: ranges.append((tiles[n][0], total_tiles, tiles[n][1])) for r in ranges: for x in range(r[0], r[1] + 1): #print "r0, r1, x", r[0], r[1], x self.tiles.append(Tile(tileid, r[2])) #print "Len", len(self.tiles) tileid += 1 position = 0 for y in range(self.region_size[1]): for x in range(self.region_size[0]): self.tiles[position].coords = (x, y) position += 1 for city in container.cities: self.newCity(city) messenger.send("generateRegion", [self.heightmap, self.tiles, self.cities, container])
def greenNoise(imgSize=(32,32),scale=0.25): """Return a PNMImage of the given size containing Perlin noise at the given scale in the green colour values of the image pixels.""" # Initialuse the PNMImage object img = PNMImage(*imgSize) # Initalise PerlinNoise2 object noise = PerlinNoise2() noise.setScale(scale) # Fill in the pixels of img, setting the red and blue values of each pixel # to 0 and the green value to Perlin noise. for x in xrange(imgSize[0]): for y in xrange(imgSize[1]): img.setRed(x,y,0) img.setBlue(x,y,0) pos = Vec2(1.0/32*x, 1.0/32*y) img.setGreen(x,y,(noise(pos)+1.0)/2.0) return img
def __init__(self, *args): ''' ''' ShowBase.__init__(self) base.setBackgroundColor(0, 0, 0) self.mdl = self.loader.loadModel("data/models/vehicles/vehicle01.egg") self.mdl.reparentTo(render) # Add the Skybox self.skybox = self.loader.loadModel("data/models/skybox.egg") t = Texture() # t.load(PNMImage("../skybox/skybox_tronic.png")) t.load(PNMImage("../skybox/test.png")) self.skybox.setTexture(t) self.skybox.setBin("background", 1) self.skybox.setDepthWrite(0) self.skybox.setDepthTest(0) self.skybox.setLightOff() self.skybox.setScale(10000) self.skybox.reparentTo(render)
def makeHeightMap(self): """Generate a new heightmap image. Panda3d GeoMipMaps require an image from which to build and update their height field. This function creates the correct image using the tile's position and the Terrain's getHeight() function. """ if SAVED_HEIGHT_MAPS: fileName = "maps/height/" + self.name + ".png" self.getRoot().setTag('EditableTerrain', '1') if self.image.read(Filename(fileName)): logging.info("read heightmap from " + fileName) return heightMapSize = self.terrain.tileSize * self.heightMapDetail + 1 self.image = PNMImage(heightMapSize, heightMapSize, 1, 65535) ySize = self.image.getYSize() - 1 getHeight = self.terrain.getHeight setGray = self.image.setGray xo = self.xOffset yo = self.yOffset d = self.heightMapDetail for x in range(self.image.getXSize()): for y in range(ySize + 1): height = getHeight(x / d + xo, y / d + yo) # feed pixel into image # why is it necessary to invert the y axis I wonder? setGray(x, ySize - y, height) #self.postProcessImage() if SAVED_HEIGHT_MAPS: fileName = "maps/height/" + self.name + ".png" logging.info("saving heightmap to " + fileName) self.image.write(Filename(fileName))
def make_blocks_texmap(self): images = [] # 0 - sand images.append( PNMImage('res/textures/{0}sand.png'.format(Config().tex_suffix))) # 1 - land images.append( PNMImage('res/textures/{0}land.png'.format(Config().tex_suffix))) # 2 - low_mount images.append( PNMImage("res/textures/{0}low_mount.png".format( Config().tex_suffix))) # 3 - mid_mount images.append( PNMImage("res/textures/{0}mid_mount.png".format( Config().tex_suffix))) # 4 - high_mount images.append( PNMImage("res/textures/{0}high_mount.png".format( Config().tex_suffix))) d = images[0].getReadXSize() # 16 x 16 textures size = d * self.map_size image_all = PNMImage(size, size) n = 0 for i in xrange(0, size, d): for j in xrange(0, size, d): image_all.copySubImage(images[n], j, i) n += 1 if n >= len(images): break if n >= len(images): break self['world_blocks'] = Texture() self['world_blocks'].load(image_all) self['world_blocks'].setMagfilter(Texture.FTLinearMipmapLinear) self['world_blocks'].setMinfilter(Texture.FTLinearMipmapLinear)