Beispiel #1
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 = MicrophonePassthroughStream(engine, self)
         self.passthroughStream.setVolume(passthroughVolume)
     else:
         log.debug('Microphone: not creating passthrough stream')
         self.passthroughStream = None
Beispiel #2
0
    def __init__(self):
        super(Input, self).__init__()
        
        self.mouse                = pygame.mouse
        self.mouseListeners       = []
        self.keyListeners         = []
        self.systemListeners      = []
        self.priorityKeyListeners = []
        self.controls             = Controls()
        self.disableKeyRepeat()

        # Initialize joysticks
        pygame.joystick.init()
        self.joystickAxes = {}
        self.joystickHats = {}

        self.joysticks = [pygame.joystick.Joystick(id) for id in range(pygame.joystick.get_count())]
        for j in self.joysticks:
            j.init()
            self.joystickAxes[j.get_id()] = [0] * j.get_numaxes()
            self.joystickHats[j.get_id()] = [(0, 0)] * j.get_numhats()
        log.debug("%d joysticks found." % (len(self.joysticks)))

        # Enable music events
        audio.Music.setEndEvent(MusicFinished)

        # Custom key names
        self.getSystemKeyName = pygame.key.name
        pygame.key.name       = self.getKeyName
Beispiel #3
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)
Beispiel #4
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.')
Beispiel #5
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):")
Beispiel #6
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)
Beispiel #7
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):")
Beispiel #8
0
    def __init__(self, engine, playerObj, scene, player = 0, bass = False):
        super(Guitar, self).__init__(engine, playerObj, scene, player=player)

        self.isDrum = False
        self.isBassGuitar = bass
        self.isVocal = False

        self.strings        = 5
        self.strings2       = 5

        self.debugMode = False
        self.gameMode2p = self.engine.world.multiMode
        self.matchingNotes = []

        self.logClassInits = self.engine.config.get("game", "log_class_inits")
        if self.logClassInits == 1:
            log.debug("Guitar class init...")

        self.lastPlayedNotes = []   #MFH - for reverting when game discovers it implied incorrectly

        self.missedNotes    = []

        self.freestyleHitFlameCounts = [0 for n in range(self.strings+1)]    #MFH

        self.fretWeight     = [0.0] * self.strings
        self.fretActivity   = [0.0] * self.strings

        self.drumFretButtons = None

        #myfingershurt:
        self.hopoStyle        = self.engine.config.get("game", "hopo_system")
        self.sfxVolume    = self.engine.config.get("audio", "SFX_volume")

        #blazingamer
        self.killfx = self.engine.config.get("performance", "killfx")
        self.killCount         = 0

        self.bigMax = 1

        #Get theme
        #now theme determination logic is only in data.py:
        self.theme = self.engine.data.theme

        self.oFlash = None

        self.lanenumber     = float(5)
        self.fretImgColNumber = float(3)

        #myfingershurt:
        self.bassGrooveNeckMode = self.engine.config.get("game", "bass_groove_neck")

        self.tailsEnabled = True

        self.loadImages()

        self.twoChordMax = False

        self.rockLevel = 0.0

        self.neck = Neck(self.engine, self, playerObj)
Beispiel #9
0
    def add(self, surface, margin = 0):
        w, h = surface.get_size()
        x, y = self.cursor

        w += margin
        h += margin

        if w > self.texture.pixelSize[0] or h > self.texture.pixelSize[1]:
            raise ValueError("Surface is too big to fit into atlas.")

        if x + w >= self.texture.pixelSize[0]:
            x = 0
            y += self.rowHeight
            self.rowHeight = 0

        if y + h >= self.texture.pixelSize[1]:
            log.debug("Texture atlas %s full after %d surfaces." % (self.texture.pixelSize, self.surfaceCount))
            raise TextureAtlasFullException()

        self.texture.loadSubsurface(surface, position = (x, y), alphaChannel = True)

        self.surfaceCount += 1
        self.rowHeight = max(self.rowHeight, h)
        self.cursor = (x + w, y + h)

        # Return the coordinates for the uploaded texture patch
        w -= margin
        h -= margin
        return  x      / float(self.texture.pixelSize[0]),  y      / float(self.texture.pixelSize[1]), \
               (x + w) / float(self.texture.pixelSize[0]), (y + h) / float(self.texture.pixelSize[1])
Beispiel #10
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()
Beispiel #11
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)
 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)
Beispiel #13
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
Beispiel #14
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))
Beispiel #15
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))
Beispiel #16
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.task.addTask(layer)
Beispiel #17
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)
Beispiel #18
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
Beispiel #19
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
Beispiel #20
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
Beispiel #21
0
    def init_oneshot(self):
        ''' Determine if oneshot mode is valid. '''
        # I think this code can be moved elsewhere...
        self.engine.cmdPlay = 0

        # Check for a valid invocation of one-shot mode.
        if self.playing is not None:
            log.debug('Validating song directory for one-shot mode.')

            library = Config.get("setlist", "base_library")
            basefolder = os.path.join(Version.dataPath(), library, "songs",
                                      self.playing)

            if not os.path.exists(os.path.join(basefolder, "song.ini")):

                if not (os.path.exists(os.path.join(basefolder, "notes.mid"))
                        or os.path.exists(
                            os.path.join(basefolder, "notes-unedited.mid"))):

                    if not (os.path.exists(os.path.join(
                            basefolder, "song.ogg")) or os.path.exists(
                                os.path.join(basefolder, "guitar.ogg"))):

                        log.warn(
                            "Song directory provided ('%s') is not a valid song directory. Starting up FoFiX in standard mode."
                            % self.playing)
                        self.engine.startupMessages.append(
                            _("Song directory provided ('%s') is not a valid song directory. Starting up FoFiX in standard mode."
                              ) % self.playing)
                        return

            # Set up one-shot mode
            log.debug('Entering one-shot mode.')
            Config.set("setlist", "selected_song", playing)

            self.engine.cmdPlay = 1

            if diff is not None:
                self.engine.cmdDiff = int(diff)
            if part is not None:
                self.engine.cmdPart = int(part)

            if players == 1:
                self.engine.cmdMode = players, mode, 0
            else:
                self.engine.cmdMode = players, 0, mode
Beispiel #22
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))
Beispiel #23
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
Beispiel #24
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))
Beispiel #25
0
 def uploadHighscores(self, url, songHash):
     try:
         d = {
             "songName": self.songName,
             "songHash": songHash,
             "scores":   self.getObfuscatedScores(),
             "version":  Version.version()
         }
         data = urllib.urlopen(url + "?" + urllib.urlencode(d)).read()
         log.debug("Score upload result: %s" % data)
         if ";" in data:
             fields = data.split(";")
         else:
             fields = [data, "0"]
         return (fields[0] == "True", int(fields[1]))
     except Exception, e:
         log.error(e)
         return (False, 0)
Beispiel #26
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)
Beispiel #27
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
Beispiel #28
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
Beispiel #29
0
    def __init__(self, indexFileName, dataFileName):
        self.dataFileName = dataFileName

        # Read the available files from the index
        f = open(indexFileName, "rb")
        magic, version1, version2, arkSize, length = unpack("IIIII", f.read(5 * 4))

        log.debug("Reading HDR file v%d.%d. Main archive is %d bytes." % (version1, version2, arkSize))

        # Read the name array
        fileNameData = f.read(length)
        fileNameCount, = unpack("I", f.read(4))
        fileNameOffsets = [unpack("I", f.read(4))[0] for i in range(fileNameCount)]

        # Read the pointers to the names
        names = []
        for i, offset in enumerate(fileNameOffsets):
            length = fileNameData[offset:].find("\x00")
            fileName = fileNameData[offset:offset + length]
            names.append(fileName)

        # Read the file names themselves
        fileCount, = unpack("I", f.read(4))

        self.files = {}
        for i in range(fileCount):
            offset, fileIndex, dirIndex, length, null = unpack("IIIII", f.read(5 * 4))
            fullName = "%s/%s" % (names[dirIndex], names[fileIndex])
            self.files[fullName] = offset, length
            log.debug("File: %s at offset %d, length %d bytes." % (fullName, offset, length))
        log.debug("Archive contains %d files." % len(self.files))
        f.close()
Beispiel #30
0
    def init_oneshot(self):
        ''' Determine if oneshot mode is valid. '''
        # I think this code can be moved elsewhere...
        self.engine.cmdPlay = 0

        # Check for a valid invocation of one-shot mode.
        if self.playing is not None:
            log.debug('Validating song directory for one-shot mode.')

            library = Config.get("setlist","base_library")
            basefolder = os.path.join(Version.dataPath(),library,"songs",self.playing)


            if not os.path.exists(os.path.join(basefolder, "song.ini")):

                if not (os.path.exists(os.path.join(basefolder, "notes.mid")) or
                        os.path.exists(os.path.join(basefolder, "notes-unedited.mid"))):

                    if not (os.path.exists(os.path.join(basefolder, "song.ogg")) or
                            os.path.exists(os.path.join(basefolder, "guitar.ogg"))):

                        log.warn("Song directory provided ('%s') is not a valid song directory. Starting up FoFiX in standard mode." % self.playing)
                        self.engine.startupMessages.append(_("Song directory provided ('%s') is not a valid song directory. Starting up FoFiX in standard mode.") % self.playing)
                        return

            # Set up one-shot mode
            log.debug('Entering one-shot mode.')
            Config.set("setlist", "selected_song", playing)

            self.engine.cmdPlay = 1

            if diff is not None:
                self.engine.cmdDiff = int(diff)
            if part is not None:
                self.engine.cmdPart = int(part)

            if players == 1:
                self.engine.cmdMode = players, mode, 0
            else:
                self.engine.cmdMode = players, 0, mode
Beispiel #31
0
 def getImgDrawing(self, fileName, openImage=True):
     imgDrawing = None
     for dataPath in self.resource.dataPaths:
         fileName1 = os.path.join(dataPath, fileName)
         if self.logLoadings == 1:
             if openImage:
                 log.notice("Trying to load image: %s" % fileName1)
             else:
                 log.notice("Checking image: %s" % fileName1)
         #check if fileName1 exists (has extension)
         if os.path.exists(fileName1):
             if openImage:
                 try:
                     imgDrawing = ImgDrawing(self.svg, fileName1)
                     return imgDrawing
                 except IOError:
                     log.warn("Unable to load image file: %s" % fileName1)
                 except OverflowError:
                     log.warn("Unable to read image file: %s" % fileName1)
             else:
                 return True
         else:
             #find extension
             fileName1 = os.path.splitext(fileName1)[0]
             files = glob.glob('%s.*' % fileName1)
             if openImage:
                 for i in range(len(files)):
                     try:
                         imgDrawing = ImgDrawing(self.svg, files[i])
                         return imgDrawing
                     except IOError:
                         log.warn("Unable to load image file: %s" %
                                  files[i])
             elif len(files) > 0:
                 return True
     #image not found
     if self.logImageNotFound:
         log.debug("Image not found: %s" % fileName)
     return False
Beispiel #32
0
 def getImgDrawing(self, fileName, openImage=True):
     imgDrawing = None
     for dataPath in self.resource.dataPaths:
         fileName1 = os.path.join(dataPath, fileName)
         if self.logLoadings == 1:
             if openImage:
                 log.notice("Trying to load image: %s" % fileName1)
             else:
                 log.notice("Checking image: %s" % fileName1)
         #check if fileName1 exists (has extension)
         if os.path.exists(fileName1):
             if openImage:
                 try:
                     imgDrawing = ImgDrawing(self.svg, fileName1)
                     return imgDrawing
                 except IOError:
                     log.warn("Unable to load image file: %s" % fileName1)
                 except OverflowError:
                     log.warn("Unable to read image file: %s" % fileName1)
             else:
                 return True
         else:
             #find extension
             fileName1 = os.path.splitext(fileName1)[0]
             files = glob.glob('%s.*' % fileName1)
             if openImage:
                 for i in range(len(files)):
                     try:
                         imgDrawing = ImgDrawing(self.svg, files[i])
                         return imgDrawing
                     except IOError:
                         log.warn("Unable to load image file: %s" % files[i])
             elif len(files) > 0:
                 return True
     #image not found
     if self.logImageNotFound:
         log.debug("Image not found: %s" % fileName)
     return False
