Browse Source

initial framework

pull/10/head
calexil 4 years ago
parent
commit
c64916bec3
100 changed files with 14396 additions and 0 deletions
  1. 5
    0
      Install
  2. 0
    0
      assets/controller.json
  3. 0
    0
      assets/gamedata.ini
  4. 1
    0
      assets/models/f/chiharu.mdl
  5. 1
    0
      assets/models/f/isabel.mdl
  6. 1
    0
      assets/models/f/lily.mdl
  7. 1
    0
      assets/models/f/sarah.mdl
  8. 1
    0
      assets/models/f/xiaoli.mdl
  9. 1
    0
      assets/models/m/bruno.mdl
  10. 1
    0
      assets/models/m/jd.mdl
  11. 1
    0
      assets/models/m/kohaku.mdl
  12. 2
    0
      assets/models/m/lee.mdl
  13. 1
    0
      assets/models/m/miguel.mdl
  14. 442
    0
      assets/pyglet/__init__.py
  15. BIN
      assets/pyglet/__init__.pyc
  16. 185
    0
      assets/pyglet/app/__init__.py
  17. BIN
      assets/pyglet/app/__init__.pyc
  18. 383
    0
      assets/pyglet/app/base.py
  19. BIN
      assets/pyglet/app/base.pyc
  20. 150
    0
      assets/pyglet/app/carbon.py
  21. 198
    0
      assets/pyglet/app/cocoa.py
  22. 149
    0
      assets/pyglet/app/win32.py
  23. 128
    0
      assets/pyglet/app/xlib.py
  24. BIN
      assets/pyglet/app/xlib.pyc
  25. 105
    0
      assets/pyglet/canvas/__init__.py
  26. BIN
      assets/pyglet/canvas/__init__.pyc
  27. 335
    0
      assets/pyglet/canvas/base.py
  28. BIN
      assets/pyglet/canvas/base.pyc
  29. 254
    0
      assets/pyglet/canvas/carbon.py
  30. 135
    0
      assets/pyglet/canvas/cocoa.py
  31. 102
    0
      assets/pyglet/canvas/win32.py
  32. 263
    0
      assets/pyglet/canvas/xlib.py
  33. BIN
      assets/pyglet/canvas/xlib.pyc
  34. 172
    0
      assets/pyglet/canvas/xlib_vidmoderestore.py
  35. BIN
      assets/pyglet/canvas/xlib_vidmoderestore.pyc
  36. 996
    0
      assets/pyglet/clock.py
  37. BIN
      assets/pyglet/clock.pyc
  38. 171
    0
      assets/pyglet/com.py
  39. 101
    0
      assets/pyglet/compat.py
  40. BIN
      assets/pyglet/compat.pyc
  41. 74
    0
      assets/pyglet/debug.py
  42. 459
    0
      assets/pyglet/event.py
  43. BIN
      assets/pyglet/event.pyc
  44. 39
    0
      assets/pyglet/extlibs/__init__.py
  45. BIN
      assets/pyglet/extlibs/__init__.pyc
  46. 10
    0
      assets/pyglet/extlibs/future/py2/_dummy_thread/__init__.py
  47. 10
    0
      assets/pyglet/extlibs/future/py2/_markupbase/__init__.py
  48. 10
    0
      assets/pyglet/extlibs/future/py2/_thread/__init__.py
  49. 12
    0
      assets/pyglet/extlibs/future/py2/builtins/__init__.py
  50. BIN
      assets/pyglet/extlibs/future/py2/builtins/__init__.pyc
  51. 13
    0
      assets/pyglet/extlibs/future/py2/configparser/__init__.py
  52. BIN
      assets/pyglet/extlibs/future/py2/configparser/__init__.pyc
  53. 9
    0
      assets/pyglet/extlibs/future/py2/copyreg/__init__.py
  54. 9
    0
      assets/pyglet/extlibs/future/py2/html/__init__.py
  55. 7
    0
      assets/pyglet/extlibs/future/py2/html/entities.py
  56. 8
    0
      assets/pyglet/extlibs/future/py2/html/parser.py
  57. 9
    0
      assets/pyglet/extlibs/future/py2/http/__init__.py
  58. 6
    0
      assets/pyglet/extlibs/future/py2/http/client.py
  59. 6
    0
      assets/pyglet/extlibs/future/py2/http/cookiejar.py
  60. 7
    0
      assets/pyglet/extlibs/future/py2/http/cookies.py
  61. 18
    0
      assets/pyglet/extlibs/future/py2/http/server.py
  62. 10
    0
      assets/pyglet/extlibs/future/py2/queue/__init__.py
  63. BIN
      assets/pyglet/extlibs/future/py2/queue/__init__.pyc
  64. 9
    0
      assets/pyglet/extlibs/future/py2/reprlib/__init__.py
  65. 9
    0
      assets/pyglet/extlibs/future/py2/socketserver/__init__.py
  66. 9
    0
      assets/pyglet/extlibs/future/py2/tkinter/__init__.py
  67. 13
    0
      assets/pyglet/extlibs/future/py2/tkinter/colorchooser.py
  68. 13
    0
      assets/pyglet/extlibs/future/py2/tkinter/commondialog.py
  69. 13
    0
      assets/pyglet/extlibs/future/py2/tkinter/constants.py
  70. 13
    0
      assets/pyglet/extlibs/future/py2/tkinter/dialog.py
  71. 13
    0
      assets/pyglet/extlibs/future/py2/tkinter/dnd.py
  72. 13
    0
      assets/pyglet/extlibs/future/py2/tkinter/filedialog.py
  73. 13
    0
      assets/pyglet/extlibs/future/py2/tkinter/font.py
  74. 13
    0
      assets/pyglet/extlibs/future/py2/tkinter/messagebox.py
  75. 13
    0
      assets/pyglet/extlibs/future/py2/tkinter/scrolledtext.py
  76. 13
    0
      assets/pyglet/extlibs/future/py2/tkinter/simpledialog.py
  77. 13
    0
      assets/pyglet/extlibs/future/py2/tkinter/tix.py
  78. 10
    0
      assets/pyglet/extlibs/future/py2/winreg/__init__.py
  79. 9
    0
      assets/pyglet/extlibs/future/py2/xmlrpc/__init__.py
  80. 5
    0
      assets/pyglet/extlibs/future/py2/xmlrpc/client.py
  81. 5
    0
      assets/pyglet/extlibs/future/py2/xmlrpc/server.py
  82. 94
    0
      assets/pyglet/extlibs/future/py2_3/future/__init__.py
  83. BIN
      assets/pyglet/extlibs/future/py2_3/future/__init__.pyc
  84. 8
    0
      assets/pyglet/extlibs/future/py2_3/future/backports/__init__.py
  85. BIN
      assets/pyglet/extlibs/future/py2_3/future/backports/__init__.pyc
  86. 422
    0
      assets/pyglet/extlibs/future/py2_3/future/backports/_markupbase.py
  87. 2152
    0
      assets/pyglet/extlibs/future/py2_3/future/backports/datetime.py
  88. 78
    0
      assets/pyglet/extlibs/future/py2_3/future/backports/email/__init__.py
  89. 232
    0
      assets/pyglet/extlibs/future/py2_3/future/backports/email/_encoded_words.py
  90. 2965
    0
      assets/pyglet/extlibs/future/py2_3/future/backports/email/_header_value_parser.py
  91. 546
    0
      assets/pyglet/extlibs/future/py2_3/future/backports/email/_parseaddr.py
  92. 365
    0
      assets/pyglet/extlibs/future/py2_3/future/backports/email/_policybase.py
  93. 120
    0
      assets/pyglet/extlibs/future/py2_3/future/backports/email/base64mime.py
  94. 409
    0
      assets/pyglet/extlibs/future/py2_3/future/backports/email/charset.py
  95. 90
    0
      assets/pyglet/extlibs/future/py2_3/future/backports/email/encoders.py
  96. 111
    0
      assets/pyglet/extlibs/future/py2_3/future/backports/email/errors.py
  97. 525
    0
      assets/pyglet/extlibs/future/py2_3/future/backports/email/feedparser.py
  98. 498
    0
      assets/pyglet/extlibs/future/py2_3/future/backports/email/generator.py
  99. 581
    0
      assets/pyglet/extlibs/future/py2_3/future/backports/email/header.py
  100. 0
    0
      assets/pyglet/extlibs/future/py2_3/future/backports/email/headerregistry.py

