コード例 #1
0
def graphics_test():
    from pyglet.gl import gl_info
    win = visual.Window([100, 100])  # some drivers want a window open first
    print("\nOpenGL info:")
    # get info about the graphics card and drivers
    print("vendor:", gl_info.get_vendor())
    print("rendering engine:", gl_info.get_renderer())
    print("OpenGL version:", gl_info.get_version())
コード例 #2
0
ファイル: info.py プロジェクト: MattIBall/psychopy
 def _setOpenGLInfo(self):
     # OpenGL info:
     self['openGLVendor'] = gl_info.get_vendor()
     self['openGLRenderingEngine'] = gl_info.get_renderer()
     self['openGLVersion'] = gl_info.get_version()
     GLextensionsOfInterest=['GL_ARB_multitexture', 'GL_EXT_framebuffer_object','GL_ARB_fragment_program',
         'GL_ARB_shader_objects','GL_ARB_vertex_shader', 'GL_ARB_texture_non_power_of_two','GL_ARB_texture_float']
 
     for ext in GLextensionsOfInterest:
         self['openGLext.'+ext] = bool(gl_info.have_extension(ext))
コード例 #3
0
def dump_gl():
    '''Dump GL info.'''
    from pyglet.gl import gl_info
    _print('gl_info.get_version():', gl_info.get_version())
    _print('gl_info.get_vendor():', gl_info.get_vendor())
    _print('gl_info.get_renderer():', gl_info.get_renderer())
    _print('gl_info.get_extensions():')
    extensions = list(gl_info.get_extensions())
    extensions.sort()
    for name in extensions:
        _print('  ', name)
コード例 #4
0
ファイル: info.py プロジェクト: Aang/sympy
def dump_gl():
    '''Dump GL info.'''
    from pyglet.gl import gl_info
    print 'gl_info.get_version():',  gl_info.get_version()
    print 'gl_info.get_vendor():',  gl_info.get_vendor()
    print 'gl_info.get_renderer():',  gl_info.get_renderer()
    print 'gl_info.get_extensions():'
    extensions = list(gl_info.get_extensions())
    extensions.sort()
    for name in extensions:
        print '  ', name
コード例 #5
0
ファイル: wizard.py プロジェクト: 9173860/psychopy
def cardOkay():
    """Returns string: okay, maybe, bad"""

    return True  # until we have a list of known-good cards

    card = gl_info.get_renderer()
    knownGoodList = []  # perhaps load from a file
    if card in knownGoodList:
        return True
    knownBadList = []
    if card in knownBadList:
        return False
コード例 #6
0
ファイル: wizard.py プロジェクト: fredericocm/psychopy
def cardOkay():
    """Returns string: okay, maybe, bad"""

    return True  # until we have a list of known-good cards

    card = gl_info.get_renderer()
    knownGoodList = []  # perhaps load from a file
    if card in knownGoodList:
        return True
    knownBadList = []
    if card in knownBadList:
        return False
コード例 #7
0
ファイル: info.py プロジェクト: chrox/psychopy
    def _setOpenGLInfo(self):
        # OpenGL info:
        self['openGLVendor'] = gl_info.get_vendor()
        self['openGLRenderingEngine'] = gl_info.get_renderer()
        self['openGLVersion'] = gl_info.get_version()
        GLextensionsOfInterest = [
            'GL_ARB_multitexture', 'GL_EXT_framebuffer_object',
            'GL_ARB_fragment_program', 'GL_ARB_shader_objects',
            'GL_ARB_vertex_shader', 'GL_ARB_texture_non_power_of_two',
            'GL_ARB_texture_float'
        ]

        for ext in GLextensionsOfInterest:
            self['openGLext.' + ext] = bool(gl_info.have_extension(ext))
コード例 #8
0
ファイル: info.py プロジェクト: cajlarsson/village
def dump_gl(context=None):
    """Dump GL info."""
    if context is not None:
        info = context.get_info()
    else:
        from pyglet.gl import gl_info as info
    print("gl_info.get_version():", info.get_version())
    print("gl_info.get_vendor():", info.get_vendor())
    print("gl_info.get_renderer():", info.get_renderer())
    print("gl_info.get_extensions():")
    extensions = list(info.get_extensions())
    extensions.sort()
    for name in extensions:
        print("  ", name)
コード例 #9
0
ファイル: info.py プロジェクト: Benrflanders/Pytris
def dump_gl(context=None):
    '''Dump GL info.'''
    if context is not None:
        info = context.get_info()
    else:
        from pyglet.gl import gl_info as info
    print 'gl_info.get_version():',  info.get_version()
    print 'gl_info.get_vendor():',  info.get_vendor()
    print 'gl_info.get_renderer():',  info.get_renderer()
    print 'gl_info.get_extensions():'
    extensions = list(info.get_extensions())
    extensions.sort()
    for name in extensions:
        print '  ', name
コード例 #10
0
ファイル: info.py プロジェクト: Yakser/TelegramBot
def dump_gl(context=None):
    """Dump GL info."""
    if context is not None:
        info = context.get_info()
    else:
        from pyglet.gl import gl_info as info
    print('gl_info.get_version():', info.get_version())
    print('gl_info.get_vendor():', info.get_vendor())
    print('gl_info.get_renderer():', info.get_renderer())
    print('gl_info.get_extensions():')
    extensions = list(info.get_extensions())
    extensions.sort()
    for name in extensions:
        print('  ', name)
コード例 #11
0
    def _setOpenGLInfo(self):
        # OpenGL info:
        self['openGLVendor'] = gl_info.get_vendor()
        self['openGLRenderingEngine'] = gl_info.get_renderer()
        self['openGLVersion'] = gl_info.get_version()
        GLextensionsOfInterest = ['GL_ARB_multitexture', 'GL_EXT_framebuffer_object',
             'GL_ARB_fragment_program', 'GL_ARB_shader_objects', 'GL_ARB_vertex_shader',
             'GL_ARB_texture_non_power_of_two', 'GL_ARB_texture_float', 'GL_STEREO']

        for ext in GLextensionsOfInterest:
            self['openGLext.'+ext] = bool(gl_info.have_extension(ext))

        maxVerts = GLint()
        glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, maxVerts)
        self['openGLmaxVerticesInVertexArray'] = maxVerts.value
コード例 #12
0
ファイル: info.py プロジェクト: alexholcombe/psychopy
    def _setOpenGLInfo(self):
        # OpenGL info:
        self['openGLVendor'] = gl_info.get_vendor()
        self['openGLRenderingEngine'] = gl_info.get_renderer()
        self['openGLVersion'] = gl_info.get_version()
        GLextensionsOfInterest = ['GL_ARB_multitexture', 'GL_EXT_framebuffer_object',
             'GL_ARB_fragment_program', 'GL_ARB_shader_objects', 'GL_ARB_vertex_shader',
             'GL_ARB_texture_non_power_of_two', 'GL_ARB_texture_float', 'GL_STEREO']

        for ext in GLextensionsOfInterest:
            self['openGLext.'+ext] = bool(gl_info.have_extension(ext))

        maxVerts = GLint()
        glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, maxVerts)
        self['openGLmaxVerticesInVertexArray'] = maxVerts.value
コード例 #13
0
def start_client():
    import ctypes
    try:
        ctypes.cdll.avbin  # force avbin load
    except:
        pass

    import logging
    import os
    import argparse
    import utils.logging

    parser = argparse.ArgumentParser(prog=sys.argv[0])
    parser.add_argument('--no-update', action='store_true')
    parser.add_argument('--with-gl-errcheck', action='store_true')
    parser.add_argument('--freeplay', action='store_true')
    parser.add_argument('--fastjoin', action='store_true')
    parser.add_argument('--dump-gameobj', action='store_true')
    parser.add_argument('--log', default='INFO')
    parser.add_argument('--color-log', action='store_true')
    parser.add_argument('--show-hidden-modes', action='store_true')

    options = parser.parse_args()

    import options as opmodule
    opmodule.options = options

    IS_PROTON = hasattr(os, 'uname') and os.uname()[:2] == ('Linux', 'Proton')

    import settings
    utils.logging.init(options.log.upper(), settings.SENTRY_DSN, IS_PROTON or options.color_log)
    utils.logging.patch_gevent_hub_print_exception()

    if options.no_update:
        import autoupdate
        autoupdate.Autoupdate = autoupdate.DummyAutoupdate

    log = logging.getLogger('start_client')

    from gevent import monkey
    monkey.patch_socket()
    monkey.patch_os()
    monkey.patch_select()
    monkey.patch_ssl()

    from game import autoenv
    autoenv.init('Client')

    import pyglet

    pyglet.options['shadow_window'] = False

    if not options.with_gl_errcheck:
        pyglet.options['debug_gl'] = False

    from pyglet.gl import gl_info
    if gl_info.get_renderer() == 'GDI Generic':
        ctypes.windll.user32.MessageBoxW(
            0,
            u'你好像没有安装显卡驱动……?这样游戏是跑不起来的。快去安装!',
            u'需要显卡驱动',
            16,
        )
        sys.exit(0)

    if sys.platform.startswith('linux') and options.dump_gameobj:
        import atexit
        import game
        atexit.register(game.GameObjectMeta._dump_gameobject_hierarchy)
        atexit.register(game.EventHandler._dump_eh_dependency_graph)

    from client.ui.entry import start_ui

    try:
        start_ui()
    except KeyboardInterrupt:
        import pyglet
        pyglet.app.exit()
        raise
    except:
        import pyglet
        pyglet.app.exit()

        if options.fastjoin:
            import pdb
            pdb.post_mortem()

        log.exception(u'UI线程崩溃,正在报告bug,请稍等下……')
        from utils.stats import stats
        stats({'event': 'crash'})

        raise