Beispiel #33
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.')
Beispiel #34
0
    def __init__(self, resource, svg):

        self.logClassInits = Config.get("game", "log_class_inits")
        if self.logClassInits == 1:
            log.debug("Data class init (Data.py)...")
        self.logLoadings = Config.get("game", "log_loadings")

        self.logImageNotFound = Config.get("log", "log_image_not_found")

        self.resource = resource
        self.svg = svg

        self.sfxVolume = Config.get("audio", "SFX_volume")
        self.crowdVolume = Config.get("audio", "crowd_volume")

        # Get theme
        themename = Config.get("coffee", "themename")
        self.themeLabel = themename
        self.themeCoOp = False

        self.players = None
        self.players = Player.loadPlayers()

        # myfingershurt: check for existence of theme path
        themepath = os.path.join(Version.dataPath(), "themes")
        self.themepath = themepath
        self.path = Version.dataPath()

        if not self.checkImgDrawing(
                os.path.join("themes", themename, "notes", "notes.png")):
            # myfingershurt: here need to ensure an existing theme is selected
            themes = []
            defaultTheme = None  # myfingershurt
            allthemes = os.listdir(themepath)
            for name in allthemes:
                if self.checkImgDrawing(
                        os.path.join("themes", name, "notes", "notes.png")):
                    themes.append(name)
                    if name == "MegaLight V4":  # myfingershurt
                        defaultTheme = name  # myfingershurt
            if defaultTheme != "MegaLight V4":  # myfingershurt
                defaultTheme = themes[0]  # myfingershurt
            # not a valid theme if notes.png isn't there!  Force default theme:
            Config.set("coffee", "themename", defaultTheme)
            # re-init Data with new default
            themename = defaultTheme
            self.themeLabel = themename

        if not os.path.exists(
                os.path.join(Version.dataPath(), "themes", themename,
                             "vocals")):
            self.vocalPath = "vocals"
        else:
            self.vocalPath = os.path.join("themes", themename, "vocals")

        self.theme = 2
        self.themeCoOp = True

        # from our current viewport's constant 3:4 aspect ratio (which is
        # always stretched to fill the video resolution)
        self.fontScreenBottom = 0.75

        self.loadPartImages()
        # myfingershurt: multi-OS compatibility file access fixes using os.path.join()
        # load font customization images

        # Worldrave - Use new defined Star3 and star4. Using star1 and star2 as
        # a fallback.

        # MFH - no more custom glyphs, these are wasting memory.
        # MFH - but we do need these star1-4 images anyway.  Leaving them
        # loaded here in the Data object.
        self.loadImgDrawing(self,
                            "star1",
                            os.path.join("themes", themename, "star1.png"),
                            textureSize=(128, 128))
        self.loadImgDrawing(self,
                            "star2",
                            os.path.join("themes", themename, "star2.png"),
                            textureSize=(128, 128))

        # MFH - let's not rely on errors here if we don't have to...
        if not self.loadImgDrawing(self,
                                   "star3",
                                   os.path.join("themes", themename,
                                                "star3.png"),
                                   textureSize=(128, 128)):
            self.star3 = self.star1
        if not self.loadImgDrawing(self,
                                   "star4",
                                   os.path.join("themes", themename,
                                                "star4.png"),
                                   textureSize=(128, 128)):
            self.star4 = self.star2

        if self.loadImgDrawing(self,
                               "starPerfect",
                               os.path.join("themes", themename,
                                            "starperfect.png"),
                               textureSize=(128, 128)):
            self.perfectStars = True
            self.maskStars = False
        else:
            self.starPerfect = self.star2
            self.fcStars = False
            self.starFC = self.star2
            self.maskStars = True
            self.perfectStars = False

        if self.perfectStars:
            if self.loadImgDrawing(self,
                                   "starFC",
                                   os.path.join("themes", themename,
                                                "starfc.png"),
                                   textureSize=(128, 128)):
                self.fcStars = True
            else:
                self.starFC = self.starPerfect
                self.fcStars = False

        # load misc images
        self.loadImgDrawing(self,
                            "loadingImage",
                            os.path.join("themes", themename, "loadingbg.png"),
                            textureSize=(256, 256))
        self.loadImgDrawing(
            self, "optionsBG",
            os.path.join("themes", themename, "menu", "optionsbg.png"))
        if self.loadImgDrawing(
                self, "submenuSelect",
                os.path.join("themes", themename, "submenuselect.png")):
            subSelectImgW = self.submenuSelect.width1()
            self.submenuSelectFound = True
            self.subSelectWFactor = 640.000 / subSelectImgW
            self.subSelectImgH = self.submenuSelect.height1()
        else:
            self.submenuSelectFound = False
            self.loadImgDrawing(
                self, "submenuSelect",
                os.path.join("themes", themename, "menu", "selected.png"))
            self.subSelectWFactor = 0
        # load all the data in parallel
        # asciiOnly = not bool(Language.language) or Language.language == "Custom"
        # reversed  = _("__lefttoright__") == "__righttoleft__" and True or False
        asciiOnly = True
        reversed = False
        scale = 1
        # evilynux - Load bigger fonts so they're nicer when scaled, scaling
        # readjusted
        fontSize = [44, 132, 34, 32, 30]
        w, h = [int(s) for s in Config.get("video", "resolution").split("x")]
        aspectRatio = float(w) / float(h)

        self.fontList = [
            ["font1", "font", "default.ttf", fontSize[4]],
            ["font2", "bigFont", "title.ttf", fontSize[1]],
            ["font3", "pauseFont", "pause.ttf", fontSize[2]],
            ["font4", "scoreFont", "score.ttf", fontSize[3]],
            ["font5", "streakFont", "streak.ttf", fontSize[3]],
            ["font6", "loadingFont", "loading.ttf", fontSize[3]],
            ["font7", "songFont", "song.ttf", fontSize[4]],
            ["font8", "songListFont", "songlist.ttf", fontSize[3]],
            ["font9", "shadowFont", "songlist.ttf", fontSize[3]],
            ["font10", "streakFont2", "streakphrase.ttf", fontSize[2]]
        ]
        for f in self.fontList:
            if self.fileExists(os.path.join("themes", themename, "fonts",
                                            f[2])):
                fn = resource.fileName(
                    os.path.join("themes", themename, "fonts", f[2]))
                f[0] = lambda: Font(fn,
                                    f[3],
                                    scale=scale * .5,
                                    reversed=reversed,
                                    systemFont=not asciiOnly,
                                    outline=False,
                                    aspectRatio=aspectRatio)
                resource.load(self, f[1], f[0], synch=True)
            elif self.fileExists(
                    os.path.join("themes", themename, "fonts", "default.ttf")):
                log.debug("Theme font not found: " + f[2])
                fn = resource.fileName(
                    os.path.join("themes", themename, "fonts", "default.ttf"))
                f[0] = lambda: Font(fn,
                                    f[3],
                                    scale=scale * .5,
                                    reversed=reversed,
                                    systemFont=not asciiOnly,
                                    outline=False,
                                    aspectRatio=aspectRatio)
                resource.load(self, f[1], f[0], synch=True)
            else:
                log.debug(
                    "Default theme font not found: %s - using built-in default"
                    % str(f[2]))
                fn = resource.fileName(os.path.join("fonts", "default.ttf"))
                f[0] = lambda: Font(fn,
                                    f[3],
                                    scale=scale * .5,
                                    reversed=reversed,
                                    systemFont=not asciiOnly,
                                    outline=False,
                                    aspectRatio=aspectRatio)
                resource.load(self, f[1], f[0], synch=True)

        self.fontDict = {
            "font": self.font,
            "bigFont": self.bigFont,
            "pauseFont": self.pauseFont,
            "scoreFont": self.scoreFont,
            "streakFont": self.streakFont,
            "songFont": self.songFont,
            "streakFont2": self.streakFont2,
            "songListFont": self.songListFont,
            "shadowFont": self.shadowFont,
            "loadingFont": self.loadingFont
        }

        assert self.fontDict['font'] == self.font

        # load sounds asynchronously
        resource.load(self, "screwUpsounds", self.loadScrewUpsounds)
        resource.load(self, "screwUpsoundsBass", self.loadScrewUpsoundsBass)
        resource.load(self, "screwUpsoundsDrums", self.loadScrewUpsoundsDrums)
        resource.load(self, "acceptSounds", self.loadAcceptSounds)
        resource.load(self, "cancelSounds", self.loadBackSounds)

        # loadSoundEffect asynchronously
        self.syncSounds = [
            ["bassDrumSound", "bassdrum.ogg"],
            ["battleUsedSound", "battleused.ogg"],
            ["CDrumSound", "crash.ogg"],
            ["clapSound", "clapsound.ogg"],
            ["coOpFailSound", "coopfail.ogg"],
            #["crowdSound","crowdcheers.ogg"],
            ["failSound", "failsound.ogg"],
            ["rescueSound", "rescue.ogg"],
            ["rockSound", "rocksound.ogg"],
            ["selectSound1", "select1.ogg"],
            ["selectSound2", "select2.ogg"],
            ["selectSound3", "select3.ogg"],
            ["starActivateSound", "staractivate.ogg"],
            ["starDeActivateSound", "stardeactivate.ogg"],
            ["starDingSound", "starding.ogg"],
            ["starLostSound", "starlost.ogg"],
            ["starReadySound", "starpowerready.ogg"],
            ["starSound", "starpower.ogg"],
            ["startSound", "start.ogg"],
            ["T1DrumSound", "tom01.ogg"],
            ["T2DrumSound", "tom02.ogg"],
            ["T3DrumSound", "tom03.ogg"]
        ]
        for self.sounds in self.syncSounds:
            if self.fileExists(
                    os.path.join("themes", themename, "sounds",
                                 self.sounds[1])):
                self.loadSoundEffect(
                    self, self.sounds[0],
                    os.path.join("themes", themename, "sounds",
                                 self.sounds[1]))
            elif self.fileExists(os.path.join("sounds", self.sounds[1])):
                log.debug("Theme sound not found: " + self.sounds[1])
                self.loadSoundEffect(self, self.sounds[0],
                                     os.path.join("sounds", self.sounds[1]))
            else:
                log.warn("File " + self.sounds[1] +
                         " not found using default instead.")
                self.loadSoundEffect(self, self.sounds[0],
                                     os.path.join("sounds", "default.ogg"))

        # TODO: Simplify crowdSound stuff so it can join the rest of us.
        # MFH - fallback on sounds/crowdcheers.ogg, and then starpower.ogg.
        # Note if the fallback crowdcheers was used or not.
        if self.fileExists(
                os.path.join("themes", themename, "sounds",
                             "crowdcheers.ogg")):
            self.loadSoundEffect(self,
                                 "crowdSound",
                                 os.path.join("themes", themename, "sounds",
                                              "crowdcheers.ogg"),
                                 crowd=True)
            self.cheerSoundFound = 2
        elif self.fileExists(os.path.join("sounds", "crowdcheers.ogg")):
            self.loadSoundEffect(self,
                                 "crowdSound",
                                 os.path.join("sounds", "crowdcheers.ogg"),
                                 crowd=True)
            self.cheerSoundFound = 1
            log.warn(
                themename +
                "/sounds/crowdcheers.ogg not found -- using data/sounds/crowdcheers.ogg instead."
            )
        else:
            self.cheerSoundFound = 0
            log.warn("crowdcheers.ogg not found -- no crowd cheering.")
 def keyPressed(self, key, unicode):
     self.lastTime = self.time
     c = self.engine.input.controls.getMapping(key)
     if key == pygame.K_SLASH and not self.searching:
         self.searching = True
     elif (key in range(30,123) or key == pygame.K_BACKSPACE) and not self.moreInfo:
         if self.searching:
             if key == pygame.K_BACKSPACE:
                 self.searchText = self.searchText[:-1]
             else:
                 self.searchText += unicode
             return
         else:
             if unicode:
                 for i, item in enumerate(self.items):
                     if isinstance(item, song.SongInfo):
                         if self.sortOrder in [0, 2, 5]:
                             sort = item.name.lower()
                         elif self.sortOrder == 1:
                             sort = item.artist.lower()
                         elif self.sortOrder == 3:
                             sort = item.album.lower()
                         elif self.sortOrder == 4:
                             sort = item.genre.lower()
                         elif self.sortOrder == 6:
                             sort = str(item.diffSong)
                         elif self.sortOrder == 7:
                             sort = str(instrumentDiff[self.scorePart.id](item))
                         elif self.sortOrder == 8:
                             sort = item.icon.lower()
                         else:
                             sort = ""
                         if sort.startswith(unicode):
                             self.selectedIndex = i
                             self.updateSelection()
                             break
     elif (c in Player.menuNo and not c in Player.cancels) or key == pygame.K_ESCAPE:
         self.engine.data.cancelSound.play()
         if self.searching:
             self.searchText = ""
             self.searching = False
             return
         if self.moreInfo:
             self.moreInfo = False
             if self.moreInfoTime > 500:
                 self.moreInfoTime = 500
             return
         if self.songLoader:
             self.songLoader.stop()
             self.songLoader = None
             return
         if self.song:
             self.song.fadeout(1000)
         if self.library != song.DEFAULT_LIBRARY and not self.tut and (self.listingMode == 0 or self.careerMode):
             self.initialItem  = self.library
             self.library      = os.path.dirname(self.library)
             if self.library == os.path.join("..", self.engine.config.get("setlist", "base_library")):
                 self.quit()
                 return
             self.selectedItem = None
             self.loadLibrary()
         else:
             self.quit()
     elif (c in Player.menuYes and not c in Player.starts) or key == pygame.K_RETURN:
         if self.searching:
             self.searching = False
             text = self.searchText.lower()
             for i, item in enumerate(self.items):
                 sort = item.name.lower()
                 if sort.startswith(text):
                     self.selectedIndex = i
                     self.updateSelection()
                     break
             self.searchText = ""
             return
         self.engine.data.acceptSound.play()
         if isinstance(self.selectedItem, song.LibraryInfo):
             self.library = self.selectedItem.libraryName
             self.startingSelected = None
             log.debug("New library selected: " + str(self.library) )
             self.loadLibrary()
         elif isinstance(self.selectedItem, song.SongInfo) and not self.selectedItem.getLocked():
             if self.listingMode == 1 and not self.careerMode:
                 self.library = self.selectedItem.libraryNam #TODO: SongDB
             self.libraryName = self.selectedItem.libraryNam
             self.songName = self.selectedItem.songName
             self.engine.config.set("setlist", "selected_library", self.libraryName)
             self.engine.config.set("setlist", "selected_song",    self.songName)
             if self.checkParts():
                 if self.queueFormat == 0:
                     self.engine.world.songQueue.addSong(self.songName, self.libraryName)
                     self.startGame()
                 elif self.queueFormat == 1:
                     if self.engine.world.songQueue.addSongCheckReady(self.songName, self.libraryName):
                         self.startGame()
     elif c in Player.menuYes and c in Player.starts:
         self.engine.data.acceptSound.play()
         if self.queueFormat == 0:
             self.engine.world.songQueue.addSong(self.songName, self.libraryName)
         self.startGame()
     elif c in Player.menuDown or key == pygame.K_DOWN:
         self.scrolling = 2
         self.scrollTime = self.scrollDelay
         self.scrollDown()
     elif c in Player.menuUp or key == pygame.K_UP:
         self.scrolling = 1
         self.scrollTime = self.scrollDelay
         self.scrollUp()
     elif c in Player.key3s or key == pygame.K_F3:
         self.previewDelay = 0
     elif c in Player.key4s or key == pygame.K_F12:
         if isinstance(self.selectedItem, song.SongInfo):
             self.moreInfo = True
     elif c in Player.menuNo and c in Player.cancels:
         self.engine.view.pushLayer(self.menu)