+ 5
- 0
Install View File

@@ -0,0 +1,5 @@
clone the git

make the script executable

run it

+ 0
- 0
assets/controller.json View File


+ 0
- 0
assets/gamedata.ini View File


+ 1
- 0
assets/models/f/chiharu.mdl View File

@@ -0,0 +1 @@
jpn

+ 1
- 0
assets/models/f/isabel.mdl View File

@@ -0,0 +1 @@
bzl

+ 1
- 0
assets/models/f/lily.mdl View File

@@ -0,0 +1 @@
uk/gb

+ 1
- 0
assets/models/f/sarah.mdl View File

@@ -0,0 +1 @@
usa

+ 1
- 0
assets/models/f/xiaoli.mdl View File

@@ -0,0 +1 @@
chn

+ 1
- 0
assets/models/m/bruno.mdl View File

@@ -0,0 +1 @@
bzl

+ 1
- 0
assets/models/m/jd.mdl View File

@@ -0,0 +1 @@
usa

+ 1
- 0
assets/models/m/kohaku.mdl View File

@@ -0,0 +1 @@
jpn

+ 2
- 0
assets/models/m/lee.mdl View File

@@ -0,0 +1,2 @@
chn


+ 1
- 0
assets/models/m/miguel.mdl View File

@@ -0,0 +1 @@
esp

+ 442
- 0
assets/pyglet/__init__.py View File

@@ -0,0 +1,442 @@
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------

'''pyglet is a cross-platform games and multimedia package.

Detailed documentation is available at http://www.pyglet.org
'''
from __future__ import print_function
from __future__ import absolute_import

# Check if future is installed, if not use included batteries
try:
import future
except ImportError:
import os.path as op
import sys
future_base = op.abspath(op.join(op.dirname(__file__), 'extlibs', 'future'))
sys.path.insert(0, op.join(future_base, 'py2_3'))
if sys.version_info[:2] < (3, 0):
sys.path.insert(0, op.join(future_base, 'py2'))
del future_base
del sys
del op
try:
import future
except ImportError:
print('Failed to get python-future')
raise

from builtins import range
from builtins import object

import os
import sys
import warnings

_is_epydoc = hasattr(sys, 'is_epydoc') and sys.is_epydoc

#: The release version of this pyglet installation.
#:
#: Valid only if pyglet was installed from a source or binary distribution
#: (i.e. not in a checked-out copy from SVN).
#:
#: Use setuptools if you need to check for a specific release version, e.g.::
#:
#: >>> import pyglet
#: >>> from pkg_resources import parse_version
#: >>> parse_version(pyglet.version) >= parse_version('1.1')
#: True
#:
version = '1.2.2'

# Pyglet platform treats *BSD systems as Linux
compat_platform = sys.platform
if "bsd" in compat_platform:
compat_platform = "linux-compat"

def _require_ctypes_version(version):
# Check ctypes version
import ctypes
req = [int(i) for i in version.split('.')]
have = [int(i) for i in ctypes.__version__.split('.')]
if not tuple(have) >= tuple(req):
raise ImportError('pyglet requires ctypes %s or later.' % version)
_require_ctypes_version('1.0.0')

_enable_optimisations = not __debug__
if getattr(sys, 'frozen', None):
_enable_optimisations = True

#: Global dict of pyglet options. To change an option from its default, you
#: must import ``pyglet`` before any sub-packages. For example::
#:
#: import pyglet
#: pyglet.options['debug_gl'] = False
#:
#: The default options can be overridden from the OS environment. The
#: corresponding environment variable for each option key is prefaced by
#: ``PYGLET_``. For example, in Bash you can set the ``debug_gl`` option with::
#:
#: PYGLET_DEBUG_GL=True; export PYGLET_DEBUG_GL
#:
#: For options requiring a tuple of values, separate each value with a comma.
#:
#: The non-development options are:
#:
#: audio
#: A sequence of the names of audio modules to attempt to load, in
#: order of preference. Valid driver names are:
#:
#: * directsound, the Windows DirectSound audio module (Windows only)
#: * pulse, the PulseAudio module (Linux only)
#: * openal, the OpenAL audio module
#: * silent, no audio
#: debug_lib
#: If True, prints the path of each dynamic library loaded.
#: debug_gl
#: If True, all calls to OpenGL functions are checked afterwards for
#: errors using ``glGetError``. This will severely impact performance,
#: but provides useful exceptions at the point of failure. By default,
#: this option is enabled if ``__debug__`` is (i.e., if Python was not run
#: with the -O option). It is disabled by default when pyglet is "frozen"
#: within a py2exe or py2app library archive.
#: shadow_window
#: By default, pyglet creates a hidden window with a GL context when
#: pyglet.gl is imported. This allows resources to be loaded before
#: the application window is created, and permits GL objects to be
#: shared between windows even after they've been closed. You can
#: disable the creation of the shadow window by setting this option to
#: False.
#:
#: Some OpenGL driver implementations may not support shared OpenGL
#: contexts and may require disabling the shadow window (and all resources
#: must be loaded after the window using them was created). Recommended
#: for advanced developers only.
#:
#: **Since:** pyglet 1.1
#: vsync
#: If set, the `pyglet.window.Window.vsync` property is ignored, and
#: this option overrides it (to either force vsync on or off). If unset,
#: or set to None, the `pyglet.window.Window.vsync` property behaves
#: as documented.
#: xsync
#: If set (the default), pyglet will attempt to synchronise the drawing of
#: double-buffered windows to the border updates of the X11 window
#: manager. This improves the appearance of the window during resize
#: operations. This option only affects double-buffered windows on
#: X11 servers supporting the Xsync extension with a window manager
#: that implements the _NET_WM_SYNC_REQUEST protocol.
#:
#: **Since:** pyglet 1.1
#: darwin_cocoa
#: If True, the Cocoa-based pyglet implementation is used as opposed to
#: the 32-bit Carbon implementation. When python is running in 64-bit mode
#: on Mac OS X 10.6 or later, this option is set to True by default.
#: Otherwise the Carbon implementation is preferred.
#:
#: **Since:** pyglet 1.2
#:
#: search_local_libs
#: If False, pyglet won't try to search for libraries in the script
#: directory and its `lib` subdirectory. This is useful to load a local
#: library instead of the system installed version. This option is set
#: to True by default.
#:
#: **Since:** pyglet 1.2
#:
options = {
'audio': ('directsound', 'pulse', 'openal', 'silent'),
'font': ('gdiplus', 'win32'), # ignored outside win32; win32 is deprecated
'debug_font': False,
'debug_gl': not _enable_optimisations,
'debug_gl_trace': False,
'debug_gl_trace_args': False,
'debug_graphics_batch': False,
'debug_lib': False,
'debug_media': False,
'debug_texture': False,
'debug_trace': False,
'debug_trace_args': False,
'debug_trace_depth': 1,
'debug_trace_flush': True,
'debug_win32': False,
'debug_x11': False,
'graphics_vbo': True,
'shadow_window': True,
'vsync': None,
'xsync': True,
'xlib_fullscreen_override_redirect': False,
'darwin_cocoa': False,
'search_local_libs': True,
}

