Exemplo n.º 1
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):")
Exemplo n.º 2
0
    def convertToTexture(self, width, height):
        if self.texture:
            return

        e = "Img drawing does not have a valid texture image."
        log.error(e)
        raise RuntimeError(e)
Exemplo n.º 3
0
    def loadVideo(self, libraryName, songName):
        vidSource = None

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

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

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

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

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

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

        optionList = []

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

        return optionList, options
Exemplo n.º 5
0
Arquivo: Config.py Projeto: htvu/fofix
    def getOptions(self, section, option):
        """
        Read the preset options of a configuration key.

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

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

        optionList = []

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

        return optionList, options
Exemplo n.º 6
0
    def loadImgDrawing(self, target, name, fileName, textureSize=None):
        """
        Load an SVG drawing synchronously.

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

        if target:
            drawing = self.resource.load(target,
                                         name,
                                         lambda: imgDrawing,
                                         synch=True)
        else:
            drawing = imgDrawing
        return drawing
Exemplo n.º 7
0
 def keyPressed(self, key, unicode):
     if key == pygame.K_LALT:
         self.altStatus = True
     elif key == pygame.K_RETURN and self.altStatus:
         if not self.engine.toggleFullscreen():
             log.error("Unable to toggle fullscreen mode.")
         return True
     elif key == pygame.K_d and self.altStatus:
         self.engine.setDebugModeEnabled(not self.engine.isDebugModeEnabled())
         return True
     elif key == pygame.K_g and self.altStatus and self.engine.isDebugModeEnabled():
         self.engine.debugLayer.gcDump()
         return True
Exemplo n.º 8
0
Arquivo: Config.py Projeto: htvu/fofix
    def getTipText(self, section, option):
        """
        Return the tip text for a configuration key.

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

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

        return text
Exemplo n.º 9
0
    def run(self):
        try:
            self.tickDelta = self.timer.tick()
            done = self.task.run()
            self.clearScreen()

            self.mainloop()

            self.video.flip()

            # Calculate FPS every 2 seconds
            if self.timer.fpsTime >= 2000:
                self.fpsEstimate = self.timer.get_fps()
                print ("%.2f fps" % self.fpsEstimate)

            self.timer.delay(self.fps)

            return done
        except KeyboardInterrupt:
            sys.exit(0)
        except SystemExit:
            sys.exit(0)
        except Exception, e:
            def clearMatrixStack(stack):
                try:
                    glMatrixMode(stack)
                    for i in range(16):
                        glPopMatrix()
                except:
                    pass

            if self.handlingException:
                # A recursive exception is fatal as we can't reliably reset the GL state
                sys.exit(1)

            self.handlingException = True
            log.error("%s: %s" % (e.__class__, e))
            import traceback
            traceback.print_exc()

            clearMatrixStack(GL_PROJECTION)
            clearMatrixStack(GL_MODELVIEW)

            Dialogs.showMessage(self, unicode(e))
            self.handlingException = False
            return True
Exemplo n.º 10
0
    def getTipText(self, section, option):
        """
        Return the tip text for a configuration key.

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

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

        return text
Exemplo n.º 11
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)
Exemplo n.º 12
0
Arquivo: Config.py Projeto: htvu/fofix
    def getDefault(self, section, option):
        """
        Read the default value of a configuration key.

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

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

        value = _convertValue(default, type)

        return value
Exemplo n.º 13
0
    def run(self):

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

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

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

        # evilynux - MainMenu class already calls this - useless?
        self.engine.quit()
Exemplo n.º 14
0
    def getDefault(self, section, option):
        """
        Read the default value of a configuration key.

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

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

        value = _convertValue(default, type)

        return value
Exemplo n.º 15
0
    def __init__(self, context, imgPath):
        self.imgPath = None
        self.texture = None
        self.context = context
        self.cache = None
        self.transform = ImgTransform()

        # Load PNG files directly
        if imgPath.endswith(".png"):
            self.texture = Texture(imgPath)
        else:
            e = "Unsupported Image format."
            log.error(e)
            raise RuntimeError(e)

        # Make sure we have a valid texture
        if not self.texture:
            e = "Unable to load texture for %s." % imgPath
            log.error(e)
            raise RuntimeError(e)
Exemplo n.º 16
0
    def run(self):

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

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

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

        # evilynux - MainMenu class already calls this - useless?
        self.engine.quit()
Exemplo n.º 17
0
    def __init__(self, context, ImgData):
        self.ImgData = None
        self.texture = None
        self.context = context
        self.cache = None
        self.filename = ImgData

        # Detect the type of data passed in
        if isinstance(ImgData, file):
            self.ImgData = ImgData.read()
        elif isinstance(ImgData, basestring):
            self.texture = Texture(ImgData)
        elif isinstance(ImgData, Image.Image): #stump: let a PIL image be passed in
            self.texture = Texture()
            self.texture.loadImage(ImgData)

        # Make sure we have a valid texture
        if not self.texture:
            if isinstance(ImgData, basestring):
                e = "Unable to load texture for %s." % ImgData
            else:
                e = "Unable to load texture for SVG file."
            log.error(e)
            raise RuntimeError(e)

        self.pixelSize = self.texture.pixelSize #the size of the image in pixels (from texture)
        self.position = [0.0,0.0]               #position of the image in the viewport
        self.scale    = [1.0,1.0]               #percentage scaling
        self.angle    = 0                       #angle of rotation (degrees)
        self.color    = (1.0,1.0,1.0,1.0)       #glColor rgba
        self.rect     = (0,1,0,1)               #texture mapping coordinates
        self.shift    = -.5                     #horizontal alignment
        self.vshift   = -.5                     #vertical alignment

        self.path = self.texture.name           #path of the image file

        self.texArray = np.zeros((4,2), dtype=np.float32)

        self.createTex()
Exemplo n.º 18
0
    def __init__(self, name = None, target = GL_TEXTURE_2D, useMipmaps = True):
        # Delete all pending textures
        try:
            func, args = cleanupQueue[0]
            del cleanupQueue[0]
            func(*args)
        except IndexError:
            pass
        except Exception as e:    #MFH - to catch "did you call glewInit?" crashes
            log.error("Texture.py texture deletion exception: %s" % e)

        self.texture = glGenTextures(1)
        self.texEnv = GL_MODULATE
        self.glTarget = target
        self.framebuffer = None
        self.useMipmaps = useMipmaps

        self.setDefaults()
        self.name = name

        if name:
            self.loadFile(name)
Exemplo n.º 19
0
    def __init__(self, name=None, target=GL_TEXTURE_2D, useMipmaps=True):
        # Delete all pending textures
        try:
            func, args = cleanupQueue[0]
            del cleanupQueue[0]
            func(*args)
        except IndexError:
            pass
        except Exception as e:  #MFH - to catch "did you call glewInit?" crashes
            log.error("Texture.py texture deletion exception: %s" % e)

        self.texture = glGenTextures(1)
        self.texEnv = GL_MODULATE
        self.glTarget = target
        self.framebuffer = None
        self.useMipmaps = useMipmaps

        self.setDefaults()
        self.name = name

        if name:
            self.loadFile(name)
Exemplo n.º 20
0
    def _initTheme(self, themename, themepath):
        """
        Select the source of graphics for the game.
        Note that currently this can only be called GameEngine on startup.

        :param themename: what to call this theme
        :type themename: str
        :param themepath: absolute path to theme folder
        :type themepath: str
        """

        log.notice('Setting theme %s from "%s"' % (themename, themepath))

        self.theme = None
        try:
            # Look for "CustomTheme.py" inside theme dir
            fp, pathname, description = imp.find_module(
                "CustomTheme", [themepath])
            try:
                # Found it! Load it.
                theme = imp.load_module("CustomTheme", fp, pathname,
                                        description)
                self.theme = theme.CustomTheme(themepath, themename)
                log.notice('Theme activated using custom class "%s"' %
                           pathname)
            except ImportError as e:
                # Unable to load module; log it, but continue with default Theme.
                log.error('Failed to load CustomTheme.py from "%s"' % pathname)
            finally:
                fp.close()
        except ImportError:
            # CustomTheme.py file is optional, but notify developer anyway.
            log.notice("No CustomTheme.py found in theme")
            pass

        if self.theme is None:
            self.theme = Theme(themepath, themename)
            log.notice("Theme activated using built-in Theme class")
        self.task.addTask(self.theme)