コード例 #14
0
ファイル: wizard.py プロジェクト: fredericocm/psychopy
    def __init__(self, firstrun=False, interactive=True, log=True):
        """Check drivers, show GUIs, run diagnostics, show report."""
        self.firstrun = firstrun
        self.prefs = prefs
        self.appName = 'PsychoPy2'
        self.name = self.appName + _translate(' Configuration Wizard')
        self.reportPath = os.path.join(self.prefs.paths['userPrefsDir'], 'firstrunReport.html')
        #self.iconfile = os.path.join(self.prefs.paths['resources'], 'psychopy.png')
        #dlg.SetIcon(wx.Icon(self.iconfile, wx.BITMAP_TYPE_PNG)) # no error but no effect

        dlg = gui.Dlg(title=self.name)
        dlg.addText('')
        if firstrun:
            dlg.addText(_translate("Welcome to PsychoPy2!"), color='blue')
            dlg.addText('')
            dlg.addText(_translate("It looks like you are running PsychoPy for the first time."))
            dlg.addText(_translate("This wizard will help you get started quickly and smoothly."))
        else:
            dlg.addText(_translate("Welcome to the configuration wizard."))

        # test for fatal configuration errors:
        fatalItemsList = []
        if not driversOkay():
            cardInfo = gl_info.get_renderer().replace('OpenGL Engine', '').strip()
            dlg.addText('')
            dlg.addText(_translate("The first configuration check is your video card's drivers. The current"), color='red')
            dlg.addText(_translate("drivers cannot support PsychoPy, so you'll need to update the drivers."), color='red')
            msg = _translate("""<p>Critical issue:\n</p><p>Your video card (%(card)s) has drivers
                that cannot support the high-performance features that PsychoPy depends on.
                Fortunately, it's typically free and straightforward to get new drivers
                directly from the manufacturer.</p>
                <p><strong>To update the drivers:</strong>
                <li> You'll need administrator privileges.
                <li> On Windows, don't use the windows option to check for updates
                  - it can report that there are no updates available.
                <li> If your card is made by NVIDIA, go to
                  <a href="http://www.nvidia.com/Drivers">the NVIDIA website</a>
                  and use the 'auto detect' option. Try here for
                  <a href="http://support.amd.com/">ATI / Radeon drivers</a>. Or try
                  <a href="http://www.google.com/search?q=download+drivers+%(card2)s">
                  this google search</a> [google.com].
                <li> Download and install the driver.
                <li> Reboot the computer.
                <li> Restart PsychoPy.</p>
                <p>If you updated the drivers and still get this message, you'll
                  need a different video card to use PsychoPy. Click
                <a href="http://www.psychopy.org/installation.html#recommended-hardware">here
                for more information</a> [psychopy.org].</p>
            """) % {'card': cardInfo, 'card2': cardInfo.replace(' ', '+')}
            fatalItemsList.append(msg)
        if not cardOkay():
            cardInfo = gl_info.get_renderer().replace('OpenGL Engine', '').strip()
            msg = _translate("""<p>Critical issue:\n</p>""")
            msg += cardInfo
            fatalItemsList.append(msg)
            pass
        # other fatal conditions? append a 'Critical issue' msg to itemsList
        if not fatalItemsList:
            dlg.addText(_translate("We'll go through a series of configuration checks in about 10 seconds. "))
            dlg.addText('')
            if firstrun:  # explain things more
                dlg.addText(_translate('Note: The display will switch to full-screen mode and will '))
                dlg.addText(_translate("then switch back. You don't need to do anything."))
            dlg.addText(_translate('Optional: For best results, please quit all email programs, web-browsers, '))
            dlg.addText(_translate('Dropbox, backup or sync services, and others.'))
            dlg.addText('')
            dlg.addText(_translate('Click OK to start, or Cancel to skip.'))
            if not self.firstrun:
                dlg.addField(label=_translate('Full details'), initial=self.prefs.app['debugMode'])
        else:
            dlg.addText('')
            dlg.addText(_translate('Click OK for more information, or Cancel to skip.'))

        # show the first dialog:
        dlg.addText('')
        if interactive:
            dlg.show()
        if fatalItemsList:
            self.htmlReport(fatal=fatalItemsList)
            self.save()
            # user ends up in browser:
            url='file://' + self.reportPath
            if interactive:
                wx.LaunchDefaultBrowser(url)
            return
        if interactive and not dlg.OK:
            return  # no configuration tests run

        # run the diagnostics:
        verbose = interactive and not self.firstrun and dlg.data[0]
        win = visual.Window(fullscr=interactive, allowGUI=False, monitor='testMonitor',
                            autoLog=log)
        itemsList = self.runDiagnostics(win, verbose)  # sets self.warnings
        win.close()
        self.htmlReport(itemsList)
        self.save()

        # display summary & options:
        dlg = gui.Dlg(title=self.name)
        dlg.addText('')
        dlg.addText(_translate('Configuration testing complete!'))
        summary = self.summary(items=itemsList)
        numWarn = len(self.warnings)
        if numWarn == 0:
            msg = _translate('All values seem reasonable (no warnings).')
        elif numWarn == 1:
            msg = _translate('1 suboptimal value was detected (%s)') % self.warnings[0]
        else:
            msg = _translate('%(num)i suboptimal values were detected (%(warn)s, ...)') % {
                'num': len(self.warnings), 'warn': self.warnings[0]}
        dlg.addText(msg)
        for item in summary:
            dlg.addText(item[0], item[1])  # (key, color)
        dlg.addText('')
        dlg.addText(_translate('Click OK for full details (will open in a web-browser),'))
        dlg.addText(_translate('or Cancel to stay in PsychoPy.'))
        dlg.addText('')
        if interactive:
            dlg.show()
            if dlg.OK:
                url = 'file://' + self.reportPath
                wx.LaunchDefaultBrowser(url)
        return
コード例 #15
0
import platform

#monitorName = 'ASUS ML 239'
monitorName = 'testMonitor'
debug = 1

resolution = [800, 600] if debug == 1 else [800, 600]

expName = 'orientation_search'
expInfo = {u'session': u'001', u'participant': u''}
dlg = gui.DlgFromDict(dictionary=expInfo, title=expName)
if dlg.OK == False: core.quit()  # user pressed cancel
expInfo['date'] = data.getDateStr()  # add a simple timestamp
expInfo['expName'] = expName

expInfo['graphic_card'] = info.get_renderer()
cpu_info = cpuinfo.get_cpu_info()
expInfo['cpu_info'] = cpu_info['brand']
expInfo['pc_name'] = platform.node()
expInfo['monitorName'] = monitorName
expInfo['resolution'] = '_'.join(str(x) for x in resolution)

mon = monitors.Monitor(monitorName)
win = visual.Window(resolution, units='deg', monitor=mon, fullscr=True)

if 0:
    if (mon.getSizePix() != resolution):
        print 'Resolution in monitor center is different from the one requested for this experiment. Please make them equal to make sure that the computations of visual angle will be correct for the resolution you want.'
        core.quit()
        win.close()