_option_types = {
'audio': tuple,
'font': tuple,
'debug_font': bool,
'debug_gl': bool,
'debug_gl_trace': bool,
'debug_gl_trace_args': bool,
'debug_graphics_batch': bool,
'debug_lib': bool,
'debug_media': bool,
'debug_texture': bool,
'debug_trace': bool,
'debug_trace_args': bool,
'debug_trace_depth': int,
'debug_trace_flush': bool,
'debug_win32': bool,
'debug_x11': bool,
'graphics_vbo': bool,
'shadow_window': bool,
'vsync': bool,
'xsync': bool,
'xlib_fullscreen_override_redirect': bool,
'darwin_cocoa': bool,
}

def _choose_darwin_platform():
"""Choose between Darwin's Carbon and Cocoa implementations."""
if compat_platform != 'darwin':
return
import struct
numbits = 8*struct.calcsize("P")
if numbits == 64:
import platform
osx_version = platform.mac_ver()[0].split(".")
if int(osx_version[0]) == 10 and int(osx_version[1]) < 6:
raise Exception('pyglet is not compatible with 64-bit Python for versions of Mac OS X prior to 10.6.')
options['darwin_cocoa'] = True
else:
options['darwin_cocoa'] = False
_choose_darwin_platform() # can be overridden by an environment variable below

def _read_environment():
'''Read defaults for options from environment'''
for key in options:
env = 'PYGLET_%s' % key.upper()
try:
value = os.environ[env]
if _option_types[key] is tuple:
options[key] = value.split(',')
elif _option_types[key] is bool:
options[key] = value in ('true', 'TRUE', 'True', '1')
elif _option_types[key] is int:
options[key] = int(value)
except KeyError:
pass
_read_environment()

if compat_platform == 'cygwin':
# This hack pretends that the posix-like ctypes provides windows
# functionality. COM does not work with this hack, so there is no
# DirectSound support.
import ctypes
ctypes.windll = ctypes.cdll
ctypes.oledll = ctypes.cdll
ctypes.WINFUNCTYPE = ctypes.CFUNCTYPE
ctypes.HRESULT = ctypes.c_long

if compat_platform == 'darwin' and not options['darwin_cocoa']:
warnings.warn('Carbon support is to be deprecated in Pyglet 1.4', PendingDeprecationWarning)

# Call tracing
# ------------

_trace_filename_abbreviations = {}