Exemplo n.º 21
0
def _init_allthemes():
    """ Alarian: Get unlimited themes by foldername """
    # this global code is in a function to hide vars from rest of file

    themepath = os.path.join(Version.dataPath(), "themes")
    themes = []
    defaultTheme = None  #myfingershurt
    allthemes = os.listdir(themepath)
    for name in allthemes:
        if os.path.exists(os.path.join(themepath, name, "notes", "notes.png")):
            themes.append(name)
            if name == "MegaLight V4":
                defaultTheme = name

    i = len(themes)
    if i == 0:
        if os.name == 'posix':
            log.error("No valid theme found!\n" +
                      "Make sure theme files are properly cased " +
                      "e.g. notes.png works, Notes.png doesn't\n")
        else:
            log.error("No valid theme found!")
        sys.exit(1)

    if defaultTheme is None:
        defaultTheme = themes[0]  #myfingershurt

    #myfingershurt: default theme must be an existing one!
    Config.define(
        "coffee",
        "themename",
        str,
        defaultTheme,
        text=_("Theme"),
        options=dict([(str(themes[n]), themes[n]) for n in range(0, i)]),
        tipText=
        _("Sets the overall graphical feel of the game. You can find and download many more at fretsonfire.net"
          ))
Exemplo n.º 22
0
Arquivo: Config.py Projeto: htvu/fofix
    def set(self, section, option, value):
        """
        Set the value of a configuration key.

        @param section:   Section name
        @param option:    Option name
        @param value:     Value name
        """

        try:
            prototype[section][option]
        except KeyError:
            log.error("Config key %s.%s not defined while writing %s." % (section, option, self.fileName))
            raise

        if not self.config.has_section(section):
            self.config.add_section(section)

        self.config.set(section, option, utf8(value))

        f = open(self.fileName, "w")
        self.config.write(f, self.type)
        f.close()
Exemplo n.º 23
0
    def setMode(self, resolution, fullscreen = False, flags = pygame.OPENGL | pygame.DOUBLEBUF,
                multisamples = 0):
        if fullscreen:
            flags |= pygame.FULLSCREEN

        self.flags      = flags
        self.fullscreen = fullscreen

        try:
            pygame.display.quit()
        except:
            pass

        pygame.display.init()

        pygame.display.gl_set_attribute(pygame.GL_RED_SIZE,   8)
        pygame.display.gl_set_attribute(pygame.GL_GREEN_SIZE, 8)
        pygame.display.gl_set_attribute(pygame.GL_BLUE_SIZE,  8)
        pygame.display.gl_set_attribute(pygame.GL_ALPHA_SIZE, 8)

        if multisamples:
            pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLEBUFFERS, 1);
            pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLESAMPLES, multisamples);

        try:
            self.screen = pygame.display.set_mode(resolution, flags)
        except Exception, e:
            log.error(str(e))
            if multisamples:
                log.warn("Video setup failed. Trying without antialiasing.")
                pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLEBUFFERS, 0);
                pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLESAMPLES, 0);
                multisamples = 0
                self.screen = pygame.display.set_mode(resolution, flags)
            else:
                log.error("Video setup failed. Make sure your graphics card supports 32 bit display modes.")
                raise
Exemplo n.º 24
0
    def loadImgDrawing(self, target, name, fileName, textureSize = None):
        """
        Load an SVG drawing synchronously.

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

        if target:
            drawing  = self.resource.load(target, name, lambda: imgDrawing, synch = True)
        else:
            drawing = imgDrawing
        return drawing
Exemplo n.º 25
0
    def set(self, section, option, value):
        """
        Set the value of a configuration key.

        @param section:   Section name
        @param option:    Option name
        @param value:     Value name
        """

        try:
            prototype[section][option]
        except KeyError:
            log.error("Config key %s.%s not defined while writing %s." %
                      (section, option, self.fileName))
            raise

        if not self.config.has_section(section):
            self.config.add_section(section)

        self.config.set(section, option, utf8(value))

        f = open(self.fileName, "w")
        self.config.write(f, self.type)
        f.close()
Exemplo n.º 26
0
 def screenError(self):
     log.error("Video setup failed. Make sure your graphics card supports 32-bit display modes.")
     raise
Exemplo n.º 27
0
    def set(self, dir):
        """Do all shader setup.
           dir = directory to load shaders from
        """

        #stump: check whether all needed extensions are actually supported
        if not glInitShaderObjectsARB():
            log.warn('OpenGL extension ARB_shader_objects not supported - shaders disabled')
            return
        if not glInitVertexShaderARB():
            log.warn('OpenGL extension ARB_vertex_shader not supported - shaders disabled')
            return
        if not glInitFragmentShaderARB():
            log.warn('OpenGL extension ARB_fragment_shader not supported - shaders disabled')
            return
        if not glInitMultitextureARB():
            log.warn('OpenGL extension ARB_multitexture not supported - shaders disabled')
            return
        if not glInitTexture3DEXT():
            if sys.platform != 'darwin':
                log.warn('OpenGL extension EXT_texture3D not supported - shaders disabled')
                return

        self.workdir = dir

        # Load textures needed by the shaders.
        try:
            self.noise3D = self.loadTex3D("noise3d.dds")
            self.outline = self.loadTex2D("outline.tga")
        except:
            log.error('Could not load shader textures - shaders disabled: ')
            return

        self.multiTex = (GL_TEXTURE0_ARB,GL_TEXTURE1_ARB,GL_TEXTURE2_ARB,GL_TEXTURE3_ARB)
        self.enabled = True
        self.turnon = True

        # Compile the shader objects that we are going to use.
        # Also set uniform shader variables to default values.
        try:
            self.make("lightning","stage")
        except:
            log.error("Error compiling lightning shader: ")
        else:
            self.enable("stage")
            self.setVar("ambientGlowHeightScale",6.0)
            self.setVar("color",(0.0,0.0,0.0,0.0))
            self.setVar("glowFallOff",0.024)
            self.setVar("height",0.44)
            self.setVar("sampleDist",0.0076)
            self.setVar("speed",1.86)
            self.setVar("vertNoise",0.78)
            self.setVar("fading",1.0)
            self.setVar("solofx",False)
            self.setVar("scalexy",(5.0,2.4))
            self.setVar("fixalpha",True)
            self.setVar("offset",(0.0,-2.5))
            self.disable()

        try:
            self.make("lightning","sololight")
        except:
            log.error("Error compiling lightning shader: ")
        else:
            self.enable("sololight")
            self.setVar("scalexy",(5.0,1.0))
            self.setVar("ambientGlow",0.5)
            self.setVar("ambientGlowHeightScale",6.0)
            self.setVar("solofx",True)
            self.setVar("height",0.3)
            self.setVar("glowFallOff",0.024)
            self.setVar("sampleDist",0.0076)
            self.setVar("fading",4.0)
            self.setVar("speed",1.86)
            self.setVar("vertNoise",0.78)
            self.setVar("solofx",True)
            self.setVar("color",(0.0,0.0,0.0,0.0))
            self.setVar("fixalpha",True)
            self.setVar("glowStrength",100.0)
            self.disable()

        try:
            self.make("lightning","tail")
        except:
            log.error("Error compiling lightning shader: ")
        else:
            self.enable("tail")
            self.setVar("scalexy",(5.0,1.0))
            self.setVar("ambientGlow",0.1)
            self.setVar("ambientGlowHeightScale",6.0)
            self.setVar("solofx",True)
            self.setVar("fading",4.0)
            self.setVar("height",0.0)
            self.setVar("glowFallOff",0.024)
            self.setVar("sampleDist",0.0076)
            self.setVar("speed",1.86)
            self.setVar("vertNoise",0.78)
            self.setVar("solofx",True)
            self.setVar("color",(0.3,0.7,0.9,0.6))
            self.setVar("glowStrength",70.0)
            self.setVar("fixalpha",True)
            self.setVar("offset",(0.0,0.0))
            self.disable()

        try:
            self.make("rockbandtail","tail2")
        except:
            log.error("Error compiling rockbandtail shader: ")
        else:
            self.enable("tail2")
            self.setVar("height",0.2)
            self.setVar("color",(0.0,0.6,1.0,1.0))
            self.setVar("speed",9.0)
            self.setVar("offset",(0.0,0.0))
            self.setVar("scalexy",(5.0,1.0))
            self.disable()

        try:
            self.make("metal","notes")
        except:
            log.error("Error compiling metal shader: ")
        else:
            self.enable("notes")
            self.disable()

        try:
            self.make("neck","neck")
        except:
            log.error("Error compiling neck shader: ")

        try:
            self.make("cd","cd")
        except:
            log.error("Error compiling cd shader: ")
Exemplo n.º 28
0
        self.engine.quit()


if __name__ == '__main__':
    try:
        # This loop restarts the game if a restart is requested
        while True:
            main = Main()
            main.run()
            if not main.restartRequested:
                break

    except (KeyboardInterrupt, SystemExit):
        raise
    except:
        log.error("Terminating due to unhandled exception: ")
        _logname = os.path.abspath(log.logFile.name)
        _errmsg = "%s\n\n%s\n%s\n%s\n%s" % (
            _("Terminating due to unhandled exception:"),
            traceback.format_exc(),
            _("If you make a bug report about this error, please include the contents of the following log file:"
              ), _logname,
            _("The log file already includes the traceback given above."))

        if os.name == 'nt':
            # If we move to PySDL2 we can replace this with a call to SDL_ShowSimpleMessageBox
            import win32api
            import win32con
            if win32api.MessageBox(
                    0, "%s\n\n%s" % (_errmsg, _("Open the logfile now?")),
                    "%s %s" % (Version.PROGRAM_NAME, Version.version()),
Exemplo n.º 29
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."
            )
Exemplo n.º 30
0
##Alarian: Get unlimited themes by foldername
themepath = os.path.join(Version.dataPath(), "themes")
themes = []
defaultTheme = None           #myfingershurt
allthemes = os.listdir(themepath)
for name in allthemes:
    if os.path.exists(os.path.join(themepath,name,"notes","notes.png")):
        themes.append(name)
        if name == "MegaLight V4":
            defaultTheme = name

i = len(themes)
if i == 0:
    if os.name == 'posix':
        log.error("No valid theme found!\n" +
                  "Make sure theme files are properly cased " +
                  "e.g. notes.png works, Notes.png doesn't\n")
    else:
        log.error("No valid theme found!")
    sys.exit(1)

if defaultTheme is None:
    defaultTheme = themes[0]    #myfingershurt

#myfingershurt: default theme must be an existing one!
Config.define("coffee", "themename",           str,   defaultTheme,      text = _("Theme"),                options = dict([(str(themes[n]),themes[n]) for n in range(0, i)]), tipText = _("Sets the overall graphical feel of the game. You can find and download many more at fretsonfire.net"))

##Alarian: End Get unlimited themes by foldername
Player.loadControls()

Exemplo n.º 31
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
Exemplo n.º 32
0
        # evilynux - MainMenu class already calls this - useless?
        self.engine.quit()

if __name__ == '__main__':
    try:
        # This loop restarts the game if a restart is requested
        while True:
            main = Main()
            main.run()
            if not main.restartRequested:
                break

    except (KeyboardInterrupt, SystemExit):
        raise
    except:
        log.error("Terminating due to unhandled exception: ")
        _logname = os.path.abspath(log.logFile.name)
        _errmsg = "%s\n\n%s\n%s\n%s\n%s" % (
          _("Terminating due to unhandled exception:"),
          traceback.format_exc(),
          _("If you make a bug report about this error, please include the contents of the following log file:"),
          _logname,
          _("The log file already includes the traceback given above."))

        if os.name == 'nt':
            # If we move to PySDL2 we can replace this with a call to SDL_ShowSimpleMessageBox
            import win32api
            import win32con
            if win32api.MessageBox(0, "%s\n\n%s" % (_errmsg, _("Open the logfile now?")), "%s %s" % (Version.PROGRAM_NAME, Version.version()), win32con.MB_YESNO|win32con.MB_ICONSTOP) == win32con.IDYES:
                log.logFile.close()
                os.startfile(_logname)
Exemplo n.º 33
0
Arquivo: Neck.py Projeto: htvu/fofix
    def __init__(self, engine, instrument, playerObj):

        self.engine         = engine
        self.player         = instrument.player
        self.instrument     = instrument

        self.isDrum       = self.instrument.isDrum
        self.isBassGuitar = self.instrument.isBassGuitar
        self.isVocal      = self.instrument.isVocal

        self.oNeckovr = None    #MFH - needs to be here to prevent crashes!

        self.staticStrings  = self.engine.config.get("performance", "static_strings")

        self.indexFps       = self.engine.config.get("video", "fps") #QQstarS

        self.neckAlpha=[] # necks transparency
        self.neckAlpha.append( self.engine.config.get("game", "necks_alpha") ) # all necks
        self.neckAlpha.append( self.neckAlpha[0] * self.engine.config.get("game", "neck_alpha") ) # normal neck
        self.neckAlpha.append( self.neckAlpha[0] * self.engine.config.get("game", "solo_neck_alpha") ) # solo neck
        self.neckAlpha.append( self.neckAlpha[0] * self.engine.config.get("game", "bg_neck_alpha") ) # bass groove neck
        self.neckAlpha.append( self.neckAlpha[0] * self.engine.config.get("game", "overlay_neck_alpha") ) # overlay neck
        self.neckAlpha.append( self.neckAlpha[0] * self.engine.config.get("game", "fail_neck_alpha") ) # fail neck
        self.neckAlpha.append( self.neckAlpha[0] * self.engine.config.get("game", "4x_neck_alpha") ) # 4x multi neck

        self.boardWidth     = self.engine.theme.neckWidth
        self.boardLength    = self.engine.theme.neckLength
        self.shaderSolocolor    = self.engine.theme.shaderSolocolor

        self.boardFadeAmount = self.engine.theme.boardFade

        self.doNecksRender = self.engine.theme.doNecksRender

        #death_au: fixed neck size

        if self.isDrum and self.engine.config.get("game", "large_drum_neck"):
            self.boardWidth     = 4.0
            self.boardLength    = 12.0

        self.beatsPerBoard  = 5.0
        self.beatsPerUnit   = self.beatsPerBoard / self.boardLength

        color = (1,1,1)
        self.vis = 1


        size = 0

        # evilynux - Neck color
        self.board_col  = np.array([[color[0],color[1],color[2], 0],
                                 [color[0],color[1],color[2], 0],
                                 [color[0],color[1],color[2], self.vis],
                                 [color[0],color[1],color[2], self.vis],
                                 [color[0],color[1],color[2], self.vis],
                                 [color[0],color[1],color[2], self.vis],
                                 [color[0],color[1],color[2], 0],
                                 [color[0],color[1],color[2], 0]], dtype=np.float32)

        w            = self.boardWidth
        l            = self.boardLength

        # evilynux - Neck vertices
        self.board_vtx = np.array([[-w / 2, 0, -2],
                                [w / 2, 0, -2],
                                [-w/ 2, 0, -1],
                                [w / 2, 0, -1],
                                [-w / 2, 0, l * .7],
                                [w / 2, 0, l * .7],
                                [-w / 2, 0, l],
                                [w / 2, 0, l]], dtype=np.float32)

        self.shader_neck_vtx = np.array([[-w / 2, 0.1, -2],
                                      [w / 2, 0.1, -2],
                                      [-w / 2, 0.1, l],
                                      [w / 2, 0.1, l]], dtype=np.float32)

        self.track_vtx = np.array([[-w / 2, 0, -2+size],
                                [w / 2, 0, -2+size],
                                [-w / 2, 0, -1+size],
                                [w / 2, 0, -1+size],
                                [-w / 2, 0, l * .7],
                                [w / 2, 0, l * .7],
                                [-w / 2, 0, l],
                                [w / 2, 0, l]], dtype=np.float32)


        self.soloLightVtx1 = np.array([[w / 2-1.0, 0.4, -2],
                                    [w / 2+1.0, 0.4, -2],
                                    [w / 2-1.0, 0.4, l],
                                    [w / 2+1.0, 0.4, l]], dtype=np.float32)

        self.soloLightVtx2 = np.array([[-w / 2+1.0, 0.4, -2],
                                    [-w / 2-1.0, 0.4, -2],
                                    [-w / 2+1.0, 0.4, l],
                                    [-w / 2-1.0, 0.4, l]], dtype=np.float32)

        self.bpm_vtx  = np.array([[-(w / 2), 0,  0],
                               [-(w / 2), 0,  0],
                               [(w / 2), 0,  0],
                               [(w / 2), 0,  0]], dtype=np.float32)


        self.board_scroll_vtx = np.array([[-w / 2, 0, 0],
                                          [w / 2, 0, 0],
                                          [-w/ 2, 0, 0],
                                          [w / 2, 0, 0],
                                          [-w/ 2, 0, 0],
                                          [w / 2, 0, 0],
                                          [-w/ 2, 0, 0],
                                          [w / 2, 0, 0]], dtype=np.float32)

        # evilynux - Sidebars vertices
        w += 0.15
        self.sidebars_vtx = np.array([[-w / 2, 0, -2],
                                   [w / 2, 0, -2],
                                   [-w/ 2, 0, -1],
                                   [w / 2, 0, -1],
                                   [-w / 2, 0, l * .7],
                                   [w / 2, 0, l * .7],
                                   [-w / 2, 0, l],
                                   [w / 2, 0, l]], dtype=np.float32)

        self.sidebars_scroll_vtx = np.array([[-w / 2, 0, 0],
                                             [w / 2, 0, 0],
                                             [-w/ 2, 0, 0],
                                             [w / 2, 0, 0],
                                             [-w/ 2, 0, 0],
                                             [w / 2, 0, 0],
                                             [-w/ 2, 0, 0],
                                             [w / 2, 0, 0]], dtype=np.float32)

        self.bpm_tex  = np.array([[0.0, 1.0],
                               [0.0, 0.0],
                               [1.0, 1.0],
                               [1.0, 0.0]], dtype=np.float32)

        self.bpm_col  = np.array([[1, 1, 1, self.vis],
                               [1, 1, 1, self.vis],
                               [1, 1, 1, self.vis],
                               [1, 1, 1, self.vis]], dtype=np.float32)

        self.board_col_flash  = np.array([[color[0],color[1],color[2], 0],
                                 [color[0],color[1],color[2], 0],
                                 [color[0],color[1],color[2], self.vis],
                                 [color[0],color[1],color[2], self.vis],
                                 [color[0],color[1],color[2], self.vis],
                                 [color[0],color[1],color[2], self.vis],
                                 [color[0],color[1],color[2], 0],
                                 [color[0],color[1],color[2], 0]], dtype=np.float32)

        self.board_tex_static = np.array([[0.0, self.project(-2 * self.beatsPerUnit)],
                                          [1.0, self.project(-2 * self.beatsPerUnit)],
                                          [0.0, self.project(-1 * self.beatsPerUnit)],
                                          [1.0, self.project(-1 * self.beatsPerUnit)],
                                          [0.0, self.project(l * self.beatsPerUnit * .7)],
                                          [1.0, self.project(l * self.beatsPerUnit * .7)],
                                          [0.0, self.project(l * self.beatsPerUnit)],
                                          [1.0, self.project(l * self.beatsPerUnit)]], dtype=np.float32)

        self.board_tex  = np.array([[0.0, 0],
                                    [1.0, 0],
                                    [0.0, 0],
                                    [1.0, 0],
                                    [0.0, 0],
                                    [1.0, 0],
                                    [0.0, 0],
                                    [1.0, 0]], dtype=np.float32)

        # evilynux - Just in case the type has became double, convert to float32
        self.board_col             = self.board_col.astype(np.float32)
        self.board_vtx             = self.board_vtx.astype(np.float32)
        self.sidebars_vtx          = self.sidebars_vtx.astype(np.float32)
        self.sidebars_scroll_vtx   = self.sidebars_scroll_vtx.astype(np.float32)
        self.bpm_tex               = self.bpm_tex.astype(np.float32)
        self.bpm_col               = self.bpm_col.astype(np.float32)
        self.soloLightVtx1         = self.soloLightVtx1.astype(np.float32)
        self.soloLightVtx2         = self.soloLightVtx2.astype(np.float32)
        self.shader_neck_vtx       = self.shader_neck_vtx.astype(np.float32)
        self.track_vtx             = self.track_vtx.astype(np.float32)
        self.board_col_flash       = self.board_col_flash.astype(np.float32)
        self.bpm_vtx               = self.bpm_vtx.astype(np.float32)
        self.board_tex_static      = self.board_tex_static.astype(np.float32)
        self.board_tex             = self.board_tex.astype(np.float32)
        self.board_scroll_vtx      = self.board_scroll_vtx.astype(np.float32)

        self.neckType = playerObj.neckType
        if self.neckType == 0:
            self.neck = engine.mainMenu.chosenNeck
        else:
            self.neck = str(playerObj.neck)
        playerObj  = None
        #Get theme
        themename = self.engine.data.themeLabel
        #now theme determination logic is only in data.py:
        self.theme = self.engine.data.theme

        self.incomingNeckMode = self.engine.config.get("game", "incoming_neck_mode")

        #blazingamer
        self.failcount = 0
        self.failcount2 = False
        self.spcount = 0
        self.spcount2 = 0
        self.bgcount = 0
        self.fourXcount = 0
        self.ovrneckoverlay = self.engine.config.get("fretboard", "ovrneckoverlay")
        self.ocount = 0

        self.currentPeriod  = 60000.0 / self.instrument.currentBpm
        self.lastBpmChange  = -1.0
        self.baseBeat       = 0.0

        #myfingershurt:
        self.bassGrooveNeckMode = self.engine.config.get("game", "bass_groove_neck")
        self.guitarSoloNeckMode = self.engine.config.get("game", "guitar_solo_neck")
        self.fourxNeckMode = self.engine.config.get("game", "4x_neck")


        self.useMidiSoloMarkers = False
        self.markSolos = 0

        neckFind = True
        themeNeckPath = os.path.join(self.engine.resource.fileName("themes", themename, "necks"))
        if self.neckType == 1 and os.path.exists(themeNeckPath):
            themeNeck = []
            neckfiles = [ f for f in os.listdir(themeNeckPath) if os.path.isfile(os.path.join(themeNeckPath, f)) ]
            neckfiles.sort()
            for i in neckfiles:
                themeNeck.append(str(i))
            if len(themeNeck) > 0:
                i = random.randint(0,len(themeNeck)-1)
                if engine.loadImgDrawing(self, "neckDrawing", os.path.join("themes", themename, "necks", themeNeck[i]), textureSize = (256, 256)):
                    neckFind = False
                    log.debug("Random theme neck chosen: " + themeNeck[i])
                else:
                    log.error("Unable to load theme neck: " + themeNeck[i])
                    # fall back to defaultneck
                    self.neck = "defaultneck"
        if neckFind:
            # evilynux - Fixed random neck -- MFH: further fixing random neck
            if self.neck == "0" or self.neck == "Neck_0" or self.neck == "randomneck":
                self.neck = []
                # evilynux - improved loading logic to support arbitrary filenames
                path = self.engine.resource.fileName("necks")
                neckfiles = [ f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f)) ]
                neckfiles.sort()
                for i in neckfiles:
                    # evilynux - Special cases, ignore these...
                    if( os.path.splitext(i)[0] == "randomneck" or os.path.splitext(i)[0] == "overdriveneck" ):
                        continue
                    else:
                        self.neck.append(str(i)[:-4]) # evilynux - filename w/o extension

                i = random.randint(0,len(self.neck)-1)
                if engine.loadImgDrawing(self, "neckDrawing", os.path.join("necks",self.neck[i]+".png"),  textureSize = (256, 256)):
                    log.debug("Random neck chosen: " + self.neck[i])
                else:
                    log.error("Unable to load neck: " + self.neck[i])
                    self.neck = "defaultneck"
                    engine.loadImgDrawing(self, "neckDrawing", os.path.join("necks",self.neck+".png"),  textureSize = (256, 256))
            else:
                # evilynux - first assume the self.neck contains the full filename
                if not engine.loadImgDrawing(self, "neckDrawing", os.path.join("necks",self.neck+".png"),  textureSize = (256, 256)):
                    if not engine.loadImgDrawing(self, "neckDrawing", os.path.join("necks","Neck_"+self.neck+".png"),  textureSize = (256, 256)):
                        engine.loadImgDrawing(self, "neckDrawing", os.path.join("necks","defaultneck.png"),  textureSize = (256, 256))

        #blazingamer:
        #this helps me clean up the code a bit
        #what it does is if you're using drums or bass
        #it checks that directory first, if it doesn't
        #exist, then it goes back to the default directory

        if self.isDrum:
            self.extension = "drums"
        elif self.isBassGuitar:
            self.extension = "bass"
        else:
            self.extension = None

        themepath = os.path.join("themes", themename, "board")

        def loadImage(name, file):
            if self.extension:
                if not engine.loadImgDrawing(self, name, os.path.join(themepath, self.extension, file)):
                    engine.loadImgDrawing(self, name, os.path.join(themepath, file))
            else:
                engine.loadImgDrawing(self, name, os.path.join(themepath, file))

        loadImage("sideBars",       "side_bars.png")
        loadImage("oSideBars",      "overdrive_side_bars.png")
        loadImage("oSoloSideBars",  "overdrive_solo_side_bars.png")
        loadImage("failSideBars",   "fail_side_bars.png")
        loadImage("soloSideBars",   "solo_side_bars.png")
        loadImage("oCenterLines",   "overdrive_center_lines.png")
        loadImage("centerLines",    "center_lines.png")
        loadImage("oNeck",          "overdriveneck.png")
        loadImage("oFlash",         "overdrive_string_flash.png")
        loadImage("bpm_halfbeat",   "bpm_halfbeat.png")
        loadImage("bpm_beat",       "bpm_beat.png")
        loadImage("bpm_measure",    "bpm_measure.png")
        loadImage("failNeck",       "failneck.png")

        if not self.failNeck:
            engine.loadImgDrawing(self, "failNeck", os.path.join("failneck.png"))

        if self.ovrneckoverlay:
            loadImage("oNeckovr", "overdriveneckovr.png")

        #myfingershurt: Bass Groove neck:
        self.bassGrooveNeck = None

        if self.isBassGuitar and self.bassGrooveNeckMode > 0:
            if self.bassGrooveNeckMode == 2:  #overlay neck
                engine.loadImgDrawing(self, "bassGrooveNeck", os.path.join(themepath, "bass", "bassgrooveneckovr.png"))
            if self.bassGrooveNeckMode == 1 or not self.bassGrooveNeck:  #replace neck
                engine.loadImgDrawing(self, "bassGrooveNeck", os.path.join(themepath, "bass", "bassgrooveneck.png"))

        #myfingershurt: Guitar Solo neck:
        self.soloNeck = None
        if not self.isVocal:
            if self.guitarSoloNeckMode > 0:
                if self.guitarSoloNeckMode == 1 or not engine.loadImgDrawing(self, "soloNeck", os.path.join(themepath, "soloneckovr.png")):  #replace neck
                    loadImage("soloNeck", "soloneck.png")
                elif self.guitarSoloNeckMode == 2 or not engine.loadImgDrawing(self, "soloNeck", os.path.join(themepath, "soloneck.png")):  #overlay neck
                    loadImage("soloNeck", "soloneckovr.png")

        self.fourMultiNeck = None
        if not self.isBassGuitar and self.fourxNeckMode > 0:
            if self.fourxNeckMode == 1:  #replace neck
                engine.loadImgDrawing(self, "fourMultiNeck", os.path.join(themepath, "fourmultineck.png"))
            if self.fourxNeckMode == 2:  #overlay neck
                engine.loadImgDrawing(self, "fourMultiNeck", os.path.join(themepath, "fourmultineckovr.png"))

        self.isFailing             = False
        self.canGuitarSolo         = self.instrument.canGuitarSolo
        self.guitarSolo            = False
        self.scoreMultiplier       = 1
        self.overdriveFlashCounts  = self.indexFps/4   #how many cycles to display the oFlash: self.indexFps/2 = 1/2 second
        self.overdriveFlashCount   = self.overdriveFlashCounts
        self.ocount                = 0
        self.paused                = False
Exemplo n.º 34
0
 def screenError(self):
     log.error(
         "Video setup failed. Make sure your graphics card supports 32-bit display modes."
     )
     raise
Exemplo n.º 35
0
    def parseFile(self, filename):
        """Text parsing method. Provides some style functionalities."""
        nf = self.engine.data.font
        ns = 0.002
        bs = 0.001
        hs = 0.003
        c1 = (1, 1, .5, 1)
        c2 = (1, .75, 0, 1)
        space = Text(nf, hs, c1, "center", " ")
        scale = 1

        path = filename
        if not os.path.exists(path):
            err = "Credits file not found: " + path
            log.error(err)
            self.credits.append(Text(nf, bs * scale, c1, "left", "%s" % err))
            return

        with open(path) as f:
            filelines = f.readlines()

        for line in filelines:
            line = line.strip("\n")
            if line.startswith("=====") or line.startswith("-----"):
                continue
            try:
                if line.startswith("!") and line.endswith("!"):
                    scale = float(line.strip("!"))
                    continue
            except ValueError:
                log.warn("CREDITS file does not parse properly")
            if line == "":
                self.credits.append(space)
            elif line.startswith("`") and line.endswith("`"):
                line = line.strip("`")
                if line.startswith("%") and line.endswith("%"):
                    line = line.strip("%")
                    try:
                        for text in self.bank[line]:
                            self.credits.append(Text(nf, bs * scale, c1, "left", "%s" % text))
                    except KeyError:
                        self.credits.append(Text(nf, bs * scale, c1, "left", "%s" % line))
                else:
                    self.credits.append(Text(nf, bs * scale, c1, "left", "%s" % line))
            elif line.startswith("_") and line.endswith("_"):
                line = line.strip("_")
                if line.startswith("%") and line.endswith("%"):
                    line = line.strip("%")
                    try:
                        for text in self.bank[line]:
                            self.credits.append(Text(nf, ns * scale, c2, "center", "%s" % text))
                    except KeyError:
                        self.credits.append(Text(nf, ns * scale, c2, "center", "%s" % line))
                else:
                    self.credits.append(Text(nf, ns * scale, c2, "center", "%s" % line))
            elif line.startswith("=") and line.endswith("="):
                line = line.strip("=")
                if line.startswith("%") and line.endswith("%"):
                    line = line.strip("%")
                    try:
                        for text in self.bank[line]:
                            self.credits.append(Text(nf, ns * scale, c1, "left", "%s" % text))
                    except KeyError:
                        self.credits.append(Text(nf, ns * scale, c1, "left", "%s" % line))
                else:
                    self.credits.append(Text(nf, ns * scale, c1, "left", "%s" % line))
            else:
                if line.startswith("%") and line.endswith("%"):
                    line = line.strip("%")
                    try:
                        for text in self.bank[line]:
                            self.credits.append(Text(nf, ns * scale, c2, "right", "%s" % text))
                    except KeyError:
                        self.credits.append(Text(nf, ns * scale, c2, "right", "%s" % line))
                else:
                    self.credits.append(Text(nf, ns * scale, c2, "right", "%s" % line))
Exemplo n.º 36
0
    def __init__(self, engine, instrument, playerObj):

        self.engine = engine
        self.player = instrument.player
        self.instrument = instrument

        self.isDrum = self.instrument.isDrum
        self.isBassGuitar = self.instrument.isBassGuitar
        self.isVocal = self.instrument.isVocal

        self.oNeckovr = None  #MFH - needs to be here to prevent crashes!

        self.staticStrings = self.engine.config.get("performance",
                                                    "static_strings")

        self.indexFps = self.engine.config.get("video", "fps")  #QQstarS

        self.neckAlpha = []  # necks transparency
        self.neckAlpha.append(self.engine.config.get(
            "game", "necks_alpha"))  # all necks
        self.neckAlpha.append(
            self.neckAlpha[0] *
            self.engine.config.get("game", "neck_alpha"))  # normal neck
        self.neckAlpha.append(
            self.neckAlpha[0] *
            self.engine.config.get("game", "solo_neck_alpha"))  # solo neck
        self.neckAlpha.append(self.neckAlpha[0] * self.engine.config.get(
            "game", "bg_neck_alpha"))  # bass groove neck
        self.neckAlpha.append(self.neckAlpha[0] * self.engine.config.get(
            "game", "overlay_neck_alpha"))  # overlay neck
        self.neckAlpha.append(
            self.neckAlpha[0] *
            self.engine.config.get("game", "fail_neck_alpha"))  # fail neck
        self.neckAlpha.append(
            self.neckAlpha[0] *
            self.engine.config.get("game", "4x_neck_alpha"))  # 4x multi neck

        self.boardWidth = self.engine.theme.neckWidth
        self.boardLength = self.engine.theme.neckLength
        self.shaderSolocolor = self.engine.theme.shaderSolocolor

        self.boardFadeAmount = self.engine.theme.boardFade

        self.doNecksRender = self.engine.theme.doNecksRender

        #death_au: fixed neck size

        if self.isDrum and self.engine.config.get("game", "large_drum_neck"):
            self.boardWidth = 4.0
            self.boardLength = 12.0

        self.beatsPerBoard = 5.0
        self.beatsPerUnit = self.beatsPerBoard / self.boardLength

        color = (1, 1, 1)
        self.vis = 1

        size = 0

        # evilynux - Neck color
        self.board_col = np.array([[color[0], color[1], color[2], 0],
                                   [color[0], color[1], color[2], 0],
                                   [color[0], color[1], color[2], self.vis],
                                   [color[0], color[1], color[2], self.vis],
                                   [color[0], color[1], color[2], self.vis],
                                   [color[0], color[1], color[2], self.vis],
                                   [color[0], color[1], color[2], 0],
                                   [color[0], color[1], color[2], 0]],
                                  dtype=np.float32)

        w = self.boardWidth
        l = self.boardLength

        # evilynux - Neck vertices
        self.board_vtx = np.array(
            [[-w / 2, 0, -2], [w / 2, 0, -2], [-w / 2, 0, -1], [w / 2, 0, -1],
             [-w / 2, 0, l * .7], [w / 2, 0, l * .7], [-w / 2, 0, l],
             [w / 2, 0, l]],
            dtype=np.float32)

        self.shader_neck_vtx = np.array([[-w / 2, 0.1, -2], [w / 2, 0.1, -2],
                                         [-w / 2, 0.1, l], [w / 2, 0.1, l]],
                                        dtype=np.float32)

        self.track_vtx = np.array(
            [[-w / 2, 0, -2 + size], [w / 2, 0, -2 + size],
             [-w / 2, 0, -1 + size], [w / 2, 0, -1 + size], [
                 -w / 2, 0, l * .7
             ], [w / 2, 0, l * .7], [-w / 2, 0, l], [w / 2, 0, l]],
            dtype=np.float32)

        self.soloLightVtx1 = np.array(
            [[w / 2 - 1.0, 0.4, -2], [w / 2 + 1.0, 0.4, -2],
             [w / 2 - 1.0, 0.4, l], [w / 2 + 1.0, 0.4, l]],
            dtype=np.float32)

        self.soloLightVtx2 = np.array(
            [[-w / 2 + 1.0, 0.4, -2], [-w / 2 - 1.0, 0.4, -2],
             [-w / 2 + 1.0, 0.4, l], [-w / 2 - 1.0, 0.4, l]],
            dtype=np.float32)

        self.bpm_vtx = np.array([[-(w / 2), 0, 0], [-(w / 2), 0, 0],
                                 [(w / 2), 0, 0], [(w / 2), 0, 0]],
                                dtype=np.float32)

        self.board_scroll_vtx = np.array(
            [[-w / 2, 0, 0], [w / 2, 0, 0], [-w / 2, 0, 0], [w / 2, 0, 0],
             [-w / 2, 0, 0], [w / 2, 0, 0], [-w / 2, 0, 0], [w / 2, 0, 0]],
            dtype=np.float32)

        # evilynux - Sidebars vertices
        w += 0.15
        self.sidebars_vtx = np.array(
            [[-w / 2, 0, -2], [w / 2, 0, -2], [-w / 2, 0, -1], [w / 2, 0, -1],
             [-w / 2, 0, l * .7], [w / 2, 0, l * .7], [-w / 2, 0, l],
             [w / 2, 0, l]],
            dtype=np.float32)

        self.sidebars_scroll_vtx = np.array(
            [[-w / 2, 0, 0], [w / 2, 0, 0], [-w / 2, 0, 0], [w / 2, 0, 0],
             [-w / 2, 0, 0], [w / 2, 0, 0], [-w / 2, 0, 0], [w / 2, 0, 0]],
            dtype=np.float32)

        self.bpm_tex = np.array(
            [[0.0, 1.0], [0.0, 0.0], [1.0, 1.0], [1.0, 0.0]], dtype=np.float32)

        self.bpm_col = np.array([[1, 1, 1, self.vis], [1, 1, 1, self.vis],
                                 [1, 1, 1, self.vis], [1, 1, 1, self.vis]],
                                dtype=np.float32)

        self.board_col_flash = np.array(
            [[color[0], color[1], color[2], 0],
             [color[0], color[1], color[2], 0],
             [color[0], color[1], color[2], self.vis],
             [color[0], color[1], color[2], self.vis],
             [color[0], color[1], color[2], self.vis],
             [color[0], color[1], color[2], self.vis],
             [color[0], color[1], color[2], 0],
             [color[0], color[1], color[2], 0]],
            dtype=np.float32)

        self.board_tex_static = np.array(
            [[0.0, self.project(-2 * self.beatsPerUnit)],
             [1.0, self.project(-2 * self.beatsPerUnit)],
             [0.0, self.project(-1 * self.beatsPerUnit)],
             [1.0, self.project(-1 * self.beatsPerUnit)],
             [0.0, self.project(l * self.beatsPerUnit * .7)],
             [1.0, self.project(l * self.beatsPerUnit * .7)],
             [0.0, self.project(l * self.beatsPerUnit)],
             [1.0, self.project(l * self.beatsPerUnit)]],
            dtype=np.float32)

        self.board_tex = np.array([[0.0, 0], [1.0, 0], [0.0, 0], [1.0, 0],
                                   [0.0, 0], [1.0, 0], [0.0, 0], [1.0, 0]],
                                  dtype=np.float32)

        # evilynux - Just in case the type has became double, convert to float32
        self.board_col = self.board_col.astype(np.float32)
        self.board_vtx = self.board_vtx.astype(np.float32)
        self.sidebars_vtx = self.sidebars_vtx.astype(np.float32)
        self.sidebars_scroll_vtx = self.sidebars_scroll_vtx.astype(np.float32)
        self.bpm_tex = self.bpm_tex.astype(np.float32)
        self.bpm_col = self.bpm_col.astype(np.float32)
        self.soloLightVtx1 = self.soloLightVtx1.astype(np.float32)
        self.soloLightVtx2 = self.soloLightVtx2.astype(np.float32)
        self.shader_neck_vtx = self.shader_neck_vtx.astype(np.float32)
        self.track_vtx = self.track_vtx.astype(np.float32)
        self.board_col_flash = self.board_col_flash.astype(np.float32)
        self.bpm_vtx = self.bpm_vtx.astype(np.float32)
        self.board_tex_static = self.board_tex_static.astype(np.float32)
        self.board_tex = self.board_tex.astype(np.float32)
        self.board_scroll_vtx = self.board_scroll_vtx.astype(np.float32)

        self.neckType = playerObj.neckType
        if self.neckType == 0:
            self.neck = engine.mainMenu.chosenNeck
        else:
            self.neck = str(playerObj.neck)
        playerObj = None
        #Get theme
        themename = self.engine.data.themeLabel
        #now theme determination logic is only in data.py:
        self.theme = self.engine.data.theme

        self.incomingNeckMode = self.engine.config.get("game",
                                                       "incoming_neck_mode")

        #blazingamer
        self.failcount = 0
        self.failcount2 = False
        self.spcount = 0
        self.spcount2 = 0
        self.bgcount = 0
        self.fourXcount = 0
        self.ovrneckoverlay = self.engine.config.get("fretboard",
                                                     "ovrneckoverlay")
        self.ocount = 0

        self.currentPeriod = 60000.0 / self.instrument.currentBpm
        self.lastBpmChange = -1.0
        self.baseBeat = 0.0

        #myfingershurt:
        self.bassGrooveNeckMode = self.engine.config.get(
            "game", "bass_groove_neck")
        self.guitarSoloNeckMode = self.engine.config.get(
            "game", "guitar_solo_neck")
        self.fourxNeckMode = self.engine.config.get("game", "4x_neck")

        self.useMidiSoloMarkers = False
        self.markSolos = 0

        neckFind = True
        themeNeckPath = os.path.join(
            self.engine.resource.fileName("themes", themename, "necks"))
        if self.neckType == 1 and os.path.exists(themeNeckPath):
            themeNeck = []
            neckfiles = [
                f for f in os.listdir(themeNeckPath)
                if os.path.isfile(os.path.join(themeNeckPath, f))
            ]
            neckfiles.sort()
            for i in neckfiles:
                themeNeck.append(str(i))
            if len(themeNeck) > 0:
                i = random.randint(0, len(themeNeck) - 1)
                if engine.loadImgDrawing(self,
                                         "neckDrawing",
                                         os.path.join("themes", themename,
                                                      "necks", themeNeck[i]),
                                         textureSize=(256, 256)):
                    neckFind = False
                    log.debug("Random theme neck chosen: " + themeNeck[i])
                else:
                    log.error("Unable to load theme neck: " + themeNeck[i])
                    # fall back to defaultneck
                    self.neck = "defaultneck"
        if neckFind:
            # evilynux - Fixed random neck -- MFH: further fixing random neck
            if self.neck == "0" or self.neck == "Neck_0" or self.neck == "randomneck":
                self.neck = []
                # evilynux - improved loading logic to support arbitrary filenames
                path = self.engine.resource.fileName("necks")
                neckfiles = [
                    f for f in os.listdir(path)
                    if os.path.isfile(os.path.join(path, f))
                ]
                neckfiles.sort()
                for i in neckfiles:
                    # evilynux - Special cases, ignore these...
                    if (os.path.splitext(i)[0] == "randomneck"
                            or os.path.splitext(i)[0] == "overdriveneck"):
                        continue
                    else:
                        self.neck.append(
                            str(i)[:-4])  # evilynux - filename w/o extension

                i = random.randint(0, len(self.neck) - 1)
                if engine.loadImgDrawing(self,
                                         "neckDrawing",
                                         os.path.join("necks",
                                                      self.neck[i] + ".png"),
                                         textureSize=(256, 256)):
                    log.debug("Random neck chosen: " + self.neck[i])
                else:
                    log.error("Unable to load neck: " + self.neck[i])
                    self.neck = "defaultneck"
                    engine.loadImgDrawing(self,
                                          "neckDrawing",
                                          os.path.join("necks",
                                                       self.neck + ".png"),
                                          textureSize=(256, 256))
            else:
                # evilynux - first assume the self.neck contains the full filename
                if not engine.loadImgDrawing(self,
                                             "neckDrawing",
                                             os.path.join(
                                                 "necks", self.neck + ".png"),
                                             textureSize=(256, 256)):
                    if not engine.loadImgDrawing(
                            self,
                            "neckDrawing",
                            os.path.join("necks",
                                         "Neck_" + self.neck + ".png"),
                            textureSize=(256, 256)):
                        engine.loadImgDrawing(self,
                                              "neckDrawing",
                                              os.path.join(
                                                  "necks", "defaultneck.png"),
                                              textureSize=(256, 256))

        #blazingamer:
        #this helps me clean up the code a bit
        #what it does is if you're using drums or bass
        #it checks that directory first, if it doesn't
        #exist, then it goes back to the default directory

        if self.isDrum:
            self.extension = "drums"
        elif self.isBassGuitar:
            self.extension = "bass"
        else:
            self.extension = None

        themepath = os.path.join("themes", themename, "board")

        def loadImage(name, file):
            if self.extension:
                if not engine.loadImgDrawing(
                        self, name,
                        os.path.join(themepath, self.extension, file)):
                    engine.loadImgDrawing(self, name,
                                          os.path.join(themepath, file))
            else:
                engine.loadImgDrawing(self, name,
                                      os.path.join(themepath, file))

        loadImage("sideBars", "side_bars.png")
        loadImage("oSideBars", "overdrive_side_bars.png")
        loadImage("oSoloSideBars", "overdrive_solo_side_bars.png")
        loadImage("failSideBars", "fail_side_bars.png")
        loadImage("soloSideBars", "solo_side_bars.png")
        loadImage("oCenterLines", "overdrive_center_lines.png")
        loadImage("centerLines", "center_lines.png")
        loadImage("oNeck", "overdriveneck.png")
        loadImage("oFlash", "overdrive_string_flash.png")
        loadImage("bpm_halfbeat", "bpm_halfbeat.png")
        loadImage("bpm_beat", "bpm_beat.png")
        loadImage("bpm_measure", "bpm_measure.png")
        loadImage("failNeck", "failneck.png")

        if not self.failNeck:
            engine.loadImgDrawing(self, "failNeck",
                                  os.path.join("failneck.png"))

        if self.ovrneckoverlay:
            loadImage("oNeckovr", "overdriveneckovr.png")

        #myfingershurt: Bass Groove neck:
        self.bassGrooveNeck = None

        if self.isBassGuitar and self.bassGrooveNeckMode > 0:
            if self.bassGrooveNeckMode == 2:  #overlay neck
                engine.loadImgDrawing(
                    self, "bassGrooveNeck",
                    os.path.join(themepath, "bass", "bassgrooveneckovr.png"))
            if self.bassGrooveNeckMode == 1 or not self.bassGrooveNeck:  #replace neck
                engine.loadImgDrawing(
                    self, "bassGrooveNeck",
                    os.path.join(themepath, "bass", "bassgrooveneck.png"))

        #myfingershurt: Guitar Solo neck:
        self.soloNeck = None
        if not self.isVocal:
            if self.guitarSoloNeckMode > 0:
                if self.guitarSoloNeckMode == 1 or not engine.loadImgDrawing(
                        self, "soloNeck",
                        os.path.join(themepath,
                                     "soloneckovr.png")):  #replace neck
                    loadImage("soloNeck", "soloneck.png")
                elif self.guitarSoloNeckMode == 2 or not engine.loadImgDrawing(
                        self, "soloNeck",
                        os.path.join(themepath,
                                     "soloneck.png")):  #overlay neck
                    loadImage("soloNeck", "soloneckovr.png")

        self.fourMultiNeck = None
        if not self.isBassGuitar and self.fourxNeckMode > 0:
            if self.fourxNeckMode == 1:  #replace neck
                engine.loadImgDrawing(
                    self, "fourMultiNeck",
                    os.path.join(themepath, "fourmultineck.png"))
            if self.fourxNeckMode == 2:  #overlay neck
                engine.loadImgDrawing(
                    self, "fourMultiNeck",
                    os.path.join(themepath, "fourmultineckovr.png"))

        self.isFailing = False
        self.canGuitarSolo = self.instrument.canGuitarSolo
        self.guitarSolo = False
        self.scoreMultiplier = 1
        self.overdriveFlashCounts = self.indexFps / 4  #how many cycles to display the oFlash: self.indexFps/2 = 1/2 second
        self.overdriveFlashCount = self.overdriveFlashCounts
        self.ocount = 0
        self.paused = False
Exemplo n.º 37
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
Exemplo n.º 38
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.")
Exemplo n.º 39
0
    def __init__(self, engine, songName = None):
        self.engine      = engine
        self.time        = 0.0
        self.offset      = 0.5 # akedrou - this seems to fix the delay issue, but I'm not sure why. Return here!
        self.speedDiv    = 20000.0
        self.speedDir    = 1.0
        self.doneList    = []
        self.themename = Config.get("coffee", "themename")

        nf = self.engine.data.font
        ns = 0.002
        bs = 0.001
        hs = 0.003
        c1 = (1, 1, .5, 1)
        c2 = (1, .75, 0, 1)
        self.text_size = nf.getLineSpacing(scale = hs)

        #akedrou - Translatable Strings:
        self.bank = {}
        self.bank['intro']      = [_("Frets on Fire X is a progression of MFH-mod,"),
                                   _("which was built on Alarian's mod,"),
                                   _("which was built on UltimateCoffee's Ultimate mod,"),
                                   _("which was built on RogueF's RF_mod 4.15,"),
                                   _("which was, of course, built on Frets on Fire 1.2.451,"),
                                   _("which was created by Unreal Voodoo")]
        self.bank['noOrder']    = [_("No particular order")]
        self.bank['accessOrder']= [_("In order of project commit access")]
        self.bank['coders']     = [_("Active Coders")]
        self.bank['otherCoding']= [_("Programming")]
        self.bank['graphics']   = [_("Graphic Design")]
        self.bank['3d']         = [_("3D Textures")]
        self.bank['logo']       = [_("FoFiX Logo Design")]
        self.bank['hollowmind'] = [_("Hollowmind Necks")]
        self.bank['themes']     = [_("Included Themes")]
        self.bank['shaders']    = [_("Shaders")]
        self.bank['sounds']     = [_("Sound Design")]
        self.bank['translators']= [_("Translators")]
        self.bank['honorary']   = [_("Honorary Credits")]
        self.bank['codeHonor']  = [_("Without whom this game would not exist")]
        self.bank['giveThanks'] = [_("Special Thanks to")]
        self.bank['community']  = [_("nwru and all of the community at fretsonfire.net")]
        self.bank['other']      = [_("Other Contributors:")]
        self.bank['tutorial']   = [_("Jurgen FoF tutorial inspired by adam02"),
                                   _("Drum test song tutorial by Heka"),
                                   _("Drum Rolls practice tutorial by venom426")]
        self.bank['disclaimer'] = [_("If you have contributed to this game and are not credited,"),
                                   _("please let us know what and when you contributed.")]
        self.bank['thanks']     = [_("Thank you for your contribution.")]
        self.bank['oversight']  = [_("Please keep in mind that it is not easy to trace down and"),
                                   _("credit every single person who contributed; if your name is"),
                                   _("not included, it was not meant to slight you."),
                                   _("It was an oversight.")]
        # evilynux - Theme strings
        self.bank['themeCreators'] = [_("%s theme credits:") % self.themename]
        self.bank['themeThanks']   = [_("%s theme specific thanks:") % self.themename]
        # Languages
        self.bank['french']        = [_("French")]
        self.bank['french90']      = [_("French (reform 1990)")]
        self.bank['german']        = [_("German")]
        self.bank['italian']       = [_("Italian")]
        self.bank['piglatin']      = [_("Pig Latin")]
        self.bank['portuguese-b']  = [_("Portuguese (Brazilian)")]
        self.bank['russian']       = [_("Russian")]
        self.bank['spanish']       = [_("Spanish")]
        self.bank['swedish']       = [_("Swedish")]

        self.videoLayer = False
        self.background = None

        vidSource = os.path.join(Version.dataPath(), 'themes', self.themename,
                                 'menu', 'credits.ogv')
        if os.path.isfile(vidSource):
            try:
                self.vidPlayer = VideoLayer(self.engine, vidSource, mute = True, loop = True)
            except (IOError, VideoPlayerError):
                log.error('Error loading credits video:')
            else:
                self.vidPlayer.play()
                self.engine.view.pushLayer(self.vidPlayer)
                self.videoLayer = True

        if not self.videoLayer and \
           not self.engine.loadImgDrawing(self, 'background', os.path.join('themes', self.themename, 'menu', 'credits.png')):
            self.background = None

        if not self.engine.loadImgDrawing(self, 'topLayer', os.path.join('themes', self.themename, 'menu', 'creditstop.png')):
            self.topLayer = None

        space = Text(nf, hs, c1, "center", " ")
        self.credits = [
          Picture(self.engine, "fofix_logo.png", .10),
          Text(nf, ns, c1, "center", "%s" % Version.version()), space]

        # evilynux: Main FoFiX credits (taken from CREDITS).
        self.parseText("CREDITS")
        self.credits.extend([space, space, space])
        # evilynux: Theme credits (taken from data/themes/<theme name>/CREDITS).
        self.parseText(os.path.join('data', 'themes', self.themename, 'CREDITS'))

        self.credits.extend( [
          space, space,
          Text(nf, ns, c1, "left",   _("Made with:")),
          Text(nf, ns, c2, "right",  "Python " + sys.version.split(' ')[0]),  #stump: the version that's actually in use
          Text(nf, bs, c2, "right",  "http://www.python.org"),
          space,
          Text(nf, ns, c2, "right",  "PyGame " + pygame.version.ver.replace('release', '')),  #stump: the version that's actually in use
          Text(nf, bs, c2, "right",  "http://www.pygame.org"),
          space,
          Text(nf, ns, c2, "right",  "PyOpenGL " + OpenGL.__version__), #evilynux: the version that's actually in use
          Text(nf, bs, c2, "right",  "http://pyopengl.sourceforge.net"),
          space,
          Text(nf, ns, c2, "right",  "Illusoft Collada module 0.3.159"),
          Text(nf, bs, c2, "right",  "http://colladablender.illusoft.com"),
          space,
          Text(nf, ns, c2, "right",  "MXM Python Midi Package 0.1.4"),
          Text(nf, bs, c2, "right",  "http://www.mxm.dk/products/public/pythonmidi"),
          space,
          space,
          Text(nf, bs, c1, "center", _("Source Code available under the GNU General Public License")),
          Text(nf, bs, c2, "center", "http://code.google.com/p/fofix"),
          space,
          space,
          Text(nf, bs, c1, "center", _("Copyright 2006, 2007 by Unreal Voodoo")),
          Text(nf, bs, c1, "center", _("Copyright 2008-2013 by Team FoFiX")),
          space,
          space
        ])