Beispiel #1
0
    def postInit(self):
        #
        # initialize game content
        #
        # camera
        base.camLens.setNearFar(1.0, 10000)
        base.camLens.setFov(75)

        a = 33
        base.camera.setPos(0, -a, a + 3)  #80)
        # collision
        base.cTrav = CollisionTraverser("base collision traverser")
        base.cHandler = CollisionHandlerEvent()
        base.cPusher = CollisionHandlerPusher()
        base.cQueue = CollisionHandlerQueue()
        base.globalClock = ClockObject.getGlobalClock()
        base.cHandler.addInPattern('%fn-into-%in')
        base.cHandler.addOutPattern('%fn-out-%in')
        base.cHandler.addAgainPattern('%fn-again-%in')
        # ai init
        base.AIworld = AIWorld(render)
        # 3d manager
        base.audio3d = Audio3DManager(base.sfxManagerList[0], camera)
        # manager
        self.archiveManager = ArchiveManager()
        self.mapManager = MapManager()
        self.initHeroInfo = None
        # Lock
        self.lock = threading.Lock()
        self.gameThread = None

        self.filters = CommonFilters(base.win, base.cam)
        # UI
        self.menu = Menu()
        self.option = Option()
        self.archive = Archive()
        self.death = Death()
        # self.oobe()
        #self.Archive_status = 0
        # self.menuMusic = loader.loadMusic("assets/audio/menuMusic.ogg")
        # self.menuMusic.setLoop(True)
        # self.fightMusic = loader.loadMusic("assets/audio/fightMusic.ogg")
        # self.fightMusic.setLoop(True)
        # base.audio3d = Audio3DManager(base.sfxManagerList[0], camera)

        self.titleVideo, self.titleCard = loadVideo('title.mp4')

        self.isInited = False
        self.isSkip = False
        self.isRenew = False
        #
        # Event handling
        #
        self.accept("escape", self.__escape)

        #
        # Start with the menu
        #
        self.request("Menu")
Beispiel #2
0
    def __init__(self):
        self.tasks = []
        self.running = False

        # Variables to be loaded during run
        self.screen = None
        self.save = None
        self.network = None
        self.mapsize = [768, 576]

        # Variables that can be loaded now
        self.loader = NetworkLoader()
        self.mapManager = MapManager(self.mapsize)
Beispiel #3
0
    def __escape(self):
        if self.state == "Menu":
            self.gameThread = None
            self.quit()
        elif self.state == "Game":
            archive = MapManager.ToDict(self.mapManager)
            self.archiveManager.SaveArchive(self.archive.v[0], archive)
            self.mapManager.room.request("Idle")
            base.musicManager.stopAllSounds()
            base.sfxManagerList[0].stopAllSounds()

            self.request("Menu")
        else:
            self.request("Menu")
Beispiel #4
0
def test():
    result = {}

    MapMgr = MapManager()
    #print sorted(MapMgr.all_blocks)

    #print "In test block_area:"
    MapMgr.block_area(MapMgr.top_blocks)
    #print sorted(MapMgr.all_blocks)
    if sorted(MapMgr.all_blocks) != sorted([5, 6, 7, 21, 22, 32]):
        result['block_area'] = 'Fault'

    #print "In test unblock_area:"
    MapMgr.unblock_area(MapMgr.top_blocks)
    if sorted(MapMgr.all_blocks) != sorted(
        [7, 41, 42, 8, 11, 12, 5, 22, 21, 6, 32]):
        #print sorted(MapMgr.all_blocks)
        #print sorted([7,41,42,8,11,12,5,22,21,6,32])
        result['unblock_area'] = 'Fault'

    if result == {}:
        return 'No faults'
    else:
        return result
 def buildBaseMap(self):        
     self.mapManager = MapManager( roi = self.roi )
     self.renderer.AddActor( self.mapManager.getBaseMapActor() )
class StructuredGridPlot(DV3DPlot):  
    
    def __init__( self,  **args ):
        DV3DPlot.__init__( self,  **args )
        self.iOrientation = 0

        self.variables = {}
        self.metadata = {}

        self.isValid = True
        self.configDialog = None
        self.stereoEnabled = 0
        self.inputSpecs = {}


        self.pipelineBuilt = False
        self.baseMapActor = None
        self.enableBasemap = True
        self.map_opacity = [ 0.4, 0.4 ]
        self.skipIndex = 1
        self.roi = None
        self.shapefilePolylineActors = {}
        self.basemapLineSpecs = {}

    def processToggleClippingCommand( self, args, config_function ):
        if args and args[0] == "InitConfig": 
            self.toggleClipping( args[1] )

    def processBasemapOpacityCommand( self, args, config_function ):
        opacity = config_function.value
        if args and args[0] == "StartConfig":
            pass
        elif args and args[0] == "Init":
            oval = config_function.initial_value
            self.mapManager.setMapOpacity( oval )
            self.render()
        elif args and args[0] == "EndConfig":
            self.processConfigParameterChange( opacity )
        elif args and args[0] == "InitConfig":
            pass
        elif args and args[0] == "Open":
            pass
        elif args and args[0] == "Close":
            pass
        elif args and args[0] == "UpdateConfig":
            value = args[2].GetValue()
            oscale = opacity.getValues()
            oscale[ args[1] ] = value
            self.mapManager.setMapOpacity(  oscale )
            opacity.setValues( oscale )
            self.render()
                
    def processVerticalScalingCommand( self, args, config_function ):
#        print "processVerticalScalingCommand: ", str(args)
        verticalScale = config_function.value
        if args and args[0] == "StartConfig":
            ispec = self.inputSpecs[ 0 ] 
            wbounds = ispec.getDataBounds()
            self.zscaleBoxWidget.On()
            self.zscaleBoxWidget.PlaceWidget(wbounds)
        elif args and args[0] == "Init":
            ispec = self.inputSpecs[ 0 ] 
            zsval = config_function.initial_value
#             plotType = ispec.getMetadata('plotType')
#             if plotType == 'xyt':
#                 tval = ispec.getMetadata('time')
#                 if tval: zsval = 10.0 / len( tval )
#             else: 
#                 lval = ispec.getMetadata('lev')
#                 if tval: zsval = 10.0 / len( lval )
#             verticalScale.setValues( [ zsval ] )
            self.setZScale( zsval  )
            verticalScale.setValue( 'count', 1 )
            self.zscaleBoxWidget = vtk.vtkBoxWidget()
            self.zscaleBoxWidget.SetInteractor( self.renderWindowInteractor )
            self.zscaleBoxWidget.SetPlaceFactor(1.0)
            self.zscaleBoxWidget.HandlesOff()
            oprop = self.zscaleBoxWidget.GetOutlineProperty() 
            oprop.SetColor( 0.0, 0.0, 0.0 )
            oprop.SetLineWidth( 2.0 )
            self.zscaleBoxWidget.SetEnabled(1) 
            self.zscaleBoxWidget.Off() 
        elif args and args[0] == "EndConfig":
            vscale = verticalScale.getValues()
            self.setZScale( vscale )
            self.zscaleBoxWidget.Off() 
            self.processConfigParameterChange( verticalScale )
        elif args and args[0] == "InitConfig":
            self.updateTextDisplay( config_function.label )
            bbar = self.getInteractionButtons()
            self.skipIndex = 2
            for islider in range(4): bbar.setSliderVisibility(  islider, islider < len(config_function.sliderLabels)  )
        elif args and args[0] == "Open":
            pass
        elif args and args[0] == "Close":
            pass
        elif args and args[0] == "UpdateConfig":
            ispec = self.inputSpecs[ 0 ] 
            vscale = args[2].GetValue()
            verticalScale.setValues( [ vscale ] )
            wbounds = ispec.getDataBounds( zscale=vscale )
            self.zscaleBoxWidget.PlaceWidget( wbounds )


#     def onKeyEvent(self, eventArgs ):
#         key = eventArgs[0]
#         md = self.getInputSpec().getMetadata()
#         if (  key == 'r'  ):
#             self.resetCamera()              
#         elif ( md and ( md.get('plotType','')=='xyz' ) and ( key == 't' )  ):
#             self.showInteractiveLens = not self.showInteractiveLens 
#             self.render() 
#         else:
#             return DV3DPlot.onKeyEvent( self, eventArgs )
#         return 1

    def getRangeBounds( self, input_index = 0 ):
        ispec = self.inputSpecs[ input_index ] 
        return ispec.getRangeBounds()  

    def setZScale( self, zscale_data, input_index = 0, **args ):
        self.setInputZScale( zscale_data, input_index, **args )

    def setRangeBounds( self, rbounds, input_index = 0 ):
        ispec = self.inputSpecs[ input_index ] 
        ispec.rangeBounds[:] = rbounds[:] 

    def setMaxScalarValue(self, iDType ):  
        if iDType   == vtk.VTK_UNSIGNED_CHAR:   self._max_scalar_value = 255
        elif iDType == vtk.VTK_UNSIGNED_SHORT:  self._max_scalar_value = 256*256-1
        elif iDType == vtk.VTK_SHORT:           self._max_scalar_value = 256*128-1
        else:                                   self._max_scalar_value = self.getRangeBounds()[1]  

    def decimateImage( self, image, decx, decy ):
        image.Update()
        dims = image.GetDimensions()
        image_size = dims[0] * dims[1]
        result = image
        if image_size > MAX_IMAGE_SIZE:
            resample = vtk.vtkImageShrink3D()
            resample.SetInput( image )
            resample.SetShrinkFactors( decx, decy, 1 )
            result = resample.GetOutput() 
            result.Update()
        return result

    def getScaleBounds(self):
        return [ 0.5, 100.0 ]
    
    def setInputZScale(self, zscale_data, input_index=0, **args  ):
        input = self.variable_reader.output( input_index )
        spacing = input.GetSpacing()
        ix, iy, iz = spacing
        sz = zscale_data[0]
        if iz <> sz:
#            print " PVM >---------------> Change input zscale: %.4f -> %.4f" % ( iz, sz )
            input.SetSpacing( ix, iy, sz )  
            input.Modified() 
            self.processScaleChange( spacing, ( ix, iy, sz ) )
        return input
    
    def getDataRangeBounds(self, inputIndex=0 ):
        ispec = self.getInputSpec( inputIndex )
        return ispec.getDataRangeBounds() if ispec else None

    def onSlicerLeftButtonPress( self, caller, event ):
        self.currentButton = self.LEFT_BUTTON   
        return 0

    def processScaleChange( self, old_spacing, new_spacing ):
        pass
#        self.updateModule()

    def onSlicerRightButtonPress( self, caller, event ):
        self.currentButton = self.RIGHT_BUTTON
        return 0
        
    def getAxes(self):
        pass

    def input( self, input_index = 0 ):
        plotButtons = self.getInteractionButtons()
        cf = plotButtons.getConfigFunction('VerticalScaling')
        if cf <> None:
            zscale_data = cf.value.getValues()
            input = self.setInputZScale( zscale_data, input_index  )
        else: 
            input = self.variable_reader.output( input_index )
        return input

    def isBuilt(self):
        return self.pipelineBuilt
    
    def initializeInputs( self, **args ):
        nOutputs = self.variable_reader.nOutputs()
        for inputIndex in range( nOutputs ):
            ispec = self.variable_reader.outputSpec( inputIndex )
            self.inputSpecs[inputIndex] = ispec 
            if self.roi == None:  
                self.roi = ispec.metadata.get( 'bounds', None )  
            self.intiTime( ispec, **args )
        self.initMetadata()
        
        
    def initMetadata(self):
        spec = self.inputSpecs[0]
        attributes = spec.metadata.get( 'attributes' , None )
#        print " Init Metadata, attributes = ", str( attributes )
        if attributes:
            self.metadata['var_name'] = attributes.get(  'long_name',  attributes.get(  'name', None ) )
            self.metadata['var_units'] = attributes.get('units', '' )

    def intiTime(self, ispec, **args):
        try:
            t = cdtime.reltime( 0, self.variable_reader.referenceTimeUnits )
            if t.cmp( cdtime.reltime( 0, ispec.referenceTimeUnits ) ) == 1:
                self.variable_reader.referenceTimeUnits = ispec.referenceTimeUnits 
            tval = args.get( 'timeValue', None )
            if tval: self.timeValue = cdtime.reltime( float( args[ 'timeValue' ] ), ispec.referenceTimeUnits )
        except:
            self.timeValue = 0.0

    def execute(self, **args ):
        if not self.isBuilt(): 
            self.initializeInputs()        
            self.buildPipeline()
            self.buildBaseMap()
            self.fetchPlotButtons()
            self.initializeConfiguration() 
            self.pipelineBuilt = True
                           
        self.updateModule( **args )                
        self.render()                            
    
    def getScalarRange( self, input_index = 0 ):
        ispec = self.inputSpecs[ input_index ] 
        return ispec.scalarRange
    
    def basemapLinesVisibilityOn(self):
        for actor_list in self.shapefilePolylineActors.values():
            for actor in actor_list: 
                if actor: actor.VisibilityOn()  

    def basemapLinesVisibilityOff(self):
        for actor_list in self.shapefilePolylineActors.values():
            for actor in actor_list: 
                if actor: actor.VisibilityOff()  

    def createBasemapPolyline( self, type, **args ):
        ispec = self.getInputSpec(0)  
        md = ispec.getMetadata()
        latLonGrid = md.get( 'latLonGrid', True )
        if latLonGrid:
            line_specs = self.basemapLineSpecs.get( type, None )
            thickness = int( round( line_specs[0] ) ) if line_specs else 0
            density = int( round( line_specs[1] ) ) if line_specs else 1
            resTypes = [ "invisible", "low", "medium", "high" ]
            if (thickness > 0) and ( density > 0 ):
                rgb=self.getLayerColor( type ) 
                textFilePath = os.path.join( os.path.dirname(__file__), "data", type, "index.txt" )
                s=shapeFileReader()
                s.setColors(rgb)
                s.setWidth( thickness )
                polys=s.getPolyLines( self.roi, textFilePath, resTypes[ density ] )        
                self.renderer.AddActor(polys)
                origin = self.planeWidgetZ.GetOrigin()
                pos = polys.GetPosition()
                pos1 = [ pos[0], pos[1], origin[2] ]
                polys.SetPosition( pos1 )
                polys_list = self.shapefilePolylineActors.get( type, [ None, None, None, None, None ] ) 
                polys_list[ density ] = polys
                self.shapefilePolylineActors[ type ] = polys_list   
 
    def setBasemapLineSpecs( self, shapefile_type, value ):
        self.basemapLineSpecs[shapefile_type] = value
        npixels = int( round( value[0] ) )
        density = int( round( value[1] ) )
        polys_list = self.shapefilePolylineActors.get( shapefile_type, [ None, None, None, None, None ] ) 
        try:
            selected_polys = polys_list[ density ]
            if not selected_polys:
                if npixels: 
                    self.createBasemapPolyline( shapefile_type )
            else:
                for polys in polys_list:
                    if polys:
                        polys.SetVisibility( npixels and ( id(polys) == id(selected_polys) ) )
                selected_polys.GetProperty().SetLineWidth( npixels )           
            self.render()
        except IndexError:
            print>>sys.stderr, " setBasemapLineSpecs: Density too large: %d " % density

    def setBasemapCoastlineLineSpecs( self, value, **args ):
        self.setBasemapLineSpecs('coastline', value )

    def setBasemapStatesLineSpecs( self, value, **args ):
        self.setBasemapLineSpecs('states', value )

    def setBasemapLakesLineSpecs( self, value, **args ):
        self.setBasemapLineSpecs('lakes', value )
        
    def setBasemapCountriesLineSpecs( self, value, **args ):
        self.setBasemapLineSpecs('countries', value )

    def getBasemapLineSpecs( self, shapefile_type ):
        return self.basemapLineSpecs.get( shapefile_type, None )
        
    def getBasemapCoastlineLineSpecs( self, **args ):
        return self.getBasemapLineSpecs('coastline' )
        
    def getBasemapStatesLineSpecs( self, **args ):
        return self.getBasemapLineSpecs('states' )

    def getBasemapLakesLineSpecs( self, **args ):
        return self.getBasemapLineSpecs('lakes' )

    def getBasemapCountriesLineSpecs( self, **args ):
        return self.getBasemapLineSpecs('countries' )



    def getInputSpec( self, input_index=0 ):
        return self.inputSpecs.get( input_index, None )

    def getDataValue( self, image_value, input_index = 0 ):
        ispec = self.inputSpecs[ input_index ] 
        return ispec.getDataValue( image_value )

    def getTimeAxis(self):
        ispec = self.getInputSpec()     
        timeAxis = ispec.getMetadata('time') if ispec else None
        return timeAxis
                    
    def getDataValues( self, image_value_list, input_index = 0 ):
        ispec = self.inputSpecs[ input_index ] 
        return ispec.getDataValues( image_value_list )  
        
    def getImageValue( self, data_value, input_index = 0 ):
        ispec = self.inputSpecs[ input_index ] 
        return ispec.getImageValue( data_value )  
    
    def getImageValues( self, data_value_list, input_index = 0 ):
        ispec = self.inputSpecs[ input_index ] 
        return ispec.getImageValues( data_value_list )  

    def scaleToImage( self, data_value, input_index = 0 ):
        ispec = self.inputSpecs[ input_index ] 
        return ispec.scaleToImage( data_value )  

#     def finalizeLeveling( self, cmap_index=0 ):
#         ispec = self.inputSpecs[ cmap_index ] 
#         ispec.addMetadata( { 'colormap' : self.getColormapSpec(), 'orientation' : self.iOrientation } ) 
#         return DV3DPlot.finalizeLeveling( self, cmap_index=0 )
 

    def initializeConfiguration( self, cmap_index=0, **args ):
        ispec = self.inputSpecs[ cmap_index ] 
        args['units'] = ispec.units
        self.buildConfigurationButton()
        self.buttonBarHandler.initializeConfigurations( **args )
        ispec.addMetadata( { 'colormap' : self.getColormapSpec(), 'orientation' : self.iOrientation } ) 
#        self.updateSliceOutput()


    def getMapOpacity(self):
        return self.map_opacity
    
    def setMapOpacity(self, opacity_vals, **args ):
        self.map_opacity = opacity_vals
        self.updateMapOpacity() 

    def updateMapOpacity(self, cmap_index=0 ):
        if self.baseMapActor:
            self.baseMapActor.SetOpacity( self.map_opacity[0] )
            self.render()

    def showInteractiveLens(self): 
        pass

    def updateLensDisplay(self, screenPos, coord):
        pass
           
    def buildBaseMap(self):        
        self.mapManager = MapManager( roi = self.roi )
        self.renderer.AddActor( self.mapManager.getBaseMapActor() )

#         if self.baseMapActor <> None: self.renderer.RemoveActor( self.baseMapActor )               
#         world_map =  None  
#         map_border_size = 20 
#             
#         self.y0 = -90.0  
#         self.x0 =  0.0  
#         dataPosition = None
#         if world_map == None:
#             self.map_file = defaultMapFile
#             self.map_cut = defaultMapCut
#         else:
#             self.map_file = world_map[0].name
#             self.map_cut = world_map[1]
#         
#         self.world_cut =  -1 
#         if  (self.roi <> None): 
#             roi_size = [ self.roi[1] - self.roi[0], self.roi[3] - self.roi[2] ] 
#             scale = (self.roi[1] - self.roi[0])/300.0
#             border_size = map_border_size * scale
#             map_cut_size = [ roi_size[0] + 2*border_size, roi_size[1] + 2*border_size ]
#             if map_cut_size[0] > 360.0: map_cut_size[0] = 360.0
#             if map_cut_size[1] > 180.0: map_cut_size[1] = 180.0
#         else:
#             map_cut_size = [ 360, 180 ]
#             
#                   
#         if self.world_cut == -1: 
#             if  (self.roi <> None): 
#                 if roi_size[0] > 180:             
#                     self.ComputeCornerPosition()
#                     self.world_cut = self.NormalizeMapLon( self.x0 )
#                 else:
#                     dataPosition = [ ( self.roi[1] + self.roi[0] ) / 2.0, ( self.roi[3] + self.roi[2] ) / 2.0 ]
#             else:
#                 dataPosition = [ 180, 0 ] # [ ( self.roi[1] + self.roi[0] ) / 2.0, ( self.roi[3] + self.roi[2] ) / 2.0 ]
#         else:
#             self.world_cut = self.map_cut
#         
#         self.imageInfo = vtk.vtkImageChangeInformation()        
#         image_reader = vtk.vtkJPEGReader()      
#         image_reader.SetFileName(  self.map_file )
#         image_reader.Update()
#         baseImage = image_reader.GetOutput() 
#         new_dims, scale = None, None
#         if dataPosition == None: 
#             old_dims = baseImage.GetDimensions()   
#             baseImage = self.RollMap( baseImage ) 
#             new_dims = baseImage.GetDimensions()
#             scale = [ 360.0/new_dims[0], 180.0/new_dims[1], 1 ]
#         else:                       
#             baseImage, new_dims = self.getBoundedMap( baseImage, dataPosition, map_cut_size, border_size )             
#             scale = [ map_cut_size[0]/new_dims[0], map_cut_size[1]/new_dims[1], 1 ]
#                           
#         self.baseMapActor = vtk.vtkImageActor()
#         self.baseMapActor.SetOrigin( 0.0, 0.0, 0.0 )
#         self.baseMapActor.SetScale( scale )
#         self.baseMapActor.SetOrientation( 0.0, 0.0, 0.0 )
#         self.baseMapActor.SetOpacity( self.map_opacity[0] )
#         mapCorner = [ self.x0, self.y0 ]
#                 
#         self.baseMapActor.SetPosition( mapCorner[0], mapCorner[1], 0.1 )
#         if vtk.VTK_MAJOR_VERSION <= 5:  self.baseMapActor.SetInput(baseImage)
#         else:                           self.baseMapActor.SetInputData(baseImage)        
#         self.mapCenter = [ self.x0 + map_cut_size[0]/2.0, self.y0 + map_cut_size[1]/2.0 ] 
#         self.mapSize = map_cut_size      
#         self.renderer.AddActor( self.baseMapActor )


#     def ComputeCornerPosition( self ):
#         if (self.roi[0] >= -180) and (self.roi[1] <= 180) and (self.roi[1] > self.roi[0]):
#             self.x0 = -180
#             return 180
#         if (self.roi[0] >= 0) and (self.roi[1] <= 360) and (self.roi[1] > self.roi[0]):
#             self.x0 = 0
#             return 0
#         self.x0 = int( round( self.roi[0] / 10.0 ) ) * 10
# #        print "Set Corner pos: %s, roi: %s " % ( str(self.x0), str(self.roi) )
        
#     def GetScaling( self, image_dims ):
#         return 360.0/image_dims[0], 180.0/image_dims[1],  1
# 
#     def GetFilePath( self, cut ):
#         filename = "%s_%d.jpg" % ( self.world_image, cut )
#         return os.path.join( self.data_dir, filename ) 
#         
#     def RollMap( self, baseImage ):
# #        baseImage.Update()
#         if self.world_cut  == self.map_cut: return baseImage
#         baseExtent = baseImage.GetExtent()
#         baseSpacing = baseImage.GetSpacing()
#         x0 = baseExtent[0]
#         x1 = baseExtent[1]
#         newCut = self.NormalizeMapLon( self.world_cut )
#         delCut = newCut - self.map_cut
# #        print "  %%%%%% Roll Map %%%%%%: world_cut=%.1f, map_cut=%.1f, newCut=%.1f " % ( float(self.world_cut), float(self.map_cut), float(newCut) )
#         imageLen = x1 - x0 + 1
#         sliceSize =  imageLen * ( delCut / 360.0 )
#         sliceCoord = int( round( x0 + sliceSize) )        
#         extent = list( baseExtent ) 
#         
#         extent[0:2] = [ x0, x0 + sliceCoord - 1 ]
#         clip0 = vtk.vtkImageClip()
#         if vtk.VTK_MAJOR_VERSION <= 5:  clip0.SetInput( baseImage )
#         else:                           clip0.SetInputData( baseImage )                
#         clip0.SetOutputWholeExtent( extent[0], extent[1], extent[2], extent[3], extent[4], extent[5] )
#         
#         extent[0:2] = [ x0 + sliceCoord, x1 ]
#         clip1 = vtk.vtkImageClip()
#         if vtk.VTK_MAJOR_VERSION <= 5:  clip1.SetInput( baseImage )
#         else:                           clip1.SetInputData( baseImage )                
#         clip1.SetOutputWholeExtent( extent[0], extent[1], extent[2], extent[3], extent[4], extent[5] )
#         
#         append = vtk.vtkImageAppend()
#         append.SetAppendAxis( 0 )
#         append.SetInputConnection ( clip1.GetOutputPort() )
#         append.AddInputConnection ( clip0.GetOutputPort() )           
#         
#         imageInfo = vtk.vtkImageChangeInformation()
#         imageInfo.SetInputConnection( append.GetOutputPort() ) 
#         imageInfo.SetOutputOrigin( 0.0, 0.0, 0.0 )
#         imageInfo.SetOutputExtentStart( 0, 0, 0 )
#         imageInfo.SetOutputSpacing( baseSpacing[0], baseSpacing[1], baseSpacing[2] )
#         
#         imageInfo.Update()
#         result = imageInfo.GetOutput() 
#         return result
# 
#     def NormalizeMapLon( self, lon ): 
#         while ( lon < ( self.map_cut - 0.01 ) ): lon = lon + 360
#         return ( ( lon - self.map_cut ) % 360 ) + self.map_cut
# 
#     def getBoundedMap( self, baseImage, dataLocation, map_cut_size, map_border_size ):
#         baseExtent = baseImage.GetExtent()
#         baseSpacing = baseImage.GetSpacing()
#         x0 = baseExtent[0]
#         x1 = baseExtent[1]
#         y0 = baseExtent[2]
#         y1 = baseExtent[3]
#         imageLen = [ x1 - x0 + 1, y1 - y0 + 1 ]
#         selectionDim = [ map_cut_size[0]/2, map_cut_size[1]/2 ]
#         dataXLoc = dataLocation[0]
#         imageInfo = vtk.vtkImageChangeInformation()
#         dataYbounds = [ dataLocation[1]-selectionDim[1], dataLocation[1]+selectionDim[1] ]
#         vertExtent = [ y0, y1 ]
#         bounded_dims = None
#         if dataYbounds[0] > -90.0:
#             yOffset = dataYbounds[0] + 90.0
#             extOffset = int( round( ( yOffset / 180.0 ) * imageLen[1] ) )
#             vertExtent[0] = y0 + extOffset
#             self.y0 = dataYbounds[0]
#         if dataYbounds[1] < 90.0:
#             yOffset = 90.0 - dataYbounds[1]
#             extOffset = int( round( ( yOffset / 180.0 ) * imageLen[1] ) )
#             vertExtent[1] = y1 - extOffset
#             
#         overlapsBorder = ( self.NormalizeMapLon(dataLocation[0]-selectionDim[0]) > self.NormalizeMapLon(dataLocation[0]+selectionDim[0]) )
#         if overlapsBorder:
#             cut0 = self.NormalizeMapLon( dataXLoc + selectionDim[0] )
#             sliceSize =  imageLen[0] * ( ( cut0 - self.map_cut ) / 360.0 )
#             sliceCoord = int( round( x0 + sliceSize) )        
#             extent = list( baseExtent )         
#             extent[0:2] = [ x0, x0 + sliceCoord - 1 ]
#             clip0 = vtk.vtkImageClip()
#             if vtk.VTK_MAJOR_VERSION <= 5:  clip0.SetInput( baseImage )
#             else:                           clip0.SetInputData( baseImage )                
#             clip0.SetOutputWholeExtent( extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5] )
#             size0 = extent[1] - extent[0] + 1
#         
#             self.x0 = dataLocation[0] - selectionDim[0]
#             cut1 = self.NormalizeMapLon( self.x0 ) 
#             sliceSize =  imageLen[0] * ( ( cut1 - self.map_cut )/ 360.0 )
#             sliceCoord = int( round( x0 + sliceSize) )       
#             extent[0:2] = [ x0 + sliceCoord, x1 ]
#             clip1 = vtk.vtkImageClip()
#             if vtk.VTK_MAJOR_VERSION <= 5:  clip1.SetInput( baseImage )
#             else:                           clip1.SetInputData( baseImage )                
#             clip1.SetOutputWholeExtent( extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5] )
#             size1 = extent[1] - extent[0] + 1
# #            print "Set Corner pos: %s, cuts: %s " % ( str(self.x0), str( (cut0, cut1) ) )
#         
#             append = vtk.vtkImageAppend()
#             append.SetAppendAxis( 0 )
#             if vtk.VTK_MAJOR_VERSION <= 5:  
#                 append.AddInput( clip1.GetOutput() )          
#                 append.AddInput( clip0.GetOutput() )
#             else:
#                 append.AddInputData( clip1.GetOutput() )          
#                 append.AddInputData( clip0.GetOutput() )
#             bounded_dims = ( size0 + size1, vertExtent[1] - vertExtent[0] + 1 )
#             
#             imageInfo.SetInputConnection( append.GetOutputPort() ) 
# 
#         else:
#                         
#             self.x0 = dataXLoc - selectionDim[0]
#             cut0 = self.NormalizeMapLon( self.x0 )
#             sliceSize =  imageLen[0] * ( ( cut0 - self.map_cut ) / 360.0 )
#             sliceCoord = int( round( x0 + sliceSize) )        
#             extent = list( baseExtent )         
#             extent[0] = x0 + sliceCoord - 1
#         
#             cut1 = self.NormalizeMapLon( dataXLoc + selectionDim[0] )
#             sliceSize =  imageLen[0] * ( ( cut1 - self.map_cut ) / 360.0 )
#             sliceCoord = int( round( x0 + sliceSize) )       
#             extent[1] = x0 + sliceCoord
#             clip = vtk.vtkImageClip()
#             if vtk.VTK_MAJOR_VERSION <= 5:  clip.SetInput( baseImage )
#             else:                           clip.SetInputData( baseImage )                
#             clip.SetOutputWholeExtent( extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5] )
#             bounded_dims = ( extent[1] - extent[0] + 1, vertExtent[1] - vertExtent[0] + 1 )
# #            print "Set Corner pos: %s, dataXLoc: %s " % ( str(self.x0), str( (dataXLoc, selectionDim[0]) ) )
# 
#             imageInfo.SetInputConnection( clip.GetOutputPort() ) 
#                        
#         imageInfo.SetOutputOrigin( 0.0, 0.0, 0.0 )
#         imageInfo.SetOutputExtentStart( 0, 0, 0 )
#         imageInfo.SetOutputSpacing( baseSpacing[0], baseSpacing[1], baseSpacing[2] )
#         imageInfo.Update() 
#                
#         result = imageInfo.GetOutput() 
#         return result, bounded_dims

    def init(self, **args ):
        init_args = args[ 'init' ]      
        n_cores = args.get( 'n_cores', 32 )    
        lut = self.getLUT()
        self.variable_reader = StructuredDataReader( init_specs=init_args, **args )
        self.variable_reader.execute( )       
        self.createRenderer( **args )
        interface = init_args[2]
        self.execute( )
        self.initializePlots()
        self.initCamera( 700.0 )
        self.start()

    def gminit( self, var1, var2, **args ): 
        var_list = [ var1 ]
        if id(var2) <> id(None): var_list.append( var2 )
        self.variable_reader = StructuredDataReader( vars=var_list, otype=self.type, **args )
        self.variable_reader.execute( )       
        self.createRenderer( **args )
        self.execute( )
        self.initializePlots()
        self.initCamera()
        self.start()
        
    def stepAnimation(self, **args):
        timestamp = self.variable_reader.stepAnimation()
        self.execute( )
        if timestamp:   self.updateTextDisplay( "Timestep: %s" % str( timestamp ) )
        else:           self.updateTextDisplay( "" )
        DV3DPlot.stepAnimation(self, **args)

    def onResizeEvent(self):
        self.updateTextDisplay( None, True )
        
    def updateTextDisplay( self, text=None, render=False ):
        if text <> None:
            metadata = self.getMetadata()
            var_name = metadata.get( 'var_name', '')
            var_units = metadata.get( 'var_units', '')
            self.labelBuff = "%s (%s)\n%s" % ( var_name, var_units, str(text) )
        DV3DPlot.updateTextDisplay( self, None, render )
            
    def toggleClipping(self, clipping_on ):
        if clipping_on:   self.clipOn()
        else:             self.clipOff()
        
    def clipOn(self):
        self.clipper.On()
        self.executeClip()

    def clipOff(self):
        self.clipper.Off()      
Beispiel #7
0
'''
Created on 08.09.2007

@author: mac
'''

from MapManager import MapManager
from MQTTConnector import MQTTConnector

mapManager = MapManager('../resources/hbf.png', 266,
                        '../resources/model/FFM-HBhf.osgb', 2, 0, 1)

c = MQTTConnector("192.168.12.6", 1883, mapManager)
c.connect()
Beispiel #8
0
cell_score_min = -0.2
cell_score_max = 0.2
Width = 10
#SET YOUR MAP SIZE HERE!
(x, y) = (5, 5)
#SET YOUR MAP SIZE HERE!
actions = ["up", "down", "left", "right"]

board = Canvas(master, width=x * Width, height=y * Width)
score = 1
restart = False
walk_reward = -0.04

#Start timing map generation
startMapGen = time.time()
mm = MapManager()

#SET YOUR MAP TYPE HERE!
#choices=['core', 'lava', 'random', 'simplex']
walls, specials, player = mm.createMap(x, y, 'simplex')
#SET YOUR MAP TYPE HERE!

#Display map generation timing
endMapGen = time.time()
print("Total map generation and validation time :", endMapGen - startMapGen,
      " seconds")

playerInit = (player[0], player[1])

cell_scores = {}
Beispiel #9
0
 def buildBaseMap(self):
     self.mapManager = MapManager(roi=self.roi)
     self.renderer.AddActor(self.mapManager.getBaseMapActor())
Beispiel #10
0
class StructuredGridPlot(DV3DPlot):
    def __init__(self, **args):
        DV3DPlot.__init__(self, **args)
        self.iOrientation = 0

        self.variables = {}
        self.metadata = {}

        self.isValid = True
        self.configDialog = None
        self.stereoEnabled = 0
        self.inputSpecs = {}

        self.pipelineBuilt = False
        self.baseMapActor = None
        self.enableBasemap = True
        self.map_opacity = [0.4, 0.4]
        self.skipIndex = 1
        self.roi = None
        self.shapefilePolylineActors = {}
        self.basemapLineSpecs = {}

    def processBasemapOpacityCommand(self, args, config_function):
        opacity = config_function.value
        if args and args[0] == "StartConfig":
            pass
        elif args and args[0] == "Init":
            oval = config_function.initial_value
            self.mapManager.setMapOpacity(oval)
        elif args and args[0] == "EndConfig":
            self.processConfigParameterChange(opacity)
        elif args and args[0] == "InitConfig":
            pass
        elif args and args[0] == "Open":
            pass
        elif args and args[0] == "Close":
            pass
        elif args and args[0] == "UpdateConfig":
            value = args[2].GetValue()
            oscale = opacity.getValues()
            oscale[args[1]] = value
            self.mapManager.setMapOpacity(oscale)
            opacity.setValues(oscale)
            self.render()

    def processVerticalScalingCommand(self, args, config_function):
        #        print "processVerticalScalingCommand: ", str(args)
        verticalScale = config_function.value
        if args and args[0] == "StartConfig":
            ispec = self.inputSpecs[0]
            wbounds = ispec.getDataBounds()
            self.zscaleBoxWidget = vtk.vtkBoxWidget()
            self.zscaleBoxWidget.SetInteractor(self.renderWindowInteractor)
            self.zscaleBoxWidget.SetPlaceFactor(1.0)
            self.zscaleBoxWidget.HandlesOff()
            self.zscaleBoxWidget.SetEnabled(1)
            oprop = self.zscaleBoxWidget.GetOutlineProperty()
            oprop.SetColor(0.0, 0.0, 0.0)
            oprop.SetLineWidth(2.0)
            self.zscaleBoxWidget.On()
            self.zscaleBoxWidget.PlaceWidget(wbounds)
#            print "  >>>>>>>>>>>>>>>>>>>>> Place box widget: ", str( wbounds )
        elif args and args[0] == "Init":
            self.parameter_initializing = True
            ispec = self.inputSpecs[0]
            zsval = config_function.initial_value
            #             plotType = ispec.getMetadata('plotType')
            #             if plotType == 'xyt':
            #                 tval = ispec.getMetadata('time')
            #                 if tval: zsval = 10.0 / len( tval )
            #             else:
            #                 lval = ispec.getMetadata('lev')
            #                 if tval: zsval = 10.0 / len( lval )
            #             verticalScale.setValues( [ zsval ] )
            self.setZScale(zsval)
            verticalScale.setValue('count', 1)
            self.parameter_initializing = False
        elif args and args[0] == "EndConfig":
            vscale = verticalScale.getValues()
            self.setZScale(vscale)
            self.zscaleBoxWidget.Off()
            self.zscaleBoxWidget.SetEnabled(0)
            self.zscaleBoxWidget = None
            self.processConfigParameterChange(verticalScale)
        elif args and args[0] == "InitConfig":
            self.updateTextDisplay(config_function.label)
            bbar = self.getInteractionButtons()
            self.skipIndex = 2
            for islider in range(4):
                bbar.setSliderVisibility(
                    islider, islider < len(config_function.sliderLabels))
        elif args and args[0] == "Open":
            pass
        elif args and args[0] == "Close":
            pass
        elif args and args[0] == "UpdateConfig":
            ispec = self.inputSpecs[0]
            vscale = args[2].GetValue()
            verticalScale.setValues([vscale])
            wbounds = ispec.getDataBounds(zscale=vscale)
            self.zscaleBoxWidget.PlaceWidget(wbounds)

#     def onKeyEvent(self, eventArgs ):
#         key = eventArgs[0]
#         md = self.getInputSpec().getMetadata()
#         if (  key == 'r'  ):
#             self.resetCamera()
#         elif ( md and ( md.get('plotType','')=='xyz' ) and ( key == 't' )  ):
#             self.showInteractiveLens = not self.showInteractiveLens
#             self.render()
#         else:
#             return DV3DPlot.onKeyEvent( self, eventArgs )
#         return 1

    def getRangeBounds(self, input_index=0):
        ispec = self.inputSpecs[input_index]
        return ispec.getRangeBounds()

    def setZScale(self, zscale_data, input_index=0, **args):
        self.setInputZScale(zscale_data, input_index, **args)

    def setRangeBounds(self, rbounds, input_index=0):
        ispec = self.inputSpecs[input_index]
        ispec.rangeBounds[:] = rbounds[:]

    def setMaxScalarValue(self, iDType):
        if iDType == vtk.VTK_UNSIGNED_CHAR: self._max_scalar_value = 255
        elif iDType == vtk.VTK_UNSIGNED_SHORT:
            self._max_scalar_value = 256 * 256 - 1
        elif iDType == vtk.VTK_SHORT:
            self._max_scalar_value = 256 * 128 - 1
        else:
            self._max_scalar_value = self.getRangeBounds()[1]

    def decimateImage(self, image, decx, decy):
        image.Update()
        dims = image.GetDimensions()
        image_size = dims[0] * dims[1]
        result = image
        if image_size > MAX_IMAGE_SIZE:
            resample = vtk.vtkImageShrink3D()
            resample.SetInput(image)
            resample.SetShrinkFactors(decx, decy, 1)
            result = resample.GetOutput()
            result.Update()
        return result

    def getScaleBounds(self):
        return [0.5, 100.0]

    def setInputZScale(self, zscale_data, input_index=0, **args):
        input = self.variable_reader.output(input_index)
        if input is not None:
            spacing = input.GetSpacing()
            ix, iy, iz = spacing
            sz = zscale_data[0]
            if iz <> sz:
                #            print " PVM >---------------> Change input zscale: %.4f -> %.4f" % ( iz, sz )
                input.SetSpacing(ix, iy, sz)
                input.Modified()
                self.processScaleChange(spacing, (ix, iy, sz))
        return input

    def getDataRangeBounds(self, inputIndex=0):
        ispec = self.getInputSpec(inputIndex)
        return ispec.getDataRangeBounds() if ispec else None

    def onSlicerLeftButtonPress(self, caller, event):
        self.currentButton = self.LEFT_BUTTON
        return 0

    def processScaleChange(self, old_spacing, new_spacing):
        pass
#        self.updateModule()

    def onSlicerRightButtonPress(self, caller, event):
        self.currentButton = self.RIGHT_BUTTON
        return 0

    def getAxes(self):
        pass

    def input(self, input_index=0):
        plotButtons = self.getInteractionButtons()
        cf = plotButtons.getConfigFunction('VerticalScaling')
        if cf <> None:
            zscale_data = cf.value.getValues()
            input = self.setInputZScale(zscale_data, input_index)
        else:
            input = self.variable_reader.output(input_index)
        return input

    def isBuilt(self):
        return self.pipelineBuilt

    def initializeInputs(self, **args):
        nOutputs = self.variable_reader.nOutputs()
        for inputIndex in range(nOutputs):
            ispec = self.variable_reader.outputSpec(inputIndex)
            self.inputSpecs[inputIndex] = ispec
            if self.roi == None:
                self.roi = ispec.metadata.get('bounds', None)
            self.intiTime(ispec, **args)
        self.initMetadata()

    def initMetadata(self):
        spec = self.inputSpecs[0]
        attributes = spec.metadata.get('attributes', None)
        #        print " Init Metadata, attributes = ", str( attributes )
        if attributes:
            self.metadata['var_name'] = attributes.get(
                'long_name', attributes.get('name', None))
            self.metadata['var_units'] = attributes.get('units', '')

    def intiTime(self, ispec, **args):
        try:
            t = cdtime.reltime(0, self.variable_reader.referenceTimeUnits)
            if t.cmp(cdtime.reltime(0, ispec.referenceTimeUnits)) == 1:
                self.variable_reader.referenceTimeUnits = ispec.referenceTimeUnits
            tval = args.get('timeValue', None)
            if tval:
                self.timeValue = cdtime.reltime(float(args['timeValue']),
                                                ispec.referenceTimeUnits)
        except:
            self.timeValue = 0.0

    def execute(self, **args):
        if not self.isBuilt():
            self.initializeInputs()
            self.buildPipeline()
            self.buildBaseMap()
            self.fetchPlotButtons()
            self.initializeConfiguration()
            self.pipelineBuilt = True

        self.updateModule(**args)
        self.render()

    def getScalarRange(self, input_index=0):
        ispec = self.inputSpecs[input_index]
        return ispec.scalarRange

    def basemapLinesVisibilityOn(self):
        for actor_list in self.shapefilePolylineActors.values():
            for actor in actor_list:
                if actor: actor.VisibilityOn()

    def basemapLinesVisibilityOff(self):
        for actor_list in self.shapefilePolylineActors.values():
            for actor in actor_list:
                if actor: actor.VisibilityOff()

    def createBasemapPolyline(self, type, **args):
        ispec = self.getInputSpec(0)
        md = ispec.getMetadata()
        latLonGrid = md.get('latLonGrid', True)
        if latLonGrid:
            line_specs = self.basemapLineSpecs.get(type, None)
            thickness = int(round(line_specs[0])) if line_specs else 0
            density = int(round(line_specs[1])) if line_specs else 1
            resTypes = ["invisible", "low", "medium", "high"]
            if (thickness > 0) and (density > 0):
                rgb = self.getLayerColor(type)
                textFilePath = os.path.join(os.path.dirname(__file__), "data",
                                            type, "index.txt")
                s = shapeFileReader()
                s.setColors(rgb)
                s.setWidth(thickness)
                polys = s.getPolyLines(self.roi, textFilePath,
                                       resTypes[density])
                self.renderer.AddActor(polys)
                origin = self.planeWidgetZ.GetOrigin()
                pos = polys.GetPosition()
                pos1 = [pos[0], pos[1], origin[2]]
                polys.SetPosition(pos1)
                polys_list = self.shapefilePolylineActors.get(
                    type, [None, None, None, None, None])
                polys_list[density] = polys
                self.shapefilePolylineActors[type] = polys_list

    def setBasemapLineSpecs(self, shapefile_type, value):
        self.basemapLineSpecs[shapefile_type] = value
        npixels = int(round(value[0]))
        density = int(round(value[1]))
        polys_list = self.shapefilePolylineActors.get(
            shapefile_type, [None, None, None, None, None])
        try:
            selected_polys = polys_list[density]
            if not selected_polys:
                if npixels:
                    self.createBasemapPolyline(shapefile_type)
            else:
                for polys in polys_list:
                    if polys:
                        polys.SetVisibility(npixels and
                                            (id(polys) == id(selected_polys)))
                selected_polys.GetProperty().SetLineWidth(npixels)
            self.render()
        except IndexError:
            print >> sys.stderr, " setBasemapLineSpecs: Density too large: %d " % density

    def setBasemapCoastlineLineSpecs(self, value, **args):
        self.setBasemapLineSpecs('coastline', value)

    def setBasemapStatesLineSpecs(self, value, **args):
        self.setBasemapLineSpecs('states', value)

    def setBasemapLakesLineSpecs(self, value, **args):
        self.setBasemapLineSpecs('lakes', value)

    def setBasemapCountriesLineSpecs(self, value, **args):
        self.setBasemapLineSpecs('countries', value)

    def getBasemapLineSpecs(self, shapefile_type):
        return self.basemapLineSpecs.get(shapefile_type, None)

    def getBasemapCoastlineLineSpecs(self, **args):
        return self.getBasemapLineSpecs('coastline')

    def getBasemapStatesLineSpecs(self, **args):
        return self.getBasemapLineSpecs('states')

    def getBasemapLakesLineSpecs(self, **args):
        return self.getBasemapLineSpecs('lakes')

    def getBasemapCountriesLineSpecs(self, **args):
        return self.getBasemapLineSpecs('countries')

    def getInputSpec(self, input_index=0):
        if input_index == -1: input_index = len(self.inputSpecs) - 1
        return self.inputSpecs.get(input_index, None)

    def getDataValue(self, image_value, input_index=0):
        ispec = self.inputSpecs[input_index]
        return ispec.getDataValue(image_value)

    def getTimeAxis(self):
        ispec = self.getInputSpec()
        timeAxis = ispec.getMetadata('time') if ispec else None
        return timeAxis

    def getDataValues(self, image_value_list, input_index=0):
        ispec = self.inputSpecs[input_index]
        return ispec.getDataValues(image_value_list)

    def getImageValue(self, data_value, input_index=0):
        ispec = self.inputSpecs[input_index]
        return ispec.getImageValue(data_value)

    def getImageValues(self, data_value_list, input_index=0):
        ispec = self.inputSpecs[input_index]
        return ispec.getImageValues(data_value_list)

    def scaleToImage(self, data_value, input_index=0):
        ispec = self.inputSpecs[input_index]
        return ispec.scaleToImage(data_value)

#     def finalizeLeveling( self, cmap_index=0 ):
#         ispec = self.inputSpecs[ cmap_index ]
#         ispec.addMetadata( { 'colormap' : self.getColormapSpec(), 'orientation' : self.iOrientation } )
#         return DV3DPlot.finalizeLeveling( self, cmap_index=0 )

    def initializeConfiguration(self, cmap_index=0, **args):
        ispec = self.inputSpecs[cmap_index]
        args['units'] = ispec.units
        self.buildConfigurationButton()
        self.buttonBarHandler.initializeConfigurations(**args)
        for plotItem in self.plotConstituents.items():
            if self.isConstituentConfigEnabled(plotItem[0]):
                ispec.addMetadata({
                    '-'.join(['colormap', plotItem[0]]):
                    self.getColormapSpec(plotItem[0]),
                    'orientation':
                    self.iOrientation
                })
#        self.updateSliceOutput()

    def getMapOpacity(self):
        return self.map_opacity

    def setMapOpacity(self, opacity_vals, **args):
        self.map_opacity = opacity_vals
        self.updateMapOpacity()

    def updateMapOpacity(self, cmap_index=0):
        if self.baseMapActor:
            self.baseMapActor.SetOpacity(self.map_opacity[0])
            self.render()

    def showInteractiveLens(self):
        pass

    def updateLensDisplay(self, screenPos, coord):
        pass

    def buildBaseMap(self):
        self.mapManager = MapManager(roi=self.roi)
        self.renderer.AddActor(self.mapManager.getBaseMapActor())

#         if self.baseMapActor <> None: self.renderer.RemoveActor( self.baseMapActor )
#         world_map =  None
#         map_border_size = 20
#
#         self.y0 = -90.0
#         self.x0 =  0.0
#         dataPosition = None
#         if world_map == None:
#             self.map_file = defaultMapFile
#             self.map_cut = defaultMapCut
#         else:
#             self.map_file = world_map[0].name
#             self.map_cut = world_map[1]
#
#         self.world_cut =  -1
#         if  (self.roi <> None):
#             roi_size = [ self.roi[1] - self.roi[0], self.roi[3] - self.roi[2] ]
#             scale = (self.roi[1] - self.roi[0])/300.0
#             border_size = map_border_size * scale
#             map_cut_size = [ roi_size[0] + 2*border_size, roi_size[1] + 2*border_size ]
#             if map_cut_size[0] > 360.0: map_cut_size[0] = 360.0
#             if map_cut_size[1] > 180.0: map_cut_size[1] = 180.0
#         else:
#             map_cut_size = [ 360, 180 ]
#
#
#         if self.world_cut == -1:
#             if  (self.roi <> None):
#                 if roi_size[0] > 180:
#                     self.ComputeCornerPosition()
#                     self.world_cut = self.NormalizeMapLon( self.x0 )
#                 else:
#                     dataPosition = [ ( self.roi[1] + self.roi[0] ) / 2.0, ( self.roi[3] + self.roi[2] ) / 2.0 ]
#             else:
#                 dataPosition = [ 180, 0 ] # [ ( self.roi[1] + self.roi[0] ) / 2.0, ( self.roi[3] + self.roi[2] ) / 2.0 ]
#         else:
#             self.world_cut = self.map_cut
#
#         self.imageInfo = vtk.vtkImageChangeInformation()
#         image_reader = vtk.vtkJPEGReader()
#         image_reader.SetFileName(  self.map_file )
#         image_reader.Update()
#         baseImage = image_reader.GetOutput()
#         new_dims, scale = None, None
#         if dataPosition == None:
#             old_dims = baseImage.GetDimensions()
#             baseImage = self.RollMap( baseImage )
#             new_dims = baseImage.GetDimensions()
#             scale = [ 360.0/new_dims[0], 180.0/new_dims[1], 1 ]
#         else:
#             baseImage, new_dims = self.getBoundedMap( baseImage, dataPosition, map_cut_size, border_size )
#             scale = [ map_cut_size[0]/new_dims[0], map_cut_size[1]/new_dims[1], 1 ]
#
#         self.baseMapActor = vtk.vtkImageActor()
#         self.baseMapActor.SetOrigin( 0.0, 0.0, 0.0 )
#         self.baseMapActor.SetScale( scale )
#         self.baseMapActor.SetOrientation( 0.0, 0.0, 0.0 )
#         self.baseMapActor.SetOpacity( self.map_opacity[0] )
#         mapCorner = [ self.x0, self.y0 ]
#
#         self.baseMapActor.SetPosition( mapCorner[0], mapCorner[1], 0.1 )
#         if vtk.VTK_MAJOR_VERSION <= 5:  self.baseMapActor.SetInput(baseImage)
#         else:                           self.baseMapActor.SetInputData(baseImage)
#         self.mapCenter = [ self.x0 + map_cut_size[0]/2.0, self.y0 + map_cut_size[1]/2.0 ]
#         self.mapSize = map_cut_size
#         self.renderer.AddActor( self.baseMapActor )

#     def ComputeCornerPosition( self ):
#         if (self.roi[0] >= -180) and (self.roi[1] <= 180) and (self.roi[1] > self.roi[0]):
#             self.x0 = -180
#             return 180
#         if (self.roi[0] >= 0) and (self.roi[1] <= 360) and (self.roi[1] > self.roi[0]):
#             self.x0 = 0
#             return 0
#         self.x0 = int( round( self.roi[0] / 10.0 ) ) * 10
# #        print "Set Corner pos: %s, roi: %s " % ( str(self.x0), str(self.roi) )

#     def GetScaling( self, image_dims ):
#         return 360.0/image_dims[0], 180.0/image_dims[1],  1
#
#     def GetFilePath( self, cut ):
#         filename = "%s_%d.jpg" % ( self.world_image, cut )
#         return os.path.join( self.data_dir, filename )
#
#     def RollMap( self, baseImage ):
# #        baseImage.Update()
#         if self.world_cut  == self.map_cut: return baseImage
#         baseExtent = baseImage.GetExtent()
#         baseSpacing = baseImage.GetSpacing()
#         x0 = baseExtent[0]
#         x1 = baseExtent[1]
#         newCut = self.NormalizeMapLon( self.world_cut )
#         delCut = newCut - self.map_cut
# #        print "  %%%%%% Roll Map %%%%%%: world_cut=%.1f, map_cut=%.1f, newCut=%.1f " % ( float(self.world_cut), float(self.map_cut), float(newCut) )
#         imageLen = x1 - x0 + 1
#         sliceSize =  imageLen * ( delCut / 360.0 )
#         sliceCoord = int( round( x0 + sliceSize) )
#         extent = list( baseExtent )
#
#         extent[0:2] = [ x0, x0 + sliceCoord - 1 ]
#         clip0 = vtk.vtkImageClip()
#         if vtk.VTK_MAJOR_VERSION <= 5:  clip0.SetInput( baseImage )
#         else:                           clip0.SetInputData( baseImage )
#         clip0.SetOutputWholeExtent( extent[0], extent[1], extent[2], extent[3], extent[4], extent[5] )
#
#         extent[0:2] = [ x0 + sliceCoord, x1 ]
#         clip1 = vtk.vtkImageClip()
#         if vtk.VTK_MAJOR_VERSION <= 5:  clip1.SetInput( baseImage )
#         else:                           clip1.SetInputData( baseImage )
#         clip1.SetOutputWholeExtent( extent[0], extent[1], extent[2], extent[3], extent[4], extent[5] )
#
#         append = vtk.vtkImageAppend()
#         append.SetAppendAxis( 0 )
#         append.SetInputConnection ( clip1.GetOutputPort() )
#         append.AddInputConnection ( clip0.GetOutputPort() )
#
#         imageInfo = vtk.vtkImageChangeInformation()
#         imageInfo.SetInputConnection( append.GetOutputPort() )
#         imageInfo.SetOutputOrigin( 0.0, 0.0, 0.0 )
#         imageInfo.SetOutputExtentStart( 0, 0, 0 )
#         imageInfo.SetOutputSpacing( baseSpacing[0], baseSpacing[1], baseSpacing[2] )
#
#         imageInfo.Update()
#         result = imageInfo.GetOutput()
#         return result
#
#     def NormalizeMapLon( self, lon ):
#         while ( lon < ( self.map_cut - 0.01 ) ): lon = lon + 360
#         return ( ( lon - self.map_cut ) % 360 ) + self.map_cut
#
#     def getBoundedMap( self, baseImage, dataLocation, map_cut_size, map_border_size ):
#         baseExtent = baseImage.GetExtent()
#         baseSpacing = baseImage.GetSpacing()
#         x0 = baseExtent[0]
#         x1 = baseExtent[1]
#         y0 = baseExtent[2]
#         y1 = baseExtent[3]
#         imageLen = [ x1 - x0 + 1, y1 - y0 + 1 ]
#         selectionDim = [ map_cut_size[0]/2, map_cut_size[1]/2 ]
#         dataXLoc = dataLocation[0]
#         imageInfo = vtk.vtkImageChangeInformation()
#         dataYbounds = [ dataLocation[1]-selectionDim[1], dataLocation[1]+selectionDim[1] ]
#         vertExtent = [ y0, y1 ]
#         bounded_dims = None
#         if dataYbounds[0] > -90.0:
#             yOffset = dataYbounds[0] + 90.0
#             extOffset = int( round( ( yOffset / 180.0 ) * imageLen[1] ) )
#             vertExtent[0] = y0 + extOffset
#             self.y0 = dataYbounds[0]
#         if dataYbounds[1] < 90.0:
#             yOffset = 90.0 - dataYbounds[1]
#             extOffset = int( round( ( yOffset / 180.0 ) * imageLen[1] ) )
#             vertExtent[1] = y1 - extOffset
#
#         overlapsBorder = ( self.NormalizeMapLon(dataLocation[0]-selectionDim[0]) > self.NormalizeMapLon(dataLocation[0]+selectionDim[0]) )
#         if overlapsBorder:
#             cut0 = self.NormalizeMapLon( dataXLoc + selectionDim[0] )
#             sliceSize =  imageLen[0] * ( ( cut0 - self.map_cut ) / 360.0 )
#             sliceCoord = int( round( x0 + sliceSize) )
#             extent = list( baseExtent )
#             extent[0:2] = [ x0, x0 + sliceCoord - 1 ]
#             clip0 = vtk.vtkImageClip()
#             if vtk.VTK_MAJOR_VERSION <= 5:  clip0.SetInput( baseImage )
#             else:                           clip0.SetInputData( baseImage )
#             clip0.SetOutputWholeExtent( extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5] )
#             size0 = extent[1] - extent[0] + 1
#
#             self.x0 = dataLocation[0] - selectionDim[0]
#             cut1 = self.NormalizeMapLon( self.x0 )
#             sliceSize =  imageLen[0] * ( ( cut1 - self.map_cut )/ 360.0 )
#             sliceCoord = int( round( x0 + sliceSize) )
#             extent[0:2] = [ x0 + sliceCoord, x1 ]
#             clip1 = vtk.vtkImageClip()
#             if vtk.VTK_MAJOR_VERSION <= 5:  clip1.SetInput( baseImage )
#             else:                           clip1.SetInputData( baseImage )
#             clip1.SetOutputWholeExtent( extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5] )
#             size1 = extent[1] - extent[0] + 1
# #            print "Set Corner pos: %s, cuts: %s " % ( str(self.x0), str( (cut0, cut1) ) )
#
#             append = vtk.vtkImageAppend()
#             append.SetAppendAxis( 0 )
#             if vtk.VTK_MAJOR_VERSION <= 5:
#                 append.AddInput( clip1.GetOutput() )
#                 append.AddInput( clip0.GetOutput() )
#             else:
#                 append.AddInputData( clip1.GetOutput() )
#                 append.AddInputData( clip0.GetOutput() )
#             bounded_dims = ( size0 + size1, vertExtent[1] - vertExtent[0] + 1 )
#
#             imageInfo.SetInputConnection( append.GetOutputPort() )
#
#         else:
#
#             self.x0 = dataXLoc - selectionDim[0]
#             cut0 = self.NormalizeMapLon( self.x0 )
#             sliceSize =  imageLen[0] * ( ( cut0 - self.map_cut ) / 360.0 )
#             sliceCoord = int( round( x0 + sliceSize) )
#             extent = list( baseExtent )
#             extent[0] = x0 + sliceCoord - 1
#
#             cut1 = self.NormalizeMapLon( dataXLoc + selectionDim[0] )
#             sliceSize =  imageLen[0] * ( ( cut1 - self.map_cut ) / 360.0 )
#             sliceCoord = int( round( x0 + sliceSize) )
#             extent[1] = x0 + sliceCoord
#             clip = vtk.vtkImageClip()
#             if vtk.VTK_MAJOR_VERSION <= 5:  clip.SetInput( baseImage )
#             else:                           clip.SetInputData( baseImage )
#             clip.SetOutputWholeExtent( extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5] )
#             bounded_dims = ( extent[1] - extent[0] + 1, vertExtent[1] - vertExtent[0] + 1 )
# #            print "Set Corner pos: %s, dataXLoc: %s " % ( str(self.x0), str( (dataXLoc, selectionDim[0]) ) )
#
#             imageInfo.SetInputConnection( clip.GetOutputPort() )
#
#         imageInfo.SetOutputOrigin( 0.0, 0.0, 0.0 )
#         imageInfo.SetOutputExtentStart( 0, 0, 0 )
#         imageInfo.SetOutputSpacing( baseSpacing[0], baseSpacing[1], baseSpacing[2] )
#         imageInfo.Update()
#
#         result = imageInfo.GetOutput()
#         return result, bounded_dims

    def init(self, **args):
        init_args = args['init']
        n_cores = args.get('n_cores', 32)
        #        lut = self.getLUT()
        self.variable_reader = StructuredDataReader(init_specs=init_args,
                                                    **args)
        self.variable_reader.execute()
        self.createRenderer(**args)
        interface = init_args[2]
        self.execute()
        self.initializePlots()
        self.initCamera(700.0)
        self.start()

    def gminit(self, var1, var2, **args):
        var_list = [var1]
        if id(var2) <> id(None): var_list.append(var2)
        self.variable_reader = StructuredDataReader(vars=var_list,
                                                    otype=self.type,
                                                    **args)
        self.variable_reader.execute()
        if "cm" in args:
            self.cfgManager = args["cm"]
        self.createRenderer(**args)
        self.execute()
        self.initializePlots()
        self.initCamera()
        self.start()

    def stepAnimation(self, **args):
        timestamp = self.variable_reader.stepAnimation()
        self.execute()
        if timestamp: self.updateTextDisplay("Timestep: %s" % str(timestamp))
        else: self.updateTextDisplay("")
        DV3DPlot.stepAnimation(self, **args)

    def onResizeEvent(self):
        self.updateTextDisplay(None, True)

    def updateTextDisplay(self, text=None, render=False):
        if text <> None:
            metadata = self.getMetadata()
            var_name = metadata.get('var_name', '')
            var_units = metadata.get('var_units', '')
            self.labelBuff = "%s (%s)\n%s" % (var_name, var_units, str(text))
        DV3DPlot.updateTextDisplay(self, None, render)

    def toggleClipping(self, clipping_on):
        if clipping_on: self.clipOn()
        else: self.clipOff()

    def clipOn(self):
        self.clipper.On()
        self.executeClip()

    def clipOff(self):
        self.clipper.Off()
Beispiel #11
0
from MapManager import MapManager
from PathFinder import PathFinder

MapMgr = MapManager()
PF = PathFinder()
mandatory_tasks = ['push_top','push_mid','push_bot']
addictional_tasks = ['take_rune','def_top','def_mid','def_bot']
task_queue = []

if !task_queue:
    task = mandatory_tasks[0]
    task_queue.append(task)
    

current_task = task_queue.pick()



if current_task == 'push_top':
    MapMgr.blockArea(MapMgr.top_blocks) #add top part of map to blocked area
    PF.goTo(MapMgr.home) #go to the home location
    destination = MapMgr.getPushPoint('top') #get point where to go to
    
Beispiel #12
0
class Main(ShowBase, FSM):
    """Main function of the application
    initialise the engine (ShowBase)"""
    def __init__(self):
        """initialise the engine"""
        ShowBase.__init__(self)
        FSM.__init__(self, "FSM-Game")

        #
        # BASIC APPLICATION CONFIGURATIONS
        #
        # disable pandas default camera driver
        self.disableMouse()
        # set background color to black
        self.setBackgroundColor(0, 0, 0)
        # set antialias for the complete sceen to automatic
        self.render.setAntialias(AntialiasAttrib.MAuto)
        # shader generator
        render.setShaderAuto()
        # Enhance font readability
        DGG.getDefaultFont().setPixelsPerUnit(100)

        #
        # CONFIGURATION LOADING
        #
        # load given variables or set defaults
        # check if audio should be muted
        mute = ConfigVariableBool("audio-mute", False).getValue()
        if mute:
            self.disableAllAudio()
        else:
            self.enableAllAudio()
        # check if particles should be enabled
        particles = ConfigVariableBool("particles-enabled", True).getValue()
        if particles:
            self.enableParticles()

        base.width = self.pipe.getDisplayWidth()
        base.height = self.pipe.getDisplayHeight()

        # check if the config file hasn't been created
        if not os.path.exists(prcFile):
            # get the displays width and height
            w = self.pipe.getDisplayWidth()
            h = self.pipe.getDisplayHeight()
            # set window properties
            # clear all properties not previously set
            base.win.clearRejectedProperties()
            # # setup new window properties
            props = WindowProperties()
            # # # Fullscreen
            props.setFullscreen(True)
            # # # set the window size to the screen resolution
            props.setSize(w, h)
            # # request the new properties
            base.win.requestProperties(props)
            pass
        elif base.appRunner:
            # As when the application is started as appRunner instance
            # it doesn't respect our loadPrcFile configurations specific
            # to the window, hence we need to manually set them here.
            for dec in range(mainConfig.getNumDeclarations()):
                #TODO: Check for all window specific variables like
                #      fullscreen, screen size, title and window
                #      decoration that you have in your configuration
                #      and set them by your own.
                if mainConfig.getVariableName(dec) == "fullscreen":
                    if not mainConfig.getDeclaration(dec).getBoolWord(0): break
                    # get the displays width and height
                    w = self.pipe.getDisplayWidth()
                    h = self.pipe.getDisplayHeight()
                    # set window properties
                    # clear all properties not previously set
                    base.win.clearRejectedProperties()
                    # setup new window properties
                    props = WindowProperties()
                    # Fullscreen
                    props.setFullscreen(True)
                    # set the window size to the screen resolution
                    props.setSize(w, h)
                    # request the new properties
                    base.win.requestProperties(props)
                    break
                pass

        # automatically safe configuration at application exit
        base.exitFunc = self.__writeConfig
        # due to the delayed window resizing and switch to fullscreen
        # we wait some time until everything is set so we can savely
        # proceed with other setups like the menus
        if base.appRunner:
            # this behaviour only happens if run from p3d files and
            # hence the appRunner is enabled
            taskMgr.doMethodLater(0.5,
                                  self.postInit,
                                  "post initialization",
                                  extraArgs=[])
        else:
            self.postInit()

    def postInit(self):
        #
        # initialize game content
        #
        # camera
        base.camLens.setNearFar(1.0, 10000)
        base.camLens.setFov(75)

        a = 33
        base.camera.setPos(0, -a, a + 3)  #80)
        # collision
        base.cTrav = CollisionTraverser("base collision traverser")
        base.cHandler = CollisionHandlerEvent()
        base.cPusher = CollisionHandlerPusher()
        base.cQueue = CollisionHandlerQueue()
        base.globalClock = ClockObject.getGlobalClock()
        base.cHandler.addInPattern('%fn-into-%in')
        base.cHandler.addOutPattern('%fn-out-%in')
        base.cHandler.addAgainPattern('%fn-again-%in')
        # ai init
        base.AIworld = AIWorld(render)
        # 3d manager
        base.audio3d = Audio3DManager(base.sfxManagerList[0], camera)
        # manager
        self.archiveManager = ArchiveManager()
        self.mapManager = MapManager()
        self.initHeroInfo = None
        # Lock
        self.lock = threading.Lock()
        self.gameThread = None

        self.filters = CommonFilters(base.win, base.cam)
        # UI
        self.menu = Menu()
        self.option = Option()
        self.archive = Archive()
        self.death = Death()
        # self.oobe()
        #self.Archive_status = 0
        # self.menuMusic = loader.loadMusic("assets/audio/menuMusic.ogg")
        # self.menuMusic.setLoop(True)
        # self.fightMusic = loader.loadMusic("assets/audio/fightMusic.ogg")
        # self.fightMusic.setLoop(True)
        # base.audio3d = Audio3DManager(base.sfxManagerList[0], camera)

        self.titleVideo, self.titleCard = loadVideo('title.mp4')

        self.isInited = False
        self.isSkip = False
        self.isRenew = False
        #
        # Event handling
        #
        self.accept("escape", self.__escape)

        #
        # Start with the menu
        #
        self.request("Menu")

    #
    # FSM PART
    #
    def enterMenu(self):
        show_cursor()
        self.accept("Menu-Game", self.request, ["Archive"])
        self.accept("Menu-Option", self.request, ["Option"])
        self.accept("Menu-Quit", self.quit)
        self.menu.show()

    def exitMenu(self):
        self.ignore("Menu-Game")
        self.ignore("Menu-Option")
        self.ignore("Menu-Quit")
        self.menu.hide()

    def enterOption(self):
        show_cursor()
        self.accept("ChangeVolume", self.ChangeMusic)
        self.accept("ChangeSound", self.ChangeSound)
        self.option.show()

    def exitOption(self):
        self.ignore("ChangeVolume")
        self.ignore("ChangeSound")
        self.option.hide()

    def enterArchive(self):
        show_cursor()
        self.accept("LoadArchive", self.LoadArchive)
        self.accept("DeleteArchive", self.DeleteArchive)
        self.accept("UpdateArchive", self.UpdateArchive)
        self.accept("NewGame", self.NewGame)
        self.UpdateArchive()

    def exitArchive(self):
        self.archive.hide()
        self.ignore("LoadArchive")
        self.ignore("DeleteArchive")
        self.ignore("UpdateArchive")
        self.ignore("NewGame")

    def enterPause(self):
        # self.accept("Pause-Newgame")
        # self.accept("Pause-Option")
        # self.accept("Pause-Back")
        show_cursor()

    def exitPause(self):
        self.ignore("Pause-Newgame")
        self.ignore("Pause-Option")
        self.ignore("Pause-Back")

    def enterInitGame(self):
        if Nodebug:
            self.titleCard.show()
            self.titleVideo.play()

    def exitInitGame(self):
        if Nodebug:
            self.titleCard.hide()
            self.titleVideo.stop()

    def enterGame(self):
        self.accept("hero-death", self.request, ["Death"])
        self.accept('game-end', self.request, ['Menu'])
        base.messenger.send('game-start', [self.isRenew])

    def exitGame(self):
        self.ignore('hero-death')
        #self.archiveManager.SaveArchive(self.archiveID,MapManager.ToDict(self.mapManager))
        pass

    def enterDeath(self):
        self.mapManager.index = 0  # renew
        self.accept("Death-Game", self.NewGame)
        self.accept("Death-Menu", self.request, ["Menu"])
        self.accept("Death-Quit", self.quit)
        self.death.show()
        show_cursor()

    def exitDeath(self):
        self.ignore("Death-Menu")
        self.ignore("Death-Quit")
        self.death.hide()

    #
    # FSM PART END
    #

    @print_func_time
    def NewGame(self):
        delayTime = self.titleVideo.length()
        archiveDir = self.archiveManager.basedir
        self.isInited = False
        self.request('InitGame')
        delayTime = self.titleVideo.length()
        if not self.isSkip:
            self.timer = threading.Timer(delayTime, self._accept_skip)
            self.timer.start()
        self.isInited = False
        checkThread = threading.Thread(target=self._thread_check, name='check')
        checkThread.start()
        self.gameThread = threading.Thread(target=self._initGame,
                                           args=(None, archiveDir),
                                           name='newgame')
        self.gameThread.start()

    def _thread_check(self):
        while (not self.isInited or not self.isSkip):
            pass
        self.isInited = False
        self.request('Game')

    @print_func_time
    def _accept_skip(self):
        self.lock.acquire()
        try:
            self.isSkip = True
        finally:
            self.lock.release()

    def _initGame(self, archive, archivePath):
        sTime = time.time()
        self.isInited = False
        self.mapManager.archivePath = archivePath
        #self.filters.setBloom()
        if self.mapManager.hero == None:
            self.mapManager.loadResource()
            self.initHeroInfo = Hero.ToDict(self.mapManager.hero)
        self.mapManager.hero.reInit(self.initHeroInfo)

        if archive == None:
            self.mapManager.genMap()
            self.isRenew = True
            if not self.isSkip:
                self.acceptOnce('enter', self._accept_skip)
        else:
            self.mapManager.reInit(archive)
            self.isRenew = False
            if not self.isSkip:
                self.acceptOnce('enter', self._accept_skip)

        self.isInited = True

    @print_func_time
    def LoadGame(self):
        self.Archive_status = 1
        self.request("Archive")

    def ChangeMusic(self):
        print self.option.slider_volume['value']

    def ChangeMusic(self):
        base.musicManager.setVolume(self.option.slider_volume['value'] / 100)

    def ChangeSound(self):
        base.sfxManagerList[0].setVolume(self.option.slider_sound['value'] /
                                         100)

    def DeleteArchive(self):
        self.archiveManager.DeleteArchive(self.archive.v[0])
        self.UpdateArchive()

    def LoadArchive(self):
        self.archiveID = self.archive.v[0]
        archive = self.archiveManager.ReadArchive(self.archiveID)
        archiveDir = self.archiveManager.basedir
        delayTime = self.titleVideo.length()
        self.request('InitGame')
        if not self.isSkip:
            self.timer = threading.Timer(delayTime, self._accept_skip)
            self.timer.start()
        self.isInited = False
        checkThread = threading.Thread(target=self._thread_check, name='check')
        checkThread.start()
        self.gameThread = threading.Thread(target=self._initGame,
                                           args=(archive, archiveDir),
                                           name='newgame')
        self.gameThread.start()

    def UpdateArchive(self):
        msg = self.archiveManager.GetArchiveListShortMsg()
        self.archive.show(msg)

    #
    # BASIC FUNCTIONS
    #

    def __escape(self):
        if self.state == "Menu":
            self.gameThread = None
            self.quit()
        elif self.state == "Game":
            archive = MapManager.ToDict(self.mapManager)
            self.archiveManager.SaveArchive(self.archive.v[0], archive)
            self.mapManager.room.request("Idle")
            base.musicManager.stopAllSounds()
            base.sfxManagerList[0].stopAllSounds()

            self.request("Menu")
        else:
            self.request("Menu")

    def quit(self):
        """This function will stop the application"""
        self.userExit()

    def __writeConfig(self):
        """Save current config in the prc file or if no prc file exists
        create one. The prc file is set in the prcFile variable"""
        page = None

        # These TODO tags are as a reminder for to add any new config
        # variables that may occur in the future
        #TODO: get values of configurations here
        particles = "#f" if not base.particleMgrEnabled else "#t"
        volume = str(round(base.musicManager.getVolume(), 2))
        mute = "#f" if base.AppHasAudioFocus else "#t"
        #TODO: add any configuration variable name that you have added
        customConfigVariables = [
            "", "particles-enabled", "audio-mute", "audio-volume"
        ]
        if os.path.exists(prcFile):
            # open the config file and change values according to current
            # application settings
            page = loadPrcFile(Filename.fromOsSpecific(prcFile))
            removeDecls = []
            for dec in range(page.getNumDeclarations()):
                # Check if our variables are given.
                # NOTE: This check has to be done to not loose our base or other
                #       manual config changes by the user
                if page.getVariableName(dec) in customConfigVariables:
                    decl = page.modifyDeclaration(dec)
                    removeDecls.append(decl)
            for dec in removeDecls:
                page.deleteDeclaration(dec)
            # NOTE: particles-enabled and audio-mute are custom variables and
            #       have to be loaded by hand at startup
            # Particles
            page.makeDeclaration("particles-enabled", particles)
            # audio
            page.makeDeclaration("audio-volume", volume)
            page.makeDeclaration("audio-mute", mute)
        else:
            # Create a config file and set default values
            cpMgr = ConfigPageManager.getGlobalPtr()
            page = cpMgr.makeExplicitPage("{} Pandaconfig".format(appName))
            # set OpenGL to be the default
            page.makeDeclaration("load-display", "pandagl")
            # get the displays width and height
            w = self.pipe.getDisplayWidth()
            h = self.pipe.getDisplayHeight()
            # set the window size in the config file
            page.makeDeclaration("win-size", "{} {}".format(w, h))
            # set the default to fullscreen in the config file
            page.makeDeclaration("fullscreen", "1")
            # particles
            page.makeDeclaration("particles-enabled", "#t")
            # audio
            page.makeDeclaration("audio-volume", volume)
            page.makeDeclaration("audio-mute", "#f")
        # create a stream to the specified config file
        configfile = OFileStream(prcFile)
        # and now write it out
        page.write(configfile)
        # close the stream
        configfile.close()