def _trace_repr(value, size=40):
value = repr(value)
if len(value) > size:
value = value[:size//2-2] + '...' + value[-size//2-1:]
return value

def _trace_frame(thread, frame, indent):
from pyglet import lib
if frame.f_code is lib._TraceFunction.__call__.__code__:
is_ctypes = True
func = frame.f_locals['self']._func
name = func.__name__
location = '[ctypes]'
else:
is_ctypes = False
code = frame.f_code
name = code.co_name
path = code.co_filename
line = code.co_firstlineno

try:
filename = _trace_filename_abbreviations[path]
except KeyError:
# Trim path down
dir = ''
path, filename = os.path.split(path)
while len(dir + filename) < 30:
filename = os.path.join(dir, filename)
path, dir = os.path.split(path)
if not dir:
filename = os.path.join('', filename)
break
else:
filename = os.path.join('...', filename)
_trace_filename_abbreviations[path] = filename

location = '(%s:%d)' % (filename, line)

if indent:
name = 'Called from %s' % name
print('[%d] %s%s %s' % (thread, indent, name, location))

if _trace_args:
if is_ctypes:
args = [_trace_repr(arg) for arg in frame.f_locals['args']]
print(' %sargs=(%s)' % (indent, ', '.join(args)))
else:
for argname in code.co_varnames[:code.co_argcount]:
try:
argvalue = _trace_repr(frame.f_locals[argname])
print(' %s%s=%s' % (indent, argname, argvalue))
except:
pass

if _trace_flush:
sys.stdout.flush()

def _thread_trace_func(thread):
def _trace_func(frame, event, arg):
if event == 'call':
indent = ''
for i in range(_trace_depth):
_trace_frame(thread, frame, indent)
indent += ' '
frame = frame.f_back
if not frame:
break

elif event == 'exception':
(exception, value, traceback) = arg
print('First chance exception raised:', repr(exception))
return _trace_func

def _install_trace():
global _trace_thread_count
sys.setprofile(_thread_trace_func(_trace_thread_count))
_trace_thread_count += 1

_trace_thread_count = 0
_trace_args = options['debug_trace_args']
_trace_depth = options['debug_trace_depth']
_trace_flush = options['debug_trace_flush']
if options['debug_trace']:
_install_trace()

# Lazy loading
# ------------

class _ModuleProxy(object):
_module = None

def __init__(self, name):
self.__dict__['_module_name'] = name

def __getattr__(self, name):
try:
return getattr(self._module, name)
except AttributeError:
if self._module is not None:
raise

import_name = 'pyglet.%s' % self._module_name
__import__(import_name)
module = sys.modules[import_name]
object.__setattr__(self, '_module', module)
globals()[self._module_name] = module
return getattr(module, name)

def __setattr__(self, name, value):
try:
setattr(self._module, name, value)
except AttributeError:
if self._module is not None:
raise

import_name = 'pyglet.%s' % self._module_name
__import__(import_name)
module = sys.modules[import_name]
object.__setattr__(self, '_module', module)
globals()[self._module_name] = module
setattr(module, name, value)

if True:
app = _ModuleProxy('app')
canvas = _ModuleProxy('canvas')
clock = _ModuleProxy('clock')
com = _ModuleProxy('com')
event = _ModuleProxy('event')
font = _ModuleProxy('font')
gl = _ModuleProxy('gl')
graphics = _ModuleProxy('graphics')
image = _ModuleProxy('image')
input = _ModuleProxy('input')
lib = _ModuleProxy('lib')
media = _ModuleProxy('media')
resource = _ModuleProxy('resource')
sprite = _ModuleProxy('sprite')
text = _ModuleProxy('text')
window = _ModuleProxy('window')

# Fool py2exe, py2app into including all top-level modules (doesn't understand
# lazy loading)
if False:
from . import app
from . import canvas
from . import clock
from . import com
from . import event
from . import font
from . import gl
from . import graphics
from . import input
from . import image
from . import lib
from . import media
from . import resource
from . import sprite
from . import text
from . import window

# Hack around some epydoc bug that causes it to think pyglet.window is None.
if False:
from . import window

BIN
assets/pyglet/__init__.pyc View File


+ 185
- 0
assets/pyglet/app/__init__.py View File

@@ -0,0 +1,185 @@
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------

'''Application-wide functionality.

Applications
------------

Most applications need only call :func:`run` after creating one or more
windows to begin processing events. For example, a simple application
consisting of one window is::

import pyglet

win = pyglet.window.Window()
pyglet.app.run()


Events
======

To handle events on the main event loop, instantiate it manually. The
following example exits the application as soon as any window is closed (the
default policy is to wait until all windows are closed)::

event_loop = pyglet.app.EventLoop()

@event_loop.event
def on_window_close(window):
event_loop.exit()

:since: pyglet 1.1


:attr:`event_loop` is the global event loop. Applications can replace this
with their own subclass of :class:`EventLoop` before calling
:meth:`EventLoop.run`.

:attr:`platform_event_loop` is the platform-dependent event loop.
Applications must not subclass or replace this :class:`PlatformEventLoop`
object.

'''
from builtins import object

__docformat__ = 'restructuredtext'
__version__ = '$Id$'

import sys
import weakref

_is_epydoc = hasattr(sys, 'is_epydoc') and sys.is_epydoc

class AppException(Exception):
pass

class WeakSet(object):
'''Set of objects, referenced weakly.

Adding an object to this set does not prevent it from being garbage
collected. Upon being garbage collected, the object is automatically
removed from the set.
'''
def __init__(self):
self._dict = weakref.WeakKeyDictionary()

def add(self, value):
self._dict[value] = True

def remove(self, value):
# Value might be removed already if this is during __del__ of the item.
self._dict.pop(value, None)

def pop(self):
value, _ = self._dict.popitem()
return value

def __iter__(self):
for key in self._dict.keys():
yield key

def __contains__(self, other):
return other in self._dict

def __len__(self):
return len(self._dict)


displays = WeakSet()
'''Set of all open displays. Instances of :class:`pyglet.canvas.Display`
are automatically added to this set upon construction. The set uses weak
references, so displays are removed from the set when they are no longer
referenced.

:deprecated: Use :func:`pyglet.canvas.get_display`.

:type: :class:`WeakSet`
'''


windows = WeakSet()
'''Set of all open windows (including invisible windows). Instances of
:class:`pyglet.window.Window` are automatically added to this set upon
construction. The set uses weak references, so windows are removed from
the set when they are no longer referenced or are closed explicitly.
'''


def run():
'''Begin processing events, scheduled functions and window updates.

This is a convenience function, equivalent to::

pyglet.app.event_loop.run()

'''
event_loop.run()

def exit():
'''Exit the application event loop.

Causes the application event loop to finish, if an event loop is currently
running. The application may not necessarily exit (for example, there may
be additional code following the `run` invocation).

This is a convenience function, equivalent to::

event_loop.exit()

'''
event_loop.exit()

from pyglet.app.base import EventLoop
from pyglet import compat_platform
if _is_epydoc:
from pyglet.app.base import PlatformEventLoop
else:
if compat_platform == 'darwin':
from pyglet import options as pyglet_options
if pyglet_options['darwin_cocoa']:
from pyglet.app.cocoa import CocoaEventLoop as PlatformEventLoop
else:
from pyglet.app.carbon import CarbonEventLoop as PlatformEventLoop
elif compat_platform in ('win32', 'cygwin'):
from pyglet.app.win32 import Win32EventLoop as PlatformEventLoop
else:
from pyglet.app.xlib import XlibEventLoop as PlatformEventLoop



event_loop = EventLoop()

platform_event_loop = PlatformEventLoop()


BIN
assets/pyglet/app/__init__.pyc View File


+ 383
- 0
assets/pyglet/app/base.py View File

@@ -0,0 +1,383 @@
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import next
from builtins import object

import platform
import queue
import sys
import threading

from pyglet import app
from pyglet import compat_platform
from pyglet import clock
from pyglet import event

_is_epydoc = hasattr(sys, 'is_epydoc') and sys.is_epydoc

class PlatformEventLoop(object):
''' Abstract class, implementation depends on platform.
:since: pyglet 1.2
'''
def __init__(self):
self._event_queue = queue.Queue()
self._is_running = threading.Event()
self._is_running.clear()

def is_running(self):
'''Return True if the event loop is currently processing, or False
if it is blocked or not activated.

:rtype: bool
'''
return self._is_running.is_set()

def post_event(self, dispatcher, event, *args):
'''Post an event into the main application thread.

The event is queued internally until the `run` method's thread
is able to dispatch the event. This method can be safely called
from any thread.

If the method is called from the `run` method's thread (for example,
from within an event handler), the event may be dispatched within
the same runloop iteration or the next one; the choice is
nondeterministic.

:Parameters:
`dispatcher` : EventDispatcher
Dispatcher to process the event.
`event` : str
Event name.
`args` : sequence
Arguments to pass to the event handlers.

'''
self._event_queue.put((dispatcher, event, args))
self.notify()

def dispatch_posted_events(self):
'''Immediately dispatch all pending events.

Normally this is called automatically by the runloop iteration.
'''
while True:
try:
dispatcher, event, args = self._event_queue.get(False)
except queue.Empty:
break

dispatcher.dispatch_event(event, *args)

def notify(self):
'''Notify the event loop that something needs processing.

If the event loop is blocked, it will unblock and perform an iteration
immediately. If the event loop is running, another iteration is
scheduled for immediate execution afterwards.
'''
raise NotImplementedError('abstract')

def start(self):
pass

def step(self, timeout=None):
''':TODO: in mac/linux: return True if didn't time out'''
raise NotImplementedError('abstract')

def set_timer(self, func, interval):
raise NotImplementedError('abstract')

def stop(self):
pass

class EventLoop(event.EventDispatcher):
'''The main run loop of the application.

Calling `run` begins the application event loop, which processes
operating system events, calls `pyglet.clock.tick` to call scheduled
functions and calls `pyglet.window.Window.on_draw` and
`pyglet.window.Window.flip` to update window contents.

Applications can subclass `EventLoop` and override certain methods
to integrate another framework's run loop, or to customise processing
in some other way. You should not in general override `run`, as
this method contains platform-specific code that ensures the application
remains responsive to the user while keeping CPU usage to a minimum.
'''

_has_exit_condition = None
_has_exit = False

def __init__(self):
self._has_exit_condition = threading.Condition()
self.clock = clock.get_default()
self.is_running = False

def run(self):
'''Begin processing events, scheduled functions and window updates.

This method returns when `has_exit` is set to True.

Developers are discouraged from overriding this method, as the
implementation is platform-specific.
'''
self.has_exit = False
self._legacy_setup()

platform_event_loop = app.platform_event_loop
platform_event_loop.start()
self.dispatch_event('on_enter')

self.is_running = True
if compat_platform == 'win32' and int(platform.win32_ver()[0]) <= 5:
self._run_estimated()
else:
self._run()
self.is_running = False

self.dispatch_event('on_exit')
platform_event_loop.stop()

def _run(self):
'''The simplest standard run loop, using constant timeout. Suitable
for well-behaving platforms (Mac, Linux and some Windows).
'''
platform_event_loop = app.platform_event_loop
while not self.has_exit:
timeout = self.idle()
platform_event_loop.step(timeout)

def _run_estimated(self):
'''Run-loop that continually estimates function mapping requested
timeout to measured timeout using a least-squares linear regression.
Suitable for oddball platforms (Windows).

XXX: There is no real relation between the timeout given by self.idle(), and used
to calculate the estimate, and the time actually spent waiting for events. I have
seen this cause a negative gradient, showing a negative relation. Then CPU use
runs out of control due to very small estimates.
'''
platform_event_loop = app.platform_event_loop

predictor = self._least_squares()
gradient, offset = next(predictor)

time = self.clock.time
while not self.has_exit:
timeout = self.idle()
if timeout is None:
estimate = None
else:
estimate = max(gradient * timeout + offset, 0.0)
if False:
print('Gradient = %f, Offset = %f' % (gradient, offset))
print('Timeout = %f, Estimate = %f' % (timeout, estimate))

t = time()
if not platform_event_loop.step(estimate) and estimate != 0.0 and \
estimate is not None:
dt = time() - t
gradient, offset = predictor.send((dt, estimate))

@staticmethod
def _least_squares(gradient=1, offset=0):
X = 0
Y = 0
XX = 0
XY = 0
n = 0

while True:
x, y = yield gradient, offset
X += x
Y += y
XX += x * x
XY += x * y
n += 1

try:
gradient = (n * XY - X * Y) / (n * XX - X * X)
offset = (Y - gradient * X) / n
except ZeroDivisionError:
# Can happen in pathalogical case; keep current
# gradient/offset for now.
pass

def _legacy_setup(self):
# Disable event queuing for dispatch_events
from pyglet.window import Window
Window._enable_event_queue = False
# Dispatch pending events
for window in app.windows:
window.switch_to()
window.dispatch_pending_events()

def enter_blocking(self):
'''Called by pyglet internal processes when the operating system
is about to block due to a user interaction. For example, this
is common when the user begins resizing or moving a window.

This method provides the event loop with an opportunity to set up
an OS timer on the platform event loop, which will continue to
be invoked during the blocking operation.

The default implementation ensures that `idle` continues to be called
as documented.

:since: pyglet 1.2
'''
timeout = self.idle()
app.platform_event_loop.set_timer(self._blocking_timer, timeout)

def exit_blocking(self):
'''Called by pyglet internal processes when the blocking operation
completes. See `enter_blocking`.
'''
app.platform_event_loop.set_timer(None, None)

def _blocking_timer(self):
timeout = self.idle()
app.platform_event_loop.set_timer(self._blocking_timer, timeout)

def idle(self):
'''Called during each iteration of the event loop.

The method is called immediately after any window events (i.e., after
any user input). The method can return a duration after which
the idle method will be called again. The method may be called
earlier if the user creates more input events. The method
can return `None` to only wait for user events.

For example, return ``1.0`` to have the idle method called every
second, or immediately after any user events.

The default implementation dispatches the
`pyglet.window.Window.on_draw` event for all windows and uses
`pyglet.clock.tick` and `pyglet.clock.get_sleep_time` on the default
clock to determine the return value.

This method should be overridden by advanced users only. To have
code execute at regular intervals, use the
`pyglet.clock.schedule` methods.

:rtype: float
:return: The number of seconds before the idle method should
be called again, or `None` to block for user input.
'''
dt = self.clock.update_time()
redraw_all = self.clock.call_scheduled_functions(dt)

# Redraw all windows
for window in app.windows:
if redraw_all or (window._legacy_invalid and window.invalid):
window.switch_to()
window.dispatch_event('on_draw')
window.flip()
window._legacy_invalid = False

# Update timout
return self.clock.get_sleep_time(True)

def _get_has_exit(self):
self._has_exit_condition.acquire()
result = self._has_exit
self._has_exit_condition.release()
return result

def _set_has_exit(self, value):
self._has_exit_condition.acquire()
self._has_exit = value
self._has_exit_condition.notify()
self._has_exit_condition.release()

has_exit = property(_get_has_exit, _set_has_exit,
doc='''Flag indicating if the event loop will exit in
the next iteration. When set, all waiting threads are interrupted (see
`sleep`).
Thread-safe since pyglet 1.2.

:see: `exit`
:type: bool
''')

def exit(self):
'''Safely exit the event loop at the end of the current iteration.

This method is a thread-safe equivalent for for setting `has_exit` to
``True``. All waiting threads will be interrupted (see
`sleep`).
'''
self._set_has_exit(True)
app.platform_event_loop.notify()

def sleep(self, timeout):
'''Wait for some amount of time, or until the `has_exit` flag is
set or `exit` is called.

This method is thread-safe.

:Parameters:
`timeout` : float
Time to wait, in seconds.

:since: pyglet 1.2

:rtype: bool
:return: ``True`` if the `has_exit` flag is now set, otherwise
``False``.
'''
self._has_exit_condition.acquire()
self._has_exit_condition.wait(timeout)
result = self._has_exit
self._has_exit_condition.release()
return result

def on_window_close(self, window):
'''Default window close handler.'''
if len(app.windows) == 0:
self.exit()

if _is_epydoc:
def on_window_close(self, window):
'''A window was closed.

This event is dispatched when a window is closed. It is not
dispatched if the window's close button was pressed but the
window did not close.

The default handler calls `exit` if no more windows are open. You
can override this handler to base your application exit on some
other policy.

:event:
'''

def on_enter(self):
'''The event loop is about to begin.

This is dispatched when the event loop is prepared to enter
the main run loop, and represents the last chance for an
application to initialise itself.

:event:
'''

def on_exit(self):
'''The event loop is about to exit.

After dispatching this event, the `run` method returns (the
application may not actually exit if you have more code
following the `run` invocation).

:event:
'''

EventLoop.register_event_type('on_window_close')
EventLoop.register_event_type('on_enter')
EventLoop.register_event_type('on_exit')

BIN
assets/pyglet/app/base.pyc View File


+ 150
- 0
assets/pyglet/app/carbon.py View File

@@ -0,0 +1,150 @@
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------

'''
'''

__docformat__ = 'restructuredtext'
__version__ = '$Id: $'

import ctypes

from pyglet import app
from pyglet.app.base import PlatformEventLoop

from pyglet.libs.darwin import *

EventLoopTimerProc = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_void_p)