コード例 #16
0
ファイル: start_client.py プロジェクト: yuzishui/thbattle
def start_client():
    import ctypes
    try:
        ctypes.cdll.avbin  # force avbin load
    except:
        pass

    import logging
    import os
    import argparse
    import crashreport

    parser = argparse.ArgumentParser(prog=sys.argv[0])
    parser.add_argument('--no-update', action='store_true')
    parser.add_argument('--with-gl-errcheck', action='store_true')
    parser.add_argument('--freeplay', action='store_true')
    parser.add_argument('--fastjoin', action='store_true')
    parser.add_argument('--dump-gameobj', action='store_true')
    parser.add_argument('--log', default='INFO')
    parser.add_argument('--color-log', action='store_true')
    parser.add_argument('--no-crashreport', action='store_true')
    parser.add_argument('--show-hidden-modes', action='store_true')

    options = parser.parse_args()

    import options as opmodule
    opmodule.options = options

    IS_PROTON = hasattr(os, 'uname') and os.uname()[:2] == ('Linux', 'Proton')

    crashreport.install_tee(options.log.upper())

    if options.no_update:
        import autoupdate
        autoupdate.Autoupdate = autoupdate.DummyAutoupdate

    if IS_PROTON or options.color_log:
        from colorlog import ColoredFormatter

        formatter = ColoredFormatter("%(log_color)s%(message)s%(reset)s",
                                     log_colors={
                                         'CRITICAL': 'bold_red',
                                         'ERROR': 'red',
                                         'WARNING': 'yellow',
                                         'INFO': 'green',
                                         'DEBUG': 'blue',
                                     })

        logging.getLogger().handlers[0].setFormatter(formatter)

    log = logging.getLogger('start_client')

    from gevent import monkey
    monkey.patch_socket()
    monkey.patch_os()
    monkey.patch_select()
    monkey.patch_ssl()

    from game import autoenv
    autoenv.init('Client')

    import pyglet

    pyglet.options['shadow_window'] = False

    if not options.with_gl_errcheck:
        pyglet.options['debug_gl'] = False

    from pyglet.gl import gl_info
    if gl_info.get_renderer() == 'GDI Generic':
        ctypes.windll.user32.MessageBoxW(
            0,
            u'你好像没有安装显卡驱动……?这样游戏是跑不起来的。快去安装!',
            u'需要显卡驱动',
            16,
        )
        sys.exit(0)

    if sys.platform.startswith('linux') and options.dump_gameobj:
        import atexit
        import game
        atexit.register(game.GameObjectMeta._dump_gameobject_hierarchy)
        atexit.register(game.EventHandler._dump_eh_dependency_graph)

    from client.ui.entry import start_ui

    try:
        start_ui()
    except KeyboardInterrupt:
        import pyglet
        pyglet.app.exit()
        raise
    except:
        import pyglet
        pyglet.app.exit()

        if options.fastjoin:
            import pdb
            pdb.post_mortem()

        if not options.no_crashreport:
            log.error(u'游戏崩溃,正在报告bug,请稍等下……')
            from utils.stats import stats
            stats({'event': 'crash'})
            from crashreport import do_crashreport
            do_crashreport()

        raise
コード例 #17
0
import pyglet
print("pyglet", pyglet.version)
# pyo is a new dependency, for sound:
try:
    import pyo
    print("pyo", '%i.%i.%i' % pyo.getVersion())
except Exception:
    print('pyo [not installed]')

from psychopy import __version__
print("\nPsychoPy", __version__)

win = visual.Window([100, 100])  # some drivers want a window open first
print("have shaders:", win._haveShaders)
print("\nOpenGL info:")
# get info about the graphics card and drivers
print("vendor:", gl_info.get_vendor())
print("rendering engine:", gl_info.get_renderer())
print("OpenGL version:", gl_info.get_version())
print("(Selected) Extensions:")
extensionsOfInterest = ['GL_ARB_multitexture',
                        'GL_EXT_framebuffer_object', 'GL_ARB_fragment_program',
                        'GL_ARB_shader_objects', 'GL_ARB_vertex_shader',
                        'GL_ARB_texture_non_power_of_two', 'GL_ARB_texture_float', 'GL_STEREO']
for ext in extensionsOfInterest:
    print("\t", bool(gl_info.have_extension(ext)), ext)
# also determine nVertices that can be used in vertex arrays
maxVerts = GLint()
glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, maxVerts)
print('\tmax vertices in vertex array:', maxVerts.value)
コード例 #18
0
ファイル: bits.py プロジェクト: alexholcombe/psychopy
 def _getGfxCardString(self):
     from pyglet.gl import gl_info
     thisStr = "%s: %s" %(gl_info.get_renderer(), gl_info.get_version())
     return thisStr
コード例 #19
0
ファイル: gamma.py プロジェクト: bjanus/psychopy
def createLinearRamp(win, rampType=None):
    """Generate the Nx3 values for a linear gamma ramp on the current platform.
    This uses heuristics about known graphics cards to guess the 'rampType' if 
    none is exlicitly given.
    
    Much of this work is ported from LoadIdentityClut.m, written by Mario Kleiner
    for the psychtoolbox
    
    rampType 0 : an 8-bit CLUT ranging 0:1
        This is seems correct for most windows machines and older OS X systems
        Known to be used by:
            OSX 10.4.9 PPC with GeForceFX-5200
        
    rampType 1 : an 8-bit CLUT ranging (1/256.0):1
        For some reason a number of macs then had a CLUT that (erroneously?) started with 1/256 rather than 0
        Known to be used by:
            OSX 10.4.9 with ATI Mobility Radeon X1600
            OSX 10.5.8 with ATI Radeon HD-2600
            maybe all ATI cards?
    
    rampType 2 : a 10-bit CLUT ranging 0:(1023/1024)
        A slightly odd 10-bit CLUT that doesn't quite finish on 1.0!
        Known to be used by:
            OSX 10.5.8 with Geforce-9200M (MacMini)
            OSX 10.5.8 with Geforce-8800
    
    rampType 3 : a nasty, bug-fixing 10bit CLUT for crumby OS X drivers
        Craziest of them all for Snow leopard. Like rampType 2, except that the upper half of the table has 1/256.0 removed?!!
        Known to be used by:
            OSX 10.6.0 with NVidia Geforce-9200M
    """
    if rampType == None:
        # try to determine rampType from heuristics
        # get sys info
        driver = gl_info.get_renderer()
        if sys.platform == "darwin":
            isOSX = True
            osxVer = platform.mac_ver()[0]
        else:
            isOSX = False
            osxVer = None

        # try to deduce ramp type
        if isOSX:
            if "NVIDIA" in driver:
                if "10.5" < osxVer < "10.6":  # leopard nVidia cards don't finish at 1.0!
                    rampType = 2
                if "10.6" < osxVer:  # snow leopard cards are plain crazy!
                    rampType = 3
            else:  # is ATI or unkown manufacturer, default to (1:256)/256
                # this is certainly correct for radeon2600 on 10.5.8 and radeonX1600 on 10.4.9
                rampType = 1
        else:  # for win32 and linux this is sensible, not clear about Vista and Windows7
            rampType = 0

        if rampType == 0:
            ramp = numpy.linspace(0.0, 1.0, num=256)
        elif rampType == 1:
            ramp = numpy.linspace(1 / 256.0, 1.0, num=256)
        elif rampType == 2:
            ramp = numpy.linspace(0, 1023.0 / 1024, num=1024)
        elif rampType == 3:
            ramp = numpy.linspace(0, 1023.0 / 1024, num=1024)
            ramp[512:] = ramp[512:] - 1 / 256.0
        log.info("Using gamma ramp type: %i" % rampType)
        return ramp
コード例 #20
0
ファイル: gl_info.py プロジェクト: izacus/pyglet
print 'Display instance is %r' % display
print 'Screens:'
for screen in display.get_screens():
    print '  %r' % screen

print 'Creating default context...'
w = pyglet.window.Window(1, 1, visible=True)

print 'GL attributes:'
attrs = w.config.get_gl_attributes()
attrs = ' '.join(['%s=%s'%(name, value) for name, value in attrs])
print '\n'.join(textwrap.wrap(attrs))

print 'GL version:', gl_info.get_version()
print 'GL vendor:', gl_info.get_vendor()
print 'GL renderer:', gl_info.get_renderer()
print 'GL extensions:'
exts = ' '.join(gl_info.get_extensions())
print ' ', '\n  '.join(textwrap.wrap(exts))

print 'GLU version:', glu_info.get_version()
print 'GLU extensions:'
exts = ' '.join(glu_info.get_extensions())
print ' ', '\n  '.join(textwrap.wrap(exts))

print

context = w.context
print 'Context is', context

if context.__class__.__name__ == 'XlibGLContext':
コード例 #21
0
ファイル: config.py プロジェクト: certik/scikits.gpu
class DriverError(Exception):
    pass

class GLSLError(Exception):
    pass

def require_extension(ext):
    """Ensure that the given graphics extension is supported.

    """
    if not gl.gl_info.have_extension('GL_' + ext):
        raise HardwareSupportError("the %s extension" % ext)

hardware_info = {'vendor': gli.get_vendor(),
                 'renderer': gli.get_renderer(),
                 'version': gli.get_version()}

# Check hardware support

_opengl_version = hardware_info['version'].split(' ')[0]
if _opengl_version < "2.0":
    raise DriverError("This package requires OpenGL v2.0 or higher. "
                      "Your version is %s." % _opengl_version)

# This extension is required to return floats outside [0, 1]
# in gl_FragColor
require_extension('ARB_color_buffer_float')
require_extension('ARB_texture_float')