Beispiel #36
0
    def __init__(self):

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

        Task.__init__(self)
        self.mouse = pygame.mouse
        self.mouseListeners = []
        self.keyListeners = []
        self.systemListeners = []
        self.priorityKeyListeners = []
        self.controls = Controls()
        self.activeGameControls = []
        self.p2Nav = self.controls.p2Nav
        self.type1 = self.controls.type[0]
        self.keyCheckerMode = Config.get("game", "key_checker_mode")
        self.disableKeyRepeat()

        self.gameGuitars = 0
        self.gameDrums = 0
        self.gameMics = 0
        self.gameBots = 0

        # Initialize joysticks
        pygame.joystick.init()
        self.joystickNames = {}
        self.joystickAxes = {}
        self.joystickHats = {}

        self.joysticks = [
            pygame.joystick.Joystick(id)
            for id in range(pygame.joystick.get_count())
        ]
        for j in self.joysticks:
            j.init()
            self.joystickNames[j.get_id()] = j.get_name()
            self.joystickAxes[j.get_id()] = [0] * j.get_numaxes()
            self.joystickHats[j.get_id()] = [(0, 0)] * j.get_numhats()
        log.debug("%d joysticks found." % len(self.joysticks))

        # Enable music events
        Music.setEndEvent(MusicFinished)
        #Music.setEndEvent()   #MFH - no event required?

        # Custom key names
        self.getSystemKeyName = pygame.key.name
        pygame.key.name = self.getKeyName

        self.midi = []
        if haveMidi:
            pygame.midi.init()
            for i in range(pygame.midi.get_count()):
                interface, name, is_input, is_output, is_opened = pygame.midi.get_device_info(
                    i)
                log.debug("Found MIDI device: %s on %s" % (name, interface))
                if not is_input:
                    log.debug("MIDI device is not an input device.")
                    continue
                try:
                    self.midi.append(pygame.midi.Input(i))
                    log.debug("Device opened as device number %d." %
                              len(self.midi))
                except pygame.midi.MidiException:
                    log.error("Error opening device for input.")
            if len(self.midi) == 0:
                log.debug("No MIDI input ports found.")
        else:
            log.notice(
                "MIDI input support is not available; install at least pygame 1.9 to get it."
            )
Beispiel #37
0
    def __init__(self, engine, playerObj, scene, player = 0):
        super(Drum, self).__init__(engine, playerObj, scene, player=player)

        self.isDrum = True
        self.isBassGuitar = False
        self.isVocal = False

        self.drumsHeldDown = [0, 0, 0, 0, 0]

        self.gameMode2p = self.engine.world.multiMode

        self.lastFretWasBassDrum = False
        self.lastFretWasT1 = False   #Faaa Drum sound
        self.lastFretWasT2 = False
        self.lastFretWasT3 = False
        self.lastFretWasC = False


        self.matchingNotes = []

        #MFH - I do not understand fully how the handicap scorecard works at the moment, nor do I have the time to figure it out.
        #... so for now, I'm just writing some extra code here for the early hitwindow size handicap.
        self.earlyHitWindowSizeFactor = 0.5

        self.starNotesInView = False
        self.openStarNotesInView = False

        self.drumFillsCount = 0
        self.drumFillsTotal = 0
        self.drumFillsHits = 0
        self.drumFillsReady = False

        self.drumFillEvents = []
        self.drumFillWasJustActive = False

        self.strings        = 4
        self.strings2       = 5
        self.playedSound  = [True, True, True, True, True]

        self.openFretActivity = 0.0
        self.openFretColor  = self.fretColors[5]

        self.lanenumber     = float(4)
        self.fretImgColNumber = float(6)

        self.logClassInits = self.engine.config.get("game", "log_class_inits")
        if self.logClassInits == 1:
            log.debug("Drum class initialization!")


        self.freestyleHitFlameCounts = [0 for n in range(self.strings+1)]    #MFH

        self.fretWeight     = [0.0] * self.strings
        self.fretActivity   = [0.0] * self.strings

        self.drumFretButtons = None

        #blazingamer
        self.opencolor = self.fretColors[5]
        self.rockLevel = 0.0

        self.bigMax = 1

        if self.engine.config.get("game", "large_drum_neck"):
            self.boardWidth     *= (4.0/3.0)
            self.boardLength    *= (4.0/3.0)

        #Get theme
        #now theme determination logic is only in data.py:
        self.theme = self.engine.data.theme

        self.tailsEnabled = False

        self.loadImages()

        self.barsColor = self.engine.theme.barsColor

        self.neck = Neck(self.engine, self, playerObj)
Beispiel #38
0
    def __init__(self, engine):
        self.engine              = engine

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

        self.time                = 0.0
        self.nextLayer           = None
        self.visibility          = 0.0
        self.active              = False

        self.showStartupMessages = False

        self.gfxVersionTag = Config.get("game", "gfx_version_tag")

        self.chosenNeck = Config.get("game", "default_neck")
        exists = 0

        if engine.loadImgDrawing(self, "ok", os.path.join("necks",self.chosenNeck+".png")):
            exists = 1
        elif engine.loadImgDrawing(self, "ok", os.path.join("necks","Neck_"+self.chosenNeck+".png")):
            exists = 1

        #MFH - fallback logic now supports a couple valid default neck filenames
        #MFH - check for Neck_1
        if exists == 0:
            if engine.loadImgDrawing(self, "ok", os.path.join("necks","Neck_1.png")):
                Config.set("game", "default_neck", "1")
                log.warn("Default chosen neck not valid; fallback Neck_1.png forced.")
                exists = 1

        #MFH - check for defaultneck
        if exists == 0:
            if engine.loadImgDrawing(self, "ok", os.path.join("necks","defaultneck.png")):
                log.warn("Default chosen neck not valid; fallback defaultneck.png forced.")
                Config.set("game", "default_neck", "defaultneck")
                exists = 1
            else:
                log.error("Default chosen neck not valid; fallbacks Neck_1.png and defaultneck.png also not valid!")

        #Get theme
        self.theme       = self.engine.data.theme
        self.themeCoOp   = self.engine.data.themeCoOp
        self.themename   = self.engine.data.themeLabel
        self.useSoloMenu = self.engine.theme.use_solo_submenu

        allowMic = True

        self.menux = self.engine.theme.menuPos[0]
        self.menuy = self.engine.theme.menuPos[1]

        self.rbmenu = self.engine.theme.menuRB

        #MFH
        self.main_menu_scale = self.engine.theme.main_menu_scaleVar
        self.main_menu_vspacing = self.engine.theme.main_menu_vspacingVar

        if not self.engine.loadImgDrawing(self, "background", os.path.join("themes",self.themename,"menu","mainbg.png")):
            self.background = None
        self.engine.loadImgDrawing(self, "BGText", os.path.join("themes",self.themename,"menu","maintext.png"))
        self.engine.loadImgDrawing(self, "optionsBG", os.path.join("themes",self.themename,"menu","optionsbg.png"))
        self.engine.loadImgDrawing(self, "optionsPanel", os.path.join("themes",self.themename,"menu","optionspanel.png"))

        #racer: added version tag
        if self.gfxVersionTag or self.engine.theme.versiontag:
            if not self.engine.loadImgDrawing(self, "version", os.path.join("themes",self.themename,"menu","versiontag.png")):
                if not self.engine.loadImgDrawing(self, "version", "versiontag.png"): #falls back on default versiontag.png in data\ folder
                    self.version = None
        else:
            self.version = None

        #myfingershurt: random main menu music function, menu.ogg and menuXX.ogg (any filename with "menu" as the first 4 letters)
        self.files = None
        filepath = self.engine.getPath(os.path.join("themes",self.themename,"sounds"))
        if os.path.isdir(filepath):
            self.files = []
            allfiles = os.listdir(filepath)
            for name in allfiles:
                if os.path.splitext(name)[1] == ".ogg":
                    if string.find(name,"menu") > -1:
                        self.files.append(name)


        if self.files:
            i = random.randint(0,len(self.files)-1)
            filename = self.files[i]
            sound = os.path.join("themes",self.themename,"sounds",filename)
            self.menumusic = True
            engine.menuMusic = True

            self.song = Music(self.engine.resource.fileName(sound))
            self.song.setVolume(self.engine.config.get("audio", "menu_volume"))
            self.song.play(0)  #no loop
        else:
            self.menumusic = False

        self.opt_text_color     = self.engine.theme.opt_text_colorVar
        self.opt_selected_color = self.engine.theme.opt_selected_colorVar

        trainingMenu = [
          (_("Tutorials"), self.showTutorial),
          (_("Practice"), lambda: self.newLocalGame(mode1p = 1)),
        ]

        self.opt_bkg_size = [float(i) for i in self.engine.theme.opt_bkg_size]
        self.opt_text_color = self.engine.theme.opt_text_colorVar
        self.opt_selected_color = self.engine.theme.opt_selected_colorVar

        if self.BGText:
            strCareer = ""
            strQuickplay = ""
            strSolo = ""
            strMultiplayer = ""
            strTraining = ""
            strSettings = ""
            strQuit = ""
        else:
            strCareer = "Career"
            strQuickplay = "Quickplay"
            strSolo = "Solo"
            strMultiplayer = "Multiplayer"
            strTraining = "Training"
            strSettings = "Settings"
            strQuit = "Quit"

        multPlayerMenu = [
            (_("Face-Off"),     lambda: self.newLocalGame(players = 2,             maxplayers = 4)),
            (_("Pro Face-Off"), lambda: self.newLocalGame(players = 2, mode2p = 1, maxplayers = 4)),
            (_("FoFiX Co-Op"),  lambda: self.newLocalGame(players = 2, mode2p = 3, maxplayers = 4, allowMic = allowMic)),
            (_("RB Co-Op"),     lambda: self.newLocalGame(players = 2, mode2p = 4, maxplayers = 4, allowMic = allowMic)),
            (_("GH Battle"),    lambda: self.newLocalGame(players = 2, mode2p = 6, allowDrum = False)), #akedrou- so you can block drums
          ]

        if not self.useSoloMenu:

            mainMenu = [
              (strCareer, lambda:   self.newLocalGame(mode1p = 2, allowMic = allowMic)),
              (strQuickplay, lambda:        self.newLocalGame(allowMic = allowMic)),
              ((strMultiplayer,"multiplayer"), multPlayerMenu),
              ((strTraining,"training"),    trainingMenu),
              ((strSettings,"settings"),  self.settingsMenu),
              (strQuit,        self.quit),
            ]

        else:

            soloMenu = [
              (_("Solo Tour"), lambda: self.newLocalGame(mode1p = 2, allowMic = allowMic)),
              (_("Quickplay"), lambda: self.newLocalGame(allowMic = allowMic)),
            ]

            mainMenu = [
              ((strSolo,"solo"), soloMenu),
              ((strMultiplayer,"multiplayer"), multPlayerMenu),
              ((strTraining,"training"),    trainingMenu),
              ((strSettings,"settings"),  self.settingsMenu),
              (strQuit,        self.quit),
            ]


        w, h, = self.engine.view.geometry[2:4]

        self.menu = Menu(self.engine, mainMenu, onClose = lambda: self.engine.view.popLayer(self), pos = (self.menux, .75-(.75*self.menuy)))

        engine.mainMenu = self    #Points engine.mainMenu to the one and only MainMenu object instance

        ## whether the main menu has come into view at least once
        self.shownOnce = False
Beispiel #39
0
    def __init__(self, engine, playerObj, scene, player = 0):
        super(Drum, self).__init__(engine, playerObj, scene, player=player)

        self.isDrum = True
        self.isBassGuitar = False
        self.isVocal = False

        self.drumsHeldDown = [0, 0, 0, 0, 0]

        self.gameMode2p = self.engine.world.multiMode

        self.lastFretWasBassDrum = False
        self.lastFretWasT1 = False   #Faaa Drum sound
        self.lastFretWasT2 = False
        self.lastFretWasT3 = False
        self.lastFretWasC = False


        self.matchingNotes = []

        #MFH - I do not understand fully how the handicap scorecard works at the moment, nor do I have the time to figure it out.
        #... so for now, I'm just writing some extra code here for the early hitwindow size handicap.
        self.earlyHitWindowSizeFactor = 0.5

        self.starNotesInView = False
        self.openStarNotesInView = False

        self.drumFillsCount = 0
        self.drumFillsTotal = 0
        self.drumFillsHits = 0
        self.drumFillsReady = False

        self.drumFillEvents = []
        self.drumFillWasJustActive = False

        self.strings        = 4
        self.strings2       = 5
        self.playedSound  = [True, True, True, True, True]

        self.openFretActivity = 0.0
        self.openFretColor  = self.fretColors[5]

        self.lanenumber     = float(4)
        self.fretImgColNumber = float(6)

        self.logClassInits = self.engine.config.get("game", "log_class_inits")
        if self.logClassInits == 1:
            log.debug("Drum class initialization!")


        self.freestyleHitFlameCounts = [0 for n in range(self.strings+1)]    #MFH

        self.fretWeight     = [0.0] * self.strings
        self.fretActivity   = [0.0] * self.strings

        #myfingershurt:
        self.hopoStyle = 0

        self.drumFretButtons = None

        #blazingamer
        self.opencolor = self.fretColors[5]
        self.rockLevel = 0.0

        self.bigMax = 1

        if self.engine.config.get("game", "large_drum_neck"):
            self.boardWidth     *= (4.0/3.0)
            self.boardLength    *= (4.0/3.0)

        #Get theme
        #now theme determination logic is only in data.py:
        self.theme = self.engine.data.theme

        self.tailsEnabled = False

        self.loadImages()

        self.barsColor = self.engine.theme.barsColor

        self.neck = Neck(self.engine, self, playerObj)