class CarbonEventLoop(PlatformEventLoop):
def __init__(self):
self._event_loop = carbon.GetMainEventLoop()
self._timer = ctypes.c_void_p()
self._timer_func = None
self._timer_func_proc = EventLoopTimerProc(self._timer_proc)
super(CarbonEventLoop, self).__init__()

def notify(self):
carbon.SetEventLoopTimerNextFireTime(
self._timer, ctypes.c_double(0.0))

def start(self):
# Create timer
timer = self._timer
carbon.InstallEventLoopTimer(self._event_loop,
ctypes.c_double(0.1), #?
ctypes.c_double(kEventDurationForever),
self._timer_func_proc,
None,
ctypes.byref(timer))

def stop(self):
carbon.RemoveEventLoopTimer(self._timer)

def step(self, timeout=None):
self.dispatch_posted_events()

event_dispatcher = carbon.GetEventDispatcherTarget()
e = ctypes.c_void_p()
if timeout is None:
timeout = kEventDurationForever
self._is_running.set()
# XXX should spin on multiple events after first timeout
if carbon.ReceiveNextEvent(0, None, ctypes.c_double(timeout),
True, ctypes.byref(e)) == 0:
carbon.SendEventToEventTarget(e, event_dispatcher)
carbon.ReleaseEvent(e)
timed_out = False
else:
timed_out = True
self._is_running.clear()