gl.glClampColorARB(gl.GL_CLAMP_VERTEX_COLOR_ARB, False)
コード例 #22
0
def getSysInfo(win):
    from collections import OrderedDict
    # based on sysInfo.py
    from pyglet.gl import gl_info, GLint, glGetIntegerv, GL_MAX_ELEMENTS_VERTICES
    import sys, platform

    sys_info = OrderedDict()
    sys_info['OS'] = OrderedDict()
    sys_info['OS']['Name'] = platform.platform()
    if sys.platform == 'darwin':
        OSXver, _, architecture = platform.mac_ver()
        sys_info['OS']['OSX Version'] = OSXver
        sys_info['OS']['OSX Architecture'] = architecture

    sys_info['Computer Hardware'] = OrderedDict()
    try:
        import psutil

        def getMemoryInfo():
            rdict = dict()
            nt = psutil.virtual_memory()
            for name in nt._fields:
                value = getattr(nt, name)
                if name != 'percent':
                    value = bytes2human(value)
                rdict[name.capitalize()] = value  # '%s%s%-10s : %7s\n'%(rstr, '\t' * indent, name.capitalize(), value)
            return rdict

        core_count = psutil.cpu_count(logical=False)
        logical_psu_count = psutil.cpu_count()
        memory_info = getMemoryInfo()
        sys_info['Computer Hardware']['CPUs (cores / logical)'] = (core_count, logical_psu_count)
        sys_info['Computer Hardware']['System Memory'] = memory_info

    except Exception:
        sys_info['Computer Hardware']['Failed'] = 'psutil 2.x + is required.'

    sys_info['Python'] = OrderedDict()
    sys_info['Python']['exe'] = sys.executable
    sys_info['Python']['version'] = sys.version

    sys_info['Packages'] = OrderedDict()
    try:
        import numpy
        sys_info['Packages']['numpy'] = numpy.__version__
    except ImportError:
        sys_info['Packages']['numpy'] = "Not Installed"
    try:
        import pyglet
        sys_info['Packages']['pyglet'] = pyglet.version
    except ImportError:
        sys_info['Packages']['pyglet'] = "Not Installed"
    try:
        import cv2
        sys_info['Packages']['cv2'] = cv2.__version__
    except ImportError:
        sys_info['Packages']['cv2'] = "Not Installed"
    try:
        import psychopy
        sys_info['Packages']['PsychoPy'] = psychopy.__version__
    except ImportError:
        sys_info['Packages']['PsychoPy'] = "Not Installed"

    sys_info['Graphics'] = OrderedDict()
    sys_info['Graphics']['shaders'] = win._haveShaders
    sys_info['Graphics']['opengl'] = OrderedDict()
    sys_info['Graphics']['opengl']['version'] = gl_info.get_version()
    sys_info['Graphics']['opengl']['vendor'] = gl_info.get_vendor()
    sys_info['Graphics']['opengl']['engine'] = gl_info.get_renderer()
    maxVerts = GLint()
    glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, maxVerts)
    sys_info['Graphics']['opengl']['Max vert in VA'] = maxVerts.value
    sys_info['Graphics']['opengl']['extensions'] = OrderedDict()
    extensionsOfInterest = ['GL_ARB_multitexture',
                            'GL_EXT_framebuffer_object', 'GL_ARB_fragment_program',
                            'GL_ARB_shader_objects', 'GL_ARB_vertex_shader',
                            'GL_ARB_texture_non_power_of_two', 'GL_ARB_texture_float', 'GL_STEREO']
    for ext in extensionsOfInterest:
        sys_info['Graphics']['opengl']['extensions'][ext] = bool(gl_info.have_extension(ext))

    sys_info['Processes'] = OrderedDict()
    if sys.platform == 'darwin':
        sys_info['Processes']['Failed'] = 'Not Supported on OSX.'
    elif SAVE_PER_PROCESS_DATA:
        try:
            import psutil

            for proc in psutil.process_iter():
                pkey = proc.pid
                vattrs = ['name', 'exe', 'ppid', 'num_threads', 'memory_percent', 'cpu_percent', 'cpu_affinity', 'nice',
                          'num_ctx_switches']
                procinfo = proc.as_dict(attrs=vattrs, ad_value=u"Access Denied")
                if procinfo['exe'] is not u"Access Denied" and (SAVE_PER_PROCESS_DATA is True or SAVE_PER_PROCESS_DATA == procinfo['name']):
                    sys_info['Processes'][pkey] = procinfo
        except ImportError:
            sys_info['Processes']['Failed'] = 'psutil 2.x + is required.'
    else:
        sys_info['Processes']['Disabled'] = 'Per Process details disabled by user.'

    return sys_info
コード例 #23
0
def createLinearRamp(win, rampType=None):
    """Generate the Nx3 values for a linear gamma ramp on the current platform.
    This uses heuristics about known graphics cards to guess the 'rampType' if 
    none is exlicitly given.
    
    Much of this work is ported from LoadIdentityClut.m, written by Mario Kleiner
    for the psychtoolbox
    
    rampType 0 : an 8-bit CLUT ranging 0:1
        This is seems correct for most windows machines and older OS X systems
        Known to be used by:
            OSX 10.4.9 PPC with GeForceFX-5200
        
    rampType 1 : an 8-bit CLUT ranging (1/256.0):1
        For some reason a number of macs then had a CLUT that (erroneously?) started with 1/256 rather than 0
        Known to be used by:
            OSX 10.4.9 with ATI Mobility Radeon X1600
            OSX 10.5.8 with ATI Radeon HD-2600
            maybe all ATI cards?
    
    rampType 2 : a 10-bit CLUT ranging 0:(1023/1024)
        A slightly odd 10-bit CLUT that doesn't quite finish on 1.0!
        Known to be used by:
            OSX 10.5.8 with Geforce-9200M (MacMini)
            OSX 10.5.8 with Geforce-8800
    
    rampType 3 : a nasty, bug-fixing 10bit CLUT for crumby OS X drivers
        Craziest of them all for Snow leopard. Like rampType 2, except that the upper half of the table has 1/256.0 removed?!!
        Known to be used by:
            OSX 10.6.0 with NVidia Geforce-9200M
    """
    if rampType == None:
        #try to determine rampType from heuristics
        #get sys info
        driver = gl_info.get_renderer()
        if sys.platform == 'darwin':
            isOSX = True
            osxVer = platform.mac_ver()[0]
        else:
            isOSX = False
            osxVer = None

        #try to deduce ramp type
        if isOSX:
            if 'NVIDIA' in driver:
                if ("10.5" < osxVer <
                        "10.6"):  #leopard nVidia cards don't finish at 1.0!
                    rampType = 2
                if ("10.6" < osxVer):  #snow leopard cards are plain crazy!
                    rampType = 3
            else:  #is ATI or unkown manufacturer, default to (1:256)/256
                #this is certainly correct for radeon2600 on 10.5.8 and radeonX1600 on 10.4.9
                rampType = 1
        else:  #for win32 and linux this is sensible, not clear about Vista and Windows7
            rampType = 0

        if rampType == 0:
            ramp = numpy.linspace(0.0, 1.0, num=256)
        elif rampType == 1:
            ramp = numpy.linspace(1 / 256.0, 1.0, num=256)
        elif rampType == 2:
            ramp = numpy.linspace(0, 1023.0 / 1024, num=1024)
        elif rampType == 3:
            ramp = numpy.linspace(0, 1023.0 / 1024, num=1024)
            ramp[512:] = ramp[512:] - 1 / 256.0
        log.info('Using gamma ramp type: %i' % rampType)
        return ramp
コード例 #24
0
import platform
from pyglet.gl import gl_info as info

print info.get_renderer()
cpu_info = cpu_info.get_cpu_info()

sf = open('sysinfo.txt', 'w+')
sf.write('Version: ' + platform.python_version() + "\n")
sf.write('Compiler: ' + platform.python_compiler() + "\n")
sf.write('Build: ' + " ".join(platform.python_build()) + "\n")
sf.write('Normal: ' + platform.platform() + "\n")
sf.write('Aliased: ' + platform.platform(aliased=True) + "\n")
sf.write('Terse: ' + platform.platform(terse=True) + "\n")
sf.write('uname: ' + " ".join(platform.uname()) + "\n")
sf.write('system: ' + platform.system() + "\n")
sf.write('node: ' + platform.node() + "\n")
sf.write('release: ' + platform.release() + "\n")
sf.write('version: ' + platform.version() + "\n")
sf.write('machine: ' + platform.machine() + "\n")
sf.write('processor: ' + platform.processor() + "\n")
sf.write('CPU: %s \n' % cpu_info['brand'])
sf.close()
コード例 #25
0
ファイル: bits.py プロジェクト: sci-tab/psychopy
 def _getGfxCardString(self):
     from pyglet.gl import gl_info
     return "%s: %s" % (gl_info.get_renderer(), gl_info.get_version())