Beispiel #40
0
 def popAllLayers(self):
     log.debug("View: Pop all")
     [self.popLayer(l) for l in list(self.layers)]
 def checkCmdPlay(self):
     info = song.loadSongInfo(self.engine, self.songName, library = self.libraryName)
     guitars = []
     drums = []
     vocals = []
     autoPart = None
     for part in info.parts:
         if part.id == 4 or part.id == 7:
             drums.append(part)
         elif part.id == 5:
             vocals.append(part)
         else:
             guitars.append(part)
         if self.engine.cmdPlay == 2 and self.engine.cmdPart is not None and len(self.playerList) == 1:
             if self.engine.cmdPart == part.id:
                 log.debug("Command-line mode: Part found!")
                 if part.id == 4 and self.engine.input.gameDrums > 0:
                     autoPart = part.id
                 elif part.id == 5 and self.engine.input.gameMics > 0:
                     autoPart = part.id
                 elif self.engine.input.gameGuitars > 0:
                     autoPart = part.id
     if autoPart is None:
         if len(drums) == 0 and self.engine.input.gameDrums > 0:
             if self.splash:
                 Dialogs.hideLoadingSplashScreen(self.engine, self.splash)
                 self.splash = None
             Dialogs.showMessage(self.engine, _("There are no drum parts in this song. Change your controllers to play."))
             if self.engine.cmdPlay == 2:
                 self.engine.cmdPlay = 0
                 return False
         if len(guitars) == 0 and self.engine.input.gameGuitars > 0:
             if self.splash:
                 Dialogs.hideLoadingSplashScreen(self.engine, self.splash)
                 self.splash = None
             Dialogs.showMessage(self.engine, _("There are no guitar parts in this song. Change your controllers to play."))
             if self.engine.cmdPlay == 2:
                 self.engine.cmdPlay = 0
                 return False
         if len(vocals) == 0 and self.engine.input.gameMics > 0:
             if self.splash:
                 Dialogs.hideLoadingSplashScreen(self.engine, self.splash)
                 self.splash = None
             Dialogs.showMessage(self.engine, _("There are no vocal parts in this song. Change your controllers to play."))
             if self.engine.cmdPlay == 2:
                 self.engine.cmdPlay = 0
                 return False
     # Make sure the difficulty we chose is available
     p = self.playerList[0].part
     player = self.playerList[0]
     if self.engine.cmdDiff is not None:
         diff = song.difficulties[self.engine.cmdDiff]
         if diff in info.partDifficulties[p.id]:
             self.playerList[0].difficulty = diff
         else:
             self.playerList[0].difficulty = info.partDifficulties[p.id][0]
     else:
         if self.splash:
             Dialogs.hideLoadingSplashScreen(self.engine, self.splash)
             self.splash = None
         self.playerList[0].difficulty = Dialogs.chooseItem(self.engine, info.partDifficulties[p.id],
                               "%s \n %s" % (song.removeSongOrderPrefixFromName(info.name), _("%s Choose a difficulty:") % player.name), selected = player.difficulty)
     return True
Beispiel #42
0
    def __init__(self):

        self.logClassInits = Config.get("game", "log_class_inits")
        if self.logClassInits == 1:
            log.debug("Controls class init (Player.py)...")
        self.controls = []
        self.controls.append(Config.get("game", "control0"))
        self.controls.append(Config.get("game", "control1"))
        self.controls.append(Config.get("game", "control2"))
        self.controls.append(Config.get("game", "control3"))
        self.config = []
        self.controlList = []
        self.maxplayers = 0
        self.guitars    = 0
        self.drums      = 0
        self.mics       = 0
        self.overlap    = []

        self.p2Nav = Config.get("game", "p2_menu_nav")
        self.drumNav = Config.get("game", "drum_navigation")

        self.keyCheckerMode = Config.get("game","key_checker_mode")

        if VFS.isfile(_makeControllerIniName(self.controls[0])):
            self.config.append(Config.load(VFS.resolveRead(_makeControllerIniName(self.controls[0])), type = 1))
            if VFS.isfile(_makeControllerIniName(self.controls[1])) and self.controls[1] != "None":
                self.config.append(Config.load(VFS.resolveRead(_makeControllerIniName(self.controls[1])), type = 1))
            else:
                self.config.append(None)
                Config.set("game", "control1", None)
                self.controls[1] = "None"
            if VFS.isfile(_makeControllerIniName(self.controls[2])) and self.controls[2] != "None":
                self.config.append(Config.load(VFS.resolveRead(_makeControllerIniName(self.controls[2])), type = 1))
            else:
                self.config.append(None)
                Config.set("game", "control2", None)
                self.controls[2] = "None"
            if VFS.isfile(_makeControllerIniName(self.controls[3])) and self.controls[3] != "None":
                self.config.append(Config.load(VFS.resolveRead(_makeControllerIniName(self.controls[3])), type = 1))
            else:
                self.config.append(None)
                Config.set("game", "control3", None)
                self.controls[3] = "None"
        else:
            confM = None
            if Microphone.supported:
                confM = Config.load(VFS.resolveRead(_makeControllerIniName("defaultm")), type = 1)
            self.config.append(Config.load(VFS.resolveRead(_makeControllerIniName("defaultg")), type = 1))
            self.config.append(Config.load(VFS.resolveRead(_makeControllerIniName("defaultd")), type = 1))
            self.config.append(confM)
            self.config.append(None)
            Config.set("game", "control0", "defaultg")
            Config.set("game", "control1", "defaultd")
            self.controls = ["defaultg", "defaultd"]
            if confM is not None:
                Config.set("game", "control2", "defaultm")
                self.controls.append("defaultm")
            else:
                Config.set("game", "control2", None)
                self.controls.append("None")
            Config.set("game", "control3", None)
            self.controls.append("None")

        self.type       = []
        self.analogKill = []
        self.analogSP   = []
        self.analogSPThresh = []
        self.analogSPSense  = []
        self.analogDrum = [] #FIXME: Analog Drum
        self.analogSlide = []
        self.analogFX   = [] #FIXME: Analog FX
        self.twoChord   = []
        self.micDevice  = []  #stump
        self.micTapSensitivity = []
        self.micPassthroughVolume = []

        self.flags = 0

        for i in self.config:
            if i:
                type = i.get("controller", "type")
                if type == 5:
                    self.mics += 1
                elif type > 1:
                    self.guitars += 1
                else:
                    self.drums += 1
                self.type.append(type)
                self.analogKill.append(i.get("controller", "analog_kill"))
                self.analogSP.append(i.get("controller", "analog_sp"))
                self.analogSPThresh.append(i.get("controller", "analog_sp_threshold"))
                self.analogSPSense.append(i.get("controller", "analog_sp_sensitivity"))
                self.analogDrum.append(i.get("controller", "analog_drum")) #FIXME: Analog Drum
                self.analogSlide.append(i.get("controller", "analog_slide"))
                self.analogFX.append(i.get("controller", "analog_fx")) #FIXME: Analog FX
                self.micDevice.append(i.get("controller", "mic_device"))  #stump
                self.micTapSensitivity.append(i.get("controller", "mic_tap_sensitivity"))
                self.micPassthroughVolume.append(i.get("controller", "mic_passthrough_volume"))
                self.twoChord.append(i.get("controller", "two_chord_max"))
                self.controlList.append(i.get("controller", "name"))
            else:
                self.type.append(None)
                self.analogKill.append(None)
                self.analogSP.append(None)
                self.analogFX.append(None) #FIXME: Analog FX
                self.twoChord.append(None)

        def keycode(name, config):
            if not config:
                return "None"
            k = config.get("controller", name)
            if k == "None":
                return "None"
            try:
                return int(k)
            except:
                return getattr(pygame, k)

        self.controlMapping = {}
        global menuUp, menuDown, menuNext, menuPrev, menuYes, menuNo
        global drum1s, drum2s, drum3s, drum4s, drum5s, bassdrums
        global key1s, key2s, key3s, key4s, key5s, keysolos, action1s, action2s, kills
        menuUp = []
        menuDown = []
        menuNext = []
        menuPrev = []
        menuYes = []
        menuNo = []
        drum1s = []
        drum2s = []
        drum3s = []
        drum4s = []
        drum5s = []
        bassdrums = []
        key1s = []
        key2s = []
        key3s = []
        key4s = []
        key5s = []
        keysolos = []
        action1s = []
        action2s = []
        kills = []

        for i, config in enumerate(self.config):
            if self.type[i] in DRUMTYPES: #drum set
                drum1s.extend([CONTROLS[i][DRUM1], CONTROLS[i][DRUM1A]])
                drum2s.extend([CONTROLS[i][DRUM2], CONTROLS[i][DRUM2A]])
                drum3s.extend([CONTROLS[i][DRUM3], CONTROLS[i][DRUM3A]])
                drum4s.extend([CONTROLS[i][DRUM4], CONTROLS[i][DRUM4A]])
                drum5s.extend([CONTROLS[i][DRUM5], CONTROLS[i][DRUM5A]])
                bassdrums.extend([CONTROLS[i][DRUMBASS], CONTROLS[i][DRUMBASSA]])
                if self.p2Nav == 1 or (self.p2Nav == 0 and i == 0):
                    if self.drumNav:
                        menuUp.extend([CONTROLS[i][DRUM2], CONTROLS[i][DRUM2A]])
                        if self.type[i] == 3:
                            menuDown.extend([CONTROLS[i][DRUM4], CONTROLS[i][DRUM4A]])
                        else:
                            menuDown.extend([CONTROLS[i][DRUM3], CONTROLS[i][DRUM3A]])
                        menuYes.extend([CONTROLS[i][DRUM5], CONTROLS[i][DRUM5A]])
                        menuNo.extend([CONTROLS[i][DRUM1], CONTROLS[i][DRUM1A]])
                    menuYes.append(CONTROLS[i][START])
                    menuNo.append(CONTROLS[i][CANCEL])
                    menuUp.append(CONTROLS[i][UP])
                    menuDown.append(CONTROLS[i][DOWN])
                    menuNext.append(CONTROLS[i][RIGHT])
                    menuPrev.append(CONTROLS[i][LEFT])
            elif self.type[i] in MICTYPES:  #stump: it's a mic
                if self.p2Nav == 1 or (self.p2Nav == 0 and i == 0):
                    menuUp.append(CONTROLS[i][UP])
                    menuDown.append(CONTROLS[i][DOWN])
                    menuNext.append(CONTROLS[i][RIGHT])
                    menuPrev.append(CONTROLS[i][LEFT])
                    menuYes.append(CONTROLS[i][START])
                    menuNo.append(CONTROLS[i][CANCEL])
            elif self.type[i] in GUITARTYPES:
                if self.type[i] == 0:
                    key1s.extend([CONTROLS[i][KEY1], CONTROLS[i][KEY1A]])
                else:
                    key1s.extend([CONTROLS[i][KEY1]])
                key2s.extend([CONTROLS[i][KEY2], CONTROLS[i][KEY2A]])
                key3s.extend([CONTROLS[i][KEY3], CONTROLS[i][KEY3A]])
                key4s.extend([CONTROLS[i][KEY4], CONTROLS[i][KEY4A]])
                key5s.extend([CONTROLS[i][KEY5], CONTROLS[i][KEY5A]])
                keysolos.extend([CONTROLS[i][KEY1A], CONTROLS[i][KEY2A], CONTROLS[i][KEY3A], CONTROLS[i][KEY4A], CONTROLS[i][KEY5A]])
                action1s.extend([CONTROLS[i][ACTION1]])
                action2s.extend([CONTROLS[i][ACTION2]])
                kills.extend([CONTROLS[i][KILL]])
                if self.p2Nav == 1 or (self.p2Nav == 0 and i == 0):
                    menuUp.extend([CONTROLS[i][ACTION1], CONTROLS[i][UP]])
                    menuDown.extend([CONTROLS[i][ACTION2], CONTROLS[i][DOWN]])
                    menuNext.extend([CONTROLS[i][RIGHT], CONTROLS[i][KEY4], CONTROLS[i][KEY4A]])
                    menuPrev.extend([CONTROLS[i][LEFT], CONTROLS[i][KEY3], CONTROLS[i][KEY3A]])
                    menuYes.extend([CONTROLS[i][KEY1], CONTROLS[i][KEY1A], CONTROLS[i][START]])
                    menuNo.extend([CONTROLS[i][KEY2], CONTROLS[i][KEY2A], CONTROLS[i][CANCEL]])

            if self.type[i] == 3:
                controlMapping = { #akedrou - drums do not need special declarations!
                  keycode("key_left", config):          CONTROLS[i][LEFT],
                  keycode("key_right", config):         CONTROLS[i][RIGHT],
                  keycode("key_up", config):            CONTROLS[i][UP],
                  keycode("key_down", config):          CONTROLS[i][DOWN],
                  keycode("key_star", config):          CONTROLS[i][STAR],
                  keycode("key_cancel", config):        CONTROLS[i][CANCEL],
                  keycode("key_1a", config):            CONTROLS[i][DRUM5A], #order is important. This minimizes key conflicts.
                  keycode("key_2a", config):            CONTROLS[i][DRUM1A],
                  keycode("key_3a", config):            CONTROLS[i][DRUM2A],
                  keycode("key_4a", config):            CONTROLS[i][DRUM3A],
                  keycode("key_5a", config):            CONTROLS[i][DRUM4A],
                  keycode("key_action2", config):       CONTROLS[i][DRUMBASSA],
                  keycode("key_1", config):             CONTROLS[i][DRUM5],
                  keycode("key_2", config):             CONTROLS[i][DRUM1],
                  keycode("key_3", config):             CONTROLS[i][DRUM2],
                  keycode("key_4", config):             CONTROLS[i][DRUM3],
                  keycode("key_5", config):             CONTROLS[i][DRUM4],
                  keycode("key_action1", config):       CONTROLS[i][DRUMBASS],
                  keycode("key_start", config):         CONTROLS[i][START],
                }
            elif self.type[i] == 2:
                controlMapping = { #akedrou - drums do not need special declarations!
                  keycode("key_left", config):          CONTROLS[i][LEFT],
                  keycode("key_right", config):         CONTROLS[i][RIGHT],
                  keycode("key_up", config):            CONTROLS[i][UP],
                  keycode("key_down", config):          CONTROLS[i][DOWN],
                  keycode("key_star", config):          CONTROLS[i][STAR],
                  keycode("key_cancel", config):        CONTROLS[i][CANCEL],
                  keycode("key_1a", config):            CONTROLS[i][DRUM5A], #order is important. This minimizes key conflicts.
                  keycode("key_2a", config):            CONTROLS[i][DRUM1A],
                  keycode("key_3a", config):            CONTROLS[i][DRUM2A],
                  keycode("key_4a", config):            CONTROLS[i][DRUM3A],
                  keycode("key_action2", config):       CONTROLS[i][DRUMBASSA],
                  keycode("key_1", config):             CONTROLS[i][DRUM5],
                  keycode("key_2", config):             CONTROLS[i][DRUM1],
                  keycode("key_3", config):             CONTROLS[i][DRUM2],
                  keycode("key_4", config):             CONTROLS[i][DRUM3],
                  keycode("key_action1", config):       CONTROLS[i][DRUMBASS],
                  keycode("key_start", config):         CONTROLS[i][START],
                }
            elif self.type[i] > -1:
                controlMapping = { #akedrou - drums do not need special declarations!
                  keycode("key_left", config):          CONTROLS[i][LEFT],
                  keycode("key_right", config):         CONTROLS[i][RIGHT],
                  keycode("key_up", config):            CONTROLS[i][UP],
                  keycode("key_down", config):          CONTROLS[i][DOWN],
                  keycode("key_cancel", config):        CONTROLS[i][CANCEL],
                  keycode("key_star", config):          CONTROLS[i][STAR],
                  keycode("key_kill", config):          CONTROLS[i][KILL],
                  keycode("key_1a", config):            CONTROLS[i][KEY1A], #order is important. This minimizes key conflicts.
                  keycode("key_2a", config):            CONTROLS[i][KEY2A],
                  keycode("key_3a", config):            CONTROLS[i][KEY3A],
                  keycode("key_4a", config):            CONTROLS[i][KEY4A],
                  keycode("key_5a", config):            CONTROLS[i][KEY5A],
                  keycode("key_1", config):             CONTROLS[i][KEY1],
                  keycode("key_2", config):             CONTROLS[i][KEY2],
                  keycode("key_3", config):             CONTROLS[i][KEY3],
                  keycode("key_4", config):             CONTROLS[i][KEY4],
                  keycode("key_5", config):             CONTROLS[i][KEY5],
                  keycode("key_action2", config):       CONTROLS[i][ACTION2],
                  keycode("key_action1", config):       CONTROLS[i][ACTION1],
                  keycode("key_start", config):         CONTROLS[i][START],
                }
            else:
                controlMapping = {}
            controlMapping = self.checkMapping(controlMapping, i)
            self.controlMapping.update(controlMapping)

        self.reverseControlMapping = dict((value, key) for key, value in self.controlMapping.iteritems() )

        # Multiple key support
        self.heldKeys = {}