return not timed_out

def set_timer(self, func, interval):
if interval is None or func is None:
interval = kEventDurationForever

self._timer_func = func
carbon.SetEventLoopTimerNextFireTime(self._timer,
ctypes.c_double(interval))

def _timer_proc(self, timer, data):
if self._timer_func:
self._timer_func()
'''
self.dispatch_posted_events()

allow_polling = True

for window in app.windows:
# Check for live resizing
if window._resizing is not None:
allow_polling = False
old_width, old_height = window._resizing
rect = Rect()
carbon.GetWindowBounds(window._window,
kWindowContentRgn,
ctypes.byref(rect))
width = rect.right - rect.left
height = rect.bottom - rect.top
if width != old_width or height != old_height:
window._resizing = width, height
window.switch_to()
window.dispatch_event('on_resize', width, height)
# Check for live dragging
if window._dragging:
allow_polling = False

# Check for deferred recreate
if window._recreate_deferred:
# Break out of ReceiveNextEvent so it can be processed
# in next iteration.
carbon.QuitEventLoop(self._event_loop)
self._force_idle = True

sleep_time = self.idle()

if sleep_time is None:
sleep_time = kEventDurationForever
elif sleep_time < 0.01 and allow_polling and self._allow_polling:
# Switch event loop to polling.
carbon.QuitEventLoop(self._event_loop)
self._force_idle = True
sleep_time = kEventDurationForever
carbon.SetEventLoopTimerNextFireTime(timer, ctypes.c_double(sleep_time))
'''

+ 198
- 0
assets/pyglet/app/cocoa.py View File

@@ -0,0 +1,198 @@
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------

'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'

from pyglet.app.base import PlatformEventLoop
from pyglet.libs.darwin.cocoapy import *

NSApplication = ObjCClass('NSApplication')
NSMenu = ObjCClass('NSMenu')
NSMenuItem = ObjCClass('NSMenuItem')
NSAutoreleasePool = ObjCClass('NSAutoreleasePool')
NSDate = ObjCClass('NSDate')
NSEvent = ObjCClass('NSEvent')
NSUserDefaults = ObjCClass('NSUserDefaults')


class AutoReleasePool(object):
def __enter__(self):
self.pool = NSAutoreleasePool.alloc().init()
return self.pool

def __exit__(self, exc_type, exc_value, traceback):
self.pool.drain()
del self.pool


def add_menu_item(menu, title, action, key):
with AutoReleasePool():
title = CFSTR(title)
action = get_selector(action)
key = CFSTR(key)
menuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
title, action, key)
menu.addItem_(menuItem)

# cleanup
title.release()
key.release()
menuItem.release()

def create_menu():
with AutoReleasePool():
appMenu = NSMenu.alloc().init()

# Hide still doesn't work!?
add_menu_item(appMenu, 'Hide!', 'hide:', 'h')
appMenu.addItem_(NSMenuItem.separatorItem())
add_menu_item(appMenu, 'Quit!', 'terminate:', 'q')

menubar = NSMenu.alloc().init()
appMenuItem = NSMenuItem.alloc().init()
appMenuItem.setSubmenu_(appMenu)
menubar.addItem_(appMenuItem)
NSApp = NSApplication.sharedApplication()
NSApp.setMainMenu_(menubar)

# cleanup
appMenu.release()
menubar.release()
appMenuItem.release()


class CocoaEventLoop(PlatformEventLoop):

def __init__(self):
super(CocoaEventLoop, self).__init__()
with AutoReleasePool():
# Prepare the default application.
self.NSApp = NSApplication.sharedApplication()
if self.NSApp.isRunning():
# Application was already started by GUI library (e.g. wxPython).
return
if not self.NSApp.mainMenu():
create_menu()
self.NSApp.setActivationPolicy_(NSApplicationActivationPolicyRegular)
# Prevent Lion / Mountain Lion from automatically saving application state.
# If we don't do this, new windows will not display on 10.8 after finishLaunching
# has been called.
defaults = NSUserDefaults.standardUserDefaults()
ignoreState = CFSTR("ApplePersistenceIgnoreState")
if not defaults.objectForKey_(ignoreState):
defaults.setBool_forKey_(True, ignoreState)
self._finished_launching = False

def start(self):
with AutoReleasePool():
if not self.NSApp.isRunning() and not self._finished_launching:
# finishLaunching should be called only once. However isRunning will not
# guard this, as we are not using the normal event loop.
self.NSApp.finishLaunching()
self.NSApp.activateIgnoringOtherApps_(True)
self._finished_launching = True

def step(self, timeout=None):
with AutoReleasePool():
self.dispatch_posted_events()

# Determine the timeout date.
if timeout is None:
# Using distantFuture as untilDate means that nextEventMatchingMask
# will wait until the next event comes along.
timeout_date = NSDate.distantFuture()
else:
timeout_date = NSDate.dateWithTimeIntervalSinceNow_(timeout)

# Retrieve the next event (if any). We wait for an event to show up
# and then process it, or if timeout_date expires we simply return.
# We only process one event per call of step().
self._is_running.set()
event = self.NSApp.nextEventMatchingMask_untilDate_inMode_dequeue_(
NSAnyEventMask, timeout_date, NSDefaultRunLoopMode, True)

# Dispatch the event (if any).
if event is not None:
event_type = event.type()
if event_type != NSApplicationDefined:
# Send out event as normal. Responders will still receive
# keyUp:, keyDown:, and flagsChanged: events.
self.NSApp.sendEvent_(event)

# Resend key events as special pyglet-specific messages
# which supplant the keyDown:, keyUp:, and flagsChanged: messages
# because NSApplication translates multiple key presses into key
# equivalents before sending them on, which means that some keyUp:
# messages are never sent for individual keys. Our pyglet-specific
# replacements ensure that we see all the raw key presses & releases.
# We also filter out key-down repeats since pyglet only sends one
# on_key_press event per key press.
if event_type == NSKeyDown and not event.isARepeat():
self.NSApp.sendAction_to_from_(get_selector("pygletKeyDown:"), None, event)
elif event_type == NSKeyUp:
self.NSApp.sendAction_to_from_(get_selector("pygletKeyUp:"), None, event)
elif event_type == NSFlagsChanged:
self.NSApp.sendAction_to_from_(get_selector("pygletFlagsChanged:"), None, event)

self.NSApp.updateWindows()
did_time_out = False
else:
did_time_out = True

self._is_running.clear()

return did_time_out

def stop(self):
pass

def notify(self):
with AutoReleasePool():
notifyEvent = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_(
NSApplicationDefined, # type
NSPoint(0.0, 0.0), # location
0, # modifierFlags
0, # timestamp
0, # windowNumber
None, # graphicsContext
0, # subtype
0, # data1
0, # data2
)

self.NSApp.postEvent_atStart_(notifyEvent, False)


+ 149
- 0
assets/pyglet/app/win32.py View File

@@ -0,0 +1,149 @@
from __future__ import absolute_import
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
# $Id:$

__docformat__ = 'restructuredtext'
__version__ = '$Id: $'

import ctypes

from pyglet import app
from .base import PlatformEventLoop

from pyglet.libs.win32 import _kernel32, _user32, types, constants
from pyglet.libs.win32.constants import *
from pyglet.libs.win32.types import *

class Win32EventLoop(PlatformEventLoop):
def __init__(self):
super(Win32EventLoop, self).__init__()

self._next_idle_time = None

# Force immediate creation of an event queue on this thread -- note
# that since event loop is created on pyglet.app import, whatever
# imports pyglet.app _must_ own the main run loop.
msg = types.MSG()
_user32.PeekMessageW(ctypes.byref(msg), 0,
constants.WM_USER, constants.WM_USER,
constants.PM_NOREMOVE)

self._event_thread = _kernel32.GetCurrentThreadId()

self._wait_objects = []
self._recreate_wait_objects_array()

self._timer_proc = types.TIMERPROC(self._timer_proc_func)
self._timer = _user32.SetTimer(
0, 0, constants.USER_TIMER_MAXIMUM, self._timer_proc)

def add_wait_object(self, object, func):
self._wait_objects.append((object, func))
self._recreate_wait_objects_array()

def remove_wait_object(self, object):
for i, (_object, _) in enumerate(self._wait_objects):
if object == _object:
del self._wait_objects[i]
break
self._recreate_wait_objects_array()

def _recreate_wait_objects_array(self):
if not self._wait_objects:
self._wait_objects_n = 0
self._wait_objects_array = None
return

self._wait_objects_n = len(self._wait_objects)
self._wait_objects_array = \
(HANDLE * self._wait_objects_n)(*[o for o, f in self._wait_objects])

def start(self):
if _kernel32.GetCurrentThreadId() != self._event_thread:
raise RuntimeError('EventLoop.run() must be called from the same ' +
'thread that imports pyglet.app')

self._timer_func = None
self._polling = False
self._allow_polling = True

def step(self, timeout=None):
self.dispatch_posted_events()

msg = types.MSG()
if timeout is None:
timeout = constants.INFINITE
else:
timeout = int(timeout * 1000) # milliseconds

result = _user32.MsgWaitForMultipleObjects(
self._wait_objects_n,
self._wait_objects_array,
False,
timeout,
constants.QS_ALLINPUT)
result -= constants.WAIT_OBJECT_0

if result == self._wait_objects_n:
while _user32.PeekMessageW(ctypes.byref(msg),
0, 0, 0, constants.PM_REMOVE):
_user32.TranslateMessage(ctypes.byref(msg))
_user32.DispatchMessageW(ctypes.byref(msg))
elif 0 <= result < self._wait_objects_n:
object, func = self._wait_objects[result]
func()

# Return True if timeout was interrupted.
return result <= self._wait_objects_n

def notify(self):
# Nudge the event loop with a message it will discard. Note that only
# user events are actually posted. The posted event will not
# interrupt the window move/size drag loop -- it seems there's no way
# to do this.
_user32.PostThreadMessageW(self._event_thread, constants.WM_USER, 0, 0)

def set_timer(self, func, interval):
if func is None or interval is None:
interval = constants.USER_TIMER_MAXIMUM
else:
interval = int(interval * 1000) # milliseconds
self._timer_func = func
_user32.SetTimer(0, self._timer, interval, self._timer_proc)
def _timer_proc_func(self, hwnd, msg, timer, t):
if self._timer_func:
self._timer_func()

+ 128
- 0
assets/pyglet/app/xlib.py View File

@@ -0,0 +1,128 @@
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------

'''
'''
from builtins import object

__docformat__ = 'restructuredtext'
__version__ = '$Id$'

import os
import select
import threading
from ctypes import *

from pyglet import app
from pyglet.app.base import PlatformEventLoop
from pyglet.compat import asbytes

class XlibSelectDevice(object):
def fileno(self):
'''Get the file handle for ``select()`` for this device.

:rtype: int
'''
raise NotImplementedError('abstract')

def select(self):
'''Perform event processing on the device.

Called when ``select()`` returns this device in its list of active
files.
'''
raise NotImplementedError('abstract')

def poll(self):
'''Check if the device has events ready to process.

:rtype: bool
:return: True if there are events to process, False otherwise.
'''
return False

class NotificationDevice(XlibSelectDevice):
def __init__(self):
self._sync_file_read, self._sync_file_write = os.pipe()
self._event = threading.Event()

def fileno(self):
return self._sync_file_read

def set(self):
self._event.set()
os.write(self._sync_file_write, asbytes('1'))

def select(self):
self._event.clear()
os.read(self._sync_file_read, 1)
app.platform_event_loop.dispatch_posted_events()

def poll(self):
return self._event.isSet()

class XlibEventLoop(PlatformEventLoop):
def __init__(self):
super(XlibEventLoop, self).__init__()
self._notification_device = NotificationDevice()
self._select_devices = set()
self._select_devices.add(self._notification_device)

def notify(self):
self._notification_device.set()

def step(self, timeout=None):
# Timeout is from EventLoop.idle(). Return after that timeout or directly
# after receiving a new event. None means: block for user input.

# Poll devices to check for already pending events (select.select is not enough)
pending_devices = []
for device in self._select_devices:
if device.poll():
pending_devices.append(device)

# If no devices were ready, wait until one gets ready
if not pending_devices:
pending_devices, _, _ = select.select(self._select_devices, (), (), timeout)

if not pending_devices:
# Notify caller that timeout expired without incoming events
return False

# Dispatch activity on matching devices
for device in pending_devices:
device.select()

# Notify caller that events were handled before timeout expired
return True

BIN
assets/pyglet/app/xlib.pyc View File


+ 105
- 0
assets/pyglet/canvas/__init__.py View File

@@ -0,0 +1,105 @@
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------

'''Display and screen management.

Rendering is performed on a :class:`Canvas`, which conceptually could be an
off-screen buffer, the content area of a :class:`pyglet.window.Window`, or an
entire screen. Currently, canvases can only be created with windows (though
windows can be set fullscreen).

Windows and canvases must belong to a :class:`Display`. On Windows and Mac OS
X there is only one display, which can be obtained with :func:`get_display`.
Linux supports multiple displays, corresponding to discrete X11 display
connections and screens. :func:`get_display` on Linux returns the default
display and screen 0 (``localhost:0.0``); if a particular screen or display is
required then :class:`Display` can be instantiated directly.

Within a display one or more screens are attached. A :class:`Screen` often
corresponds to a physical attached monitor, however a monitor or projector set
up to clone another screen will not be listed. Use :meth:`Display.get_screens`
to get a list of the attached screens; these can then be queried for their
sizes and virtual positions on the desktop.

The size of a screen is determined by its current mode, which can be changed
by the application; see the documentation for :class:`Screen`.

:since: pyglet 1.2
'''

import sys
_is_epydoc = hasattr(sys, 'is_epydoc') and sys.is_epydoc

def get_display():
'''Get the default display device.

If there is already a :class:`Display` connection, that display will be
returned. Otherwise, a default :class:`Display` is created and returned.
If multiple display connections are active, an arbitrary one is returned.

:since: pyglet 1.2

:rtype: :class:`Display`
'''
# If there's an existing display, return it (return arbitrary display if
# there are multiple).
from pyglet.app import displays
for display in displays:
return display

# Otherwise, create a new display and return it.
return Display()

if _is_epydoc:
from pyglet.canvas.base import Display, Screen, Canvas, ScreenMode
else:
from pyglet import compat_platform
if compat_platform == 'darwin':
from pyglet import options as pyglet_options
if pyglet_options['darwin_cocoa']:
from pyglet.canvas.cocoa import CocoaDisplay as Display
from pyglet.canvas.cocoa import CocoaScreen as Screen
from pyglet.canvas.cocoa import CocoaCanvas as Canvas
else:
from pyglet.canvas.carbon import CarbonDisplay as Display
from pyglet.canvas.carbon import CarbonScreen as Screen
from pyglet.canvas.carbon import CarbonCanvas as Canvas
elif compat_platform in ('win32', 'cygwin'):
from pyglet.canvas.win32 import Win32Display as Display
from pyglet.canvas.win32 import Win32Screen as Screen
from pyglet.canvas.win32 import Win32Canvas as Canvas
else:
from pyglet.canvas.xlib import XlibDisplay as Display
from pyglet.canvas.xlib import XlibScreen as Screen
from pyglet.canvas.xlib import XlibCanvas as Canvas

BIN
assets/pyglet/canvas/__init__.pyc View File


+ 335
- 0
assets/pyglet/canvas/base.py View File

@@ -0,0 +1,335 @@
from builtins import object
#!/usr/bin/python
# $Id:$

from pyglet import app
from pyglet import gl
from pyglet import window

class Display(object):
'''A display device supporting one or more screens.

:guide:`displays`
:since: pyglet 1.2
'''

name = None
'''Name of this display, if applicable.

:type: str
'''
x_screen = None
'''The X11 screen number of this display, if applicable.

:type: int
'''
def __init__(self, name=None, x_screen=None):
'''Create a display connection for the given name and screen.

On X11, :attr:`name` is of the form ``"hostname:display"``, where the
default is usually ``":1"``. On X11, :attr:`x_screen` gives the X
screen number to use with this display. A pyglet display can only be
used with one X screen; open multiple display connections to access
multiple X screens.
Note that TwinView, Xinerama, xrandr and other extensions present
multiple monitors on a single X screen; this is usually the preferred
mechanism for working with multiple monitors under X11 and allows each
screen to be accessed through a single pyglet `Display`.

On platforms other than X11, :attr:`name` and :attr:`x_screen` are
ignored; there is only a single display device on these systems.

:Parameters:
`name` : str
The name of the display to connect to.
`x_screen` : int
The X11 screen number to use.

'''
app.displays.add(self)

def get_screens(self):
'''Get the available screens.

A typical multi-monitor workstation comprises one :class:`Display`
with multiple :class:`Screen` s. This method returns a list of
screens which can be enumerated to select one for full-screen display.

For the purposes of creating an OpenGL config, the default screen
will suffice.

:rtype: list of :class:`Screen`
'''
raise NotImplementedError('abstract')

def get_default_screen(self):
'''Get the default screen as specified by the user's operating system
preferences.

:rtype: :class:`Screen`
'''
return self.get_screens()[0]

def get_windows(self):
'''Get the windows currently attached to this display.

:rtype: sequence of :class:`~pyglet.window.Window`
'''
return [window for window in app.windows if window.display is self]

class Screen(object):
'''A virtual monitor that supports fullscreen windows.

Screens typically map onto a physical display such as a
monitor, television or projector. Selecting a screen for a window
has no effect unless the window is made fullscreen, in which case
the window will fill only that particular virtual screen.

The :attr:`width` and :attr:`height` attributes of a screen give the
current resolution of the screen. The :attr:`x` and :attr:`y` attributes
give the global location of the top-left corner of the screen. This is
useful for determining if screens are arranged above or next to one
another.
Use :func:`~Display.get_screens` or :func:`~Display.get_default_screen`
to obtain an instance of this class.

:guide:`screens`
'''

def __init__(self, display, x, y, width, height):
'''
:parameters:
`display` : `~pyglet.canvas.Display`
:attr:`display`
`x` : int
Left edge :attr:`x`
`y` : int
Top edge :attr:`y`
`width` : int
:attr:`width`
`height` : int
:attr:`height`
'''
self.display = display
'''Display this screen belongs to.'''
self.x = x
'''Left edge of the screen on the virtual desktop.'''
self.y = y
'''Top edge of the screen on the virtual desktop.'''
self.width = width
'''Width of the screen, in pixels.'''
self.height = height
'''Height of the screen, in pixels.'''

def __repr__(self):
return '%s(x=%d, y=%d, width=%d, height=%d)' % \
(self.__class__.__name__, self.x, self.y, self.width, self.height)

def get_best_config(self, template=None):
'''Get the best available GL config.

Any required attributes can be specified in `template`. If
no configuration matches the template,
:class:`~pyglet.window.NoSuchConfigException` will be raised.

:deprecated: Use :meth:`pyglet.gl.Config.match`.

:Parameters:
`template` : `pyglet.gl.Config`
A configuration with desired attributes filled in.

:rtype: :class:`~pyglet.gl.Config`
:return: A configuration supported by the platform that best
fulfils the needs described by the template.
'''
configs = None
if template is None:
for template_config in [
gl.Config(double_buffer=True, depth_size=24),
gl.Config(double_buffer=True, depth_size=16),
None]:
try:
configs = self.get_matching_configs(template_config)
break
except NoSuchConfigException:
pass
else:
configs = self.get_matching_configs(template)
if not configs:
raise window.NoSuchConfigException()
return configs[0]

def get_matching_configs(self, template):
'''Get a list of configs that match a specification.

Any attributes specified in `template` will have values equal
to or greater in each returned config. If no configs satisfy
the template, an empty list is returned.

:deprecated: Use :meth:`pyglet.gl.Config.match`.

:Parameters:
`template` : `pyglet.gl.Config`
A configuration with desired attributes filled in.

:rtype: list of :class:`~pyglet.gl.Config`
:return: A list of matching configs.
'''
raise NotImplementedError('abstract')

def get_modes(self):
'''Get a list of screen modes supported by this screen.

:rtype: list of :class:`ScreenMode`

:since: pyglet 1.2
'''
raise NotImplementedError('abstract')

def get_mode(self):
'''Get the current display mode for this screen.

:rtype: :class:`ScreenMode`

:since: pyglet 1.2
'''
raise NotImplementedError('abstract')

def get_closest_mode(self, width, height):
'''Get the screen mode that best matches a given size.

If no supported mode exactly equals the requested size, a larger one
is returned; or ``None`` if no mode is large enough.

:Parameters:
`width` : int
Requested screen width.
`height` : int
Requested screen height.

:rtype: :class:`ScreenMode`

:since: pyglet 1.2
'''
# Best mode is one with smallest resolution larger than width/height,
# with depth and refresh rate equal to current mode.
current = self.get_mode()

best = None
for mode in self.get_modes():
# Reject resolutions that are too small
if mode.width < width or mode.height < height:
continue

if best is None:
best = mode

# Must strictly dominate dimensions
if (mode.width <= best.width and mode.height <= best.height and
(mode.width < best.width or mode.height < best.height)):
best = mode

# Preferably match rate, then depth.
if mode.width == best.width and mode.height == best.height:
points = 0
if mode.rate == current.rate:
points += 2
if best.rate == current.rate:
points -= 2
if mode.depth == current.depth:
points += 1
if best.depth == current.depth:
points -= 1
if points > 0:
best = mode
return best

def set_mode(self, mode):
'''Set the display mode for this screen.

The mode must be one previously returned by :meth:`get_mode` or
:meth:`get_modes`.