コード例 #26
0
def getSysInfo(win):
    try:
        from collections import OrderedDict
    except:
        from psychopy.iohub import OrderedDict
    # based on sysInfo.py
    from pyglet.gl import gl_info, GLint, glGetIntegerv, GL_MAX_ELEMENTS_VERTICES
    import sys, platform

    sys_info = OrderedDict()
    sys_info["OS"] = OrderedDict()
    sys_info["OS"]["Name"] = platform.platform()
    if sys.platform == "darwin":
        OSXver, _, architecture = platform.mac_ver()
        sys_info["OS"]["OSX Version"] = OSXver
        sys_info["OS"]["OSX Architecture"] = architecture

    sys_info["Computer Hardware"] = OrderedDict()
    try:
        import psutil

        def getMemoryInfo():
            rdict = dict()
            nt = psutil.virtual_memory()
            for name in nt._fields:
                value = getattr(nt, name)
                if name != "percent":
                    value = bytes2human(value)
                rdict[name.capitalize()] = value  #'%s%s%-10s : %7s\n'%(rstr,'\t'*indent,name.capitalize(), value)
            return rdict

        core_count = psutil.cpu_count(logical=False)
        logical_psu_count = psutil.cpu_count()
        memory_info = getMemoryInfo()
        sys_info["Computer Hardware"]["CPUs (cores / logical)"] = (core_count, logical_psu_count)
        sys_info["Computer Hardware"]["System Memory"] = memory_info

    except:
        sys_info["Computer Hardware"]["Failed"] = "psutil 2.x + is required."

    sys_info["Python"] = OrderedDict()
    sys_info["Python"]["exe"] = sys.executable
    sys_info["Python"]["version"] = sys.version

    sys_info["Packages"] = OrderedDict()
    try:
        import numpy

        sys_info["Packages"]["numpy"] = numpy.__version__
    except:
        sys_info["Packages"]["numpy"] = "Not Installed"
    try:
        import pyglet

        sys_info["Packages"]["pyglet"] = pyglet.version
    except:
        sys_info["Packages"]["pyglet"] = "Not Installed"
    try:
        import cv2

        sys_info["Packages"]["cv2"] = cv2.__version__
    except:
        sys_info["Packages"]["cv2"] = "Not Installed"
    try:
        import psychopy

        sys_info["Packages"]["PsychoPy"] = psychopy.__version__
    except:
        sys_info["Packages"]["PsychoPy"] = "Not Installed"

    sys_info["Graphics"] = OrderedDict()
    sys_info["Graphics"]["shaders"] = win._haveShaders
    sys_info["Graphics"]["opengl"] = OrderedDict()
    sys_info["Graphics"]["opengl"]["version"] = gl_info.get_version()
    sys_info["Graphics"]["opengl"]["vendor"] = gl_info.get_vendor()
    sys_info["Graphics"]["opengl"]["engine"] = gl_info.get_renderer()
    maxVerts = GLint()
    glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, maxVerts)
    sys_info["Graphics"]["opengl"]["Max vert in VA"] = maxVerts.value
    sys_info["Graphics"]["opengl"]["extensions"] = OrderedDict()
    extensionsOfInterest = [
        "GL_ARB_multitexture",
        "GL_EXT_framebuffer_object",
        "GL_ARB_fragment_program",
        "GL_ARB_shader_objects",
        "GL_ARB_vertex_shader",
        "GL_ARB_texture_non_power_of_two",
        "GL_ARB_texture_float",
        "GL_STEREO",
    ]
    for ext in extensionsOfInterest:
        sys_info["Graphics"]["opengl"]["extensions"][ext] = bool(gl_info.have_extension(ext))

    sys_info["Processes"] = OrderedDict()
    if sys.platform == "darwin":
        sys_info["Processes"]["Failed"] = "Not Supported on OSX."
    elif SAVE_PER_PROCESS_DATA:
        try:
            import psutil

            for proc in psutil.process_iter():
                pkey = proc.pid
                vattrs = [
                    "name",
                    "exe",
                    "ppid",
                    "num_threads",
                    "memory_percent",
                    "cpu_percent",
                    "cpu_affinity",
                    "nice",
                    "num_ctx_switches",
                ]
                procinfo = proc.as_dict(attrs=vattrs, ad_value=u"Access Denied")
                if procinfo["exe"] is not u"Access Denied" and (
                    SAVE_PER_PROCESS_DATA is True or SAVE_PER_PROCESS_DATA == procinfo["name"]
                ):
                    sys_info["Processes"][pkey] = procinfo
        except:
            sys_info["Processes"]["Failed"] = "psutil 2.x + is required."
    else:
        sys_info["Processes"]["Disabled"] = "Per Process details disabled by user."

    return sys_info
コード例 #27
0
ファイル: start_client.py プロジェクト: 17night/thbattle
def start_client():
    import ctypes

    try:
        ctypes.cdll.avbin  # force avbin load
    except:
        pass

    import logging
    import os
    import argparse
    import crashreport

    parser = argparse.ArgumentParser(prog=sys.argv[0])
    parser.add_argument("--no-update", action="store_true")
    parser.add_argument("--with-gl-errcheck", action="store_true")
    parser.add_argument("--freeplay", action="store_true")
    parser.add_argument("--fastjoin", action="store_true")
    parser.add_argument("--dump-gameobj", action="store_true")
    parser.add_argument("--log", default="INFO")
    parser.add_argument("--color-log", action="store_true")
    parser.add_argument("--no-crashreport", action="store_true")
    parser.add_argument("--show-hidden-modes", action="store_true")

    options = parser.parse_args()

    import options as opmodule

    opmodule.options = options

    IS_PROTON = hasattr(os, "uname") and os.uname()[:2] == ("Linux", "Proton")

    crashreport.install_tee(options.log.upper())

    if options.no_update:
        import autoupdate

        autoupdate.Autoupdate = autoupdate.DummyAutoupdate

    if IS_PROTON or options.color_log:
        from colorlog import ColoredFormatter

        formatter = ColoredFormatter(
            "%(log_color)s%(message)s%(reset)s",
            log_colors={"CRITICAL": "bold_red", "ERROR": "red", "WARNING": "yellow", "INFO": "green", "DEBUG": "blue"},
        )

        logging.getLogger().handlers[0].setFormatter(formatter)

    log = logging.getLogger("start_client")

    from gevent import monkey

    monkey.patch_socket()
    monkey.patch_os()
    monkey.patch_select()
    monkey.patch_ssl()

    from game import autoenv

    autoenv.init("Client")

    import pyglet

    pyglet.options["shadow_window"] = False

    if not options.with_gl_errcheck:
        pyglet.options["debug_gl"] = False

    from pyglet.gl import gl_info

    if gl_info.get_renderer() == "GDI Generic":
        ctypes.windll.user32.MessageBoxW(0, u"你好像没有安装显卡驱动……?这样游戏是跑不起来的。快去安装!", u"需要显卡驱动", 16)
        sys.exit(0)

    if sys.platform.startswith("linux") and options.dump_gameobj:
        import atexit
        import game

        atexit.register(game.GameObjectMeta._dump_gameobject_hierarchy)
        atexit.register(game.EventHandler._dump_eh_dependency_graph)

    from client.ui.entry import start_ui

    try:
        start_ui()
    except KeyboardInterrupt:
        import pyglet

        pyglet.app.exit()
        raise
    except:
        import pyglet

        pyglet.app.exit()

        if options.fastjoin:
            import pdb

            pdb.post_mortem()

        if not options.no_crashreport:
            log.error(u"游戏崩溃,正在报告bug,请稍等下……")
            from utils.stats import stats

            stats({"event": "crash"})
            from crashreport import do_crashreport

            do_crashreport()

        raise