Beispiel #43
0
    def load(self, libraryName, songName, practiceMode = False):
        if self.scene.coOpType:
            rm = os.path.join("themes", self.themename, "rockmeter_coop.ini")
        elif self.scene.battle:
            rm = os.path.join("themes", self.themename, "rockmeter_profaceoff.ini")
        elif self.scene.gamePlayers > 1:
            rm = os.path.join("themes", self.themename, "rockmeter_faceoff.ini")
        else:
            rm = os.path.join("themes", self.themename, "rockmeter.ini")

        if os.path.exists(os.path.join("..", "data", rm)):
            rockmeter = self.engine.resource.fileName(rm)
        else:
            rockmeter = self.engine.resource.fileName(os.path.join("themes", self.themename, "rockmeter.ini"))

        self.rockmeter = Rockmeter.Rockmeter(self.scene, rockmeter, self.scene.coOpType)

        # evilynux - Fixes a self.background not defined crash
        self.background = None
        #MFH - new background stage logic:
        if self.mode == 2:   #blank / no stage
            self.songStage = 0
            self.rotationMode = 0
        elif practiceMode:   #check for existing practice stage; always disable stage rotation here
            self.songStage = 0
            self.rotationMode = 0
            self.mode = 1
            #separated practice stages for the instruments by k.i.d
            if self.scene.instruments[0].isDrum:
                background = "practicedrum"
            elif self.scene.instruments[0].isBassGuitar:
                background = "practicebass"
            else:
                background = "practice"
            if not self.engine.loadImgDrawing(self, "background", os.path.join("themes",self.themename,"backgrounds",background)):
                #MFH - must first fall back on the old practice.png before forcing blank stage mode!
                if not self.engine.loadImgDrawing(self, "background", os.path.join("themes",self.themename,"backgrounds","practice")):
                    log.warn("No practice stage, falling back on a forced Blank stage mode") # evilynux
                    self.mode = 2    #if no practice stage, just fall back on a forced Blank stage mode

        elif self.songStage == 1:    #check for song-specific background
            test = True
            if not self.engine.loadImgDrawing(self, "background", os.path.join(libraryName, songName, "background")):
                log.notice("No song-specific stage found") # evilynux
                test = False
            if test:  #does a song-specific background exist?
                self.rotationMode = 0
                self.mode = 1
            else:
                self.songStage = 0

        #MFH - now, after the above logic, we can run the normal stage mode logic
        #      only worrying about checking for Blank, song-specific and
        #      practice stage modes
        if self.mode != 2 and self.mode != 3 and self.songStage == 0 and not practiceMode: #still need to load stage(s)
            #myfingershurt: assign this first
            if self.mode == 1:   #just use Default.png
                if not self.engine.loadImgDrawing(self, "background", os.path.join(self.path, "default")):
                    log.warn("No default stage; falling back on a forced Blank stage mode") # evilynux
                    self.mode = 2    #if no practice stage, just fall back on a forced Blank stage mode

            ##This checks how many Stage-background we have to select from
            if self.mode == 0 and self.rotationMode == 0:  #MFH: just display a random stage
                files = []
                fileIndex = 0
                allfiles = os.listdir(self.pathfull)
                for name in allfiles:
                    if os.path.splitext(name)[0].lower() != "practice" and os.path.splitext(name)[0].lower() != "practicedrum" and os.path.splitext(name)[0].lower() != "practicebass" and name != ".git":
                        log.debug("Valid background found, index (" + str(fileIndex) + "): " + name)
                        files.append(name)
                        fileIndex += 1
                    else:
                        log.debug("Practice background filtered: " + name)

                # evilynux - improved error handling, fallback to blank background if no background are found
                if fileIndex == 0:
                    log.warn("No valid stage found!")
                    self.mode = 2;
                else:
                    i = random.randint(0,len(files)-1)
                    filename = files[i]
            ##End check number of Stage-backgrounds
                    if not self.engine.loadImgDrawing(self, "background", os.path.join(self.path, filename)):
                        self.mode = 2;

            elif self.rotationMode > 0 and self.mode != 2:
                files = []
                fileIndex = 0

                if self.animatedFolder == "Random": #Select one of the subfolders under stages\ to animate randomly
                    numAniStageFolders = len(self.engine.stageFolders)
                    if numAniStageFolders > 0:
                        self.animatedFolder = random.choice(self.engine.stageFolders)
                    else:
                        self.animatedFolder = "Normal"

                elif self.animatedFolder == "None":
                    self.mode = 2

                if self.animatedFolder != "Normal" and self.mode != 2: #just use the base Stages folder for rotation
                    self.path = os.path.join("themes",self.themename,"backgrounds",self.animatedFolder)
                    self.pathfull = self.engine.getPath(self.path)
                    self.animation = True

                allfiles = os.listdir(self.pathfull)
                for name in allfiles:

                    if os.path.splitext(name)[1].lower() == ".png" or os.path.splitext(name)[1].lower() == ".jpg" or os.path.splitext(name)[1].lower() == ".jpeg":
                        if os.path.splitext(name)[0].lower() != "practice" and os.path.splitext(name)[0].lower() != "practicedrum" and os.path.splitext(name)[0].lower() != "practicebass":
                            log.debug("Valid background found, index (" + str(fileIndex) + "): " + name)
                            files.append(name)
                            fileIndex += 1
                        else:
                            log.debug("Practice background filtered: " + name)
                    files.sort()

            if self.rotationMode > 0 and self.mode != 2:   #alarian: blank stage option is not selected
            #myfingershurt: just populate the image array in order, they are pulled in whatever order requested:
                for j in range(len(files)):
                    self.engine.loadImgDrawing(self, "backgroundA", os.path.join(self.path, files[j]))
                    self.imgArr.append(getattr(self, "backgroundA", os.path.join(self.path, files[j])))

        if self.rotationMode > 0 and len(self.imgArr) == 0:
            self.rotationMode = 0
Beispiel #44
0
    def __init__(self):

        self.logClassInits = Config.get("game", "log_class_inits")
        if self.logClassInits == 1:
            log.debug("Controls class init (Player.py)...")
        self.controls = []
        self.controls.append(Config.get("game", "control0"))
        self.controls.append(Config.get("game", "control1"))
        self.controls.append(Config.get("game", "control2"))
        self.controls.append(Config.get("game", "control3"))
        self.config = []
        self.controlList = []
        self.maxplayers = 0
        self.guitars    = 0
        self.drums      = 0
        self.mics       = 0
        self.overlap    = []

        self.p2Nav = Config.get("game", "p2_menu_nav")
        self.drumNav = Config.get("game", "drum_navigation")

        self.keyCheckerMode = Config.get("game","key_checker_mode")

        if VFS.isfile(_makeControllerIniName(self.controls[0])):
            self.config.append(Config.load(VFS.resolveRead(_makeControllerIniName(self.controls[0])), type = 1))
            if VFS.isfile(_makeControllerIniName(self.controls[1])) and self.controls[1] != "None":
                self.config.append(Config.load(VFS.resolveRead(_makeControllerIniName(self.controls[1])), type = 1))
            else:
                self.config.append(None)
                Config.set("game", "control1", None)
                self.controls[1] = "None"
            if VFS.isfile(_makeControllerIniName(self.controls[2])) and self.controls[2] != "None":
                self.config.append(Config.load(VFS.resolveRead(_makeControllerIniName(self.controls[2])), type = 1))
            else:
                self.config.append(None)
                Config.set("game", "control2", None)
                self.controls[2] = "None"
            if VFS.isfile(_makeControllerIniName(self.controls[3])) and self.controls[3] != "None":
                self.config.append(Config.load(VFS.resolveRead(_makeControllerIniName(self.controls[3])), type = 1))
            else:
                self.config.append(None)
                Config.set("game", "control3", None)
                self.controls[3] = "None"
        else:
            confM = None
            if Microphone.supported:
                confM = Config.load(VFS.resolveRead(_makeControllerIniName("defaultm")), type = 1)
            self.config.append(Config.load(VFS.resolveRead(_makeControllerIniName("defaultg")), type = 1))
            self.config.append(Config.load(VFS.resolveRead(_makeControllerIniName("defaultd")), type = 1))
            self.config.append(confM)
            self.config.append(None)
            Config.set("game", "control0", "defaultg")
            Config.set("game", "control1", "defaultd")
            self.controls = ["defaultg", "defaultd"]
            if confM is not None:
                Config.set("game", "control2", "defaultm")
                self.controls.append("defaultm")
            else:
                Config.set("game", "control2", None)
                self.controls.append("None")
            Config.set("game", "control3", None)
            self.controls.append("None")

        self.type       = []
        self.analogKill = []
        self.analogSP   = []
        self.analogSPThresh = []
        self.analogSPSense  = []
        self.analogDrum = [] #FIXME: Analog Drum
        self.analogSlide = []
        self.analogFX   = [] #FIXME: Analog FX
        self.twoChord   = []
        self.micDevice  = []  #stump
        self.micTapSensitivity = []
        self.micPassthroughVolume = []

        self.flags = 0

        for i in self.config:
            if i:
                type = i.get("controller", "type")
                if type == 5:
                    self.mics += 1
                elif type > 1:
                    self.guitars += 1
                else:
                    self.drums += 1
                self.type.append(type)
                self.analogKill.append(i.get("controller", "analog_kill"))
                self.analogSP.append(i.get("controller", "analog_sp"))
                self.analogSPThresh.append(i.get("controller", "analog_sp_threshold"))
                self.analogSPSense.append(i.get("controller", "analog_sp_sensitivity"))
                self.analogDrum.append(i.get("controller", "analog_drum")) #FIXME: Analog Drum
                self.analogSlide.append(i.get("controller", "analog_slide"))
                self.analogFX.append(i.get("controller", "analog_fx")) #FIXME: Analog FX
                self.micDevice.append(i.get("controller", "mic_device"))  #stump
                self.micTapSensitivity.append(i.get("controller", "mic_tap_sensitivity"))
                self.micPassthroughVolume.append(i.get("controller", "mic_passthrough_volume"))
                self.twoChord.append(i.get("controller", "two_chord_max"))
                self.controlList.append(i.get("controller", "name"))
            else:
                self.type.append(None)
                self.analogKill.append(None)
                self.analogSP.append(None)
                self.analogFX.append(None) #FIXME: Analog FX
                self.twoChord.append(None)

        def keycode(name, config):
            if not config:
                return "None"
            k = config.get("controller", name)
            if k == "None":
                return "None"
            try:
                return int(k)
            except:
                return getattr(pygame, k)

        self.controlMapping = {}
        global menuUp, menuDown, menuNext, menuPrev, menuYes, menuNo
        global drum1s, drum2s, drum3s, drum4s, drum5s, bassdrums
        global key1s, key2s, key3s, key4s, key5s, keysolos, action1s, action2s, kills
        menuUp = []
        menuDown = []
        menuNext = []
        menuPrev = []
        menuYes = []
        menuNo = []
        drum1s = []
        drum2s = []
        drum3s = []
        drum4s = []
        drum5s = []
        bassdrums = []
        key1s = []
        key2s = []
        key3s = []
        key4s = []
        key5s = []
        keysolos = []
        action1s = []
        action2s = []
        kills = []

        for i, config in enumerate(self.config):
            if self.type[i] in DRUMTYPES: #drum set
                drum1s.extend([CONTROLS[i][DRUM1], CONTROLS[i][DRUM1A]])
                drum2s.extend([CONTROLS[i][DRUM2], CONTROLS[i][DRUM2A]])
                drum3s.extend([CONTROLS[i][DRUM3], CONTROLS[i][DRUM3A]])
                drum4s.extend([CONTROLS[i][DRUM4], CONTROLS[i][DRUM4A]])
                drum5s.extend([CONTROLS[i][DRUM5], CONTROLS[i][DRUM5A]])
                bassdrums.extend([CONTROLS[i][DRUMBASS], CONTROLS[i][DRUMBASSA]])
                if self.p2Nav == 1 or (self.p2Nav == 0 and i == 0):
                    if self.drumNav:
                        menuUp.extend([CONTROLS[i][DRUM2], CONTROLS[i][DRUM2A]])
                        if self.type[i] == 3:
                            menuDown.extend([CONTROLS[i][DRUM4], CONTROLS[i][DRUM4A]])
                        else:
                            menuDown.extend([CONTROLS[i][DRUM3], CONTROLS[i][DRUM3A]])
                        menuYes.extend([CONTROLS[i][DRUM5], CONTROLS[i][DRUM5A]])
                        menuNo.extend([CONTROLS[i][DRUM1], CONTROLS[i][DRUM1A]])
                    menuYes.append(CONTROLS[i][START])
                    menuNo.append(CONTROLS[i][CANCEL])
                    menuUp.append(CONTROLS[i][UP])
                    menuDown.append(CONTROLS[i][DOWN])
                    menuNext.append(CONTROLS[i][RIGHT])
                    menuPrev.append(CONTROLS[i][LEFT])
            elif self.type[i] in MICTYPES:  #stump: it's a mic
                if self.p2Nav == 1 or (self.p2Nav == 0 and i == 0):
                    menuUp.append(CONTROLS[i][UP])
                    menuDown.append(CONTROLS[i][DOWN])
                    menuNext.append(CONTROLS[i][RIGHT])
                    menuPrev.append(CONTROLS[i][LEFT])
                    menuYes.append(CONTROLS[i][START])
                    menuNo.append(CONTROLS[i][CANCEL])
            elif self.type[i] in GUITARTYPES:
                if self.type[i] == 0:
                    key1s.extend([CONTROLS[i][KEY1], CONTROLS[i][KEY1A]])
                else:
                    key1s.extend([CONTROLS[i][KEY1]])
                key2s.extend([CONTROLS[i][KEY2], CONTROLS[i][KEY2A]])
                key3s.extend([CONTROLS[i][KEY3], CONTROLS[i][KEY3A]])
                key4s.extend([CONTROLS[i][KEY4], CONTROLS[i][KEY4A]])
                key5s.extend([CONTROLS[i][KEY5], CONTROLS[i][KEY5A]])
                keysolos.extend([CONTROLS[i][KEY1A], CONTROLS[i][KEY2A], CONTROLS[i][KEY3A], CONTROLS[i][KEY4A], CONTROLS[i][KEY5A]])
                action1s.extend([CONTROLS[i][ACTION1]])
                action2s.extend([CONTROLS[i][ACTION2]])
                kills.extend([CONTROLS[i][KILL]])
                if self.p2Nav == 1 or (self.p2Nav == 0 and i == 0):
                    menuUp.extend([CONTROLS[i][ACTION1], CONTROLS[i][UP]])
                    menuDown.extend([CONTROLS[i][ACTION2], CONTROLS[i][DOWN]])
                    menuNext.extend([CONTROLS[i][RIGHT], CONTROLS[i][KEY4], CONTROLS[i][KEY4A]])
                    menuPrev.extend([CONTROLS[i][LEFT], CONTROLS[i][KEY3], CONTROLS[i][KEY3A]])
                    menuYes.extend([CONTROLS[i][KEY1], CONTROLS[i][KEY1A], CONTROLS[i][START]])
                    menuNo.extend([CONTROLS[i][KEY2], CONTROLS[i][KEY2A], CONTROLS[i][CANCEL]])

            if self.type[i] == 3:
                controlMapping = { #akedrou - drums do not need special declarations!
                  keycode("key_left", config):          CONTROLS[i][LEFT],
                  keycode("key_right", config):         CONTROLS[i][RIGHT],
                  keycode("key_up", config):            CONTROLS[i][UP],
                  keycode("key_down", config):          CONTROLS[i][DOWN],
                  keycode("key_star", config):          CONTROLS[i][STAR],
                  keycode("key_cancel", config):        CONTROLS[i][CANCEL],
                  keycode("key_1a", config):            CONTROLS[i][DRUM5A], #order is important. This minimizes key conflicts.
                  keycode("key_2a", config):            CONTROLS[i][DRUM1A],
                  keycode("key_3a", config):            CONTROLS[i][DRUM2A],
                  keycode("key_4a", config):            CONTROLS[i][DRUM3A],
                  keycode("key_5a", config):            CONTROLS[i][DRUM4A],
                  keycode("key_action2", config):       CONTROLS[i][DRUMBASSA],
                  keycode("key_1", config):             CONTROLS[i][DRUM5],
                  keycode("key_2", config):             CONTROLS[i][DRUM1],
                  keycode("key_3", config):             CONTROLS[i][DRUM2],
                  keycode("key_4", config):             CONTROLS[i][DRUM3],
                  keycode("key_5", config):             CONTROLS[i][DRUM4],
                  keycode("key_action1", config):       CONTROLS[i][DRUMBASS],
                  keycode("key_start", config):         CONTROLS[i][START],
                }
            elif self.type[i] == 2:
                controlMapping = { #akedrou - drums do not need special declarations!
                  keycode("key_left", config):          CONTROLS[i][LEFT],
                  keycode("key_right", config):         CONTROLS[i][RIGHT],
                  keycode("key_up", config):            CONTROLS[i][UP],
                  keycode("key_down", config):          CONTROLS[i][DOWN],
                  keycode("key_star", config):          CONTROLS[i][STAR],
                  keycode("key_cancel", config):        CONTROLS[i][CANCEL],
                  keycode("key_1a", config):            CONTROLS[i][DRUM5A], #order is important. This minimizes key conflicts.
                  keycode("key_2a", config):            CONTROLS[i][DRUM1A],
                  keycode("key_3a", config):            CONTROLS[i][DRUM2A],
                  keycode("key_4a", config):            CONTROLS[i][DRUM3A],
                  keycode("key_action2", config):       CONTROLS[i][DRUMBASSA],
                  keycode("key_1", config):             CONTROLS[i][DRUM5],
                  keycode("key_2", config):             CONTROLS[i][DRUM1],
                  keycode("key_3", config):             CONTROLS[i][DRUM2],
                  keycode("key_4", config):             CONTROLS[i][DRUM3],
                  keycode("key_action1", config):       CONTROLS[i][DRUMBASS],
                  keycode("key_start", config):         CONTROLS[i][START],
                }
            elif self.type[i] > -1:
                controlMapping = { #akedrou - drums do not need special declarations!
                  keycode("key_left", config):          CONTROLS[i][LEFT],
                  keycode("key_right", config):         CONTROLS[i][RIGHT],
                  keycode("key_up", config):            CONTROLS[i][UP],
                  keycode("key_down", config):          CONTROLS[i][DOWN],
                  keycode("key_cancel", config):        CONTROLS[i][CANCEL],
                  keycode("key_star", config):          CONTROLS[i][STAR],
                  keycode("key_kill", config):          CONTROLS[i][KILL],
                  keycode("key_1a", config):            CONTROLS[i][KEY1A], #order is important. This minimizes key conflicts.
                  keycode("key_2a", config):            CONTROLS[i][KEY2A],
                  keycode("key_3a", config):            CONTROLS[i][KEY3A],
                  keycode("key_4a", config):            CONTROLS[i][KEY4A],
                  keycode("key_5a", config):            CONTROLS[i][KEY5A],
                  keycode("key_1", config):             CONTROLS[i][KEY1],
                  keycode("key_2", config):             CONTROLS[i][KEY2],
                  keycode("key_3", config):             CONTROLS[i][KEY3],
                  keycode("key_4", config):             CONTROLS[i][KEY4],
                  keycode("key_5", config):             CONTROLS[i][KEY5],
                  keycode("key_action2", config):       CONTROLS[i][ACTION2],
                  keycode("key_action1", config):       CONTROLS[i][ACTION1],
                  keycode("key_start", config):         CONTROLS[i][START],
                }
            else:
                controlMapping = {}
            controlMapping = self.checkMapping(controlMapping, i)
            self.controlMapping.update(controlMapping)

        self.reverseControlMapping = dict((value, key) for key, value in self.controlMapping.iteritems() )

        # Multiple key support
        self.heldKeys = {}
Beispiel #45
0
    def __init__(self, engine, playerObj, scene, player=0, bass=False):
        super(Guitar, self).__init__(engine, playerObj, scene, player=player)

        self.isDrum = False
        self.isBassGuitar = bass
        self.isVocal = False

        self.strings = 5
        self.strings2 = 5

        self.debugMode = False
        self.gameMode2p = self.engine.world.multiMode
        self.matchingNotes = []

        self.logClassInits = self.engine.config.get("game", "log_class_inits")
        if self.logClassInits == 1:
            log.debug("Guitar class init...")

        self.lastPlayedNotes = [
        ]  #MFH - for reverting when game discovers it implied incorrectly

        self.missedNotes = []

        self.freestyleHitFlameCounts = [0
                                        for n in range(self.strings + 1)]  #MFH

        self.fretWeight = [0.0] * self.strings
        self.fretActivity = [0.0] * self.strings

        self.drumFretButtons = None

        #myfingershurt:
        self.hopoStyle = self.engine.config.get("game", "hopo_system")
        self.sfxVolume = self.engine.config.get("audio", "SFX_volume")

        #blazingamer
        self.killfx = self.engine.config.get("performance", "killfx")
        self.killCount = 0

        self.bigMax = 1

        #Get theme
        #now theme determination logic is only in data.py:
        self.theme = self.engine.data.theme

        self.oFlash = None

        self.lanenumber = float(5)
        self.fretImgColNumber = float(3)

        #myfingershurt:
        self.bassGrooveNeckMode = self.engine.config.get(
            "game", "bass_groove_neck")

        self.tailsEnabled = True

        self.loadImages()

        self.twoChordMax = False

        self.rockLevel = 0.0

        self.neck = Neck(self.engine, self, playerObj)
Beispiel #46
0
    def __init__(self, engine, choices, name = None, onClose = None, onCancel = None, pos = (.2, .31), viewSize = 6, fadeScreen = False, font = "font", mainMenu = None, textColor = None, selectedColor = None, append_submenu_char = True, selectedIndex = None, showTips = True, selectedBox = False):
        self.engine       = engine

        self.logClassInits = self.engine.config.get("game", "log_class_inits")
        if self.logClassInits == 1:
            log.debug("Menu class init (Menu.py)...")

        #Get theme
        self.themename = self.engine.data.themeLabel
        self.theme = self.engine.data.theme

        self.choices      = []
        self.currentIndex = 0
        #MFH
        if selectedIndex:
            self.currentIndex = selectedIndex
        self.time         = 0
        self.onClose      = onClose
        self.onCancel     = onCancel
        self.viewOffset   = 0
        self.name     = name # akedrou - for graphical support
        self.mainMenu = False
        self.graphicMenu = False
        self.useSelectedBox = selectedBox
        self.useGraphics = self.engine.config.get("game", "use_graphical_submenu")
        self.gfxText = None

        self.scrolling = 0
        self.delay     = 0
        self.rate      = 0
        self.scroller  = [0, self.scrollUp, self.scrollDown, self.scrollLeft, self.scrollRight]

        self.textColor = textColor
        self.selectedColor = selectedColor
        self.tipColor = self.engine.theme.menuTipTextColor

        self.drumNav = self.engine.config.get("game", "drum_navigation")  #MFH

        if self.name and self.useGraphics > 0:
            try:
                if self.engine.loadImgDrawing(self, "menuBackground", os.path.join("themes",self.themename,"menu","%s.png" % self.name)):
                    if self.menuBackground.height1() == 1:
                        raise KeyError
                else:
                    raise KeyError
                self.gfxText = "%stext%d" % (self.name, len(choices))
                if not self.engine.loadImgDrawing(self, "menuText", os.path.join("themes",self.themename,"menu","%s.png" % self.gfxText)):
                    raise KeyError
                self.graphicMenu = True
                self.menux = self.engine.theme.submenuX[self.gfxText]
                self.menuy = self.engine.theme.submenuY[self.gfxText]
                self.menuScale = self.engine.theme.submenuScale[self.gfxText]
                self.vSpace = self.engine.theme.submenuVSpace[self.gfxText]
                if str(self.menux) != "None" and str(self.menuy) != "None":
                    self.menux = float(self.menux)
                    self.menuy = float(self.menuy)
                else:
                    self.menux = .4
                    self.menuy = .4
                if str(self.menuScale) != "None":
                    self.menuScale = float(self.menuScale)
                else:
                    self.menuScale = .5
                if str(self.vSpace) != "None":
                    self.vSpace = float(self.vSpace)
                else:
                    self.vSpace = .08
                log.debug("Graphic menu enabled for submenu: %s" % self.name)
            except KeyError:
                log.warn("Your theme does not appear to properly support the %s graphical submenu. Check to be sure you have the latest version of your theme." % self.name)
                self.menuBackground = None
                self.menuText = None


        if pos == (.2, .66 - .35):  #MFH - default position, not called with a special one - this is a submenu:
            self.sub_menu_x = self.engine.theme.sub_menu_xVar
            self.sub_menu_y = self.engine.theme.sub_menu_yVar

            if engine.data.theme == 0:
                if self.sub_menu_x is None:
                    self.sub_menu_x = .44
                if self.sub_menu_y is None:
                    self.sub_menu_y = .14
            elif engine.data.theme == 1:
                if self.sub_menu_x is None:
                    self.sub_menu_x = .38
                if self.sub_menu_y is None:
                    self.sub_menu_y = .15
            elif engine.data.theme == 2:
                if self.sub_menu_x is None:
                    self.sub_menu_x = .25
                if self.sub_menu_y is None:
                    self.sub_menu_y = .14

            pos = (self.sub_menu_x, self.sub_menu_y)

        if viewSize == 6:   #MFH - default viewsize
            if self.theme in [0, 1, 2]:#8bit
                viewSize = 10

        self.pos          = pos
        self.viewSize     = viewSize
        self.fadeScreen   = fadeScreen
        self.font         = font
        if self.font == "font":
            self.font = self.engine.data.font
        self.tipFont = self.engine.theme.menuTipTextFont
        if self.tipFont == "None":
            self.tipFont = self.font
        else:
            self.tipFont = self.engine.data.fontDict[self.tipFont]
        self.active = False
        self.mainMenu = mainMenu

        self.showTips = showTips
        if self.showTips:
            self.showTips = self.engine.theme.menuTipTextDisplay
        self.tipDelay = 700
        self.tipTimerEnabled = False
        self.tipScroll = 0
        self.tipScrollB = None
        self.tipScrollSpace = self.engine.theme.menuTipTextScrollSpace
        self.tipScale = self.engine.theme.menuTipTextScale
        self.tipDir = 0
        self.tipSize = 0
        self.tipY = self.engine.theme.menuTipTextY
        self.tipScrollMode = self.engine.theme.menuTipTextScrollMode # - 0 for constant scroll; 1 for back and forth

        for c in choices:
            try:
                text, callback = c
                if isinstance(text, tuple):
                    if len(text) == 2: # a submenu's name
                        c = Choice(text[0], callback, name = text[1], append_submenu_char = append_submenu_char)
                    else: # Dialogs menus - FileChooser, NeckChooser, ItemChooser - this last to be changed soon
                        c = Choice(text[0], callback, values = text[2], valueIndex = text[1], append_submenu_char = append_submenu_char)
                else:
                    c = Choice(text, callback, append_submenu_char = append_submenu_char)
            except ValueError:
                text, callback, tipText = c
                if isinstance(text, tuple):
                    if len(text) == 2: # a submenu's name
                        c = Choice(text[0], callback, name = text[1], append_submenu_char = append_submenu_char, tipText = tipText)
                    else: # Dialogs menus - FileChooser, NeckChooser, ItemChooser - this last to be changed soon
                        c = Choice(text[0], callback, values = text[2], valueIndex = text[1], append_submenu_char = append_submenu_char, tipText = tipText)
                else:
                    c = Choice(text, callback, append_submenu_char = append_submenu_char, tipText = tipText)
            except TypeError:
                pass
            self.choices.append(c)

        self.setTipScroll()
Beispiel #47
0
    def __init__(self, config = None):

        log.debug("GameEngine class init (GameEngine.py)...")
        self.mainMenu = None    #placeholder for main menu object - to prevent reinstantiation

        self.currentScene = None

        self.versionString = version  #stump: other version stuff moved to allow full version string to be retrieved without instantiating GameEngine
        self.uploadVersion = "%s-4.0" % Version.PROGRAM_NAME #akedrou - the version passed to the upload site.

        self.dataPath = Version.dataPath()
        log.debug(self.versionString + " starting up...")
        log.debug("Python version: " + sys.version.split(' ')[0])
        log.debug("Pygame version: " + str(pygame.version.ver) )
        log.debug("PyOpenGL version: " + OpenGL.__version__)
        log.debug("Numpy version: " + np.__version__)
        log.debug("PIL version: " + Image.VERSION)
        log.debug("sys.argv: " + repr(sys.argv))
        log.debug("os.name: " + os.name)
        log.debug("sys.platform: " + sys.platform)
        if os.name == 'nt':
            import win32api
            log.debug("win32api.GetVersionEx(1): " + repr(win32api.GetVersionEx(1)))
        elif os.name == 'posix':
            log.debug("os.uname(): " + repr(os.uname()))

        """
        Constructor.
        @param config:  L{Config} instance for settings
        """

        self.tutorialFolder = "tutorials"

        if not config:
            config = Config.load()

        self.config  = config

        self.fps = self.config.get("video", "fps")

        self.running = True
        self.clock = FpsTimer()
        self.tickDelta = 0
        self.task = TaskEngine(self)

        # Compatiblity task management
        self.addTask = self.task.addTask
        self.removeTask = self.task.removeTask
        self.pauseTask = self.task.pauseTask
        self.resumeTask = self.task.resumeTask

        self.title             = self.versionString
        self.restartRequested  = False

        # evilynux - Check if theme icon exists first, then fallback on FoFiX icon.
        themename = self.config.get("coffee", "themename")
        themeicon = os.path.join(Version.dataPath(), "themes", themename, "icon.png")
        fofixicon = os.path.join(Version.dataPath(), "fofix_icon.png")
        icon = None
        if os.path.exists(themeicon):
            icon = themeicon
        elif os.path.exists(fofixicon):
            icon = fofixicon

        self.video             = Video(self.title, icon)
        if self.config.get("video", "disable_screensaver"):
            self.video.disableScreensaver()

        self.audio             = Audio()
        self.fpsEstimate       = 0
        self.priority          = self.config.get("engine", "highpriority")
        self.show_fps          = self.config.get("video", "show_fps")
        self.advSettings       = self.config.get("game", "adv_settings")
        self.restartRequired   = False
        self.quicksetRestart   = False
        self.quicksetPerf      = self.config.get("quickset", "performance")
        self.scrollRate        = self.config.get("game", "scroll_rate")
        self.scrollDelay       = self.config.get("game", "scroll_delay")

        log.debug("Initializing audio.")
        frequency    = self.config.get("audio", "frequency")
        bits         = self.config.get("audio", "bits")
        stereo       = self.config.get("audio", "stereo")
        bufferSize   = self.config.get("audio", "buffersize")
        self.audio.open(frequency = frequency, bits = bits, stereo = stereo, bufferSize = bufferSize)

        self.cmdPlay           = 0
        self.cmdMode           = None
        self.cmdDiff           = None
        self.cmdPart           = None

        self.gameStarted       = False
        self.world             = None

        self.audioSpeedFactor  = 1.0

        log.debug("Initializing video.")
        #myfingershurt: ensuring windowed mode starts up in center of the screen instead of cascading positions:
        os.environ['SDL_VIDEO_WINDOW_POS'] = 'center'

        width, height = [int(s) for s in self.config.get("video", "resolution").split("x")]
        fullscreen    = self.config.get("video", "fullscreen")
        multisamples  = self.config.get("video", "multisamples")
        self.video.setMode((width, height), fullscreen = fullscreen, multisamples = multisamples)
        log.debug("OpenGL version: " + glGetString(GL_VERSION))
        log.debug("OpenGL vendor: " + glGetString(GL_VENDOR))
        log.debug("OpenGL renderer: " + glGetString(GL_RENDERER))
        log.debug("OpenGL extensions: " + ' '.join(sorted(glGetString(GL_EXTENSIONS).split())))

        if self.video.default:
            self.config.set("video", "fullscreen", False)
            self.config.set("video", "resolution", "800x600")

        if self.config.get("video", "shader_use"):
            shaders.set(os.path.join(Version.dataPath(), "shaders"))

        # Enable the high priority timer if configured
        if self.priority:
            log.debug("Enabling high priority timer.")
            self.fps = 0 # High priority

        # evilynux - This was generating an error on the first pass (at least under
        #            GNU/Linux) as the Viewport was not set yet.
        try:
            viewport = glGetIntegerv(GL_VIEWPORT)
        except:
            viewport = [0, 0, width, height]
        h = viewport[3] - viewport[1]
        w = viewport[2] - viewport[0]
        geometry = (0, 0, w, h)
        self.svg = SvgContext(geometry)
        glViewport(int(viewport[0]), int(viewport[1]), int(viewport[2]), int(viewport[3]))

        self.startupMessages   = self.video.error
        self.input     = Input()
        self.view      = View(self, geometry)
        self.resizeScreen(w, h)

        self.resource  = Resource(Version.dataPath())
        self.mainloop  = self.loading
        self.menuMusic = False

        self.setlistMsg = None


        # Load game modifications
        Mod.init(self)
        self.task.addTask(self.input, synced = False)

        self.task.addTask(self.view, synced = False)

        self.task.addTask(self.resource, synced = False)

        self.data = Data(self.resource, self.svg)

        ##MFH: Animated stage folder selection option
        #<themename>\Stages still contains the backgrounds for when stage rotation is off, and practice.png
        #subfolders under Stages\ will each be treated as a separate animated stage set

        self.stageFolders = []
        currentTheme = themename

        stagespath = os.path.join(Version.dataPath(), "themes", currentTheme, "backgrounds")
        themepath  = os.path.join(Version.dataPath(), "themes", currentTheme)
        if os.path.exists(stagespath):
            self.stageFolders = []
            allFolders = os.listdir(stagespath)   #this also includes all the stage files - so check to see if there is at least one .png file inside each folder to be sure it's an animated stage folder
            for name in allFolders:
                aniStageFolderListing = []
                thisIsAnAnimatedStageFolder = False
                try:
                    aniStageFolderListing = os.listdir(os.path.join(stagespath,name))
                except Exception:
                    thisIsAnAnimatedStageFolder = False
                for aniFile in aniStageFolderListing:
                    if os.path.splitext(aniFile)[1] in [".png", ".jpg", ".jpeg"]:
                        # we've found at least one .png file here, chances are this is a valid animated stage folder
                        thisIsAnAnimatedStageFolder = True
                if thisIsAnAnimatedStageFolder:
                    self.stageFolders.append(name)


            i = len(self.stageFolders)
            if i > 0: #only set default to first animated subfolder if one exists - otherwise use Normal!
                defaultAniStage = str(self.stageFolders[0])
            else:
                defaultAniStage = "Normal"
            log.debug("Default animated stage for " + currentTheme + " theme = " + defaultAniStage)
            aniStageOptions = dict([(str(self.stageFolders[n]),self.stageFolders[n]) for n in range(0, i)])
            aniStageOptions.update({"Normal":_("Slideshow")})
            if i > 1:   #only add Random setting if more than one animated stage exists
                aniStageOptions.update({"Random":_("Random")})
            Config.define("game", "animated_stage_folder", str, defaultAniStage, text = _("Animated Stage"), options = aniStageOptions )

            #MFH: here, need to track and check a new ini entry for last theme - so when theme changes we can re-default animated stage to first found
            lastTheme = self.config.get("game","last_theme")
            if lastTheme == "" or lastTheme != currentTheme:   #MFH - no last theme, and theme just changed:
                self.config.set("game","animated_stage_folder",defaultAniStage)   #force defaultAniStage
            self.config.set("game","last_theme",currentTheme)

            selectedAnimatedStage = self.config.get("game", "animated_stage_folder")
            if selectedAnimatedStage != "Normal" and selectedAnimatedStage != "Random":
                if not os.path.exists(os.path.join(stagespath,selectedAnimatedStage)):
                    log.warn("Selected animated stage folder " + selectedAnimatedStage + " does not exist, forcing Normal.")
                    self.config.set("game","animated_stage_folder","Normal") #MFH: force "Standard" currently selected animated stage folder is invalid
        else:
            Config.define("game", "animated_stage_folder", str, "None", text = _("Animated Stage"), options = ["None",_("None")])
            log.warn("No stages\ folder found, forcing None setting for Animated Stage.")
            self.config.set("game","animated_stage_folder", "None") #MFH: force "None" when Stages folder can't be found



        try:
            fp, pathname, description = imp.find_module("CustomTheme",[themepath])
            theme = imp.load_module("CustomTheme", fp, pathname, description)
            self.theme = theme.CustomTheme(themepath, themename)
        except ImportError:
            self.theme = Theme(themepath, themename)

        self.task.addTask(self.theme)


        self.input.addKeyListener(FullScreenSwitcher(self), priority = True)
        self.input.addSystemEventListener(SystemEventHandler(self))

        self.debugLayer         = None
        self.startupLayer       = None
        self.loadingScreenShown = False
        self.graphicMenuShown   = False

        log.debug("Ready.")
 def loadSongs(self, libraries):
     log.debug("Loading songs in %s" % self.library)
     self.engine.resource.load(self, "songs", lambda: song.getAvailableSongsAndTitles(self.engine, self.library, progressCallback=self.progressCallback), onLoad = self.prepareSetlist, synch = True)
