Exemple #1
0
    def disableScreensaver(self):
        if os.name == 'nt':
            # See the DisableScreensaver and RestoreScreensaver functions in
            # modules/video_output/msw/common.c in the source code for VLC.
            import win32gui
            import win32con
            import atexit

            Log.debug('Disabling screensaver.')

            old_lowpowertimeout = win32gui.SystemParametersInfo(win32con.SPI_GETLOWPOWERTIMEOUT)
            if old_lowpowertimeout != 0:
                atexit.register(lambda: win32gui.SystemParametersInfo(win32con.SPI_SETLOWPOWERTIMEOUT, old_lowpowertimeout))
                win32gui.SystemParametersInfo(win32con.SPI_SETLOWPOWERTIMEOUT, 0)

            old_powerofftimeout = win32gui.SystemParametersInfo(win32con.SPI_GETPOWEROFFTIMEOUT)
            if old_powerofftimeout != 0:
                atexit.register(lambda: win32gui.SystemParametersInfo(win32con.SPI_SETPOWEROFFTIMEOUT, old_powerofftimeout))
                win32gui.SystemParametersInfo(win32con.SPI_SETPOWEROFFTIMEOUT, 0)

            old_screensavetimeout = win32gui.SystemParametersInfo(win32con.SPI_GETSCREENSAVETIMEOUT)
            if old_screensavetimeout != 0:
                atexit.register(lambda: win32gui.SystemParametersInfo(win32con.SPI_SETSCREENSAVETIMEOUT, old_screensavetimeout))
                win32gui.SystemParametersInfo(win32con.SPI_SETSCREENSAVETIMEOUT, 0)

        else:
            Log.debug('Screensaver disabling is not implemented on this platform.')
Exemple #2
0
 def keyName(value):
     if value in CONTROL1:
         name = "Controller 1"
         control = CONTROL1
         n = 0
     elif value in CONTROL2:
         name = "Controller 2"
         control = CONTROL2
         n = 1
     elif value in CONTROL3:
         name = "Controller 3"
         control = CONTROL3
         n = 2
     else:
         name = "Controller 4"
         control = CONTROL4
         n = 3
     for j in range(20):
         if value == control[j]:
             if self.type[n] == 2:
                 return name + " " + drumkey4names[j]
             elif self.type[n] == 3:
                 return name + " " + drumkey5names[j]
             else:
                 return name + " " + guitarkeynames[j]
     else:
         Log.notice("Key value not found.")
         return "Error"
Exemple #3
0
    def loadVideo(self, libraryName, songName):
        vidSource = None

        if self.songStage == 1:
            songBackgroundVideoPath = os.path.join(libraryName, songName, "background.ogv")
            if os.path.isfile(songBackgroundVideoPath):
                vidSource = songBackgroundVideoPath
                loop = False
            else:
                Log.warn("Video not found: %s" % songBackgroundVideoPath)

        if vidSource is None:
            vidSource = os.path.join(self.pathfull, "default.ogv")
            loop = True

        if not os.path.isfile(vidSource):
            Log.warn("Video not found: %s" % vidSource)
            Log.warn("Falling back to default stage mode.")
            self.mode = 1 # Fallback
            return

        try: # Catches invalid video files or unsupported formats
            Log.debug("Attempting to load video: %s" % vidSource)
            self.vidPlayer = VideoLayer(self.engine, vidSource,
                                        mute = True, loop = loop)
            self.engine.view.pushLayer(self.vidPlayer)
        except (IOError, VideoPlayerError):
            self.mode = 1
            Log.error("Failed to load song video (falling back to default stage mode):")
Exemple #4
0
    def getOptions(self, section, option):
        """
        Read the preset options of a configuration key.

        @param section:   Section name
        @param option:    Option name
        @return:          Tuple of Key list and Values list
        """

        try:
            options = self.prototype[section][option].options.values()
            keys = self.prototype[section][option].options.keys()
            type = self.prototype[section][option].type
        except KeyError:
            Log.error("Config key %s.%s not defined while reading %s." %
                      (section, option, self.fileName))
            raise

        optionList = []

        if type != None:
            for i in range(len(options)):
                value = _convertValue(keys[i], type)
                optionList.append(value)

        return optionList, options
Exemple #5
0
    def popLayer(self, layer):
        Log.debug("View: Pop: %s" % layer.__class__.__name__)

        if layer in self.incoming:
            self.incoming.remove(layer)
        if layer in self.layers and not layer in self.outgoing:
            self.outgoing.append(layer)
Exemple #6
0
    def load(self,
             target=None,
             name=None,
             function=lambda: None,
             synch=False,
             onLoad=None,
             onCancel=None):

        if self.logLoadings == 1:
            Log.notice("Loading %s.%s %s" %
                       (target.__class__.__name__, name,
                        synch and "synchronously" or "asynchronously"))

        l = Loader(target,
                   name,
                   function,
                   self.resultQueue,
                   self.loaderSemaphore,
                   onLoad=onLoad,
                   onCancel=onCancel)
        if synch:
            l.load()
            return l.finish()
        else:
            self.loaders.append(l)
            l.start()
            return l
Exemple #7
0
    def loadImgDrawing(self, target, name, fileName, textureSize=None):
        """
        Load an SVG drawing synchronously.

        @param target:      An object that will own the drawing
        @param name:        The name of the attribute the drawing will be assigned to
        @param fileName:    The name of the file in the data directory
        @param textureSize: Either None or (x, y), in which case the file will
                            be rendered to an x by y texture
        @return:            L{ImgDrawing} instance
        """
        imgDrawing = self.getImgDrawing(fileName)
        if not imgDrawing:
            if target and name:
                setattr(target, name, None)
            else:
                Log.error("Image not found: " + fileName)
                return None

        if target:
            drawing = self.resource.load(target,
                                         name,
                                         lambda: imgDrawing,
                                         synch=True)
        else:
            drawing = imgDrawing
        return drawing
Exemple #8
0
    def loadVideo(self, libraryName, songName):
        vidSource = None

        if self.songStage == 1:
            songBackgroundVideoPath = os.path.join(libraryName, songName,
                                                   "background.ogv")
            if os.path.isfile(songBackgroundVideoPath):
                vidSource = songBackgroundVideoPath
                loop = False
            else:
                Log.warn("Video not found: %s" % songBackgroundVideoPath)

        if vidSource is None:
            vidSource = os.path.join(self.pathfull, "default.ogv")
            loop = True

        if not os.path.isfile(vidSource):
            Log.warn("Video not found: %s" % vidSource)
            Log.warn("Falling back to default stage mode.")
            self.mode = 1  # Fallback
            return

        try:  # Catches invalid video files or unsupported formats
            Log.debug("Attempting to load video: %s" % vidSource)
            self.vidPlayer = VideoLayer(self.engine,
                                        vidSource,
                                        mute=True,
                                        loop=loop)
            self.engine.view.pushLayer(self.vidPlayer)
        except (IOError, VideoPlayerError):
            self.mode = 1
            Log.error(
                "Failed to load song video (falling back to default stage mode):"
            )
Exemple #9
0
 def __init__(self, engine, controlnum, samprate=44100):
     Task.__init__(self)
     self.engine = engine
     self.controlnum = controlnum
     devnum = self.engine.input.controls.micDevice[controlnum]
     if devnum == -1:
         devnum = None
         self.devname = pa.get_default_input_device_info()['name']
     else:
         self.devname = pa.get_device_info_by_index(devnum)['name']
     self.mic = pa.open(samprate, 1, pyaudio.paFloat32, input=True, input_device_index=devnum, start=False)
     self.analyzer = pypitch.Analyzer(samprate)
     self.mic_started = False
     self.lastPeak    = 0
     self.detectTaps  = True
     self.tapStatus   = False
     self.tapThreshold = -self.engine.input.controls.micTapSensitivity[controlnum]
     self.passthroughQueue = []
     passthroughVolume = self.engine.input.controls.micPassthroughVolume[controlnum]
     if passthroughVolume > 0.0:
         Log.debug('Microphone: creating passthrough stream at %d%% volume' % round(passthroughVolume * 100))
         self.passthroughStream = Audio.MicrophonePassthroughStream(engine, self)
         self.passthroughStream.setVolume(passthroughVolume)
     else:
         Log.debug('Microphone: not creating passthrough stream')
         self.passthroughStream = None
Exemple #10
0
    def getOptions(self, section, option):
        """
        Read the preset options of a configuration key.

        @param section:   Section name
        @param option:    Option name
        @return:          Tuple of Key list and Values list
        """

        try:
            options = self.prototype[section][option].options.values()
            keys    = self.prototype[section][option].options.keys()
            type    = self.prototype[section][option].type
        except KeyError:
            Log.error("Config key %s.%s not defined while reading %s." % (section, option, self.fileName))
            raise

        optionList = []

        if type != None:
            for i in range(len(options)):
                value = _convertValue(keys[i], type)
                optionList.append(value)

        return optionList, options
Exemple #11
0
    def popLayer(self, layer):
        Log.debug("View: Pop: %s" % layer.__class__.__name__)

        if layer in self.incoming:
            self.incoming.remove(layer)
        if layer in self.layers and layer not in self.outgoing:
            self.outgoing.append(layer)
Exemple #12
0
 def finishGame(self):
     if not self.world:
         Log.notice("GameEngine.finishGame called before World created.")
         return
     self.world.finishGame()
     self.world = None
     self.gameStarted = False
     self.view.pushLayer(self.mainMenu)
Exemple #13
0
def getAvailableMods(engine):
    modPath = _getModPath(engine)
    try:
        dirList = os.listdir(modPath)
    except OSError:
        Log.warn("Could not find mods directory")
        return []
    return [m for m in dirList if os.path.isdir(os.path.join(modPath, m)) and not m.startswith(".")]
Exemple #14
0
 def finishGame(self):
     if not self.world:
         Log.notice("GameEngine.finishGame called before World created.")
         return
     self.world.finishGame()
     self.world = None
     self.gameStarted = False
     self.view.pushLayer(self.mainMenu)
Exemple #15
0
    def __init__(self, guitarScene, configFileName, coOp = False):

        self.scene            = guitarScene
        self.engine           = guitarScene.engine
        self.layers = {}          #collection of all the layers in the rockmeter
        self.layersForRender = {} #collection of layers that are rendered separate from any group
        self.layerGroups = {}     #collection of layer groups
        self.sharedLayerGroups = {}
        self.sharedLayers = {}    #these layers are for coOp use only
        self.sharedLayersForRender = {}
        self.sharedGroups = {}

        self.coOp = coOp
        self.config = LinedConfigParser()
        self.config.read(configFileName)

        self.themename = self.engine.data.themeLabel

        try:
            themepath = os.path.join(Version.dataPath(), "themes", self.themename)
            fp, pathname, description = imp.find_module("CustomRMLayers",[themepath])
            self.customRMLayers = imp.load_module("CustomRMLayers", fp, pathname, description)
        except ImportError:
            self.customRMLayers = None
            Log.notice("Custom Rockmeter layers are not available")

        # Build the layers
        for i in range(Rockmeter._layerLimit):
            types = [
                     "Image",
                     "Text",
                     "Circle",
                     "Custom"
                    ]

            for t in types:
                self.section = "layer%d:%s" % (i, t)
                if not self.config.has_section(self.section):
                    continue
                else:
                    if t == types[1]:
                        self.createFont(self.section, i)
                    elif t == types[2]:
                        self.createCircle(self.section, i)
                    elif t == types[3]:
                        self.createCustom(self.section, i)
                    else:
                        self.createImage(self.section, i)
                    break

        for i in range(Rockmeter._groupLimit):
            self.section = "Group%d" % i
            if not self.config.has_section(self.section):
                continue
            else:
                self.createGroup(self.section, i)

        self.reset()
Exemple #16
0
 def start(self):
     if not self.mic_started:
         self.mic_started = True
         self.mic.start_stream()
         self.engine.addTask(self, synchronized=False)
         Log.debug('Microphone: started %s' % self.devname)
         if self.passthroughStream is not None:
             Log.debug('Microphone: starting passthrough stream')
             self.passthroughStream.play()
Exemple #17
0
 def stop(self):
     if self.mic_started:
         if self.passthroughStream is not None:
             Log.debug('Microphone: stopping passthrough stream')
             self.passthroughStream.stop()
         self.engine.removeTask(self)
         self.mic.stop_stream()
         self.mic_started = False
         Log.debug('Microphone: stopped %s' % self.devname)
Exemple #18
0
 def start(self):
     if not self.mic_started:
         self.mic_started = True
         self.mic.start_stream()
         self.engine.addTask(self)
         Log.debug('Microphone: started %s' % self.devname)
         if self.passthroughStream is not None:
             Log.debug('Microphone: starting passthrough stream')
             self.passthroughStream.play()
Exemple #19
0
 def stop(self):
     if self.mic_started:
         if self.passthroughStream is not None:
             Log.debug('Microphone: stopping passthrough stream')
             self.passthroughStream.stop()
         self.engine.removeTask(self)
         self.mic.stop_stream()
         self.mic_started = False
         Log.debug('Microphone: stopped %s' % self.devname)
Exemple #20
0
    def __init__(self, guitarScene, configFileName):
        self.scene = guitarScene
        self.engine = guitarScene.engine
        self.config = LinedConfigParser()
        self.backgroundLayers = []
        self.foregroundLayers = []
        self.textures = {}
        self.reset()

        self.wFull = None  #MFH - needed for new stage background handling
        self.hFull = None

        # evilynux - imported myfingershurt stuff from GuitarScene
        self.mode = self.engine.config.get("game", "stage_mode")
        self.songStage = self.engine.config.get("game", "song_stage")
        self.animatedFolder = self.engine.config.get("game",
                                                     "animated_stage_folder")

        # evilynux - imported myfingershurt stuff from GuitarScene w/ minor modifs
        #MFH TODO - alter logic to accommodate separated animation and slideshow
        #           settings based on selected animated stage folder
        animationMode = self.engine.config.get("game", "stage_animate")
        slideShowMode = self.engine.config.get("game", "rotate_stages")

        if self.animatedFolder == _("None"):
            self.rotationMode = 0  #MFH: if no animated stage folders are available, disable rotation.
        elif self.animatedFolder == "Normal":
            self.rotationMode = slideShowMode
        else:
            self.rotationMode = animationMode

        self.imgArr = []  #QQstarS:random
        self.imgArrScaleFactors = []  #MFH - for precalculated scale factors
        self.rotateDelay = self.engine.config.get(
            "game", "stage_rotate_delay"
        )  #myfingershurt - user defined stage rotate delay
        self.animateDelay = self.engine.config.get(
            "game", "stage_animate_delay"
        )  #myfingershurt - user defined stage rotate delay
        self.animation = False

        self.indexCount = 0  #QQstarS:random time counter
        self.arrNum = 0  #QQstarS:random the array num
        self.arrDir = 1  #forwards

        self.config.read(configFileName)

        # evilynux - Improved stage error handling
        self.themename = self.engine.data.themeLabel
        self.path = os.path.join("themes", self.themename, "backgrounds")
        self.pathfull = self.engine.getPath(self.path)
        if not os.path.exists(self.pathfull):  # evilynux
            Log.warn("Stage folder does not exist: %s" % self.pathfull)
            self.mode = 1  # Fallback to song-specific stage

        self.loadLayers(configFileName)
Exemple #21
0
    def fileName(self, *name, **args):

        #myfingershurt: the following should be global, and only done at startup.  Not every damn time a file is loaded.
        songPath = self.songPath

        if not args.get("writable", False):
            for dataPath in self.dataPaths + songPath:
                readOnlyPath = os.path.join(dataPath, *name)
                # If the requested file is in the read-write path and not in the
                # read-only path, use the existing read-write one.
                if os.path.isfile(readOnlyPath):
                    return readOnlyPath
                elif os.path.isdir(readOnlyPath):
                    return readOnlyPath
                readWritePath = os.path.join(getWritableResourcePath(), *name)
                if os.path.isfile(readWritePath):
                    return readWritePath
            return readOnlyPath
        else:
            for dataPath in [self.dataPaths[-1]] + songPath:
                readOnlyPath = os.path.join(dataPath, *name)
                if not (os.path.isfile(readOnlyPath)
                        or os.path.isdir(readOnlyPath)):
                    continue
                try:
                    # First see if we can write to the original file
                    if os.access(readOnlyPath, os.W_OK):
                        return readOnlyPath
                    # If the original file does not exist, see if we can write to its directory
                    if not os.path.isfile(readOnlyPath) and os.access(
                            os.path.dirname(readOnlyPath), os.W_OK):
                        pass
                except:
                    raise
                # If the resource exists in the read-only path, make a copy to the
                # read-write path.
                readWritePath = os.path.join(getWritableResourcePath(), *name)
                if not os.path.isfile(readWritePath) and os.path.isfile(
                        readOnlyPath):
                    Log.notice("Copying '%s' to writable data directory." %
                               "/".join(name))
                    try:
                        os.makedirs(os.path.dirname(readWritePath))
                    except:
                        pass
                    shutil.copy(readOnlyPath, readWritePath)
                    self.makeWritable(readWritePath)
                # Create directories if needed
                if not os.path.isdir(readWritePath) and os.path.isdir(
                        readOnlyPath):
                    Log.notice("Creating writable directory '%s'." %
                               "/".join(name))
                    os.makedirs(readWritePath)
                    self.makeWritable(readWritePath)
                return readWritePath
            return readOnlyPath
Exemple #22
0
 def loadLibrary(self):
     Log.debug("Loading libraries in %s" % self.library)
     self.loaded = False
     self.tiersPresent = False
     if self.splash:
         Dialogs.changeLoadingSplashScreenText(self.engine, self.splash, _("Browsing Collection..."))
     else:
         self.splash = Dialogs.showLoadingSplashScreen(self.engine, _("Browsing Collection..."))
         self.loadStartTime = time.time()
     self.engine.resource.load(self, "libraries", lambda: Song.getAvailableLibraries(self.engine, self.library), onLoad = self.loadSongs, synch = True)
Exemple #23
0
 def getSoundObjectList(self, soundPath, soundPrefix, numSounds, soundExtension = ".ogg"):   #MFH
     Log.debug("{0}1{2} - {0}{1}{2} found in {3}".format(soundPrefix, numSounds, soundExtension, soundPath))
     
     sounds = []
     for i in xrange(1, numSounds+1):
         filePath = os.path.join(soundPath, "%s%d%s" % (soundPrefix, i, soundExtension) )
         soundObject = Sound(self.resource.fileName(filePath))
         sounds.append(soundObject)
         
     return sounds
Exemple #24
0
 def __init__(self, name = None, target = GL_TEXTURE_2D, useMipmaps = True):
     # Delete all pending textures
     try:
         func, args = cleanupQueue[0]
         del cleanupQueue[0]
         func(*args)
     except IndexError:
         pass
     except Exception, e:    #MFH - to catch "did you call glewInit?" crashes
         Log.error("Texture.py texture deletion exception: %s" % e)
Exemple #25
0
def getAvailableMods(engine):
    modPath = _getModPath(engine)
    try:
        dirList = os.listdir(modPath)
    except OSError:
        Log.warn("Could not find mods directory")
        return []
    return [
        m for m in dirList
        if os.path.isdir(os.path.join(modPath, m)) and not m.startswith(".")
    ]
Exemple #26
0
    def showTutorial(self):
        # evilynux - Make sure tutorial exists before launching
        tutorialpath = self.engine.tutorialFolder
        if not os.path.isdir(self.engine.resource.fileName(tutorialpath)):
            Log.debug("No folder found: %s" % tutorialpath)
            Dialogs.showMessage(self.engine, _("No tutorials found!"))
            return

        self.engine.startWorld(1, None, 0, 0, tutorial = True)

        self.launchLayer(lambda: Lobby(self.engine))
Exemple #27
0
    def showTutorial(self):
        # evilynux - Make sure tutorial exists before launching
        tutorialpath = self.engine.tutorialFolder
        if not os.path.isdir(self.engine.resource.fileName(tutorialpath)):
            Log.debug("No folder found: %s" % tutorialpath)
            Dialogs.showMessage(self.engine, _("No tutorials found!"))
            return

        self.engine.startWorld(1, None, 0, 0, tutorial = True)

        self.launchLayer(lambda: Lobby(self.engine))
Exemple #28
0
 def multisampleReset(self, resolution):
     Log.warn("Video setup failed. Trying without antialiasing.")
     pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLEBUFFERS, 0)
     pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLESAMPLES, 0)
     self.multisamples = 0
     try:
         self.screen = pygame.display.set_mode(resolution, self.flags)
     except Exception, e:
         if "video mode" in str(e):
             self.resolutionReset()
         else:
             self.screenError()
Exemple #29
0
    def __init__(self, guitarScene, configFileName):
        self.scene            = guitarScene
        self.engine           = guitarScene.engine
        self.config           = LinedConfigParser()
        self.backgroundLayers = []
        self.foregroundLayers = []
        self.textures         = {}
        self.reset()


        self.wFull = None   #MFH - needed for new stage background handling
        self.hFull = None

        # evilynux - imported myfingershurt stuff from GuitarScene
        self.mode = self.engine.config.get("game", "stage_mode")
        self.songStage = self.engine.config.get("game", "song_stage")
        self.animatedFolder = self.engine.config.get("game", "animated_stage_folder")

        # evilynux - imported myfingershurt stuff from GuitarScene w/ minor modifs
        #MFH TODO - alter logic to accommodate separated animation and slideshow
        #           settings based on selected animated stage folder
        animationMode = self.engine.config.get("game", "stage_animate")
        slideShowMode = self.engine.config.get("game", "rotate_stages")

        if self.animatedFolder == _("None"):
            self.rotationMode = 0   #MFH: if no animated stage folders are available, disable rotation.
        elif self.animatedFolder == "Normal":
            self.rotationMode = slideShowMode
        else:
            self.rotationMode = animationMode

        self.imgArr = [] #QQstarS:random
        self.imgArrScaleFactors = []  #MFH - for precalculated scale factors
        self.rotateDelay = self.engine.config.get("game",  "stage_rotate_delay") #myfingershurt - user defined stage rotate delay
        self.animateDelay = self.engine.config.get("game",  "stage_animate_delay") #myfingershurt - user defined stage rotate delay
        self.animation = False

        self.indexCount = 0 #QQstarS:random time counter
        self.arrNum = 0 #QQstarS:random the array num
        self.arrDir = 1 #forwards

        self.config.read(configFileName)

        # evilynux - Improved stage error handling
        self.themename = self.engine.data.themeLabel
        self.path = os.path.join("themes",self.themename,"backgrounds")
        self.pathfull = self.engine.getPath(self.path)
        if not os.path.exists(self.pathfull): # evilynux
            Log.warn("Stage folder does not exist: %s" % self.pathfull)
            self.mode = 1 # Fallback to song-specific stage

        self.loadLayers(configFileName)
Exemple #30
0
    def pushLayer(self, layer):
        Log.debug("View: Push: %s" % layer.__class__.__name__)

        if not layer in self.layers:
            self.layers.append(layer)
            self.incoming.append(layer)
            self.visibility[layer] = 0.0
            layer.shown()
        elif layer in self.outgoing:
            layer.hidden()
            layer.shown()
            self.outgoing.remove(layer)
        self.engine.addTask(layer)
Exemple #31
0
 def keyPressed(self, key, unicode):
     if key == pygame.K_LALT:
         self.altStatus = True
     elif key == pygame.K_RETURN and self.altStatus:
         if not self.engine.toggleFullscreen():
             Log.error("Unable to toggle fullscreen mode.")
         return True
     elif key == pygame.K_d and self.altStatus:
         self.engine.setDebugModeEnabled(not self.engine.isDebugModeEnabled())
         return True
     elif key == pygame.K_g and self.altStatus and self.engine.isDebugModeEnabled():
         self.engine.debugLayer.gcDump()
         return True
Exemple #32
0
    def pushLayer(self, layer):
        Log.debug("View: Push: %s" % layer.__class__.__name__)

        if layer not in self.layers:
            self.layers.append(layer)
            self.incoming.append(layer)
            self.visibility[layer] = 0.0
            layer.shown()
        elif layer in self.outgoing:
            layer.hidden()
            layer.shown()
            self.outgoing.remove(layer)
        self.engine.addTask(layer)
Exemple #33
0
    def load(self, target = None, name = None, function = lambda: None, synch = False, onLoad = None, onCancel = None):

        if self.logLoadings == 1:
            Log.notice("Loading %s.%s %s" % (target.__class__.__name__, name, synch and "synchronously" or "asynchronously"))

        l = Loader(target, name, function, self.resultQueue, self.loaderSemaphore, onLoad = onLoad, onCancel = onCancel)
        if synch:
            l.load()
            return l.finish()
        else:
            self.loaders.append(l)
            l.start()
            return l
Exemple #34
0
 def keyPressed(self, key, unicode):
     if key == pygame.K_LALT:
         self.altStatus = True
     elif key == pygame.K_RETURN and self.altStatus:
         if not self.engine.toggleFullscreen():
             Log.error("Unable to toggle fullscreen mode.")
         return True
     elif key == pygame.K_d and self.altStatus:
         self.engine.setDebugModeEnabled(not self.engine.isDebugModeEnabled())
         return True
     elif key == pygame.K_g and self.altStatus and self.engine.isDebugModeEnabled():
         self.engine.debugLayer.gcDump()
         return True
Exemple #35
0
    def __init__(self, name, number):

        self.logClassInits = Config.get("game", "log_class_inits")
        if self.logClassInits == 1:
            Log.debug("Player class init (Player.py)...")

        self.name     = name

        self.reset()
        self.keyList     = None

        self.progressKeys = []
        self.drums        = []
        self.keys         = []
        self.soloKeys     = []
        self.soloShift    = None
        self.soloSlide    = False
        self.actions      = []
        self.yes          = []
        self.no           = []
        self.conf         = []
        self.up           = []
        self.down         = []
        self.left         = []
        self.right        = []
        self.controller   = -1
        self.controlType  = -1

        self.guitarNum    = None
        self.number       = number

        self.bassGrooveEnabled = False
        self.currentTheme = 1

        self.lefty       = _playerDB.execute('SELECT `lefty` FROM `players` WHERE `name` = ?', [self.name]).fetchone()[0]
        self.twoChordMax = _playerDB.execute('SELECT `twochord` FROM `players` WHERE `name` = ?', [self.name]).fetchone()[0]
        self.drumflip    = _playerDB.execute('SELECT `drumflip` FROM `players` WHERE `name` = ?', [self.name]).fetchone()[0]
        self.assistMode  = _playerDB.execute('SELECT `assist` FROM `players` WHERE `name` = ?', [self.name]).fetchone()[0]
        self.autoKick    = _playerDB.execute('SELECT `autokick` FROM `players` WHERE `name` = ?', [self.name]).fetchone()[0]
        self.neck        = _playerDB.execute('SELECT `neck` FROM `players` WHERE `name` = ?', [self.name]).fetchone()[0]
        self.neckType    = _playerDB.execute('SELECT `necktype` FROM `players` WHERE `name` = ?', [self.name]).fetchone()[0]
        self.whichPart   = _playerDB.execute('SELECT `part` FROM `players` WHERE `name` = ?', [self.name]).fetchone()[0]
        self._upname      = _playerDB.execute('SELECT `upname` FROM `players` WHERE `name` = ?', [self.name]).fetchone()[0]
        self._difficulty  = _playerDB.execute('SELECT `difficulty` FROM `players` WHERE `name` = ?', [self.name]).fetchone()[0]
        #MFH - need to store selected practice mode and start position here
        self.practiceMode = False
        self.practiceSpeed = 1.0
        self.practiceSection = None
        self.startPos = 0.0

        self.hopoFreq = None
Exemple #36
0
 def resolutionReset(self):
     Log.warn("Video setup failed. Trying default windowed resolution.")
     self.error.append(_("Video setup failed with your resolution settings, and so were reset to defaults."))
     if self.fullscreen:
         self.flags ^= pygame.FULLSCREEN
         self.fullscreen = False
     try:
         self.screen = pygame.display.set_mode((800,600), self.flags)
         self.default = True
     except Exception:
         if self.multisamples:
             self.multisampleReset((800, 600))
         else:
             self.screenError()
Exemple #37
0
    def fileName(self, *name, **args):

        #myfingershurt: the following should be global, and only done at startup.  Not every damn time a file is loaded.
        songPath = self.songPath

        if not args.get("writable", False):
            for dataPath in self.dataPaths + songPath:
                readOnlyPath = os.path.join(dataPath, *name)
                # If the requested file is in the read-write path and not in the
                # read-only path, use the existing read-write one.
                if os.path.isfile(readOnlyPath):
                    return readOnlyPath
                elif os.path.isdir(readOnlyPath):
                    return readOnlyPath
                readWritePath = os.path.join(getWritableResourcePath(), *name)
                if os.path.isfile(readWritePath):
                    return readWritePath
            return readOnlyPath
        else:
            for dataPath in [self.dataPaths[-1]] + songPath:
                readOnlyPath = os.path.join(dataPath, *name)
                if not (os.path.isfile(readOnlyPath) or os.path.isdir(readOnlyPath)):
                    continue
                try:
                    # First see if we can write to the original file
                    if os.access(readOnlyPath, os.W_OK):
                        return readOnlyPath
                    # If the original file does not exist, see if we can write to its directory
                    if not os.path.isfile(readOnlyPath) and os.access(os.path.dirname(readOnlyPath), os.W_OK):
                        pass
                except:
                    raise
                # If the resource exists in the read-only path, make a copy to the
                # read-write path.
                readWritePath = os.path.join(getWritableResourcePath(), *name)
                if not os.path.isfile(readWritePath) and os.path.isfile(readOnlyPath):
                    Log.notice("Copying '%s' to writable data directory." % "/".join(name))
                    try:
                        os.makedirs(os.path.dirname(readWritePath))
                    except:
                        pass
                    shutil.copy(readOnlyPath, readWritePath)
                    self.makeWritable(readWritePath)
                # Create directories if needed
                if not os.path.isdir(readWritePath) and os.path.isdir(readOnlyPath):
                    Log.notice("Creating writable directory '%s'." % "/".join(name))
                    os.makedirs(readWritePath)
                    self.makeWritable(readWritePath)
                return readWritePath
            return readOnlyPath
Exemple #38
0
    def finish(self):
        if self.canceled:
            if self.onCancel:
                self.onCancel()
            return

        if self.logLoadings == 1:
            Log.notice("Loaded %s.%s in %.3f seconds" % (self.target.__class__.__name__, self.name, self.time))

        if self.exception:
            raise self.exception[0], self.exception[1], self.exception[2]
        if self.target and self.name:
            setattr(self.target, self.name, self.result)
        if self.onLoad:
            self.onLoad(self.result)
        return self.result
Exemple #39
0
    def getTipText(self, section, option):
        """
        Return the tip text for a configuration key.

        @param section:   Section name
        @param option:    Option name
        @return:          Tip Text String
        """

        try:
            text = self.prototype[section][option].tipText
        except KeyError:
            Log.error("Config key %s.%s not defined while reading %s." % (section, option, self.fileName))
            raise

        return text
Exemple #40
0
    def finish(self):
        if self.canceled:
            if self.onCancel:
                self.onCancel()
            return

        if self.logLoadings == 1:
            Log.notice("Loaded %s.%s in %.3f seconds" % (self.target.__class__.__name__, self.name, self.time))

        if self.exception:
            raise self.exception[0], self.exception[1], self.exception[2]
        if self.target and self.name:
            setattr(self.target, self.name, self.result)
        if self.onLoad:
            self.onLoad(self.result)
        return self.result
Exemple #41
0
    def loadTex2D(self, fname, type = GL_RGB):
        file = os.path.join(self.workdir,fname)
        if os.path.exists(file):
            img = pygame.image.load(file)
            noise = pygame.image.tostring(img, "RGB")
        else:
            Log.debug("Can't load %s; generating random 2D noise instead." % fname)
            return self.makeNoise2D(16)

        texture = 0
        glBindTexture(GL_TEXTURE_2D, texture)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
        glTexImage2D(GL_TEXTURE_2D, 0, 1, img.get_width(), img.get_height(), 0, type, GL_UNSIGNED_BYTE, noise)
        return texture
Exemple #42
0
    def getTipText(self, section, option):
        """
        Return the tip text for a configuration key.

        @param section:   Section name
        @param option:    Option name
        @return:          Tip Text String
        """

        try:
            text = self.prototype[section][option].tipText
        except KeyError:
            Log.error("Config key %s.%s not defined while reading %s." %
                      (section, option, self.fileName))
            raise

        return text
Exemple #43
0
 def gcDump(self):
     before = len(gc.get_objects())
     coll   = gc.collect()
     after  = len(gc.get_objects())
     Log.debug("%d GC objects collected, total %d -> %d." % (coll, before, after))
     fn = "gcdump.txt"
     f = open(fn, "w")
     n = 0
     gc.collect()
     for obj in gc.garbage:
         try:
             print >>f, obj
             n += 1
         except:
             pass
     f.close()
     Log.debug("Wrote a dump of %d GC garbage objects to %s." % (n, fn))
Exemple #44
0
    def open(self, frequency = 22050, bits = 16, stereo = True, bufferSize = 1024):
        try:
            pygame.mixer.quit()
        except:
            pass

        try:
            pygame.mixer.init(frequency, -bits, stereo and 2 or 1, bufferSize)
        except:
            Log.warn("Audio setup failed. Trying with default configuration.")
            pygame.mixer.init()

        Log.debug("Audio configuration: %s" % str(pygame.mixer.get_init()))

        #myfingershurt: ensuring we have enough audio channels!
        pygame.mixer.set_num_channels(10)

        return True
Exemple #45
0
    def open(self, frequency = 22050, bits = 16, stereo = True, bufferSize = 1024):
        try:
            pygame.mixer.quit()
        except:
            pass

        try:
            pygame.mixer.init(frequency, -bits, stereo and 2 or 1, bufferSize)
        except:
            Log.warn("Audio setup failed. Trying with default configuration.")
            pygame.mixer.init()

        Log.debug("Audio configuration: %s" % str(pygame.mixer.get_init()))

        #myfingershurt: ensuring we have enough audio channels!
        pygame.mixer.set_num_channels(10)

        return True
Exemple #46
0
    def loadTex2D(self, fname, type=GL_RGB):
        file = os.path.join(self.workdir, fname)
        if os.path.exists(file):
            img = pygame.image.load(file)
            noise = pygame.image.tostring(img, "RGB")
        else:
            Log.debug("Can't load %s; generating random 2D noise instead." %
                      fname)
            return self.makeNoise2D(16)

        texture = 0
        glBindTexture(GL_TEXTURE_2D, texture)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
        glTexImage2D(GL_TEXTURE_2D, 0, 1, img.get_width(), img.get_height(), 0,
                     type, GL_UNSIGNED_BYTE, noise)
        return texture
Exemple #47
0
    def run(self):

        # Perhapse this could be implemented in a better way...
        # Play the intro video if it is present, we have the capability, and
        # we are not in one-shot mode.
        if not self.engine.cmdPlay:
            themename = Config.get("coffee", "themename")
            vidSource = os.path.join(Version.dataPath(), 'themes', themename,
                                     'menu', 'intro.ogv')
            if os.path.isfile(vidSource):
                try:
                    vidPlayer = VideoLayer(self.engine,
                                           vidSource,
                                           cancellable=True)
                except (IOError, VideoPlayerError):
                    Log.error("Error loading intro video:")
                else:
                    vidPlayer.play()
                    self.engine.view.pushLayer(vidPlayer)
                    self.videoLayer = True
                    self.engine.ticksAtStart = pygame.time.get_ticks()
                    while not vidPlayer.finished:
                        self.engine.run()
                    self.engine.view.popLayer(vidPlayer)
                    self.engine.view.pushLayer(MainMenu(self.engine))
        if not self.videoLayer:
            self.engine.setStartupLayer(MainMenu(self.engine))

        # Run the main game loop.
        try:
            self.engine.ticksAtStart = pygame.time.get_ticks()
            while self.engine.run():
                pass
        except KeyboardInterrupt:
            Log.notice("Left mainloop due to KeyboardInterrupt.")
            # don't reraise

        # Restart the program if the engine is asking that we do so.
        if self.engine.restartRequested:
            self.restart()

        # evilynux - MainMenu class already calls this - useless?
        self.engine.quit()
Exemple #48
0
 def run(self, ticks):
     while self.mic.get_read_available() > 1024:
         try:
             chunk = self.mic.read(1024)
         except IOError as e:
             if e.args[1] == pyaudio.paInputOverflowed:
                 Log.notice('Microphone: ignoring input buffer overflow')
                 chunk = '\x00' * 4096
             else:
                 raise
         if self.passthroughStream is not None:
             self.passthroughQueue.append(chunk)
         self.analyzer.input(np.frombuffer(chunk, dtype=np.float32))
         self.analyzer.process()
         pk = self.analyzer.getPeak()
         if self.detectTaps:
             if pk > self.tapThreshold and pk > self.lastPeak + 5.0:
                 self.tapStatus = True
         self.lastPeak = pk
Exemple #49
0
    def make(self, fname, name = ""):
        """Compile a shader.
           fname = base filename for shader files
           name  = name to use for this shader (defaults to fname)

           Returns nothing, or raises an exception on error."""

        if name == "":
            name = fname
        fullname = os.path.join(self.workdir, fname)
        vertname, fragname = fullname+".vert", fullname+".frag"
        Log.debug('Compiling shader "%s" from %s and %s.' % (name, vertname, fragname))
        program = self.compile(open(vertname), open(fragname))
        sArray = {"program": program, "name": name, "textures": []}
        self.getVars(vertname, program, sArray)
        self.getVars(fragname, program, sArray)
        self.shaders[name] = sArray
        if "Noise3D" in self.shaders[name]:
            self.setTexture("Noise3D",self.noise3D,name)
Exemple #50
0
    def make(self, fname, name=""):
        """Compile a shader.
           fname = base filename for shader files
           name  = name to use for this shader (defaults to fname)

           Returns nothing, or raises an exception on error."""

        if name == "":
            name = fname
        fullname = os.path.join(self.workdir, fname)
        vertname, fragname = fullname + ".vert", fullname + ".frag"
        Log.debug('Compiling shader "%s" from %s and %s.' %
                  (name, vertname, fragname))
        program = self.compile(open(vertname), open(fragname))
        sArray = {"program": program, "name": name, "textures": []}
        self.getVars(vertname, program, sArray)
        self.getVars(fragname, program, sArray)
        self.shaders[name] = sArray
        if self.shaders[name].has_key("Noise3D"):
            self.setTexture("Noise3D", self.noise3D, name)
Exemple #51
0
 def run(self, ticks):
     while self.mic.get_read_available() > 1024:
         try:
             chunk = self.mic.read(1024)
         except IOError as e:
             if e.args[1] == pyaudio.paInputOverflowed:
                 Log.notice(
                     'Microphone: ignoring input buffer overflow')
                 chunk = '\x00' * 4096
             else:
                 raise
         if self.passthroughStream is not None:
             self.passthroughQueue.append(chunk)
         self.analyzer.input(np.frombuffer(chunk, dtype=np.float32))
         self.analyzer.process()
         pk = self.analyzer.getPeak()
         if self.detectTaps:
             if pk > self.tapThreshold and pk > self.lastPeak + 5.0:
                 self.tapStatus = True
         self.lastPeak = pk
Exemple #52
0
    def getDefault(self, section, option):
        """
        Read the default value of a configuration key.

        @param section:   Section name
        @param option:    Option name
        @return:          Key value
        """

        try:
            type = self.prototype[section][option].type
            default = self.prototype[section][option].default
        except KeyError:
            Log.error("Config key %s.%s not defined while reading %s." %
                      (section, option, self.fileName))
            raise

        value = _convertValue(default, type)

        return value
Exemple #53
0
 def loadImage(self, image):
     """Load the texture from a PIL image"""
     image = image.transpose(Image.FLIP_TOP_BOTTOM)
     if image.mode == "RGBA":
         string = image.tostring('raw', 'RGBA', 0, -1)
         self.loadRaw(image.size, string, GL_RGBA, 4)
     elif image.mode == "RGB":
         string = image.tostring('raw', 'RGB', 0, -1)
         self.loadRaw(image.size, string, GL_RGB, 3)
     elif image.mode == "L":
         string = image.tostring('raw', 'L', 0, -1)
         self.loadRaw(image.size, string, GL_LUMINANCE, 1)
     else:
         try:
             image = image.convert('RGB')
             Log.warn("Unsupported image mode '%s' converted to 'RGB'. May have unexpected results." % image.mode)
             string = image.tostring('raw', 'RGB', 0, -1)
             self.loadRaw(image.size, string, GL_RGB, 3)
         except:
             raise TextureException("Unsupported image mode '%s'" % image.mode)
Exemple #54
0
    def loadTex3D(self, fname, type=GL_RED):
        file = os.path.join(self.workdir, fname)
        if os.path.exists(file):
            noise = open(file).read()
            size = int(len(noise)**(1 / 3.0))
        else:
            Log.debug("Can't load %s; generating random 3D noise instead." %
                      file)
            return self.makeNoise3D(16)

        texture = 0

        glBindTexture(GL_TEXTURE_3D_EXT, texture)
        glTexParameterf(GL_TEXTURE_3D_EXT, GL_TEXTURE_WRAP_S, GL_REPEAT)
        glTexParameterf(GL_TEXTURE_3D_EXT, GL_TEXTURE_WRAP_T, GL_REPEAT)
        glTexParameterf(GL_TEXTURE_3D_EXT, GL_TEXTURE_WRAP_R_EXT, GL_REPEAT)
        glTexParameterf(GL_TEXTURE_3D_EXT, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
        glTexParameterf(GL_TEXTURE_3D_EXT, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
        glTexImage3DEXT(GL_TEXTURE_3D_EXT, 0, 1, size, size, size, 0, type,
                        GL_UNSIGNED_BYTE, noise)
        return texture