コード例 #28
0
ファイル: start_client.py プロジェクト: zzkklep/thbattle
def start_client():
    import ctypes
    try:
        ctypes.cdll.avbin  # force avbin load
    except:
        pass

    import logging
    import os
    import argparse
    import utils.logging

    parser = argparse.ArgumentParser(prog=sys.argv[0])
    parser.add_argument('--no-update', action='store_true')
    parser.add_argument('--with-gl-errcheck', action='store_true')
    parser.add_argument('--freeplay', action='store_true')
    parser.add_argument('--fastjoin', type=int, default=None)
    parser.add_argument('--dump-gameobj', action='store_true')
    parser.add_argument('--log', default='INFO')
    parser.add_argument('--color-log', action='store_true')
    parser.add_argument('--zoom', type=float, default=1.0)
    parser.add_argument('--show-hidden-modes', action='store_true')
    parser.add_argument('--multiple-instances', action='store_true')

    options = parser.parse_args()

    import options as opmodule
    opmodule.options = options

    IS_PROTON = hasattr(os, 'uname') and os.uname()[:2] == ('Linux', 'Proton')

    import settings
    utils.logging.init(options.log.upper(), settings.SENTRY_DSN, settings.VERSION, IS_PROTON or options.color_log)

    if options.no_update:
        import autoupdate
        autoupdate.Autoupdate = autoupdate.DummyAutoupdate

    log = logging.getLogger('start_client')

    if sys.platform.startswith('win32') and not options.multiple_instances:
        from utils.mutex import NamedMutex
        thb_mutex = NamedMutex('thbattle-mutex')
        if not thb_mutex.acquire(0):
            log.error('Multiple instances detected, exiting')
            ctypes.windll.user32.MessageBoxW(
                0,
                u'请遵守社区规范,素质游戏,不要开启多个游戏实例!',
                u'东方符斗祭',
                16,
            )
            sys.exit(0)

        opmodule.mutex = thb_mutex
    else:
        opmodule.mutex = None


    from gevent import monkey
    monkey.patch_socket()
    monkey.patch_os()
    monkey.patch_select()
    monkey.patch_ssl()

    from game import autoenv
    autoenv.init('Client')

    import pyglet

    pyglet.options['shadow_window'] = False

    if not options.with_gl_errcheck:
        pyglet.options['debug_gl'] = False

    from pyglet.gl import gl_info
    if gl_info.get_renderer() == 'GDI Generic':
        ctypes.windll.user32.MessageBoxW(
            0,
            u'你好像没有安装显卡驱动……?这样游戏是跑不起来的。快去安装!',
            u'需要显卡驱动',
            16,
        )
        sys.exit(0)

    if sys.platform.startswith('linux') and options.dump_gameobj:
        import atexit
        import game.base
        atexit.register(game.base.GameObjectMeta._dump_gameobject_hierarchy)
        atexit.register(game.base.EventHandler._dump_eh_dependency_graph)

    from client.ui.entry import start_ui

    # PIL compat
    from PIL import Image
    try:
        Image.frombytes
        Image.Image.tobytes
    except AttributeError:
        log.info('Patching PIL {from,to}bytes')
        Image.frombytes = Image.fromstring
        Image.Image.tobytes = Image.Image.tostring

    # ----------

    try:
        start_ui()
    except KeyboardInterrupt:
        import pyglet
        pyglet.app.exit()
        raise
    except:
        import pyglet
        pyglet.app.exit()

        if options.fastjoin:
            import pdb
            pdb.post_mortem()

        log.exception(u'UI线程崩溃,正在报告bug,请稍等下……')
        from utils.stats import stats
        stats({'event': 'crash'})

        raise
コード例 #29
0
ファイル: wizard.py プロジェクト: 9173860/psychopy
    def __init__(self, firstrun=False):
        """Check drivers, show GUIs, run diagnostics, show report."""
        self.firstrun = firstrun
        self.prefs = prefs
        self.appName = 'PsychoPy2'
        self.name = self.appName + ' Configuration Wizard'
        self.reportPath = os.path.join(self.prefs.paths['userPrefsDir'], 'firstrunReport.html')
        #self.iconfile = os.path.join(self.prefs.paths['resources'], 'psychopy.png')
        #dlg.SetIcon(wx.Icon(self.iconfile, wx.BITMAP_TYPE_PNG)) # no error but no effect

        dlg = gui.Dlg(title=self.name)
        dlg.addText('')
        if firstrun:
            dlg.addText("Welcome! It looks like you are running PsychoPy for the first time.")
            dlg.addText("This wizard will help you get started quickly and smoothly.")
        else:
            dlg.addText("Welcome to the configuration wizard.")

        # test for fatal configuration errors:
        fatalItemsList = []
        if not driversOkay():
            cardInfo = gl_info.get_renderer().replace('OpenGL Engine', '').strip()
            dlg.addText('')
            dlg.addText("The first configuration check is your video card's drivers. The current", color='red')
            dlg.addText("drivers cannot support PsychoPy, so you'll need to update the drivers.", color='red')
            msg = """<p>Critical issue:\n</p><p>Your video card (%s) has drivers
                that cannot support the high-performance features that PsychoPy depends on.
                Fortunately, its typically free and straightforward to get new drivers
                directly from the manufacturer.</p>
                <p><strong>To update the drivers:</strong>
                <li> You'll need administrator privileges.
                <li> On Windows, don't use the windows option to check for updates
                  - it can report that there are no updates available.
                <li> If your card is made by NVIDIA, go to
                  <a href="http://www.nvidia.com/Drivers">the NVIDIA website</a>
                  and use the 'auto detect' option. Try here for
                  <a href="http://support.amd.com/">ATI / Radeon drivers</a>. Or try
                  <a href="http://www.google.com/search?q=download+drivers+%s">
                  this google search</a> [google.com].
                <li> Download and install the driver.
                <li> Reboot the computer.
                <li> Restart PsychoPy.</p>
                <p>If you updated the drivers and still get this message, you'll
                  need a different video card to use PsychoPy. Click
                <a href="http://www.psychopy.org/installation.html#recommended-hardware">here
                for more information</a> [psychopy.org].</p>
            """ % (cardInfo, cardInfo.replace(' ', '+'))
            fatalItemsList.append(msg)
        if not cardOkay():
            cardInfo = gl_info.get_renderer().replace('OpenGL Engine', '').strip()
            msg = """<p>Critical issue:\n</p>"""
            msg += cardInfo
            fatalItemsList.append(msg)
            pass
        # other fatal conditions? append a 'Critical issue' msg to itemsList
        if not fatalItemsList:
            dlg.addText("We'll go through a series of configuration checks in about 10 seconds. ")
            dlg.addText('')
            if firstrun:  # explain things more
                dlg.addText('Note: The display will switch to full-screen mode and will ')
                dlg.addText("then switch back. You don't need to do anything.")
            dlg.addText('Optional: For best results, please quit all email programs, web-browsers, ')
            dlg.addText('Dropbox, backup or sync services, and the like.')
            dlg.addText('')
            dlg.addText('Click OK to start, or Cancel to skip.')
            if not self.firstrun:
                dlg.addField(label='Full details', initial=self.prefs.app['debugMode'])
        else:
            dlg.addText('')
            dlg.addText('Click OK for more information, or Cancel to skip.')

        # show the first dialog:
        dlg.addText('')
        dlg.show()
        if fatalItemsList:
            self.htmlReport(fatal=fatalItemsList)
            self.save()
            # user ends up in browser:
            url='file://' + self.reportPath
            wx.LaunchDefaultBrowser(url)
            return
        if not dlg.OK:
            return  # no configuration tests run

        # run the diagnostics:
        verbose = not self.firstrun and dlg.data[0]
        win = visual.Window(fullscr=True, allowGUI=False, monitor='testMonitor')
        itemsList = self.runDiagnostics(win, verbose)  # sets self.warnings
        win.close()
        self.htmlReport(itemsList)
        self.save()

        # display summary & options:
        dlg = gui.Dlg(title=self.name)
        dlg.addText('')
        dlg.addText('Configuration testing complete!')
        summary = self.summary(items=itemsList)
        numWarn = len(self.warnings)
        if numWarn == 0:
            msg = 'All values seem reasonable (no warnings).'
        elif numWarn == 1:
            msg = '1 suboptimal value was detected (%s)' % self.warnings[0]
        else:
            msg = '%i suboptimal values were detected (%s, ...)' % (len(self.warnings), self.warnings[0])
        dlg.addText(msg)
        for item in summary:
            dlg.addText(item[0], item[1])  # (key, color)
        dlg.addText('')
        dlg.addText('Click OK for full details (will open in a web-browser),')
        dlg.addText('or Cancel to stay in PsychoPy.')
        dlg.addText('')
        dlg.show()
        if dlg.OK:
            url = 'file://' + self.reportPath
            wx.LaunchDefaultBrowser(url)