Beispiel #49
0
    def __init__(self, engine):
        self.engine = engine

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

        self.time = 0.0
        self.nextLayer = None
        self.visibility = 0.0
        self.active = False

        self.showStartupMessages = False

        self.gfxVersionTag = Config.get("game", "gfx_version_tag")

        self.chosenNeck = Config.get("game", "default_neck")
        exists = 0

        if engine.loadImgDrawing(
                self, "ok", os.path.join("necks", self.chosenNeck + ".png")):
            exists = 1
        elif engine.loadImgDrawing(
                self, "ok",
                os.path.join("necks", "Neck_" + self.chosenNeck + ".png")):
            exists = 1

        #MFH - fallback logic now supports a couple valid default neck filenames
        #MFH - check for Neck_1
        if exists == 0:
            if engine.loadImgDrawing(self, "ok",
                                     os.path.join("necks", "Neck_1.png")):
                Config.set("game", "default_neck", "1")
                log.warn(
                    "Default chosen neck not valid; fallback Neck_1.png forced."
                )
                exists = 1

        #MFH - check for defaultneck
        if exists == 0:
            if engine.loadImgDrawing(self, "ok",
                                     os.path.join("necks", "defaultneck.png")):
                log.warn(
                    "Default chosen neck not valid; fallback defaultneck.png forced."
                )
                Config.set("game", "default_neck", "defaultneck")
                exists = 1
            else:
                log.error(
                    "Default chosen neck not valid; fallbacks Neck_1.png and defaultneck.png also not valid!"
                )

        #Get theme
        self.theme = self.engine.data.theme
        self.themeCoOp = self.engine.data.themeCoOp
        self.themename = self.engine.data.themeLabel
        self.useSoloMenu = self.engine.theme.use_solo_submenu

        allowMic = True

        self.menux = self.engine.theme.menuPos[0]
        self.menuy = self.engine.theme.menuPos[1]

        self.rbmenu = self.engine.theme.menuRB

        #MFH
        self.main_menu_scale = self.engine.theme.main_menu_scaleVar
        self.main_menu_vspacing = self.engine.theme.main_menu_vspacingVar

        if not self.engine.loadImgDrawing(
                self, "background",
                os.path.join("themes", self.themename, "menu", "mainbg.png")):
            self.background = None
        self.engine.loadImgDrawing(
            self, "BGText",
            os.path.join("themes", self.themename, "menu", "maintext.png"))
        self.engine.loadImgDrawing(
            self, "optionsBG",
            os.path.join("themes", self.themename, "menu", "optionsbg.png"))
        self.engine.loadImgDrawing(
            self, "optionsPanel",
            os.path.join("themes", self.themename, "menu", "optionspanel.png"))

        #racer: added version tag
        if self.gfxVersionTag or self.engine.theme.versiontag:
            if not self.engine.loadImgDrawing(
                    self, "version",
                    os.path.join("themes", self.themename, "menu",
                                 "versiontag.png")):
                if not self.engine.loadImgDrawing(
                        self, "version", "versiontag.png"
                ):  #falls back on default versiontag.png in data\ folder
                    self.version = None
        else:
            self.version = None

        #myfingershurt: random main menu music function, menu.ogg and menuXX.ogg (any filename with "menu" as the first 4 letters)
        self.files = None
        filepath = self.engine.getPath(
            os.path.join("themes", self.themename, "sounds"))
        if os.path.isdir(filepath):
            self.files = []
            allfiles = os.listdir(filepath)
            for name in allfiles:
                if os.path.splitext(name)[1] == ".ogg":
                    if string.find(name, "menu") > -1:
                        self.files.append(name)

        if self.files:
            i = random.randint(0, len(self.files) - 1)
            filename = self.files[i]
            sound = os.path.join("themes", self.themename, "sounds", filename)
            self.menumusic = True
            engine.menuMusic = True

            self.song = Music(self.engine.resource.fileName(sound))
            self.song.setVolume(self.engine.config.get("audio", "menu_volume"))
            self.song.play(0)  #no loop
        else:
            self.menumusic = False

        self.opt_text_color = self.engine.theme.opt_text_colorVar
        self.opt_selected_color = self.engine.theme.opt_selected_colorVar

        trainingMenu = [
            (_("Tutorials"), self.showTutorial),
            (_("Practice"), lambda: self.newLocalGame(mode1p=1)),
        ]

        self.opt_bkg_size = [float(i) for i in self.engine.theme.opt_bkg_size]
        self.opt_text_color = self.engine.theme.opt_text_colorVar
        self.opt_selected_color = self.engine.theme.opt_selected_colorVar

        if self.BGText:
            strCareer = ""
            strQuickplay = ""
            strSolo = ""
            strMultiplayer = ""
            strTraining = ""
            strSettings = ""
            strQuit = ""
        else:
            strCareer = "Career"
            strQuickplay = "Quickplay"
            strSolo = "Solo"
            strMultiplayer = "Multiplayer"
            strTraining = "Training"
            strSettings = "Settings"
            strQuit = "Quit"

        multPlayerMenu = [
            (_("Face-Off"),
             lambda: self.newLocalGame(players=2, maxplayers=4)),
            (_("Pro Face-Off"),
             lambda: self.newLocalGame(players=2, mode2p=1, maxplayers=4)),
            (_("FoFiX Co-Op"), lambda: self.newLocalGame(
                players=2, mode2p=3, maxplayers=4, allowMic=allowMic)),
            (_("RB Co-Op"), lambda: self.newLocalGame(
                players=2, mode2p=4, maxplayers=4, allowMic=allowMic)),
            (_("GH Battle"),
             lambda: self.newLocalGame(players=2, mode2p=6, allowDrum=False)
             ),  #akedrou- so you can block drums
        ]

        if not self.useSoloMenu:

            mainMenu = [
                (strCareer,
                 lambda: self.newLocalGame(mode1p=2, allowMic=allowMic)),
                (strQuickplay, lambda: self.newLocalGame(allowMic=allowMic)),
                ((strMultiplayer, "multiplayer"), multPlayerMenu),
                ((strTraining, "training"), trainingMenu),
                ((strSettings, "settings"), self.settingsMenu),
                (strQuit, self.quit),
            ]

        else:

            soloMenu = [
                (_("Solo Tour"),
                 lambda: self.newLocalGame(mode1p=2, allowMic=allowMic)),
                (_("Quickplay"), lambda: self.newLocalGame(allowMic=allowMic)),
            ]

            mainMenu = [
                ((strSolo, "solo"), soloMenu),
                ((strMultiplayer, "multiplayer"), multPlayerMenu),
                ((strTraining, "training"), trainingMenu),
                ((strSettings, "settings"), self.settingsMenu),
                (strQuit, self.quit),
            ]

        w, h, = self.engine.view.geometry[2:4]

        self.menu = Menu(self.engine,
                         mainMenu,
                         onClose=lambda: self.engine.view.popLayer(self),
                         pos=(self.menux, .75 - (.75 * self.menuy)))

        engine.mainMenu = self  #Points engine.mainMenu to the one and only MainMenu object instance

        ## whether the main menu has come into view at least once
        self.shownOnce = False
Beispiel #50
0
 def popAllLayers(self):
     log.debug("View: Pop all")
     [self.popLayer(l) for l in list(self.layers)]
    def prepareSetlist(self, songs):
        if self.songLoader:
            self.songLoader.stop()
        msg = self.engine.setlistMsg
        self.engine.setlistMsg = None
        self.selectedIndex = 0
        if self.listingMode == 0 or self.careerMode:
            self.items = self.libraries + self.songs
        else:
            self.items = self.songs
        self.itemRenderAngles = [0.0]  * len(self.items)
        self.itemLabels       = [None] * len(self.items)
        self.searching        = False
        self.searchText       = ""

        shownItems = []
        for item in self.items: #remove things we don't want to see. Some redundancy, but that's okay.
            if isinstance(item, song.TitleInfo) or isinstance(item, song.SortTitleInfo):
                if self.showCareerTiers == 2:
                    if isinstance(item, song.TitleInfo):
                        if len(shownItems) > 0:
                            if isinstance(shownItems[-1], song.TitleInfo):
                                shownItems.pop()
                        shownItems.append(item)
                    elif isinstance(item, song.SortTitleInfo):
                        continue
                else:
                    if isinstance(item, song.TitleInfo):
                        continue
                    elif isinstance(item, song.SortTitleInfo):
                        if not self.showSortTiers:
                            continue
                        if len(shownItems) > 0:
                            if isinstance(shownItems[-1], song.SortTitleInfo):
                                shownItems.pop()
                        shownItems.append(item)
            elif isinstance(item, song.SongInfo):
                if self.careerMode and (not self.showLockedSongs) and item.getLocked():
                    continue
                else:
                    shownItems.append(item)
            else:
                shownItems.append(item)
        if len(shownItems) > 0:
            if isinstance(shownItems[-1], song.TitleInfo) or isinstance(shownItems[-1], song.SortTitleInfo):
                shownItems.pop()

        if len(self.items) > 0 and len(shownItems) == 0:
            msg = _("No songs in this setlist are available to play!")
            if self.careerMode:
                msg = msg + " " + _("Make sure you have a working career pack!")
            Dialogs.showMessage(self.engine, msg)
        elif len(shownItems) > 0:
            for item in shownItems:
                if isinstance(item, song.SongInfo) or isinstance(item, song.LibraryInfo):
                    self.items = shownItems #make sure at least one item is selectable
                    break
            else:
                msg = _("No songs in this setlist are available to play!")
                if self.careerMode:
                    msg = msg + " " + _("Make sure you have a working career pack!")
                Dialogs.showMessage(self.engine, msg)
                self.items = []

        if self.items == []:    #MFH: Catch when there ain't a damn thing in the current folder - back out!
            if self.library != song.DEFAULT_LIBRARY:
                Dialogs.hideLoadingSplashScreen(self.engine, self.splash)
                self.splash = None
                self.startingSelected = self.library
                self.library     = os.path.dirname(self.library)
                self.selectedItem = None
                self.loadLibrary()
                return

        log.debug("Setlist loaded.")

        self.loaded           = True

        if self.setlistStyle == 1:
            for i in range(self.headerSkip):
                self.items.insert(0, song.BlankSpaceInfo())
            for i in range(self.footerSkip):
                self.items.append(song.BlankSpaceInfo())

        if self.startingSelected is not None:
            for i, item in enumerate(self.items):
                if isinstance(item, song.SongInfo) and self.startingSelected == item.songName: #TODO: SongDB
                    self.selectedIndex =  i
                    break
                elif isinstance(item, song.LibraryInfo) and self.startingSelected == item.libraryName:
                    self.selectedIndex =  i
                    break

        for item in self.items:
            if isinstance(item, song.SongInfo):
                item.name = song.removeSongOrderPrefixFromName(item.name) #TODO: I don't like this.
            elif not self.tiersPresent and (isinstance(item, song.TitleInfo) or isinstance(item, song.SortTitleInfo)):
                self.tiersPresent = True

        while isinstance(self.items[self.selectedIndex], song.BlankSpaceInfo) or ((isinstance(self.items[self.selectedIndex], song.TitleInfo) or isinstance(self.items[self.selectedIndex], song.SortTitleInfo)) and not self.selectTiers):
            self.selectedIndex += 1
            if self.selectedIndex >= len(self.items):
                self.selectedIndex = 0

        self.itemRenderAngles = [0.0]  * len(self.items)
        self.itemLabels       = [None] * len(self.items)

        if self.preloadSongLabels:
            for i in range(len(self.items)):
                self.loadStartTime = time.time()
                Dialogs.changeLoadingSplashScreenText(self.engine, self.splash, _("Loading Album Artwork..."))
                self.loadItemLabel(i, preload = True)

        self.updateSelection()
        Dialogs.hideLoadingSplashScreen(self.engine, self.splash)
        self.splash = None