コード例 #30
0
ファイル: sysInfoDlg.py プロジェクト: yeganesereshgi/psychopy
    def getInfoText(self):
        """Get system information text."""
        outputText = ""  # text to return

        # show the PsychoPy version
        from psychopy import __version__
        outputText += self.getLine("PsychoPy", __version__)

        # get system paths
        outputText += self.getLine("\nPaths to files on the system:")
        for key in ['userPrefsFile', 'appDataFile', 'demos', 'appFile']:
            outputText += self.getLine(
                "    %s: %s" % (key, preferences.prefs.paths[key]))

        # system information such as OS, CPU and memory
        outputText += self.getLine("\nSystem Info:")
        outputText += self.getLine(
            ' '*4, 'Operating System: {}'.format(platform.platform()))
        outputText += self.getLine(
            ' ' * 4, 'Processor: {}'.format(platform.processor()))

        # requires psutil
        try:
            import psutil
            outputText += self.getLine(
                ' ' * 4, 'CPU freq (MHz): {}'.format(psutil.cpu_freq().max))
            outputText += self.getLine(
                ' ' * 4, 'CPU cores: {} (physical), {} (logical)'.format(
                    psutil.cpu_count(False), psutil.cpu_count()))
            outputText += self.getLine(
                ' ' * 4, 'Installed memory: {} (Total), {} (Available)'.format(
                    *psutil.virtual_memory()))
        except ImportError:
            outputText += self.getLine(' ' * 4, 'CPU freq (MHz): N/A')
            outputText += self.getLine(
                ' ' * 4, 'CPU cores: {} (logical)'.format(os.cpu_count()))
            outputText += self.getLine(' ' * 4, 'Installed memory: N/A')

        # if on MacOS
        if sys.platform == 'darwin':
            OSXver, junk, architecture = platform.mac_ver()
            outputText += self.getLine(
                ' ' * 4, "macOS %s running on %s" % (OSXver, architecture))

        # Python information
        outputText += self.getLine("\nPython info:")
        outputText += self.getLine(' '*4, 'Executable path:', sys.executable)
        outputText += self.getLine(' '*4, 'Version:', sys.version)
        outputText += self.getLine(' ' * 4, '(Selected) Installed Packages:')
        import numpy
        outputText += self.getLine(' '*8, "numpy ({})".format(
            numpy.__version__))
        import scipy
        outputText += self.getLine(' '*8, "scipy ({})".format(
            scipy.__version__))
        import matplotlib
        outputText += self.getLine(' '*8, "matplotlib ({})".format(
            matplotlib.__version__))
        import pyglet
        outputText += self.getLine(' '*8, "pyglet ({})".format(pyglet.version))
        try:
            import glfw
            outputText += self.getLine(' '*8, "PyGLFW ({})".format(
                glfw.__version__))
        except Exception:
            outputText += self.getLine(' '*8, 'PyGLFW [not installed]')

        # sound related
        try:
            import pyo
            outputText += self.getLine(
                ' '*8, "pyo", ('%i.%i.%i' % pyo.getVersion()))
        except Exception:
            outputText += self.getLine(' '*8, 'pyo [not installed]')
        try:
            import psychtoolbox
            outputText += self.getLine(' '*8, "psychtoolbox ({})".format(
                psychtoolbox._version.__version__))
        except Exception:
            outputText += self.getLine(' '*8, 'psychtoolbox [not installed]')

        # wxpython version
        try:
            import wx
            outputText += self.getLine(' '*8, "wxPython ({})".format(
                wx.__version__))
        except Exception:
            outputText += self.getLine(' '*8, 'wxPython [not installed]')

        # get OpenGL details
        win = visual.Window([100, 100])  # some drivers want a window open first

        outputText += self.getLine("\nOpenGL Info:")
        # # get info about the graphics card and drivers
        outputText += self.getLine(
            ' '*4, "Vendor:", gl_info.get_vendor())
        outputText += self.getLine(
            ' '*4, "Rendering engine:", gl_info.get_renderer())
        outputText += self.getLine(
            ' '*4, "OpenGL version:", gl_info.get_version())
        outputText += self.getLine(
            ' '*4, "Shaders supported: ", win._haveShaders)

        # get opengl extensions
        outputText += self.getLine(' '*4, "(Selected) Extensions:")
        extensionsOfInterest = [
            'GL_ARB_multitexture',
            'GL_EXT_framebuffer_object',
            'GL_ARB_fragment_program',
            'GL_ARB_shader_objects',
            'GL_ARB_vertex_shader',
            'GL_ARB_texture_non_power_of_two',
            'GL_ARB_texture_float',
            'GL_STEREO']

        for ext in extensionsOfInterest:
            outputText += self.getLine(
                ' '*8, ext + ':', bool(gl_info.have_extension(ext)))

        # also determine nVertices that can be used in vertex arrays
        maxVerts = GLint()
        glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, maxVerts)
        outputText += self.getLine(
            ' '*4, 'max vertices in vertex array:', maxVerts.value)

        win.close()

        return outputText
コード例 #31
0
def getSysInfo(win):
    try:
        from collections import OrderedDict
    except Exception:
        from psychopy.iohub import OrderedDict
    # based on sysInfo.py
    from pyglet.gl import gl_info, GLint, glGetIntegerv, GL_MAX_ELEMENTS_VERTICES
    import sys, platform

    sys_info = OrderedDict()
    sys_info['OS'] = OrderedDict()
    sys_info['OS']['Name'] = platform.platform()
    if sys.platform == 'darwin':
        OSXver, _, architecture = platform.mac_ver()
        sys_info['OS']['OSX Version'] = OSXver
        sys_info['OS']['OSX Architecture'] = architecture

    sys_info['Computer Hardware'] = OrderedDict()
    try:
        import psutil

        def getMemoryInfo():
            rdict = dict()
            nt = psutil.virtual_memory()
            for name in nt._fields:
                value = getattr(nt, name)
                if name != 'percent':
                    value = bytes2human(value)
                rdict[name.capitalize(
                )] = value  # '%s%s%-10s : %7s\n'%(rstr, '\t' * indent, name.capitalize(), value)
            return rdict

        core_count = psutil.cpu_count(logical=False)
        logical_psu_count = psutil.cpu_count()
        memory_info = getMemoryInfo()
        sys_info['Computer Hardware']['CPUs (cores / logical)'] = (
            core_count, logical_psu_count)
        sys_info['Computer Hardware']['System Memory'] = memory_info

    except Exception:
        sys_info['Computer Hardware']['Failed'] = 'psutil 2.x + is required.'

    sys_info['Python'] = OrderedDict()
    sys_info['Python']['exe'] = sys.executable
    sys_info['Python']['version'] = sys.version

    sys_info['Packages'] = OrderedDict()
    try:
        import numpy
        sys_info['Packages']['numpy'] = numpy.__version__
    except ImportError:
        sys_info['Packages']['numpy'] = "Not Installed"
    try:
        import pyglet
        sys_info['Packages']['pyglet'] = pyglet.version
    except ImportError:
        sys_info['Packages']['pyglet'] = "Not Installed"
    try:
        import cv2
        sys_info['Packages']['cv2'] = cv2.__version__
    except ImportError:
        sys_info['Packages']['cv2'] = "Not Installed"
    try:
        import psychopy
        sys_info['Packages']['PsychoPy'] = psychopy.__version__
    except ImportError:
        sys_info['Packages']['PsychoPy'] = "Not Installed"

    sys_info['Graphics'] = OrderedDict()
    sys_info['Graphics']['shaders'] = win._haveShaders
    sys_info['Graphics']['opengl'] = OrderedDict()
    sys_info['Graphics']['opengl']['version'] = gl_info.get_version()
    sys_info['Graphics']['opengl']['vendor'] = gl_info.get_vendor()
    sys_info['Graphics']['opengl']['engine'] = gl_info.get_renderer()
    maxVerts = GLint()
    glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, maxVerts)
    sys_info['Graphics']['opengl']['Max vert in VA'] = maxVerts.value
    sys_info['Graphics']['opengl']['extensions'] = OrderedDict()
    extensionsOfInterest = [
        'GL_ARB_multitexture', 'GL_EXT_framebuffer_object',
        'GL_ARB_fragment_program', 'GL_ARB_shader_objects',
        'GL_ARB_vertex_shader', 'GL_ARB_texture_non_power_of_two',
        'GL_ARB_texture_float', 'GL_STEREO'
    ]
    for ext in extensionsOfInterest:
        sys_info['Graphics']['opengl']['extensions'][ext] = bool(
            gl_info.have_extension(ext))

    sys_info['Processes'] = OrderedDict()
    if sys.platform == 'darwin':
        sys_info['Processes']['Failed'] = 'Not Supported on OSX.'
    elif SAVE_PER_PROCESS_DATA:
        try:
            import psutil

            for proc in psutil.process_iter():
                pkey = proc.pid
                vattrs = [
                    'name', 'exe', 'ppid', 'num_threads', 'memory_percent',
                    'cpu_percent', 'cpu_affinity', 'nice', 'num_ctx_switches'
                ]
                procinfo = proc.as_dict(attrs=vattrs,
                                        ad_value=u"Access Denied")
                if procinfo['exe'] is not u"Access Denied" and (
                        SAVE_PER_PROCESS_DATA is True
                        or SAVE_PER_PROCESS_DATA == procinfo['name']):
                    sys_info['Processes'][pkey] = procinfo
        except ImportError:
            sys_info['Processes']['Failed'] = 'psutil 2.x + is required.'
    else:
        sys_info['Processes'][
            'Disabled'] = 'Per Process details disabled by user.'

    return sys_info
コード例 #32
0
ファイル: gl_info.py プロジェクト: JetDoughnut/yeet
    print('  %r' % screen)

print()
print('Creating default context...')
w = pyglet.window.Window(1, 1, visible=True)
print('Window:')
print('  %s' % w)

print('GL attributes:')
attrs = w.config.get_gl_attributes()
attrs = ' '.join(['%s=%s' % (name, value) for name, value in attrs])
print(' ', '\n  '.join(textwrap.wrap(attrs)))

print('GL version:', gl_info.get_version())
print('GL vendor:', gl_info.get_vendor())
print('GL renderer:', gl_info.get_renderer())
print('GL extensions:')
exts = ' '.join(gl_info.get_extensions())
print(' ', '\n  '.join(textwrap.wrap(exts)))

print()

context = w.context
print('Context is', context)

if "xlib" in globals() and isinstance(context, xlib.BaseXlibContext):
    from pyglet.gl import glx_info
    print('GLX %s direct' % (context.is_direct() and 'is' or 'is not'))
    if not glx_info.have_version(1, 1):
        print("GLX server version: 1.0")
    else:
コード例 #33
0
def start_client():
    import ctypes
    try:
        ctypes.cdll.avbin  # force avbin load
    except:
        pass

    import logging
    import os
    import argparse
    import utils.logging

    parser = argparse.ArgumentParser(prog=sys.argv[0])
    parser.add_argument('--no-update', action='store_true')
    parser.add_argument('--with-gl-errcheck', action='store_true')
    parser.add_argument('--freeplay', action='store_true')
    parser.add_argument('--fastjoin', type=int, default=None)
    parser.add_argument('--dump-gameobj', action='store_true')
    parser.add_argument('--log', default='INFO')
    parser.add_argument('--color-log', action='store_true')
    parser.add_argument('--zoom', type=float, default=1.0)
    parser.add_argument('--show-hidden-modes', action='store_true')

    options = parser.parse_args()

    import options as opmodule
    opmodule.options = options

    IS_PROTON = hasattr(os, 'uname') and os.uname()[:2] == ('Linux', 'Proton')

    import settings
    utils.logging.init(options.log.upper(), settings.SENTRY_DSN, settings.VERSION, IS_PROTON or options.color_log)

    if options.no_update:
        import autoupdate
        autoupdate.Autoupdate = autoupdate.DummyAutoupdate

    log = logging.getLogger('start_client')

    from gevent import monkey
    monkey.patch_socket()
    monkey.patch_os()
    monkey.patch_select()
    monkey.patch_ssl()

    from game import autoenv
    autoenv.init('Client')

    import pyglet

    pyglet.options['shadow_window'] = False

    if not options.with_gl_errcheck:
        pyglet.options['debug_gl'] = False

    from pyglet.gl import gl_info
    if gl_info.get_renderer() == 'GDI Generic':
        ctypes.windll.user32.MessageBoxW(
            0,
            u'你好像没有安装显卡驱动……?这样游戏是跑不起来的。快去安装!',
            u'需要显卡驱动',
            16,
        )
        sys.exit(0)

    if sys.platform.startswith('linux') and options.dump_gameobj:
        import atexit
        import game.base
        atexit.register(game.base.GameObjectMeta._dump_gameobject_hierarchy)
        atexit.register(game.base.EventHandler._dump_eh_dependency_graph)

    from client.ui.entry import start_ui

    # PIL compat
    from PIL import Image
    try:
        Image.frombytes
        Image.Image.tobytes
    except AttributeError:
        log.info('Patching PIL {from,to}bytes')
        Image.frombytes = Image.fromstring
        Image.Image.tobytes = Image.Image.tostring

    # ----------

    try:
        start_ui()
    except KeyboardInterrupt:
        import pyglet
        pyglet.app.exit()
        raise
    except:
        import pyglet
        pyglet.app.exit()

        if options.fastjoin:
            import pdb
            pdb.post_mortem()

        log.exception(u'UI线程崩溃,正在报告bug,请稍等下……')
        from utils.stats import stats
        stats({'event': 'crash'})

        raise
コード例 #34
0
ファイル: ToolServer.py プロジェクト: cmorgan/dypy
    def run(self):
        import pyglet
        pyglet.options['debug_gl'] = False        
        
        from dypy.tools.PortraitTool import PortraitTool
        from dypy.tools.OrbitTool import OrbitTool
        from dypy.tools.CobwebTool import CobwebTool
        # unfortunately, pyglet imports must occur in the same scope as the pyglet window
        from pyglet.gl import glBlendFunc, glEnable, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, \
            GL_BLEND, glClear, GL_COLOR_BUFFER_BIT, glMatrixMode, GL_PROJECTION, GL_MODELVIEW, \
            glLoadIdentity, glTranslatef, glRotatef, gl_info, glViewport, glOrtho, \
            glHint, GL_LINE_SMOOTH, GL_LINE_SMOOTH_HINT, GL_NICEST, glDisable
        import pyglet.clock
        import pyglet.window
        import select
        
        self.window = pyglet.window.Window(width=self.width, height=self.height, visible=False)
        self.window.set_location(450, 0)
        self.window.on_resize = self.on_resize
        self.window.on_close = self.on_close
        self.window.on_key_press = self.on_key_press
        self.window.on_mouse_drag = self.on_mouse_drag
        self.window.on_mouse_scroll = self.on_mouse_scroll
        self.window.on_mouse_press = self.on_mouse_press
        self.window.on_mouse_release = self.on_mouse_release
        
        # create and wait for object server
        self.object_server = PyroServer()
        self.object_server.start()
        self.object_server.waitUntilStarted()
        
        # create p5 vr glove server
        self.glove_server = P5Device(self)
        self.glove_server.start()
        
        # create nintento wiimote server
        self.wiimote_server = WiimoteDevice(self)
        self.wiimote_server.start()
        
        # create 3Dconnexion space navigator server
        self.sn_server = SpaceNavigatorDevice(self)
        self.sn_server.start() 

        # visualization parameters
        self.rotation_velocity = 0.8
        self.iteration = 0
        self.reset_rotation()
        self.set_axes_center()
        self.set_bounds((-1, 1), (-1, 1), (-1, 1), False)
        
        # don't hog more cpu than is useful
        pyglet.clock.set_fps_limit(self.fps)
        
        # create tools and connect them to server
        self.object_server.daemon.connect(self, 'ToolServer')
        
        t = PortraitTool(server=self)
        self.object_server.daemon.connect(t, 'PortraitTool')
        
        t = CobwebTool(server=self)
        self.object_server.daemon.connect(t, 'CobwebTool')
        
        t = OrbitTool(server=self)
        self.object_server.daemon.connect(t, 'OrbitTool')
        
        self.update_tool(t)
        
        # set alpha blending function
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        
        # enable line anti-aliasing
        glEnable(GL_LINE_SMOOTH)
        glHint(GL_LINE_SMOOTH_HINT, GL_NICEST)   
        
        # gl diagnostics
        dypy.debug("ToolServer", "GL version is %s." % gl_info.get_version())
        dypy.debug("ToolServer", "GL renderer is %s." % gl_info.get_renderer())
        dypy.debug("ToolServer", "Pyglet version is %s." % pyglet.version)
        
        # event flags
        self.ready = True
        self.tool_updated = False
        self.window_resized = False
        self.visible = False
        self.visibility_changed = False
        self.show_axes = False

        while not self.window.has_exit:            
            pyglet.clock.tick()          
            gl_lock.acquire()
            
            try:
                self.window.dispatch_events()
                
                if self.visibility_changed:
                    self.visibility_changed = False
                    self.window.set_visible(self.visible)
                
                if self.tool_updated:
                    self.tool_updated = False
                    self.tool.init_points()
                
                if self.window_resized:
                    self.window_resized = False
         
                    if (self.x_min == 0 and self.x_max == 0) or (self.y_min == 0 and self.y_max == 0):
                        continue
                    
                    glViewport(0, 0, self.width, self.height)
            
                    glMatrixMode(GL_PROJECTION)
                    glLoadIdentity()
                    
                    dypy.debug("ToolServer", "Setting projection to %.1f %.1f %.1f %.1f %.1f %.1f" % (self.x_min, self.x_max, self.y_min, self.y_max, -self.dimension_max, self.dimension_max))
                    glOrtho(self.x_min, self.x_max, self.y_min, self.y_max, -self.dimension_max**2, self.dimension_max**2)            
                
                if self.window.visible:
        			# reset model matrix
                    glMatrixMode(GL_MODELVIEW)
                    glLoadIdentity()
        			
                    # translate to center
                    glTranslatef(self.x_center, self.y_center, self.z_center)
        			
                    # rotate around axes
                    glRotatef(self.x_rotate, 1, 0, 0)
                    glRotatef(self.y_rotate, 0, 1, 0)
                    glRotatef(self.z_rotate, 0, 0, 1)
        			
                    # clear iteration 0 as well as iteration 1 to clear axes after rotation
                    if self.iteration <= 1 or self.tool.clear_each_frame:
                        glClear(GL_COLOR_BUFFER_BIT)
                        glEnable(GL_BLEND)
                        
                    # draw reference axes during rotation only
                    if self.show_axes:
                        self.draw_axes()
                        glDisable(GL_BLEND)
                    
                    # translate back to lower left corner
                    glTranslatef(-self.x_center, -self.y_center, -self.z_center)    
        
                    # tell the tool to draw its content
                    self.tool.draw_points()
    
                    # iteration is done, swap display buffers
                    self.iteration += 1
                    self.window.flip()
    
                # process server requests
                socks = self.object_server.daemon.getServerSockets()
                ins, outs, exs = select.select(socks, [], [], 0)
                
                for s in socks:
                    if s in ins:
                        self.object_server.daemon.handleRequests()
                        break
            except Exception, detail:
                print type(detail), detail
            finally: