pygame-1.9.1release/ 0000755 0001750 0001750 00000000000 11236514371 014246 5 ustar vincent vincent pygame-1.9.1release/test/ 0000755 0001750 0001750 00000000000 11236514371 015225 5 ustar vincent vincent pygame-1.9.1release/src/ 0000755 0001750 0001750 00000000000 11236514371 015035 5 ustar vincent vincent pygame-1.9.1release/pygame.egg-info/ 0000755 0001750 0001750 00000000000 11236514371 017222 5 ustar vincent vincent pygame-1.9.1release/lib/ 0000755 0001750 0001750 00000000000 11637747402 015024 5 ustar vincent vincent pygame-1.9.1release/examples/ 0000755 0001750 0001750 00000000000 11236514371 016064 5 ustar vincent vincent pygame-1.9.1release/docs/ 0000755 0001750 0001750 00000000000 11236514371 015176 5 ustar vincent vincent pygame-1.9.1release/test/util/ 0000755 0001750 0001750 00000000000 11236514371 016202 5 ustar vincent vincent pygame-1.9.1release/test/test_utils/ 0000755 0001750 0001750 00000000000 11236514371 017424 5 ustar vincent vincent pygame-1.9.1release/test/run_tests__tests/ 0000755 0001750 0001750 00000000000 11236514371 020634 5 ustar vincent vincent pygame-1.9.1release/test/fixtures/ 0000755 0001750 0001750 00000000000 11236514371 017076 5 ustar vincent vincent pygame-1.9.1release/src/SDL_gfx/ 0000755 0001750 0001750 00000000000 11236514371 016323 5 ustar vincent vincent pygame-1.9.1release/lib/threads/ 0000755 0001750 0001750 00000000000 11236514371 016446 5 ustar vincent vincent pygame-1.9.1release/lib/gp2x/ 0000755 0001750 0001750 00000000000 11236514371 015674 5 ustar vincent vincent pygame-1.9.1release/examples/macosx/ 0000755 0001750 0001750 00000000000 11236514371 017356 5 ustar vincent vincent pygame-1.9.1release/examples/data/ 0000755 0001750 0001750 00000000000 11236514371 016775 5 ustar vincent vincent pygame-1.9.1release/docs/tut/ 0000755 0001750 0001750 00000000000 11236514371 016012 5 ustar vincent vincent pygame-1.9.1release/docs/ref/ 0000755 0001750 0001750 00000000000 11236514371 015752 5 ustar vincent vincent pygame-1.9.1release/test/util/build_page/ 0000755 0001750 0001750 00000000000 11236514371 020275 5 ustar vincent vincent pygame-1.9.1release/test/run_tests__tests/timeout/ 0000755 0001750 0001750 00000000000 11236514371 022322 5 ustar vincent vincent pygame-1.9.1release/test/run_tests__tests/print_stdout/ 0000755 0001750 0001750 00000000000 11236514371 023372 5 ustar vincent vincent pygame-1.9.1release/test/run_tests__tests/print_stderr/ 0000755 0001750 0001750 00000000000 11236514371 023353 5 ustar vincent vincent pygame-1.9.1release/test/run_tests__tests/infinite_loop/ 0000755 0001750 0001750 00000000000 11236514371 023472 5 ustar vincent vincent pygame-1.9.1release/test/run_tests__tests/incomplete_todo/ 0000755 0001750 0001750 00000000000 11236514371 024020 5 ustar vincent vincent pygame-1.9.1release/test/run_tests__tests/incomplete/ 0000755 0001750 0001750 00000000000 11236514371 022773 5 ustar vincent vincent pygame-1.9.1release/test/run_tests__tests/failures1/ 0000755 0001750 0001750 00000000000 11236514371 022527 5 ustar vincent vincent pygame-1.9.1release/test/run_tests__tests/exclude/ 0000755 0001750 0001750 00000000000 11236514371 022265 5 ustar vincent vincent pygame-1.9.1release/test/run_tests__tests/everything/ 0000755 0001750 0001750 00000000000 11236514371 023020 5 ustar vincent vincent pygame-1.9.1release/test/run_tests__tests/all_ok/ 0000755 0001750 0001750 00000000000 11236514371 022075 5 ustar vincent vincent pygame-1.9.1release/test/fixtures/xbm_cursors/ 0000755 0001750 0001750 00000000000 11236514371 021444 5 ustar vincent vincent pygame-1.9.1release/examples/macosx/aliens_app_example/ 0000755 0001750 0001750 00000000000 11236514371 023204 5 ustar vincent vincent pygame-1.9.1release/docs/tut/tom/ 0000755 0001750 0001750 00000000000 11236514371 016611 5 ustar vincent vincent pygame-1.9.1release/docs/tut/surfarray/ 0000755 0001750 0001750 00000000000 11236514371 020030 5 ustar vincent vincent pygame-1.9.1release/docs/tut/intro/ 0000755 0001750 0001750 00000000000 11236514371 017145 5 ustar vincent vincent pygame-1.9.1release/docs/tut/chimp/ 0000755 0001750 0001750 00000000000 11236514371 017112 5 ustar vincent vincent pygame-1.9.1release/docs/tut/camera/ 0000755 0001750 0001750 00000000000 11236514371 017242 5 ustar vincent vincent pygame-1.9.1release/test/util/build_page/upload_results/ 0000755 0001750 0001750 00000000000 11236514371 023342 5 ustar vincent vincent pygame-1.9.1release/test/util/build_page/results/ 0000755 0001750 0001750 00000000000 11236514371 021776 5 ustar vincent vincent pygame-1.9.1release/test/util/build_page/libs/ 0000755 0001750 0001750 00000000000 11236514371 021226 5 ustar vincent vincent pygame-1.9.1release/examples/macosx/aliens_app_example/English.lproj/ 0000755 0001750 0001750 00000000000 11236514371 025722 5 ustar vincent vincent pygame-1.9.1release/test/util/build_page/libs/pywebsite/ 0000755 0001750 0001750 00000000000 11236514371 023241 5 ustar vincent vincent pygame-1.9.1release/test/util/build_page/libs/build_client/ 0000755 0001750 0001750 00000000000 11236514371 023663 5 ustar vincent vincent pygame-1.9.1release/examples/macosx/aliens_app_example/English.lproj/MainMenu.nib/ 0000755 0001750 0001750 00000000000 11236514371 030202 5 ustar vincent vincent pygame-1.9.1release/test/util/build_page/libs/build_client/test_fixtures/ 0000755 0001750 0001750 00000000000 11236514371 026573 5 ustar vincent vincent pygame-1.9.1release/test/util/build_page/libs/build_client/config/ 0000755 0001750 0001750 00000000000 11236514371 025130 5 ustar vincent vincent pygame-1.9.1release/WHATSNEW 0000644 0001750 0001750 00000163552 11236512106 015437 0 ustar vincent vincent # This is a list of changes in pygame's history.
#
# SVN revision numbers, and CVS tag names are placed before the date
# BREAK = change breaks existing code
# BUG = fixed a bug that was (or could have been) crashing
[SVN 2573] August 6, 2009
[BUG] missing readme.html in MANIFEST.in causes install to fail
on pythons with setuptools installed.
[SVN 2519] July 17, 2009
[BUG] fix pygame.font.get_fonts() bug for Python 3.1 and Windows.
[SVN 2517-2518] July 17, 2009
[BUG] unit test framework fails for Python 3.1 on Windows due
to str/bytes confusion
[SVN 2516] July 16, 2009
Pygame dependency build now replaces the configure
generated SDL_config.py, which MSVC can not use, with
SDL_config_win32.py
[SVN 2515] July 15, 2009
[BUG] surface docs typo patch submitted by Lorenz Quack
[SVN 2503-2505] July 13, 2009
[BUG] bugzilla 29, patch to use SDL_VIDEO_DRIVER_X11 DISABLE_X11. Thanks Robert A. Lerche.
So can compile pygame without X11 again.
[BUG] fixed bad midi test.
[BUG] pygame.gfxdraw docstrings were not there. Now... they... are.
[SVN 2491-2495] July 9, 2009
[BUG] Fixed up quit bug in eventlist.py example. Thanks Evan Kroske!
[BUG] Made the test code more compatible with python2.3.
[BUG] python3.1 support for OSX.
[SVN 2486-2488] July 8, 2009
[BUG] 64bit issues with Surface.get_masks and UintFromObj.
thanks Lorenz Quack!
[BUG] Color slicing works with python3 now too.
[SVN 2481] July 7, 2009
[BUG] typo in examples/sound_array_demos.py Thanks Evan Kroske!
[SVN 2472] July 6, 2009
[BUG]Fixed some failing tests for Color and LONG_MAX on 64bit python.
From Campbell Barton.FloatFromObj speedup.
register_quit cleanup.
PyErr_Format used in CheckSDLVersions.
[SVN 2454] July 2, 2009
[BUG] Patch to work around cpu detection bugs in SDL 64bit from Lenard.
Thanks to Lorenz for bug hunting.
[SVN 2380-2381] Jun 19, 2009
Color.set_length method... to change Color length to 1,2,3 or 4.
Surface.get_palette(_at) return Color with length 3.
[SVN 2366] Jun 17, 2009
[BUG] Memory leak in a few modules. Thanks Lorenz Quack.
[SVN 2365] Jun 16, 2009
Started to add basic slice support to Color type.
[SVN 2311] Jun 4, 2009
Fixed another Color regression... colors are now tasty again when pickled.
[SVN 2305] Jun 2, 2009
Make pygame.tests.__init__.py import __main__.py. This is done
consistently with other pygame.tests modules.
[SVN 2294-2303] Jun 1, 2009
Added some notes about Color instead of tuple for some Surface functions.
Midi, no abort on dealloc by default. have explicit close/abort available.
Updated midi docs.
Sysfont tests pass ok on OSX now(and windows+linux etc).
Sysfont on OSX more resiliant. Broke up tests to find broken ones more
easily.
Updated test/README.TXT for tags files... eg: some_module_tags.py.
Added a little tool to help with creating WHATSNEW from svn logs.
Add a little TODO to svn_log_to_whatsnew.py to make its WHATSNEW output
nicer.
[SVN 2289-2293] May 31, 2009
Fix midi_test.py so Python3 compiles it without errors.
Let Surface methods accept and return Color instances.
Minor type correction in Rect docs.
Extend background unit test default timeout to 2 minutes.
Add gfxdraw unit tests and fix uncovered bugs.
[SVN 2284-2287] May 30, 2009
Sysfont, added fallback for OSX that doesn't have X11.
Tests and fixes for midi. Better validation Input/Output to avoid crashes.
Fixed up test which was failing on ubuntu with python2.x.
[SVN 2278] May 29, 2009
Fixed test to not fail on OSX which doesn't have midi devices by default.
[SVN 2264-2269] May 27, 2009
Enable font_test.py on Windows.
Add svn properties to track which files are converted to Python 3.x.
Updated docs for cursors.load_xbm, thanks Saul Spatz, and Thomas Ibbotson.
Cursors update note.
[SVN 2248-2261] May 26, 2009
Disable debug printing for Windows build of portmidi.
Symbian Launcher:
- Removed unneeded buffer to save memory
- Removed fade from slide animations to improve performance
- Increased heap size to 100k,4Mb
- Don't byte compile regular scripts so they can be easily edited.
Symbian other:
- The pygame library is now zipped as well for better performance.
Removed color.py warning from Symbian. It is used as wrapper for the
native module.
Camera module and computer vision tutorial.
Cleaning camera module documentation and makeref on transform.
Added palette_colors to mask.from_threshold. TODO notes to some
functions.
[BUG] surflock.c PySurface_LockBy was leaking weakrefs.
Thanks Tom Rothamel.
[SVN 2242-2245] May 25, 2009
Added a palette_colors option to average_surfaces... which doesn't handle
palette using surfaces correctly(yet).
Fixed possible memory leak. Made some comments about return values.
Recompile pymp.pyx with Cython. Enable Python 3.x support of midi module.
Enable midi_test.py for Python 3.x.
[SVN 2230-2237] May 24, 2009
Added some more midi tests.
Python 3.x: disable midi_test.py and clean out movieext from setup.py.
A tool for generating .doc docs from .py docstrings, and new midi.doc.
Shortened midi.get_default_*_device_id to get_default_*_id.
Fixed up create_doc_from_py and updated a few documentation items.
Updated a doc for pygame.midi.time.
[SVN 2216-2219] May 23, 2009
Simplified sysfont.initsysfonts_win() fonts directory scan.
In init functions: fix minor Python 3.x related memory leaks and clean up
indentation.
Fix sndarray_test.py problem where failed to detect unsupported formats.
[SVN 2201-2212] May 22, 2009
Added missing gfxdraw wrapper for Symbian.
Fixed to work on PyS60 1.9.4 The pygame python files are compiled into
byte-code. Feature of scons-for-symbian.
Have sysfont.py search the Windows font directory default fonts before
checking the registry.
Added another possible registry key where there might be fonts on win.
Fix possible problem with WINDIR, windir environment variable name.
[SVN 2193-2199] May 21, 2009
Small svn prop tweak with run_tests.py and ignore font_test.py for Python
3.x on Windows.
More font unit tests and a unit test bug fix.
Add some interactive font unit tests to fill in some holes.
Move locals.doc and remove redundant constant descriptions. instead refer
to other module pages.
Add TIMER_RESOLUTION description to time.doc.
[SVN 2183-2189] May 20, 2009
Remove defunct movieext.c (ancient non-working ffmpeg movie module).
Clean up props/modes on lib/midi.py.
Undo unintended changes in r 2184.
Partial support for OSX sysfont... 10.5.x onwards. just use unix method.
Additions to font_test.py and sysfont.py.
[SVN 2165-2180] May 19, 2009
Minor doc corrections to midi example's output_main.
Add setmods script missing from r 2129.
Added -x on lib files... Should this be moved into the setup.py ?.
Make python -m pygame.docs bring up the docs in a browser. also fix Python
3 issues with executable packages.
Add gfxdraw docs.
Marked camera, gfxdraw, and scrap as experimental in the docs.
House_lo.mp3 crashes smpeg on Debian Linux. Remove from unit tests and add
MP3 warning to docs.
Finished midi docs.
Added the start of some midi tests... all stubs.
Updated generated docs.
[SVN 2163] May 18, 2009
Fix midi.py examples quit() bug.
[SVN 2154-2161] May 17, 2009
Added channel argument to note_on and note_off methods.
Fixing up spacing between functions.
Fix midi.py example init bug for --list option.
Fix midi channels changed default channel to 0 added to note_on and
set_instrument.
Starting to add docs in the pygame style to midi module.
[SVN 2126-2132] May 14, 2009
Add pygame.examples.go shortcut.
Add movieplayer example to the documents.
Some doc updates for test tags and python -m option.
Remove svn:executable tags and add setmods script to set executable
permissions.
Allowed the use of python -m pygame.tests.
[SVN 2117-2122] May 13, 2009
A little tag test with the examples.
Undo prop change in rev 2120 test.
[BUG] Fixed bug in font.c where pygame.font.Font returned the wrong
exception type and message when a font file was not found.
Thanks Bo Jangeborg.
[SVN 2113-2115] May 11, 2009
Fixed color.c for Symbian Updated Symbian build instructions Updated
makeref.py with '--no-code-docs' feature to set empty module docstrings.
Add _tags.py modules to pygame.tests. This is an alternative
module level __tags__ globals in the unit test _test.py files
themselves. The __tags__ global is placed in the corresponding
_tags.py file instead. This means test modules can be skipped
by the pygame.tests.go test framework without actually loading the
test module and running possibly problematic code. It also means
the test framework can report on which test modules were skipped
and why.
[SVN 2110-2112] May 10, 2009
Adapt run_tests.py test framework to Python 3.1.
Add automatic skip of unimplemented modules to run_tests.py framework.
Undo broken rev 2111.
[SVN 2103-2106] May 9, 2009
Minor fixes for symbian merge.
Merging from symbian branch.
[BUG] pygame.transform.threshold behaved incorrectly when passed a
Python long for the threshold argument.
[SVN 2078-2102] May 8, 2009
Starting to merge in sybian_s60 branch.
Pygame unit test framework now works with Python 3.1. This includes the
run_tests__tests submodule.
Increase timeout limit to 2 min. for run_tests.py subprocesses.
This allows surface_test.py more time to complete (timed out on
automated build sites Mac.)
All standard Pygame extension modules compile and run with Python 3.
For a Python 3 build setup.py skips unsupported modules.
[SVN 2074-2077] May 7, 2009
Just skip the scrap not-init test completely; Figure out how to test for
OS X later. scrap not properly supported on OS X anyway
Fix string comprehension bug in sndarray_test.py.
Try to allow scrap test in base_test.py on non-OS X platforms.
[SVN 2065-2073] May 06, 2009
Adapt fastevent module for Python 3.1.
OS X now passes tests. See if the problem in base_test.py is with scrap.
Allow all Python modules to install with Python 3.1, though some may not
work correctly.
Update python 3.1 README to reflect current status.
Adapt overlay for python 3.1; untested though importing doesn't crash
anything.
OS X problem with base_test.py isolated to scrap module. Try a temporary
workaround.
Adapt joystick and cdrom modules for Python 3.1.
Try again with OS X and base_test.py.
[SVN 2058-2064] May 05, 2009
Why does base_test.py fail on OS X?.
Yet more OS X testing with base_test.py.
More OS X testing of base_test.py.
Adapt mask module for Python 3.1.
Fix font.c problem with Python 3.1.
Undo accidental changes to Setup.in and __init__.py.
Add scroll.py example to Python 3.1 adapted programs.
[SVN 2055-2057] May 04, 2009
More code fixes to transform.c for non-MMX machines.
Clean up METH_NOARG functions which were accidently given a second C
argument in display.c.
Make scrap test in base_test.py conditional on the presence of scrap.
[SVN 2052] May 03, 2009
Fix compiler error in transform.c for non-MMX machines.
[SVN 2049-2050] May 02, 2009
Merging with python3 branch r 2048.
Port Python 3 specific files from python3 branch.
[SVN 2047] May 1, 2009
Merge python3 branch back into trunk. This allows a minimal Pygame
system to be built for Python 3. It also improves error checking
in module init functions.
[SVN 2046] Apr 30, 2009
[BUG] SDL_gfx used WIN32 macro instead of _WIN32 to detected Windows.
[SVN 2040] Apr 24, 2009
SDL_gfx module officially added to Pygame.
[SVN 2024] Apr 18, 2009
A quick fix for jpeg saving not checking color order in 24 bit surfaces
Note that there is a similar bug remaining in the camera module.
[SVN 2019] Apr 15, 2009
Merge src/__init__.py from python3 branch back into trunk.
[SVN 2009-2017] Apr 13, 2009
Add equality/inequality Event comparison as per mailing list request.
Patch from Sean Berry updating missing tests for Rects.
[SVN 1997] Apr 11, 2009
Make gfxdraw build on Windows.
[SVN 1993] Apr 06, 2009
Bmp gives out of memory error... so use png instead.
[SVN 1983-1985] Mar 30, 2009
Oops... hopefully this will work with mac/win.
Trying to move the source around to fix the compile bug...
Removing gfxdraw from compiling by default until get a chance to fix...
[SVN 1980-1982] Mar 29, 2009
Included a couple of files from SDL_gfx for the gfxdraw module.
Added some more documentation, and a TODO note to the top of the file.
A tool for finding out what is documented, and what isn't.
[SVN 1974-1976] Mar 26, 2009
Fixes gfxdraw.filled_polygon bug involving the point list.
More point list bug fixes.
[SVN 1973] Mar 25, 2009
Adds tentative SDL_gfx module.
[SVN 1969] Mar 24, 2009
Some minor comment corrections.
[SVN 1967] Mar 16, 2009
Yuv420 reimplemented with formulas from libv4l.
[SVN 1966] Mar 13, 2009
Re-add yuyv to rgb based on libv4l by Hans de Goede, licensed LGPL.
[SVN 1965] Mar 12, 2009
Licensing problems in the Camera module. Fixes the licensing for the
Bayer to RGB function. Removes YUYV to RGB and YUV420 to YUV and RGB
functions until they are properly licensed.
[SVN 1962] Mar 05, 2009
Fix bug that let the example scroll past the bottom.
[SVN 1960] Mar 03, 2009
Don't need aliens_bootstrap.py as far as I can see. Updated checks for
music module. Made README.txt instructions correct.
[SVN 1956-1957] Mar 01, 2009
Fixed some typos.
Started adding documentation for pygame.midi module.
[SVN 1954] Feb 25, 2009
Allowed holding down the mouse, or key to scroll.
[SVN 1940-1953] Feb 22, 2009
Add 8 bit-per-pixel support to Surface.blit blends.
Added Surface.scroll method along with the scroll.py example.
Added a runtime check for old unneeded files.
Made the error message nicer... and added checks for old py files too.
Removed debug print from warn_unwanted_files().
Add some comments, and a doc string to warn_unwanted_files.
Camera.init tries to detect correct platform camera module to use.
Added a few empty methods to opencv camera class that _camera uses.
Fixed dest_surf on opencv camera driver, added missing methods to vidcap
one.
[BUG]Made colorkey and blanket alpha blits handle a surface blit to self.
This addresses Bugzilla bug 19.
[SVN 1937] Feb 19, 2009
Add self-blit capacity to Pygame surfaces.
[SVN 1934] Feb 18, 2009
Surface raises a ValueError if the mask argument is rejected by SDL.
Before this the mangled, and invalid, SDL value was used.
[SVN 1931-1932] Feb 16, 2009
Fixed to work with new test file layout. Also imports modules if not
found.
Moved camera.c _camera.c . created a lib/camera.py.
[SVN 1928-1929] Feb 15, 2009
Made it use the pygame.examples.camera to test it. Filled in missing
methods.
Fix erroneous ALPHA_BLEND macro argument.
[SVN 1926-1927] Feb 14, 2009
Add psuedo-import to __init__.py atexit, required by pygame.base.
Remove an accidental colordict import introduced into __init__.py.
[SVN 1924-1925] Feb 12, 2009
Add Rect.copy method as per Bugzilla feature request 25.
Adding another import declaration for py2app/py2exe.
This makes using py2exe easy again.
[SVN 1922-1923] Feb 11, 2009
[BUG] Fix per-pixel-alpha unpacking in surface fill-blends.
[BUG] Fix 24 bit-per-pixel fill-blends.
BLEND_RGBA_xxx and more BLEND_xxx tests; related bug fixes (mostly 24 bit
surface related).
Fix per-pixel alpha bug involving pixel unpacking.
[SVN 1920] Feb 11, 2009
The Pygame documents and examples are now part of the Pygame package,
directories docs and examples respectively.
[SVN 1916] Feb 8, 2009
[BUG] Fix segmentation fault with register_quit, Bugzilla bug 20.
[SVN 1912] Feb 6, 2009
[BUG] Extension modules failed to raise an error when required modules
failed to import, as can happen with an incomplete py2exe/py2app
executable. This would later lead to mysterious segfaults. Extension
modules now forward import errors in the init function.
[SVN 1903] Feb 3, 2009
[BUG] _numpysurfarray.array_alpha() when a per-pixel alpha surface also
has blanket alpha.
[SVN 1893] Jan 29, 2009
[BUG] Documentation infers that mixer.init and mixer.pre_init have keyword
arguments. Added as per Bugzilla issue 6.
[BUG] Documentation states that mixer buffer sizes must be a power of 2.
New default buffer size is 4096. This was the implicit size anyway as
buffer size values were rounded up the the nearest power of 2.
[SVN 1888-1889] Jan 29, 2009
sound_array_demos.py now uses either NumPy or Numeric.
_numpysndarray.py bug fix submitted by Nicholas Dudfield.
[SVN 1886] Jan 28, 2009
Updated msys config to use a fake PORTTIME variable... so it builds again
with mingw.
[SVN 1881-1883] Jan 27, 2009
Add array_alpha and array_colorkey tests to surfarray_test.py.
array_alpha values incompatible with unmap_rgb for 16 bit surfaces -
fixed in _numpysurfarray.py, ignored in deprecated _numericsurfarray.c.
For 16 bit surfaces make surfarray.array_alpha values consistent with those
returned by Surface.unmap_rgb.
Revert unintended change to surface.rgb_map in rev 1875.
Surfarray tests for make_surface, map_array, pixels2d and pixels_alpha,
Finished surfarray_test.py.
[SVN 1880] Jan 26, 2009
Made it so we can use ctypes, instead of requiring win32 modules for the
windows test runner.
[SVN 1871-1879] Jan 25, 2009
Completing the process to actually have numpy be the default.
Make subprocesses mode default for test runner.
Small fix for the nosubprocess change.
Fix pygame.init() problem in surfarray_test.py.
Surface.unmap_rgb now METH_O.
Add surface.map_rgb unit test.
Add surfarray.array2d, array3d, pixels2d and pixels3d unit tests.
Make surfarray_test skip tests known to fail with Numeric.
Making mac build with portmidi lib linked in.
[SVN 1863-1870] Jan 24, 2009
Add array2d test to surfarray_test.py.
Move surfarray surface lock test to surfarray_test.py.
Surfarray.array3d unit test and 16 bitsize bug fix.
Surfarray get_arraytype, get_arraytypes and use_arraytype tests.
Edit tests module docs.
Another small tests doc typo.
Making it so we don't swallow exceptions...
[SVN 1854-1861] Jan 23, 2009
Making it so we won't try to re-enter application installation.
Fix VC compiler error and make small code tweaks.
Add blit_array test for surface shifts.
Surfarray_test does nothing if no array module installed.
Add array tags to tests requiring NumPy or Numeric.
Numpy now takes priority over Numeric in sndarry and surfarray.
Fixed __hasnumpy/__hasnumeric confusion in sndarray.
[SVN 1852] Jan 22, 2009
[BUG] Fix Bugzilla bug 24 where surfarray.blit_array fails with a
24 bit surface. A new blit_array, using the array structure interface,
was added to a new _arraysurfarray extension module.
[SVN 1849-1853] Jan 22, 2009
[BUG] Fix Bugzilla bug 24 where surfarray.blit_array fails with a
24 bit surface. A new blit_array, using the array structure interface,
was added to a new _arraysurfarray extension module.
Fix NumPy bug in arraydemo.py and add an array choice command line
arguemnt.
Removed PyObjC dependency on OSX.
[SVN 1845-1848] Jan 19, 2009
Make the main function consistent accross examples, taking arguments
where the programs except command line arguments.
Add examples module document page.
Minor change to usage message in test_runner.py.
Make some hyperlinks in the examples doc work.
The Pygame examples is now a Pygame subpackage. Example programs can be
imported as modules and run by their main functions. The package
documentation is now part of the Pygame module docs.
[SVN 1841-1843] Jan 16, 2009
Add pygame/tests/fixtures to installation (broken in previous setup.py
changes).
Add arguments to pygame.tests.run().
Add addition fake tests to installation.
[SVN 1839-1840] Jan 15, 2009
Color objects now support equality/inequality comparison with other
Color objects and color tuples.
Jpeg image saving is not thread safe on windows after all.
[SVN 1834-1838] Jan 14, 2009
Examples\midi.py: add list option and main() function.
Remove absolete Windows doc installer stuff.
Remove old default Windows setup info.
Fix porttime Setup.in change.
[SVN 1829-1833] Jan 13, 2009
Added argv arguments to main() too, and used pygame.quit.
Updated portmidi config for unix and darwin. tested on ubuntu, not osx.
Added libporttime dependency, as required by ubuntu.
Added get_device_info function.
Printed out device info. Allowed setting device id on the cmd line.
[SVN 1819-1827] Jan 12, 2009
Pygame docs: fixed some links.
Docs added to Pygame package.
Added __init__.py to make examples a package.
Examples can be run from outside the examples directory.
Corrects some terminology in the tests package doc.
Call pygame.quit to clean up things. closes window when called from
pygame.examples.chimp.main() finishes, and for when run from idle.
Update setup.py to reflect examples becoming a package.
Updated examples so that they all have a main() and use pygame.quit.
Pygame documents now installed as part of the pygame package directory.
[SVN 1816-1817] Jan 11, 2009
Pygame.tests: prepare run_tests__tests for addition.
Pygame.examples: completely installs.
[SVN 1813-1815] Jan 10, 2009
Pygame unit test suite is now the pygame.tests package. For Pygame
development the unit tests still run from test in the installation
directory without conflicts.
[SVN 1802-1804] Jan 07, 2009
Refactored midi.py example and added comments.
Finished midi.py keyboard example, added velocity.
Added test command to setup.py. so you can do 'python setup.py test'.
[SVN 1796-1798] Jan 05, 2009
Mask convolve function and tests from Michael George.
Update docs for pygame.mixer.music.load: thanks Forrest Voight.
Clean up some carriage return confusion in the docs.
[SVN 1793-1794] Jan 04, 2009
Update midi example to add animated keyboard keys.
Add scripts to build Python 2.6/3.0 Windows dependencies linked to msvcr90.
[SVN 1776-1777] Dec 27, 2008
Add get default device functions for midi module.
Expand midi output example into a musical keyboard demo.
[SVN 1772-1775] Dec 24, 2008
Pypm: temporary Setup.in fix to add header and library paths for Windows
prebuilt.
Added Output class and atexit stuff similar to Lenards code.
Added output example from Lenard, and moved input example out of midi
module into the midi example.
[SVN 1764-1771] Dec 23, 2008
Windows prebuilts: Python 2.6 preparation.
Added pygame.mixer_music fake import in function to maybe help with py2app.
Undo fake import for py2app.
Try rearranging stuff for py2app.
Add portmidi to Windows build.
Added code from pyportmidi to be used from pygame.midi.
Added pyportmidi 0.0.4 changes from Tim Thompson. Thanks!.
[SVN 1759-1760] Dec 22, 2008
The freetype dll was not being copied into the site-packages/pygame dir on
windows.
Added start of midi module which uses portmidi.
[SVN 1755-1758] Dec 19, 2008
Added in an extra debugging line... for testing with py2app.
Fixed error for msvc compiler.
Moved brackets closer... suspecting possible dodgey introspection in
py2app.
Missed freeing surface on malloc out of memory error for saving jpegs.
[SVN 1751-1754] Dec 18, 2008
Added some debugging notes for py2app mixer_music issue.
Msys_build_deps.py: added portmidi.
Setup_Win.in: add portmidi.
[SVN 1749-1750] Dec 17, 2008
Add program to list Pygame modules accessed by a unit test module.
[BUG] Bug 28: possible fix.
Dec 05, 2008
exposed mask C API from Michael George. Thanks!
Aug 30, 2008
[BUG] Fixed CREATE_PIXEL macro's use of Aloss
which was making surface.fill with surfaces with no alpha go green
release_1_8_1release
[SVN 1537] Jul 28, 2008
pygame 1.8.1release released.
Jul 18, 2008
Added Surface.set_masks and .set_shifts useful for using data in
b,g,r,a mode... and other fun hacks.
Jul 14, 2008
[BUG] Fixed bug with transform.threshold() not honoring third surface
Updated transform.threshold() docs Thanks Nirav Patel
Jul 10, 2008
Added patch for filelikes in mixer.music.load thanks Forrest Voight!
Jul 8, 2008
run_tests.py improved with --help and running stuff in subprocesses.
Jun 25, 2008
Added many extra empty test stubs for untested things. Thanks Nicholas!
Test runner that works with subprocess and threads to isolate tests.
So that if a crash happens in one test the other tests still run.
Thanks Nicholas!
[BUG] Added a fix for rotate on multiples of 90.0000001-90.99999 degrees.
Thanks Charlie Nolan, and Marcus!
Jun 21, 2008
Added BLEND_RGBA_* special flags for blit, and fill.
Jun 16, 2008
Reworked locking code. Locks are now more strict and can only be
removed by the object(s), that caused them.
New Surface.get_locks() method, which returns the currently existing
locks.
[BUG] Fixed Surface.get_locked() bug for Surfaces which do not
require locking, but have third-party locks attached.
Jun 13, 2008
[BUG] Fixed bug with mixer.get_init() Thanks Frankie Robertson!
[BUG] Fixed long alpha overflow bug in Surface.set_alpha().
Jun 9, 2008
[BUG] Fixed locking and reference count leaks in Numeric surfarray
implementation.
May 31, 2008
Updated sprite documentation - mainly for new stuff added in pygame 1.8.0
May 24, 2008
New Color class for color management.
Apr 30, 2008
updates to the sprite.py collision functions that update them to match
the modules coding style, include appropriate comments, and are
about 20% faster. It also includes a collide_circle_ratio function
for completeness, and perhaps most importantly, fixes a bug in
colide_mask which kept it from working correctly. Also added unittests
for the collision functions. Thanks John Krukoff!
[BUG] sound crackles on windows; restored chunk size
calculation to pre 1143
Added \#!/usr/bin/env python to the top of examples that didn't have it.
Apr 13, 2008
[BUG] Fixed pygame.surfarray.pixels3d() for 24bpp surfaces using numpy.
Thanks Lorenz Quack!
Apr 12, 2008
[BUG] Fixed png saving, and saving jpeg with capital letter extensions
Thanks Nick Irvine!
Apr 11, 2008
New PixelArray.compare() method to compare two PixelArrays.
Apr 8, 2008
[BUG] Fixed pygame.draw.aaline() for cases in which only a single point
has to be drawn.
Apr 4, 2008
New PixelArray.replace() and PixelArray.extract() methods to quickly
replace or extract a certain color.
Apr 3, 2008
Added iter support to PixelArray.
Apr 2, 2008
[BUG] Fixed mask settings for 8-bit surfaces created by
surfarray.make_surface()
[BUG] Fixed integer color value assignment bound checking in PixelArray.
Mar 30, 2008
Added subscript support to PixelArray and PixelArray.make_surface()
to create a new surface from the PixelArray view.
Fixed mask namespace pollution and docs.
release_1_8_0release
Mar 18, 2008
Updated credits.
Mac OSX binary now has movie module working.
1.8.0rc5
Mar 16, 2008
the play functions of mixer.Channel and mixer.Sound both now take keyword
arguments, and accept a fade_ms argument that makes the sound fade in
Mar 9, 2008
pygame.display.set_mode() will now respect the screen resolution settings
for the width or height set to 0 as supported by SDL >= 1.2.10.
Thanks Lorenz Quack!
Mar 5, 2008
[BUG] Stopped releasing GIL on png, and jpeg saving functions because
they do not seem to be thread safe.
[BUG] A work around for 8 bit samples being stereo reversed with SDL_mixer.
Also check the return value of Mix_SetPanning, and raise an
error on volume errors.
[BUG] Changed default chunk size for pygame.mixer to 1024*3. Which is
the magic number which stops scratchy sounds on most systems.
However it does make sounds a bit laggier... it's best provided as
a config item for users.
Updated pygame.display.update() to release the GIL whilst doing things,
so other threads can do things whilst it's updating the screen.
Some comments to help Mac OSX people installing, and compiling pygame.
About bdist_mpkg in setup, and also fixed an exception message
to be nicer about requiring pyobjc.
Mar 3, 2008
[BUG] Fixed up pygame.mask.from_surface, got color key, and perpixel alpha
modes reversed.
Also added better test to the mask test.
Also it wasn't testing pygame.mask.from_surface at all!
Added pygame.sprite.collide_mask to join the mask_* collision functions.
Started adding test for pygame.sprite.spritecollide.
Feb 19, 2008
Added Surface.get_bounding_rect() method, which returns the smallest
rect for the surface, that contains visible (non-transparent) data.
Feb 14, 2008
Updated constants GL_SWAP_CONTROL,GL_ACCELERATED_VISUAL,BUTTON_X1,BUTTON_X2
Added pygame.key.get_repeat to see how holding keys down repeats. This is
the sister function of pygame.ket.set_repeat.
MacOSX, and Windows binaries now use latest SDL 1.2.13
Feb 11, 2008
An example of using pygame with no windowing system. Useful for webserver
scripts, or for little utilities.
Updated mac_scrap to pass some tests, and raise NotImplementedError
otherwise.
Further Windows build updates:
For MinGW/MSYS the build process now finds the MSYS and MinGW
directories automatically. gcc links to msvcr71.dll without
requiring changes to the gcc specs file. This makes the build
process GCC Version 4 ready. By default all DLLs are Win32 GUI,
but can be console. The build progams will run from either the
Windows or MSYS terminal.
Fixed a bug where DLLs were not installed in the package directory.
For Windows, everything now goes into the package directory.
build_deps.py renamed to msys_build_deps.py to avoid confusion.
Jan 26, 2008
pygame.sndarray noew can change between Numeric and numpy using the
new methods pygame.sndarray.use_arraytype () and
pygame.sndarray.get_arraytypes ().
Jan 24, 2008
Updated the configuration and build process under Windows. In
config_msys.py and config.py os.popen is replaced with the newer
subprocess.Popen so the MSYS will run. Calls to raw_input now
show the prompt on an MSYS console. In an MSYS build paths
written to Setup are now Windows paths for distutils. The hard
coded DLL file paths have been removed from setup.py. It now
gets the paths from Setup. Consequently, setup.py is now VC/MinGW
agnostic.
Added build_deps.py, an all-in-one dependency builder for
Windows. Requires MinGW and MSYS.
Jan 8, 2008
pygame.surfarray now can change between Numeric and numpy using the
new methods pygame.surfarray.use_arraytype () and
pygame.surfarray.get_arraytypes ().
Jan 4, 2008
Removed Numeric compile time dependency.
Added numpy surface array support.
Dec 31, 2007
New method pygame.get_sdl_byteorder () to get the SDL byte order.
Dec 15, 2007
Mask can now get bounding rects of set bits.
pygame.transform can find edges in an image, get the average surface
of many surfaces and also threshold an image by color.
Sep 1, 2007
Added get_buffer() methods to Surface, and Sound - which return a new
BufferProxy - which is a buffer interface only class. Thanks Marcus!
Aug 23, 2007
pygame.image.tostring changes from Brian Fisher.
RGBA_PREMULT & ARGB_PREMULT type to image.tostring (a very
nice thing for getting images into OpenGL)
Aug 22, 2007
PixelArray from Marcus. It's going to be a replacement for surfarray.
[BUG] Fixed some bugs in Surface with SRCALPHA and input validation.
Thanks Lenard Lindstrom and Brian Fisher.
Aug 15, 2007
The sprite module has had some big changes from DR0ID. It now has a
LayeredUpdates, and LayeredDirty groups. For using layers when
rendering the sprites. LayeredDirty is an alternative to
RenderUpdates that automatically finds the best display method
(either full screen updates, or dirty rect updates). It's faster
if you have sprites that don't move. Thanks DR0ID!
Added pygame.mask.from_surface which can make a Mask object from
a surface. It's 128x faster than the python version!
pygame.movie bug fix. Thanks Lenard Lindstrom!
Jun 25, 2007
Removed QNX support from scrap module. Thanks Marcus!
Added smoothscale(with MMX!) function from Richard Goedeken
Jun 27, 2007
Fixes from Marcus for ref counting bugs.
Also using METH_NOARGS for functions with no arguments.
Which should make some functions slightly faster.
Thanks Marcus, and thanks Campbell Barton for spotting them.
May 30, 2007
Fixed some documentation. mask, scrap, font modules.
Fixed the mask.set_at get_at functions to raise a nice exception.
Thanks piman!
surface.fill() now takes the same BLEND_ADD BLEND_SUB etc flags that
surface.blit() takes. Which makes fade to white, and fade to black
type operates simple and fast. Thanks Marcus!!
Added the GL_SWAP_CONTROL constant from SDL. Thanks Eyal Lotem!
Added the new blitters from Marcus. These speed up the blend functions
and the alpha blit function.
Added a -warnings flag to setup.py for extra warnings with gcc.
A fix from Marcus for the scrap module in X11.
May 9, 2007
Windows image copy/paste is working for scrap.
Adding bitmask code from Ulf Ekström - for pixelperfect collision.
Still need to get unittest, documentation and some more methods added.
There's a unittest with some problems checked in.
May 2, 2007
[BUG] fromstring,tostring work for alpha. Thanks Brian Fisher.
[BUG] Surf.set_clip(None) works correctly. Thanks Diego Essaya.
Scrap changes from Marcus so windows/osx compile.
Added scancode attribute to keyboard events. Thanks Quentin Smith.
[BUG] movie_set_display hangs on movie file-like object. Thanks Martin.
Apr 26, 2007
Some code cleanups from Marcus von Appen. min->MIN, indentation, other.
A rewritten scrap module. Hasn't been tested on osx/windows.
Dec 15, 2006
Some config changes to make scrap compile correctly on freebsd and debian.
Nov 27, 2006
Fixes scrap, image, overlay, compiling on windows. Thanks John Popplewell!
Allowed threads within the transform module. Releasing GIL around C stuff.
Nov 5, 2006
Fix for SysFont infinite loop bug. Thanks Regis Desgroppes!
Compilation fix on MacOSX. Thanks Emmanuel Hainry!
Nov 4, 2006
Documentation fixes.
Jun 16, 2006
Allowed passing in the destination surface to the transform.scale and
transform.scale2x. This is faster if reusing the surface.
Jun 15, 2006
[BUG] Font fix for empty string causing segfault. Added unittest.
Jun 10, 2006
64bit compile fixes for Fedora from Christopher Stone
Jun 8, 2006
Documentation changes.
Move to subversion instead of cvs.
May 28, 2006
Added saving surfaces as a .jpg or .jpeg file. Works if imageext is there.
May 27, 2006
Added saving surfaces as a .png file. Works if imageext is there.
Saves as 24 bit RGB or as 32bit RGBA pngs depending on the surface.
May 20, 2006
Documentation updates merged in from some doc comments on website.
[BUG] pygame.transform.* functions now retain SRCALPHA info after scaling.
Some new unittests for pygame.display.update, pygame.transform.scale.
May 18, 2006
Patch from Peter Nicolai to add the channel to the sound queued event.
April 25, 2006
Added some new blend modes to blit. Add,sub,mult,max,min.
[BUG] Fixed SRCALPHA blending. Thanks Lenard Lindstrom!
April 9, 2006
Added mac_scrap module for macintosh clipboard support.
April 8, 2006
Added scrap module for accessing the clipboard. As well as an example.
Added access to the XEvent structure on unix/X11 installs.
March 11, 2006
Fix for config_unix for x86_64 and SDL lib path. Thanks Matthew L Daniel.
[BUG]Fix for parent init in sprite.GroupSingle. Thanks Alexander Sashnov.
March 1, 2006
A cursors.py example from Kamilche. Thanks!
February 11, 2006
Changed the behaviour of Clock.tick to use SDL_Delay instead of a busy
loop. Added a tick_busy_loop which uses the old behaviour. This
is more consistent with what people think Clock.tick() will do.
That is, not use 100% cpu to get more accurate timing.
testsprite.py example, which is based off the testsprite.c in SDL
shows the performance of sprites, and is a good test.
Added gp2x package which contains some constants for the gp2x buttons.
This will be where gp2x specific functionality will live.
January 12, 2006
Endian patch for set_at() from Ivo Danihelka.
December 19, 2005
Updates for Overlay. Detect hardware accel and allow "redisplay".
November 7, 2005
Fix for sprite.AbstractGroup.has inf recursion bug. thanks Randy Kaelber.
Began work on a sprite unittest.
October 28, 2005
fix for do_set_icon when display not initialised. Thanks John Popplewell!
Added missing read_unix_fonts_cache function. Thanks again John Popplewell.
October 24, 2005
Add support for 64bit data types in surfarray.blit_array()
October 2, 2005
switch to the new reference documentation system
September 8, 2005
surface.array_colorkey now unlocks the surface after use[BUG].
September 1, 2005
music.queue() now raises exception if load fails.
release_1_7_1release
August 15, 2005
Fix to make Chinese fonts work better on windows.
From retsyo AT eyou Dot com.
Fix for Channel.set_volume() to not use panning if seting overall volume.
Made setup put in missing files into the source distribution.
Fix for fastevents example on linux.
August 10, 2005
Fix for overlay.c to compile in windows.
Fixed some warnings for font, and rotozoom with gcc4.
Added an example for fastevents.
Fix for config_unix.py with wrong paths for /usr/local
July 28, 2005
Fix for sprite module[BUG]. fastevent module for faster sdl event processing.
Updated examples.
March 7, 2005
sysfont patch, which checks two places for fonts on weird windows machines from Atul Varma.
pygame.get_sdl_version(), improved Mac OS X support from Bob Ippolito.
new sound_array.py example from Rene Dudfield based on ShreadWheats example.
August 8, 2004
cleanup aaline drawing, from Michael Urman
July 17, 2004
image.frombuffer() for lightning fast fromstring()'s
SysFont extra styles being applied incorrect
psuedo "configure" and "Makefile" for foolproof installs
draw.aaline now works with pixel alphas
July 16, 2004
mixer.set_num_channels() no longer crashes [BUG]
mixer.music.get_pos() properly tracks when paused
pygame.display.get_wm_info() added, gets a dictionary
Overlay object, from Dmitry Borisov
July 6, 2004
Sound object newstyle types
added Sound.get_length()
July 5, 2004
Add Bo Jangeborg's cursor compile with added 'xor'
Add Bo Jangeborg's system cursors as compileable strings
July 3, 2004
Newstyle fonts crashing with bad filenames [BUG]
June 28, 2004
Surface.set_clip(None) crashed [BUG]
Remove pygame's (now) redundant lock counting
June 27, 2004
Fix several negative or zero size problems [BUG]
draw.arc outside image crashed [BUG]
draw.arc artifacts cleaned
June 26, 2004
Rect.fit() added
Surface.get_rect() accepts keyword args for assignment
transform.chop() added, from Matthias Spiller
June 25, 2004
Font becomes new style type, inheritable, weakrefable
June 22, 2004
Rect type updated, weakrefable
(warning, Rect attributes broken for now)
June 21, 2004
Surfaces now weakref'able
display surface protected from pygame.quit()
display and Surfaces protected from resolution <=0
June 19, 2004
Chad Lester's excellent work on sndarray
ffmpeg movie backend renamed to movieext, experimental
v1.6 movie module restored
May 1, 2004
updated sprite module, Joe Wresching
March 29, 2004
checkin movie current rewrite, still rough, libavcodec
February 24, 2004
no longer parachute SIGPIPE, like SDL 1.2.7
February 15, 2004
small cleanups to internal Sprite and Group
February 9, 2004
help protect int overflow
December 25, 2003
sprite groups are now iterators
SysFont better unix parsing
November 18, 2003
Remove legacy python code. Ver 2.2 is minimum
pygame-16
October 23, 2003
final updates for 1.6
October 15, 2003
Rects now stored with ints (not shorts)
October 2, 2003
Add ARGB support to fromstring and tostring
September 29, 2003
Replaced Objective C with PyObjC code for MacOS X
Fixed 1 pixel horizontal/vertical line draw
September 27, 2003
Fix reading from file file-like objects (thx Timothy Stranex)
September 21, 2003
Fix sysfont registry bug on winNT arch
September 18, 2003
Fix color problem when saving opengl screenshot
September 10, 2003
SysFont now accepts None like regular Font
August 10, 2003
fix JOYHAT_RIGHT input (thanks Latimerius)
system font names have punctuation removed
July 26, 2003
add GL_STEREO
July 22, 2003
add GL_MULTISAMPLEBUFFERS and GL_MULTISAMPLESAMPLES
June 11, 2003
Surface.set_at() respects clip area
cleaned fill circle draw
June 8, 2003
add system font; SysFont,get_system_fonts,match_system_font
June 7, 2003
Font() no longer segfaults on bad filename [BUG]
add color module for simple color manipulations
June 6, 2003
set_palette_at() index 0 fix
draw.arc() (thanks Lalo Martins)
Rects are pickleable
May 12, 2003
Brett Calcott's quick fix for 'trunc' on visualc
May 10, 2003
fix Derek Simkowiak's find of problem alphas
March 10, 2003
add OPENGL support to image.tostring()
March 9, 2003
Bug in Clock.tick() was delaying double
load Font objects from any python file-like object
February 26, 2003
Sprite and Group now new-style classes
Februrary 12, 2003
fix immediate returns for first time.delay and time.wait
February 11, 2003
more OSX SDLmain.m patches from Andrew Straw
February 5, 2003
antialiased lines, from Jorge Gonzalez
allow Font.render() with empty string
February 2, 2003
refcount bug in Font.size [BUG]
December 5, 2002
tilerow stuff removed
December 2, 2002
experimental pygame.draw.tilerow()
November 14, 2002
fix unicode bugs in Font (thanks, hcyun)
November 12, 2002
AdvanceMAME Scale2X scaling now in transform.scale2x()
October 22, 2002
mixer can queue sounds and music
channels can send finished event for sounds
October 19, 2002
can free software surfaces without video initialized
added "x", "y", "w", and "h" attribs to Rect (like SDL)
RenderUpdates.draw() doesn't union nonoverlapping
October 16, 2002
fix crash with subsubsurface blits [BUG]
added Surface.get_offset() and get_abs_offset()
added Surface.get_parent() and get_abs_parent()
October 6, 2002
added event.clear() to efficiently clear the queue
October 1, 2002
sprite.RenderGroups wasn't clearing killed sprites after draw()
September 3, 2002
passing None as the end time to CD.play() plays to cd end
added pygame.vernum, a tuple of python version values
September 2, 2002
add Movie.render_frame, thanks James Mazer
cursors.load_xbm skips comments, thanks Herve
August 20, 2002
fix rectstyle arguments
August 15, 2002
Hervé Cauwelier's fix for xbm cursors without spaces
Auguest 14, 2002
switched to FSF's FreeSansBold default font
new font.get_default_font()
cleanup harmless void** typing
July 24, 2002
Ole Martin Bjoerndalen's CD.play fix
July 17, 2002
Michael Hudson's unicode cleanups
June 15, 2002
added get_time() and get_rawtime() to Clock
pygame-15
May 30, 2002
final updates for 1.5
May 28, 2002
changed default font to helmet bold
May 27, 2002
added smart class to handle missing modules
May 17, 2002
added display.set_gamma_ramp(). thx andrew
May 16, 2002
custom blitters to handle destination pixel alphas
fix recursive subsurfaces and subsurface blit returns
May 13, 2002
fixed CD.play()
May 8, 2002
music.play() start time works
image.save() can save TGA images
cannot subsurface a subsurface [BREAK]
blits to subsurfaces are passed through
May 7, 2002
added the sndarray module
added surfarray.make_surface()
April 25, 2002
added gl_set_attribute(), gl_get_attribute()
April 16, 2002
mixer keeps a reference to playing Sound objects
channel.set_volume() can take 2 volumes for panning
music.play() can take a starting position for the song
April 14, 2002
bug when re-initializing pygame.display [BUG]
April 8, 2002
rectstyle now includes any object with a "rect" attrib
rects now have collidedict() and collidedictall()
March 27, 2002
fixes for windows music.get_pos() and windows config
March 23, 2002
big config.py update
music.get_pos() (thx Michael Urman)
March 20, 2002
sprite.spritecollideany() now works as described
March 4, 2002
sprite.RenderClear can accept a function as bgd
February 19, 2002
event.peek() returns next event [BREAK?]
Event objects have 'truth' operator
February 13, 2002
all draw primitives have a default width
February 11, 2002
Rect unionall() and unionall_ip() fixed
February 10, 2002
pygame.init() not required for proper cleanup [BUG]
CD.play() fixed for tracks above 0
February 8, 2002
Rect and Surface subclassable types
February 1, 2002
locking problem with 90 degree rotate [BUG]
set_icon overrides default icon
January 31, 2002
removed emberrasing debug printing
draw.rect does inside edge for bottomright
pygame-14
January 29, 2002
everything bumped for the 1.4 release
January 28, 2002
update SDL_rotozoom to 2.0.3
January 26, 2002
special cases for 90 degree transform.rotate()
OSX cleanups for commandline (thanks Bob)
added sprite.spritecollideany()
January 23, 2002
transform.rotate() does alpha if image has alphaplane
transform.rotate() no longer "off by one" in the x axis
added CD.get_all() to get information for all tracks
CD.play() can now take an option start and end time
January 17, 2002
smarter importing code
default pygame icon for window
January 16, 2002
started implementing basic unit tests
several bug cleanups with Rects (thx unit tests)
January 14, 2002
display.update() boundaries fixed
January 11, 2002
Surface.set_clip() can take None to clear the clipping
January 7, 2002
fixed sprite.Group.has
January 6, 2002
Merge with bob's inital MacOSX changes
January 5, 2002
new and upgraded importing [BREAK?]
fixed numberhandling in set_alpha and set_colorkey
January 2, 2002
Group add/remove methods work
December 31, 2001
pygame parachute does tracebacks with python2.2
December 20, 2001
Surface.set_alpha() and set_colorkey() accept None
event.set_allowed() and set_blocked() accept None
pygame-13
December 17, 2001
small preps for the full 1.3 release
December 15, 2001
small changes to sprite before release
December 2, 2001
small protection for display Surfaces after display.quit()
December 1, 2001
made time.delay() more accurate [BREAK]
created time.wait() to work like old delay()
added time.Clock objects for framerate tracking
November 26, 2001
Surface.convert() doesn't segfault before pygame.init()
November 20, 2001
added pygame.sprite.Group.update()
Surface.blit() protection for alpha->8bit relaxed
November 19, 2001
fixed image.fromstring() for "RGBA" mode
November 18, 2001
can stream python file-like objects to SDL threads
November 15, 2001
cleanups for transform.rotate
November 13, 2001
added sprite module
November 12, 2001
image.tostring() "RGBA" works with colorkey
November 3, 2001
filled shape drawing now clips properly [BUG]
Rect object correctly compare (==,<,>)
November 2, 2001
pygame.time.get_ticks() returns 0 before pygame.init()
October 22, 2001
small fix for filled ellipses/circles
September 27, 2001
drawing filled circles returns bounding rect
ellipses and circles drawn inside given area
mixer init can take chunksize
fix in clipped horizontal line drawing [BUG]
September 26, 2001
key.set_repeat() raises exception on error, smarter args
September 22, 2001
added Rect.clamp_ip, for inplace clamping
display.update(None) will update full screen
September 21, 2001
Surface.convert() respects the SRCALPHA flag when passing depth
pygame-12
September 1, 2001
fixed typo in pygame.cursor
Aug 30, 2001
added VIDEOEXPOSE event
Aug 29, 2001
changed initializations, to allow easier embedding
Aug 28, 2001
added circle and rect convenciences to pygame.draw
removed debug printing from draw.polygon
Aug 25, 2001
added looping, scaling, and audio to for Movies
Aug 15, 2001
added pygame.movie module with MPEG video playback
July 31, 2001
fixed mixer.music refcount
July 26, 2001
custom events work with event.peek() and event.get()
added event.get_blocked() function to query blocked types
July 23, 2001
music specifically halted when quitting (should not matter?)
mixer.get_init() now returns the initialized playback format
July 21, 2001
all events can be posted, not just USEREVENT
subsurfaces inherit colorkey and alpha settings
Jul 20, 2001
default font "finding" is smarter
Jul 17, 2001
added polygon() and ellipse() to pygame.draw
lines with width>2 are now correct (was one too small)
Jul 16, 2001
can work with software surfaces before pygame.init()
Surface.convert() now can take arguments like pygame.Surface()
pygame.display.set_icon() sets the windowmanager icon
Jul 15, 2001
fixed bad internal display reference counting [BUG]
Jul 14, 2001
still makes clean-ish exit if segfault in exit handling
Jul 10, 2001
image.tostring makes alpha from colorkey, if asking for RGBA
Jul 6, 2001
added python 1.5.2 compatability
June 25, 2001
horizontal transform.flip() was reading pixels off by one [BUG]
June 24, 2001
calling set_mode will change all references to the display surface
pygame-11
Jun 23, 2001
removed smooth underline font render protection
Jun 19, 2001
fixed botched image.save() function
Jun 15, 2001
new inplace Rect calls: move_ip, union_ip, etc
Jun 11, 2001
smarter locking with subsurfaces
added transform.rotozoom(), which uses builtin SDL_rotozoom
May 31, 2001
correctly handle unicode filenames
May 29, 2001
set display physical palette with display.set_palette()
added transform module (with rotate and scale)
May 26, 2001
code compiles with macos now
May 23, 2001
fixed line drawing of width 1
draw.lines() was broken with sections outside clip
May 22, 2001
added midleft, midright, midtop, and midbottom to Rect
added Rect.unionall() function to union a list of Rects
fixed problem in 16bit surfarrays
new image.tostring() and image.fromstring()
May 20, 2001
applied dave wallace's patch to fix memory freeing
May 17, 2001
a few small compile time warning cleanups
May 16, 2001
line drawing functions now use an optional width
May 15, 2001
image module is now builtin, but formats are optional
enhanced save function in image (handles opengl)
Surface.save is now depracated
May 14, 2001
smarter internal module handling
fixed blit() (broken on May 9th change)
May 10, 2001
USEREVENT events now pass through the queue
Event() may be called with keyword args and/or a dict
Font.render() won't render underlines while smoothing [BUG]
May 9, 2001
8bit subsurfaces inherit their parents colormap
blit keeps SDL from crashing with alpha onto 8bit
Apr 30, 2001
loading Sounds from python objects now works [BUG]
loading from python objects now thread safe [BUG]
Apr 19, 2001
applied Niki Spahiev's memory leak patch in event.c
removed minor memleak from each module's init
Apr 18, 2001
added opengl support (with example)
fixed display.get_init()
current music is free'd when mixer is quit
better thread sharing in various video calls
fixed GCC compiler error in constants.c
Apr 10, 2001
mixer now uses the requested sample format/size
Apr 08, 2001
properly free SDL objects on malloc errors
fixed rectangle cropping in pygame.display.update()
pygame-10
Apr 05, 2001
Everything set for the 1.0 release
Apr 04, 2001
cursors.load_xbm work on images without hotspots
Apr 03, 2001
swapped endian-ness for pixels_alpha()
Mar 29, 2001
fixed key.set_mods() (thanks rubysdl)
rework setup scripts for 1.0 release
relaxed sdl version checking
Mar 21, 2001
initial support for compiling on mac
fixed odd case with locking subsurfaces
Mar 20, 2001
font and mixer now properly auto quit()
Mar 19, 2001
Surfaces won't crash after display module is quit [BUG]
Mar 18, 2001
friendlier type casting in surfarray (for some compilers)
removed non-ANSI C code
Mar 17, 2001
pygame.Surface is smarter with SRCALPHA flag
fixed several small bugs in surfarray [BUG]
new surfarray example and tutorial
Mar 16, 2001
Fixed memory leak in Rect constructor
Fixed improper exception in display.update(with_4_args)
Feb 15, 2001
calling Sound.play() will make sure the channel
that gets selected has volume set to full
Feb 14, 2001
fixed Surface.set_colorkey() with no args [BUG]
Feb 13, 2001
fixed return rect from line drawing routines
small fix when drawing horizontal lines
pygame-09
Feb 12, 2001
added NOFRAME to pygame.constants
Feb 11, 2001
workaround python parsing error for pygame.time.delay(-1)
Feb 9, 2001
setting rectangle width/height/size changes the
right/bottom edges (instead of top/right) [BREAK]
Feb 6, 2001
fixed the music unpause() function
Jan 31, 2001
functions taking RGBA colors can also accept mapped ints
Jan 30, 2001
added draw.lines()
Jan 29, 2001
extremely revamped surface locking mechnisms
new Surface.subsurface for shared surfaces
Jan 25, 2001
added the draw module, with clipped line function
added alpha routines in surfarray module
more locking checks for surfarray
make extra sure all of SDL is shutdown properly
Jan 24, 2001
funcs that need locked surfaces will temporarily lock them
(Surface.set_at, Surface.get_at, surfarray.arrayXd)
Jan 23, 2001
display.update() no longer effects input Rects [BREAK]
Surface.fill() no longer effects input Rect [BREAK]
small memory leak in display.update() fixed
Jan 18, 2001
cursor.read_xbm() renamed to cursor.load_xbm() [BREAK]
Jan 17, 2001
documentation updated to include python modules too
Jan 16, 2001
cursors module beefed up
Jan 15, 2001
fix Surface.get_at() for 24bit surfaces
endian cleanups for surfarray
Jan 8, 2001
more warning cleanups
music-finished callback fixed
replaces SDL's parachute with smarter python version
Jan 6, 2001
added pygame.version module
pygame-05
Jan 6, 2001
Final cleanups for the new release
Jan 4, 2001
Surface.blit() allows for rects as dest position
surfarray cleanups and improvements
Dec 22, 2000
timer threads properly shutdown
Dec 14, 2000
display.set_mode pretending shorts are ints [BUG]
pygame-04
Dec 14, 2000
music module had incorrect names for volume functions
chimp example and full tutorial added
Dec 13, 2000
display.update() is entirely better in many ways [BUG]
Dec 3, 2000
fixed timing issues. negative time.delay() will become 0
Nov 30, 2000
UserRect module added
all objects now have a matching type; SurfaceType, etc
Nov 29, 2000
joystick module rewrite finished [BREAK]
cdrom module rewrite finished [BREAK]
all constructors using capitalized function names [BREAK]
(Rect, pygame.Surface, pygame.font.Font, etc)
Nov 28, 2000
Surface.convert() better handles surface flags
All color arguments (and returns) are RGBA format [BREAK]
Removed Surface.map_rgba and unmap_rgba [BREAK]
Added a default font, used by passing None as font file
pygame-03
Nov 20, 2000
Added Surface.save() to create BMPs.
Nov 16, 2000
Surface.set_clip() fixed when passing no args [BUG]
Nov 15, 2000
time.set_timer() now handles multiple timers
rect(), surface(), event() renamed to \
new_rect, new_surface(), new_event() [BREAK]
all new_XX() functions were added to pygame.locals
Moved pygame.music to a member of pygame.mixer [BREAK]
Surface.blit takes a source rectangle instead of pos, size [BREAK]
pygame.display.set_clip() correctly accepts rectstyle arg [BUG]
Added Surface.get_flags() and Surface.get_pitch()
Added set_cursor and get_cursor to pygame.mouse
New module, pygame.cursors, contains sample cursors
Nov 14, 2000
Release the Python Global Interpreter Lock on delays and IO
Added timer events to pygame.time (check vgrade example)
New music playback finished events
surfarray.blit_array() supports all bit depths
Nov 11, 2000
pygame.display.set_mode() uses int, not short, for size [BUG]
Nov 10, 2000
Committed to CVS
Added pygame.display.get_driver()
pygame-1.9.1release/setup_win_common.py 0000644 0001750 0001750 00000002032 11112371675 020203 0 ustar vincent vincent # -*- encoding: utf-8 -*-
# module setup_win_common.py
"""A module for reading the information common to all Windows setups.
Exports read and get_definitions.
"""
path = 'Setup_Win_Common.in'
class Definition(object):
def __init__(self, name, value):
self.name = name
self.value = value
def read():
"""Return the contents of the Windows Common Setup as a string"""
setup_in = open(path)
try:
return setup_in.read()
finally:
setup_in.close()
def get_definitions():
"""Return a list of definitions in the Windows Common Setup
Each macro definition object has a 'name' and 'value' attribute.
"""
import re
setup_in = open(path)
try:
deps = []
match = re.compile(r'([a-zA-Z0-9_]+) += +(.+)$').match
for line in setup_in:
m = match(line)
if m is not None:
deps.append(Definition(m.group(1), m.group(2)))
return deps
finally:
setup_in.close()
__all__= ['read', 'get_dependencies']
pygame-1.9.1release/Setup_Win_Common.in 0000644 0001750 0001750 00000000106 11112371675 020021 0 ustar vincent vincent # Windows specific flags for Pygame modules.
SCRAP = -luser32 -lgdi32
pygame-1.9.1release/Setup_Darwin.in 0000644 0001750 0001750 00000000150 11136037612 017173 0 ustar vincent vincent #This file defines platform specific modules for mac os x
sdlmain_osx src/sdlmain_osx.m $(SDL) $(DEBUG)
pygame-1.9.1release/setup.py 0000644 0001750 0001750 00000046674 11236512106 015773 0 ustar vincent vincent #!/usr/bin/env python
#
# This is the distutils setup script for pygame.
# Full instructions are in "install.txt" or "install.html"
#
# To configure, compile, install, just run this script.
DESCRIPTION = """Pygame is a Python wrapper module for the
SDL multimedia library. It contains python functions and classes
that will allow you to use SDL's support for playing cdroms,
audio and video output, and keyboard, mouse and joystick input."""
EXTRAS = {}
METADATA = {
"name": "pygame",
"version": "1.9.1release",
"license": "LGPL",
"url": "http://www.pygame.org",
"author": "Pete Shinners, Rene Dudfield, Marcus von Appen, Bob Pendleton, others...",
"author_email": "pygame@seul.org",
"description": "Python Game Development",
"long_description": DESCRIPTION,
}
import sys
if "bdist_msi" in sys.argv:
# hack the version name to a format msi doesn't have trouble with
METADATA["version"] = METADATA["version"].replace("pre", "a0")
METADATA["version"] = METADATA["version"].replace("rc", "b0")
METADATA["version"] = METADATA["version"].replace("release", "")
if not hasattr(sys, 'version_info') or sys.version_info < (2,3):
raise SystemExit("Pygame requires Python version 2.3 or above.")
#get us to the correct directory
import os, sys
path = os.path.split(os.path.abspath(sys.argv[0]))[0]
os.chdir(path)
#os.environ["CFLAGS"] = "-W -Wall -Wpointer-arith -Wcast-qual -Winline " + \
# "-Wcast-align -Wconversion -Wstrict-prototypes " + \
# "-Wmissing-prototypes -Wmissing-declarations " + \
# "-Wnested-externs -Wshadow -Wredundant-decls"
if "-warnings" in sys.argv:
os.environ["CFLAGS"] = "-W -Wimplicit-int " + \
"-Wimplicit-function-declaration " + \
"-Wimplicit -Wmain -Wreturn-type -Wunused -Wswitch " + \
"-Wcomment -Wtrigraphs -Wformat -Wchar-subscripts " + \
"-Wuninitialized -Wparentheses " +\
"-Wpointer-arith -Wcast-qual -Winline -Wcast-align " + \
"-Wconversion -Wstrict-prototypes " + \
"-Wmissing-prototypes -Wmissing-declarations " + \
"-Wnested-externs -Wshadow -Wredundant-decls"
sys.argv.remove ("-warnings")
import os.path, glob, stat
import distutils.sysconfig
from distutils.core import setup, Extension, Command
from distutils.extension import read_setup_file
from distutils.command.install_data import install_data
# Python 3.0 patch
if sys.version_info[0:2] == (3, 0):
import distutils.version
def _cmp(x, y):
try:
if x < y:
return -1
elif x == y:
return 0
return 1
except TypeError:
return NotImplemented
distutils.version.cmp = _cmp
del _cmp
def add_datafiles(data_files, dest_dir, pattern):
"""Add directory structures to data files according to a pattern"""
src_dir, elements = pattern
def do_directory(root_dest_path, root_src_path, elements):
files = []
for e in elements:
if isinstance(e, list):
src_dir, elems = e
dest_path = '/'.join([root_dest_path, src_dir])
src_path = os.path.join(root_src_path, src_dir)
do_directory(dest_path, src_path, elems)
else:
files.extend(glob.glob(os.path.join(root_src_path, e)))
if files:
data_files.append((root_dest_path, files))
do_directory(dest_dir, src_dir, elements)
# allow optionally using setuptools for bdist_egg.
if "-setuptools" in sys.argv:
from setuptools import setup, find_packages
sys.argv.remove ("-setuptools")
# NOTE: the bdist_mpkg_support is for darwin.
try:
import bdist_mpkg_support
from setuptools import setup, Extension
except ImportError:
pass
else:
EXTRAS.update({
'options': bdist_mpkg_support.options,
'setup_requires': ['bdist_mpkg>=0.4.2'],
#'install_requires': ['pyobjc'],
#'dependency_links': ['http://rene.f0o.com/~rene/stuff/macosx/']
})
#headers to install
headers = glob.glob(os.path.join('src', '*.h'))
headers.remove(os.path.join('src', 'numeric_arrayobject.h'))
headers.remove(os.path.join('src', 'scale.h'))
#sanity check for any arguments
if len(sys.argv) == 1:
reply = raw_input('\nNo Arguments Given, Perform Default Install? [Y/n]')
if not reply or reply[0].lower() != 'n':
sys.argv.append('install')
#make sure there is a Setup file
if not os.path.isfile('Setup'):
print ('\n\nWARNING, No "Setup" File Exists, Running "config.py"')
import config
config.main()
print ('\nContinuing With "setup.py"')
try:
s_mtime = os.stat("Setup")[stat.ST_MTIME]
sin_mtime = os.stat("Setup.in")[stat.ST_MTIME]
if sin_mtime > s_mtime:
print ('\n\nWARNING, "Setup.in" newer than "Setup",'
'you might need to modify "Setup".')
except:
pass
# get compile info for all extensions
try:
extensions = read_setup_file('Setup')
except:
print ("""Error with the "Setup" file,
perhaps make a clean copy from "Setup.in".""")
raise
#python 3.x: remove modules not yet ported
if sys.version_info >= (3, 0, 0):
python3_skip = ['scrap',
'_camera',
'_numericsurfarray',
'_numericsndarray',
]
tmp_extensions = extensions
extensions = []
for e in tmp_extensions:
if e.name in python3_skip:
print ("Skipping module %s for Python %s build." %
(e.name, sys.version))
else:
extensions.append(e)
del tmp_extensions
#extra files to install
data_path = os.path.join(distutils.sysconfig.get_python_lib(), 'pygame')
pygame_data_files = []
data_files = [('pygame', pygame_data_files)]
#add files in distribution directory
pygame_data_files.append('LGPL')
pygame_data_files.append('readme.html')
pygame_data_files.append('install.html')
#add non .py files in lib directory
for f in glob.glob(os.path.join('lib', '*')):
if not f[-3:] == '.py' and not f[-4:] == '.doc' and os.path.isfile(f):
pygame_data_files.append(f)
#tests/fixtures
add_datafiles(data_files, 'pygame/tests',
['test',
[['fixtures',
[['xbm_cursors',
['*.xbm']]]]]])
#examples
add_datafiles(data_files, 'pygame/examples',
['examples',
['readme.txt',
['data',
['*']],
['macosx',
['*.py',
['aliens_app_example',
['*.py',
'README.txt',
['English.lproj',
['aliens.icns',
['MainMenu.nib',
['*']]]]]]]]]])
#docs
add_datafiles(data_files, 'pygame/docs',
['docs',
['*.html',
'*.gif',
['ref',
['*.html']],
['tut',
['*.html',
['chimp',
['*.html',
'*.gif']],
['intro',
['*.html',
'*.gif',
'*.jpg']],
['surfarray',
['*.html',
'*.jpg']],
['tom',
['*.html',
'*.png']]]]]])
#required. This will be filled if doing a Windows build.
cmdclass = {}
#try to find DLLs and copy them too (only on windows)
if sys.platform == 'win32':
from distutils.command.build_ext import build_ext
# mingw32distutils is optional. But we need the mingw32 compiler(s).
try:
# Allow the choice between Win32 GUI and console DLLs.
import mingw32distutils
except ImportError:
mingw32_compilers = ['ming32']
else:
mingw32_compilers = mingw32distutils.compilers
if sys.version_info < (2, 4):
try:
import config
# a separate method for finding dlls with mingw.
if config.is_msys_mingw():
# fix up the paths for msys compiling.
import distutils_mods
distutils.cygwinccompiler.Mingw32 = distutils_mods.mingcomp
except ImportError:
pass
#add dependency DLLs to the project
lib_dependencies = {}
for e in extensions:
if e.name.startswith('COPYLIB_'):
lib_dependencies[e.name[8:]] = e.libraries
def dependencies(roots):
"""Return a set of dependencies for the list of library file roots
The return set is a dictionary keyed on library root name with values of 1.
"""
root_set = {}
for root in roots:
try:
deps = lib_dependencies[root]
except KeyError:
pass
else:
root_set[root] = 1
root_set.update(dependencies(deps))
return root_set
the_dlls = {}
required_dlls = {}
for e in extensions:
if e.name.startswith('COPYLIB_'):
the_dlls[e.name[8:]] = e.library_dirs[0]
else:
required_dlls.update(dependencies(e.libraries))
# join the required_dlls and the_dlls keys together.
lib_names = {}
for lib in list(required_dlls.keys()) + list(the_dlls.keys()):
lib_names[lib] = 1
for lib in lib_names.keys():
#next DLL; a distutils bug requires the paths to have Windows separators
f = the_dlls[lib].replace('/', os.sep)
if f == '_':
print ("WARNING, DLL for %s library not found." % lib)
else:
pygame_data_files.append(f)
class WinBuildExt(build_ext):
"""This build_ext sets necessary environment variables for MinGW"""
# __sdl_lib_dir is possible location of msvcrt replacement import
# libraries, if they exist. Pygame module base only links to SDL so
# should have the SDL library directory as its only -L option.
for e in extensions:
if e.name == 'base':
__sdl_lib_dir = e.library_dirs[0].replace('/', os.sep)
break
def run(self):
"""Extended to set MINGW_ROOT_DIRECTORY, PATH and LIBRARY_PATH"""
if self.compiler in mingw32_compilers:
# Add MinGW environment variables.
if 'MINGW_ROOT_DIRECTORY' not in os.environ:
# Use MinGW setup conifiguration file if present.
import mingwcfg
try:
mingw_root = mingwcfg.read()
except IOError:
raise RuntimeError(
"mingw32: required environment variable"
" MINGW_ROOT_DIRECTORY not set")
os.environ['MINGW_ROOT_DIRECTORY'] = mingw_root
path = os.environ['PATH']
os.environ['PATH'] = ';'.join([os.path.join(mingw_root, 'bin'),
path])
if sys.version_info >= (2, 6):
# The Visual Studio 2008 C library is msvcr90.dll.
c_runtime_path = os.path.join(self.__sdl_lib_dir, 'msvcr90')
elif sys.version_info >= (2, 4):
# The Visual Studio 2003 C library is msvcr71.dll.
c_runtime_path = os.path.join(self.__sdl_lib_dir, 'msvcr71')
else:
# The Visual Studio 6.0 C library is msvcrt.dll,
# the MinGW default.
c_runtime_path = ''
if c_runtime_path and os.path.isdir(c_runtime_path):
# Override the default msvcrt.dll linkage.
os.environ['LIBRARY_PATH'] = c_runtime_path
elif not (c_runtime_path or
glob.glob(os.path.join(self.__sdl_lib_dir,
'msvcr*'))):
pass
else:
raise RuntimeError("The dependencies are linked to"
" the wrong C runtime for"
" Python %i.%i" %
sys.version_info[:2])
build_ext.run(self)
cmdclass['build_ext'] = WinBuildExt
# Add the precompiled smooth scale MMX functions to transform.
def replace_scale_mmx():
for e in extensions:
if e.name == 'transform':
e.extra_objects.append(
os.path.join('obj', 'win32', 'scale_mmx.obj'))
for i in range(len(e.sources)):
if e.sources[i].endswith('scale_mmx.c'):
del e.sources[i]
return
replace_scale_mmx()
#clean up the list of extensions
for e in extensions[:]:
if e.name.startswith('COPYLIB_'):
extensions.remove(e) #don't compile the COPYLIBs, just clean them
else:
e.name = 'pygame.' + e.name #prepend package name on modules
#data installer with improved intelligence over distutils
#data files are copied into the project directory instead
#of willy-nilly
class smart_install_data(install_data):
def run(self):
#need to change self.install_dir to the actual library dir
install_cmd = self.get_finalized_command('install')
self.install_dir = getattr(install_cmd, 'install_lib')
return install_data.run(self)
cmdclass['install_data'] = smart_install_data
if "bdist_msi" in sys.argv:
# if you are making an msi, we want it to overwrite files
from distutils.command import bdist_msi
import msilib
class bdist_msi_overwrite_on_install(bdist_msi.bdist_msi):
def run(self):
bdist_msi.bdist_msi.run(self)
# Remove obsolete files.
comp = "pygame1" # Pygame component
prop = comp # Directory property
records = [("surfarray.pyd", comp,
"SURFAR~1.PYD|surfarray.pyd", prop, 1),
("sndarray.pyd", comp,
"SNDARRAY.PYD|sndarray.pyd", prop, 1),
("camera.pyd", comp, "CAMERA.PYD|camera.pyd", prop, 1),
("color.py", comp, "COLOR.PY|color.py", prop, 1),
("color.pyc", comp, "COLOR.PYC|color.pyc", prop, 1),
("color.pyo", comp, "COLOR.PYO|color.pyo", prop, 1)]
msilib.add_data(self.db, "RemoveFile", records)
# Overwrite outdated files.
fullname = self.distribution.get_fullname()
installer_name = self.get_installer_filename(fullname)
print ("changing %s to overwrite files on install" % installer_name)
msilib.add_data(self.db, "Property", [("REINSTALLMODE", "amus")])
self.db.Commit()
cmdclass['bdist_msi'] = bdist_msi_overwrite_on_install
# test command. For doing 'python setup.py test'
class TestCommand(Command):
user_options = [ ]
def initialize_options(self):
self._dir = os.getcwd()
def finalize_options(self):
pass
def run(self):
'''
runs the tests with default options.
'''
import subprocess
return subprocess.call([sys.executable, "run_tests.py"])
cmdclass['test'] = TestCommand
# Prune empty file lists.
date_files = [(path, files) for path, files in data_files if files]
#finally,
#call distutils with all needed info
PACKAGEDATA = {
"cmdclass": cmdclass,
"packages": ['pygame', 'pygame.gp2x', 'pygame.threads',
'pygame.tests',
'pygame.tests.test_utils',
'pygame.tests.run_tests__tests',
'pygame.tests.run_tests__tests.all_ok',
'pygame.tests.run_tests__tests.failures1',
'pygame.tests.run_tests__tests.incomplete',
'pygame.tests.run_tests__tests.infinite_loop',
'pygame.tests.run_tests__tests.print_stderr',
'pygame.tests.run_tests__tests.print_stdout',
'pygame.tests.run_tests__tests.incomplete_todo',
'pygame.tests.run_tests__tests.exclude',
'pygame.tests.run_tests__tests.timeout',
'pygame.tests.run_tests__tests.everything',
'pygame.docs',
'pygame.examples'],
"package_dir": {'pygame': 'lib',
'pygame.threads': 'lib/threads',
'pygame.gp2x': 'lib/gp2x',
'pygame.tests': 'test',
'pygame.docs': 'docs',
'pygame.examples': 'examples'},
"headers": headers,
"ext_modules": extensions,
"data_files": data_files,
}
PACKAGEDATA.update(METADATA)
PACKAGEDATA.update(EXTRAS)
setup(**PACKAGEDATA)
def remove_old_files():
# try and figure out where we are installed.
#pygame could be installed in a weird location because of
# setuptools or something else. The only sane way seems to be by trying
# first to import it, and see where the imported one is.
#
# Otherwise we might delete some files from another installation.
try:
import pygame.base
use_pygame = 1
except:
use_pygame = 0
if use_pygame:
install_path= os.path.split(pygame.base.__file__)[0]
extension_ext = os.path.splitext(pygame.base.__file__)[1]
else:
if not os.path.exists(data_path):
return
install_path = data_path
base_file = glob.glob(os.path.join(data_path, "base*"))
if not base_file:
return
extension_ext = os.path.splitext(base_file[0])[1]
# here are the .so/.pyd files we need to ask to remove.
ext_to_remove = ["camera"]
# here are the .py/.pyo/.pyc files we need to ask to remove.
py_to_remove = ["color"]
os.path.join(data_path, 'color.py')
if os.name == "e32": # Don't warn on Symbian. The color.py is used as a wrapper.
py_to_remove = []
# See if any of the files are there.
extension_files = ["%s%s" % (x, extension_ext) for x in ext_to_remove]
py_files = ["%s%s" % (x, py_ext)
for py_ext in [".py", ".pyc", ".pyo"]
for x in py_to_remove]
files = py_files + extension_files
unwanted_files = []
for f in files:
unwanted_files.append( os.path.join( install_path, f ) )
ask_remove = []
for f in unwanted_files:
if os.path.exists(f):
ask_remove.append(f)
for f in ask_remove:
try:
print("trying to remove old file :%s: ..." %f)
os.remove(f)
print("Successfully removed :%s:." % f)
except:
print("FAILED to remove old file :%s:" % f)
if "install" in sys.argv:
# remove some old files.
# only call after a successful install. Should only reach here if there is
# a successful install... otherwise setup() raises an error.
try:
remove_old_files()
except:
pass
pygame-1.9.1release/Setup.in 0000644 0001750 0001750 00000005110 11223035224 015662 0 ustar vincent vincent #This Setup file is used by the setup.py script to configure the
#python extensions. You will likely use the "config.py" which will
#build a correct Setup file for you based on your system settings.
#If not, the format is simple enough to edit by hand. First change
#the needed commandline flags for each dependency, then comment out
#any unavailable optional modules in the first optional section.
#--StartConfig
SDL = -I/usr/include/SDL -D_REENTRANT -lSDL
FONT = -lSDL_ttf
IMAGE = -lSDL_image
MIXER = -lSDL_mixer
SMPEG = -lsmpeg
PNG = -lpng
JPEG = -ljpeg
SCRAP = -lX11
PORTMIDI = -lportmidi
PORTTIME = -lporttime
#--EndConfig
#DEBUG = -C-W -C-Wall
DEBUG =
#the following modules are optional. you will want to compile
#everything you can, but you can ignore ones you don't have
#dependencies for, just comment them out
imageext src/imageext.c $(SDL) $(IMAGE) $(PNG) $(JPEG) $(DEBUG)
font src/font.c $(SDL) $(FONT) $(DEBUG)
mixer src/mixer.c $(SDL) $(MIXER) $(DEBUG)
mixer_music src/music.c $(SDL) $(MIXER) $(DEBUG)
_numericsurfarray src/_numericsurfarray.c $(SDL) $(DEBUG)
_numericsndarray src/_numericsndarray.c $(SDL) $(MIXER) $(DEBUG)
movie src/movie.c $(SDL) $(SMPEG) $(DEBUG)
scrap src/scrap.c $(SDL) $(SCRAP) $(DEBUG)
_camera src/_camera.c src/camera_v4l2.c src/camera_v4l.c $(SDL) $(DEBUG)
pypm src/pypm.c $(SDL) $(PORTMIDI) $(PORTTIME) $(DEBUG)
GFX = src/SDL_gfx/SDL_gfxPrimitives.c
#GFX = src/SDL_gfx/SDL_gfxBlitFunc.c src/SDL_gfx/SDL_gfxPrimitives.c
gfxdraw src/gfxdraw.c $(SDL) $(GFX) $(DEBUG)
#these modules are required for pygame to run. they only require
#SDL as a dependency. these should not be altered
base src/base.c $(SDL) $(DEBUG)
cdrom src/cdrom.c $(SDL) $(DEBUG)
color src/color.c $(SDL) $(DEBUG)
constants src/constants.c $(SDL) $(DEBUG)
display src/display.c $(SDL) $(DEBUG)
event src/event.c $(SDL) $(DEBUG)
fastevent src/fastevent.c src/fastevents.c $(SDL) $(DEBUG)
key src/key.c $(SDL) $(DEBUG)
mouse src/mouse.c $(SDL) $(DEBUG)
rect src/rect.c $(SDL) $(DEBUG)
rwobject src/rwobject.c $(SDL) $(DEBUG)
surface src/surface.c src/alphablit.c src/surface_fill.c $(SDL) $(DEBUG)
surflock src/surflock.c $(SDL) $(DEBUG)
time src/time.c $(SDL) $(DEBUG)
joystick src/joystick.c $(SDL) $(DEBUG)
draw src/draw.c $(SDL) $(DEBUG)
image src/image.c $(SDL) $(DEBUG)
overlay src/overlay.c $(SDL) $(DEBUG)
transform src/transform.c src/rotozoom.c src/scale2x.c src/scale_mmx.c $(SDL) $(DEBUG) -D_NO_MMX_FOR_X86_64
mask src/mask.c src/bitmask.c $(SDL) $(DEBUG)
bufferproxy src/bufferproxy.c $(SDL) $(DEBUG)
pixelarray src/pixelarray.c $(SDL) $(DEBUG)
_arraysurfarray src/_arraysurfarray.c $(SDL) $(DEBUG)
pygame-1.9.1release/setup.cfg 0000644 0001750 0001750 00000000073 11236514371 016067 0 ustar vincent vincent [egg_info]
tag_build =
tag_date = 0
tag_svn_revision = 0
pygame-1.9.1release/run_tests.py 0000644 0001750 0001750 00000000245 11205061230 016632 0 ustar vincent vincent #!/usr/bin/env python
"""Run one or more Pygame unittest modules in the test directory
For command line options use the --help option.
"""
import test.__main__
pygame-1.9.1release/README.txt 0000644 0001750 0001750 00000013206 11236512106 015740 0 ustar vincent vincent
Pygame Readme
Version 1.9.1release Python Game Development
Originally by Pete Shinners, now an open source community project.
http://www.pygame.org
pygame@seul.org
About
Pygame is a cross-platfrom library designed to make it easy to
write multimedia software, such as games, in Python. Pygame
requires the Python language and SDL multimedia library. It can
also make use of several other popular libraries.
Installation
You should definitely begin by installing a binary package for your
system. The binary packages usually come with or give the
information needed for dependencies. Choose an appropriate
installer for your system and version of python from the pygame
downloads page. http://www.pygame.org/download.shtml
Installing from source is fairly automated. The most work will
involve compiling and installing all the pygame dependencies. Once
that is done run the "setup.py" script which will attempt to
auto-configure, build, and install pygame.
Much more information about installing and compiling is available
in the install.html file.
Help
If you are just getting started with pygame, you should be able to
get started fairly quickly. Pygame comes with many tutorials and
introductions. There is also full reference documentation for the
entire library. Browse the documentation from the documenantation
index. docs/index.html.
On the pygame website, there is also an online copy of this
documentation. You should know that the online documentation stays
up to date with the development version of pygame in svn. This may
be a bit newer than the version of pygame you are using.
Best of all the examples directory has many playable small programs
which can get started playing with the code right away.
Credits
Thanks to everyone who has helped contribute to this library.
Special thanks are also in order.
Marcus Von Appen - many changes, and fixes, 1.7.1+ freebsd maintainer.
Lenard Lindstrom - the 1.8+ windows maintainer, many changes, and fixes.
Brian Fisher - for svn auto builder, bug tracker and many contributions.
Rene Dudfield - many changes, and fixes, 1.7+ release manager/maintainer.
Phil Hassey - for his work on the pygame.org website.
DR0ID for his work on the sprite module.
Richard Goedeken for his smoothscale function.
Ulf Ekström for his pixel perfect collision detection code.
Pete Shinners - orginal author.
David Clark - for filling the right-hand-man position
Ed Boraas and Francis Irving - Debian packages
Maxim Sobolev - FreeBSD packaging
Bob Ippolito - MacOS and OS X porting (much work!)
Jan Ekhol, Ray Kelm, and Peter Nicolai - putting up with my early
design ideas
Nat Pryce for starting our unit tests
Dan Richter for documentation work
TheCorruptor for his incredible logos and graphics
Nicholas Dudfield - many test improvements.
Alex Folkner - for pygame-ctypes
Thanks to those sending in patches and fixes: Niki Spahiev, Gordon
Tyler, Nathaniel Pryce, Dave Wallace, John Popplewell, Michael Urman,
Andrew Straw, Michael Hudson, Ole Martin Bjoerndalen, Hervé Cauwelier,
James Mazer, Lalo Martins, Timothy Stranex, Chad Lester, Matthias
Spiller, Bo Jangeborg, Dmitry Borisov, Campbell Barton, Diego Essaya,
Eyal Lotem, Regis Desgroppes, Emmanuel Hainry, Randy Kaelber
Matthew L Daniel, Nirav Patel, Forrest Voight, Charlie Nolan,
Frankie Robertson, John Krukoff, Lorenz Quack, Nick Irvine,
Michael George, Saul Spatz, Thomas Ibbotson, Tom Rothamel, Evan Kroske,
Cambell Barton.
And our bug hunters above and beyond: Angus, Guillaume Proux, Frank
Raiser, Austin Henry, Kaweh Kazemi, Arturo Aldama, Mike Mulcheck,
Michael Benfield, David Lau
There's many more folks out there who've submitted helpful ideas, kept
this project going, and basically made my life easer, Thanks!
Many thank you's for people making documentation comments, and adding to the
pygame.org wiki.
Also many thanks for people creating games and putting them on the
pygame.org website for others to learn from and enjoy.
Lots of thanks to James Paige for hosting the pygame bugzilla.
Also a big thanks to Roger Dingledine and the crew at SEUL.ORG for our
excellent hosting.
Dependencies
Pygame is obviously strongly dependent on SDL and Python. It also
links to and embeds several other smaller libraries. The font
module relies on SDL_tff, which is dependent on freetype. The mixer
(and mixer.music) modules depend on SDL_mixer. The image module
depends on SDL_image, which also can use libjpeg and libpng. The
transform module has an embedded version of SDL_rotozoom for its
own rotozoom function. The surfarray module requires the python
Numeric package for its multidimensional numeric arrays.
Todo / Ideas (feel free to submit)
http://www.pygame.org/wiki/todo/
License
This library is distributed under GNU LGPL version 2.1, which can
be found in the file "doc/LGPL". I reserve the right to place
future versions of this library under a different license.
http://www.gnu.org/copyleft/lesser.html
This basically means you can use pygame in any project you want,
but if you make any changes or additions to pygame itself, those
must be released with a compatible license. (preferably submitted
back to the pygame project). Closed source and commercial games are
fine.
The programs in the "examples" subdirectory are in the public
domain.
pygame-1.9.1release/readme.html 0000644 0001750 0001750 00000015153 11236512106 016370 0 ustar vincent vincent Pygame Readme
About
Pygame is a cross-platfrom library designed to make it easy to write
multimedia software, such as games, in Python. Pygame requires the
Python language and SDL multimedia library. It can also make use of
several other popular libraries.
Installation
You should definitely begin by installing a binary package
for your system. The binary packages usually come with or
give the information needed for dependencies. Choose an
appropriate installer for your system and version of python
from the pygame downloads page.
http://www.pygame.org/download.shtml
Installing from source is fairly automated. The most work will involve
compiling and installing all the pygame dependencies. Once that is done
run the "setup.py" script which will attempt to auto-configure, build,
and install pygame.
Much more information about installing and compiling is available in the
install.html file.
Help
If you are just getting started with pygame, you should be able
to get started fairly quickly. Pygame comes with many tutorials
and introductions. There is also full reference documentation for
the entire library. Browse the documentation from the documenantation
index. docs/index.html.
On the pygame website, there is also an online copy of this
documentation. You should know that the online documentation stays
up to date with the development version of pygame in svn. This may
be a bit newer than the version of pygame you are using.
Best of all the examples directory has many
playable small programs which can get started playing with the
code right away.
Credits
Thanks to everyone who has helped contribute to this library.
Special thanks are also in order.
Marcus Von Appen - many changes, and fixes, 1.7.1+ freebsd maintainer.
Lenard Lindstrom - the 1.8+ windows maintainer, many changes, and fixes.
Brian Fisher - for svn auto builder, bug tracker and many contributions.
Rene Dudfield - many changes, and fixes, 1.7+ release manager/maintainer.
Phil Hassey - for his work on the pygame.org website.
DR0ID for his work on the sprite module.
Richard Goedeken for his smoothscale function.
Ulf Ekström for his pixel perfect collision detection code.
Pete Shinners - orginal author.
David Clark - for filling the right-hand-man position
Ed Boraas and Francis Irving - Debian packages
Maxim Sobolev - FreeBSD packaging
Bob Ippolito - MacOS and OS X porting (much work!)
Jan Ekhol, Ray Kelm, and Peter Nicolai - putting up
with my early design ideas
Nat Pryce for starting our unit tests
Dan Richter for documentation work
TheCorruptor for his incredible logos and graphics
Nicholas Dudfield - many test improvements.
Alex Folkner - for pygame-ctypes
Thanks to those sending in patches and fixes: Niki Spahiev, Gordon
Tyler, Nathaniel Pryce, Dave Wallace, John Popplewell, Michael Urman,
Andrew Straw, Michael Hudson, Ole Martin Bjoerndalen, Hervé Cauwelier,
James Mazer, Lalo Martins, Timothy Stranex, Chad Lester, Matthias
Spiller, Bo Jangeborg, Dmitry Borisov, Campbell Barton, Diego Essaya,
Eyal Lotem, Regis Desgroppes, Emmanuel Hainry, Randy Kaelber
Matthew L Daniel, Nirav Patel, Forrest Voight, Charlie Nolan,
Frankie Robertson, John Krukoff, Lorenz Quack, Nick Irvine,
Michael George, Saul Spatz, Thomas Ibbotson, Tom Rothamel, Evan Kroske,
Cambell Barton.
And our bug hunters above and beyond:
Angus, Guillaume Proux, Frank Raiser,
Austin Henry, Kaweh Kazemi, Arturo Aldama,
Mike Mulcheck, Rene Dudfield, Michael Benfield,
David Lau
There's many more folks out there who've submitted helpful ideas,
kept this project going, and basically made my life easer, Thanks!
Many thank you's for people making documentation comments, and adding to the
pygame.org wiki.
Also many thanks for people creating games and putting them on the
pygame.org website for others to learn from and enjoy.
Lots of thanks to James Paige for hosting the pygame bugzilla.
Also a big thanks to Roger Dingledine and the crew at SEUL.ORG
for our excellent hosting.
Dependencies
Pygame is obviously strongly dependent on SDL and Python. It also
links to and embeds several other smaller libraries. The font module
relies on SDL_tff, which is dependent on freetype. The mixer (and
mixer.music) modules depend on SDL_mixer. The image module depends
on SDL_image, which also can use libjpeg and libpng. The transform
module has an embedded version of SDL_rotozoom for its own rotozoom
function. The surfarray module requires the python Numeric package
for its multidimensional numeric arrays.
Todo / Ideas (feel free to submit)
http://www.pygame.org/wiki/todo/
License
This library is distributed under GNU LGPL version 2.1, which can be
found in the file "doc/LGPL". I reserve the right to place future
versions of this library under a different license.
http://www.gnu.org/copyleft/lesser.html
This basically means you can use pygame in any project you want, but
if you make any changes or additions to pygame itself, those must be
released with a compatible license. (preferably submitted back to the
pygame project). Closed source and commercial games are fine.
The programs in the "examples" subdirectory are in the public domain.
pygame-1.9.1release/PKG-INFO 0000644 0001750 0001750 00000001027 11236514371 015343 0 ustar vincent vincent Metadata-Version: 1.0
Name: pygame
Version: 1.9.1release
Summary: Python Game Development
Home-page: http://www.pygame.org
Author: Pete Shinners, Rene Dudfield, Marcus von Appen, Bob Pendleton, others...
Author-email: pygame@seul.org
License: LGPL
Description: Pygame is a Python wrapper module for the
SDL multimedia library. It contains python functions and classes
that will allow you to use SDL's support for playing cdroms,
audio and video output, and keyboard, mouse and joystick input.
Platform: UNKNOWN
pygame-1.9.1release/msysio.py 0000644 0001750 0001750 00000002506 11207055754 016151 0 ustar vincent vincent # module msysio.py
# Requires Python 2.2 or better.
"""Provide helpful routines for interactive IO on the MSYS console"""
# Output needs to be flushed to be seen. It is especially important
# when prompting for user input.
import sys
import os
__all__ = ['raw_input_', 'print_', 'is_msys']
# 2.x/3.x compatibility stuff
try:
raw_input
except NameError:
raw_input = input
# Exported functions
__all__ = ['raw_input_', 'print_', 'is_msys']
# 2.x/3.x compatibility stuff
try:
raw_input
except NameError:
raw_input = input
# Exported functions
def raw_input_(prompt=None):
"""Prompt for user input in an MSYS console friendly way"""
if prompt is None:
prompt = ''
print_(prompt, end='')
return raw_input()
def print_(*args, **kwds):
"""Print arguments in an MSYS console friendly way
Keyword arguments:
file, sep, end
"""
stream = kwds.get('file', sys.stdout)
sep = kwds.get('sep', ' ')
end = kwds.get('end', '\n')
if args:
stream.write(sep.join([str(arg) for arg in args]))
if end:
stream.write(end)
try:
stream.flush()
except AttributeError:
pass
def is_msys():
"""Return true if the execution environment is MSYS"""
try:
return os.environ['OSTYPE'] == 'msys'
except KeyError:
return False
pygame-1.9.1release/msys_link_VC_2008_dlls.py 0000644 0001750 0001750 00000105740 11130022066 020702 0 ustar vincent vincent #!/usr/bin/env python
# -*- coding: ascii -*-
# Program msys_link_VC_2008_dlls.py
# Requires Python 2.4 or later and win32api.
"""Link dependency DLLs against the Visual C 2008 run-time using MinGW and MSYS
Configured for Pygame 1.8 and Python 2.6 and up.
By default the DLLs and export libraries are installed in directory ./lib_VC_2008.
msys_build_deps.py must run first to build the static libaries.
This program can be run from a Windows cmd.exe or MSYS terminal.
The recognized, and optional, environment variables are:
SHELL - MSYS shell program path - already defined in the MSYS terminal
LDFLAGS - linker options - prepended to flags set by the program
LIBRARY_PATH - library directory paths - appended to those used by this
program
To get a list of command line options run
python build_deps.py --help
This program has been tested against the following libraries:
SDL 1.2 (.13) revision 4114 from SVN
SDL_image 1.2.6
SDL_mixer 1.2 (.8) revision 3942 from SVN
SDL_ttf 2.0.9
smpeg revision 370 from SVN
freetype 2.3.7
libogg 1.1.3
libvorbis 1.2.0
FLAC 1.2.1
tiff 3.8.2
libpng 1.2.32
jpeg 6b
zlib 1.2.3
The build environment used:
gcc-core-3.4.5
binutils-2.17.50
mingwrt-3.15.1
win32api-3.12
pexports 0.43
MSYS-1.0.10
Builds have been performed on Windows 98 and XP.
Build issues:
For pre-2007 computers: MSYS bug "[ 1170716 ] executing a shell scripts
gives a memory leak" (http://sourceforge.net/tracker/
index.php?func=detail&aid=1170716&group_id=2435&atid=102435)
It may not be possible to use the --all option to build all Pygame
dependencies in one session. Instead the job may need to be split into two
or more sessions, with a reboot of the operatingsystem between each. Use
the --help-args option to list the libraries in the their proper build
order.
"""
import msys
from optparse import OptionParser, Option, OptionValueError
import os
import sys
import time
import re
import copy
DEFAULT_DEST_DIR_NAME = 'lib_VC_2008'
def print_(*args, **kwds):
msys.msys_print(*args, **kwds)
def merge_strings(*args, **kwds):
"""Returns non empty string joined by sep
The default separator is an empty string.
"""
sep = kwds.get('sep', '')
return sep.join([s for s in args if s])
class BuildError(StandardError):
"""Raised for missing source paths and failed script runs"""
pass
class Dependency(object):
"""Builds a library"""
def __init__(self, name, dlls, shell_script):
self.name = name
self.dlls = dlls
self.shell_script = shell_script
def build(self, msys):
return_code = msys.run_shell_script(self.shell_script)
if return_code != 0:
raise BuildError("The build for %s failed with code %d" %
(self.name, return_code))
class Preparation(object):
"""Perform necessary build environment preperations"""
def __init__(self, name, shell_script):
self.name = name
self.path = ''
self.paths = []
self.dlls = []
self.shell_script = shell_script
def build(self, msys):
return_code = msys.run_shell_script(self.shell_script)
if return_code != 0:
raise BuildError("Preparation '%s' failed with code %d" %
(self.name, return_code))
def build(dependencies, msys):
"""Execute that shell scripts for all dependencies"""
for dep in dependencies:
dep.build(msys)
def check_directory_path(option, opt, value):
# Remove those double quotes that Windows won't.
if re.match(r'([A-Za-z]:){0,1}[^"<>:|?*]+$', value) is None:
raise OptionValueError("option %s: invalid path" % value)
return value
class MyOption(Option):
TYPES = Option.TYPES + ("dir",)
TYPE_CHECKER = copy.copy(Option.TYPE_CHECKER)
TYPE_CHECKER["dir"] = check_directory_path
def command_line():
"""Process the command line and return the options"""
usage = ("usage: %prog [options] --all\n"
" %prog [options] [args]\n"
"\n"
"Build the Pygame dependencies. The args, if given, are\n"
"libraries to include or exclude.\n"
"\n"
"At startup this program may prompt for missing information.\n"
"Be aware of this before redirecting output or leaving the\n"
"program unattended. Once the 'Starting build' message appears\n"
"no more user input is required. The build process will"
"abort on the first error, as library build order is important.\n"
"\n"
"See --include and --help-args.\n"
"\n"
"For more details see the program's document string\n")
parser = OptionParser(usage, option_class=MyOption)
parser.add_option('-a', '--all', action='store_true', dest='build_all',
help="Include all libraries in the build")
parser.set_defaults(build_all=False)
parser.add_option('--console', action='store_true', dest='console',
help="Link with the console subsystem:"
" defaults to Win32 GUI")
parser.set_defaults(console=False)
parser.add_option('--no-strip', action='store_false', dest='strip',
help="Do not strip the library")
parser.set_defaults(strip=True)
parser.add_option('-e', '--exclude', action='store_true', dest='exclude',
help="Exclude the specified libraries")
parser.set_defaults(exclude=False)
parser.add_option('-d', '--destination-dir', type='dir',
dest='destination_dir',
help="Where the DLLs and export libraries will go",
metavar='PATH')
parser.set_defaults(destination_dir=DEFAULT_DEST_DIR_NAME)
parser.add_option('-m', '--msys-root', action='store', type='dir',
dest='msys_directory',
help="MSYS directory path, which may include"
" the 1.x subdirectory")
parser.add_option('--help-args', action='store_true', dest='arg_help',
help="Show a list of recognised libraries,"
" in build order, and exit")
parser.set_defaults(arg_help=False)
return parser.parse_args()
def set_environment_variables(msys, options):
"""Set the environment variables used by the scripts"""
environ = msys.environ
msys_root = msys.msys_root
destination_dir = os.path.abspath(options.destination_dir)
environ['BDWD'] = msys.windows_to_msys(destination_dir)
environ['BDBIN'] = '/usr/local/bin'
environ['BDLIB'] = '/usr/local/lib'
subsystem = '-mwindows'
if options.console:
subsystem = '-mconsole'
strip = ''
if options.strip:
strip = '-Wl,--strip-all'
environ['LDFLAGS'] = merge_strings(environ.get('LDFLAGS', ''),
subsystem,
strip,
sep=' ')
library_path = os.path.join(msys_root, 'local', 'lib')
msvcr90_path = os.path.join(destination_dir, 'msvcr90')
environ['DBMSVCR90'] = msys.windows_to_msys(msvcr90_path)
# For dependency libraries and msvcrt hiding.
environ['LIBRARY_PATH'] = merge_strings(msvcr90_path,
environ.get('LIBRARY_PATH', ''),
sep=';')
class ChooseError(StandardError):
"""Failer to select dependencies"""
pass
def choose_dependencies(dependencies, options, args):
"""Return the dependencies to actually build"""
if options.build_all:
if args:
raise ChooseError("No library names are accepted"
" for the --all option.")
if options.exclude:
return []
else:
return dependencies
if args:
names = [d.name for d in dependencies]
args = [a.upper() for a in args]
for a in args:
if a not in names:
msg = ["%s is an unknown library; valid choices are:" % a]
msg.extend(names)
raise ChooseError('\n'.join(msg))
if options.exclude:
return [d for d in dependencies if d.name not in args]
return [d for d in dependencies if d.name in args]
return []
def summary(dependencies, msys, start_time, chosen_deps, options):
"""Display a summary report of new, existing and missing DLLs"""
import datetime
print_("\n\n=== Summary ===")
if start_time is not None:
print_(" Elapse time:",
datetime.timedelta(seconds=time.time()-start_time))
bin_dir = options.destination_dir
for d in dependencies:
name = d.name
dlls = d.dlls
for dll in dlls:
dll_path = os.path.join(bin_dir, dll)
try:
mod_time = os.path.getmtime(dll_path)
except:
msg = "No DLL"
else:
if mod_time >= start_time:
msg = "Installed new DLL %s" % dll_path
else:
msg = "-- (old DLL %s)" % dll_path
print_(" %-10s: %s" % (name, msg))
def main(dependencies, msvcr90_preparation, msys_preparation):
"""Build the dependencies according to the command line options."""
options, args = command_line()
if options.arg_help:
print_("These are the Pygame library dependencies:")
for dep in dependencies:
print_(" ", dep.name)
return 0
try:
chosen_deps = choose_dependencies(dependencies, options, args)
except ChooseError, e:
print_(e)
return 1
print_("Destination directory:", options.destination_dir)
if not chosen_deps:
if not args:
print_("No libraries specified.")
elif options.build_all:
print_("All libraries excluded")
chosen_deps.insert(0, msvcr90_preparation)
chosen_deps.insert(0, msys_preparation)
try:
msys_directory = options.msys_directory
except AttributeError:
msys_directory = None
try:
m = msys.Msys(msys_directory)
except msys.MsysException, e:
print_(e)
return 1
start_time = None
return_code = 1
set_environment_variables(m, options)
print_("\n=== Starting build ===")
start_time = time.time() # For file timestamp checks.
try:
build(chosen_deps, m)
except BuildError, e:
print_("Build aborted:", e)
else:
# A successful build!
return_code = 0
summary(dependencies, m, start_time, chosen_deps, options)
return return_code
#
# Build specific code
#
# This list includes the MSYS shell scripts to build each library. Each script
# runs in an environment where MINGW_ROOT_DIRECTORY is defined and the MinGW
# bin directory is in PATH. DBWD, is the working directory. A script will cd to
# it before doing anything else. BDBIN is the location of the dependency DLLs.
# BDLIB is the location of the dependency libraries. LDFLAGS are linker flags.
#
# The list order corresponds to build order. It is critical.
dependencies = [
Dependency('SDL', ['SDL.dll'], """
set -e
cd "$BDWD"
pexports "$BDBIN/SDL.dll" >SDL.def
gcc -shared $LDFLAGS -o SDL.dll -def SDL.def "$BDLIB/libSDL.a" -lwinmm -ldxguid
dlltool -D SDL.dll -d SDL.def -l libSDL.dll.a
ranlib libSDL.dll.a
strip --strip-all SDL.dll
"""),
Dependency('Z', ['zlib1.dll'], """
set -e
cd "$BDWD"
pexports "$BDBIN/zlib1.dll" >z.def
gcc -shared $LDFLAGS -o zlib1.dll -def z.def "$BDLIB/libz.a"
dlltool -D zlib1.dll -d z.def -l libz.dll.a
ranlib libz.dll.a
strip --strip-all zlib1.dll
"""),
Dependency('FREETYPE', ['libfreetype-6.dll'], """
set -e
cd "$BDWD"
pexports "$BDBIN/libfreetype-6.dll" >freetype.def
gcc -shared $LDFLAGS -L. -o libfreetype-6.dll -def freetype.def \
"$BDLIB/libfreetype.a" -lz
dlltool -D libfreetype-6.dll -d freetype.def -l libfreetype.dll.a
ranlib libfreetype.dll.a
strip --strip-all libfreetype-6.dll
"""),
Dependency('FONT', ['SDL_ttf.dll'], """
set -e
cd "$BDWD"
pexports "$BDBIN/SDL_ttf.dll" >SDL_ttf.def
gcc -shared $LDFLAGS -L. "-L$BDLIB" -o SDL_ttf.dll -def SDL_ttf.def \
"$BDLIB/libSDL_ttf.a" -lSDL -lfreetype
dlltool -D SDL_ttf.dll -d SDL_ttf.def -l libSDL_ttf.dll.a
ranlib libSDL_ttf.dll.a
strip --strip-all SDL_ttf.dll
"""),
Dependency('PNG', ['libpng12-0.dll'], """
set -e
cd "$BDWD"
pexports "$BDBIN/libpng12-0.dll" >png.def
gcc -shared $LDFLAGS -L. -o libpng12-0.dll -def png.def "$BDLIB/libpng.a" -lz
dlltool -D libpng12-0.dll -d png.def -l libpng.dll.a
ranlib libpng.dll.a
strip --strip-all libpng12-0.dll
"""),
Dependency('JPEG', ['jpeg.dll'], """
set -e
cd "$BDWD"
pexports "$BDBIN/jpeg.dll" >jpeg.def
gcc -shared $LDFLAGS -o jpeg.dll -def jpeg.def "$BDLIB/libjpeg.a"
dlltool -D jpeg.dll -d jpeg.def -l libjpeg.dll.a
ranlib libjpeg.dll.a
strip --strip-all jpeg.dll
"""),
Dependency('TIFF', ['libtiff.dll'], """
set -e
cd "$BDWD"
pexports "$BDBIN/libtiff.dll" >tiff.def
gcc -shared $LDFLAGS -L. -o libtiff.dll -def tiff.def \
"$BDLIB/libtiff.a" -ljpeg -lz
dlltool -D libtiff.dll -d tiff.def -l libtiff.dll.a
ranlib libtiff.dll.a
strip --strip-all libtiff.dll
"""),
Dependency('IMAGE', ['SDL_image.dll'], """
set -e
cd "$BDWD"
pexports "$BDBIN/SDL_image.dll" >SDL_image.def
gcc -shared $LDFLAGS -L. -o SDL_image.dll -def SDL_image.def \
"$BDLIB/libSDL_image.a" -lSDL -ljpeg -lpng -ltiff
dlltool -D SDL_image.dll -d SDL_image.def -l libSDL_image.dll.a
ranlib libSDL_image.dll.a
strip --strip-all SDL_image.dll
"""),
Dependency('SMPEG', ['smpeg.dll'], """
set -e
cd "$BDWD"
pexports "$BDBIN/smpeg.dll" >smpeg.def
g++ -shared $LDFLAGS -L. -o smpeg.dll -def smpeg.def \
"$BDLIB/libsmpeg.a" -lSDL
dlltool -D smpeg.dll -d smpeg.def -l libsmpeg.dll.a
ranlib libsmpeg.dll.a
strip --strip-all smpeg.dll
"""),
Dependency('OGG', ['libogg-0.dll'], """
set -e
cd "$BDWD"
pexports "$BDBIN/libogg-0.dll" >ogg.def
gcc -shared $LDFLAGS -o libogg-0.dll -def ogg.def "$BDLIB/libogg.a"
dlltool -D libogg-0.dll -d ogg.def -l libogg.dll.a
ranlib libogg.dll.a
strip --strip-all libogg-0.dll
"""),
Dependency('VORBIS', ['libvorbis-0.dll', 'libvorbisfile-3.dll'], """
set -e
cd "$BDWD"
pexports "$BDBIN/libvorbis-0.dll" >vorbis.def
gcc -shared $LDFLAGS -L. -o libvorbis-0.dll -def vorbis.def \
"$BDLIB/libvorbis.a" -logg
dlltool -D libvorbis-0.dll -d vorbis.def -l libvorbis.dll.a
ranlib libvorbis.dll.a
strip --strip-all libvorbis-0.dll
pexports "$BDBIN/libvorbisfile-3.dll" >vorbisfile.def
gcc -shared $LDFLAGS -L. -o libvorbisfile-3.dll -def vorbisfile.def \
"$BDLIB/libvorbisfile.a" -lvorbis -logg
dlltool -D libvorbisfile-3.dll -d vorbisfile.def -l libvorbisfile.dll.a
ranlib libvorbisfile.dll.a
strip --strip-all libvorbisfile-3.dll
"""),
Dependency('MIXER', ['SDL_mixer.dll'], """
set -e
cd "$BDWD"
pexports "$BDBIN/SDL_mixer.dll" >SDL_mixer.def
gcc -shared $LDFLAGS -L. -L/usr/local/lib -o SDL_mixer.dll -def SDL_mixer.def \
"$BDLIB/libSDL_mixer.a" -lSDL -lsmpeg -lvorbisfile -lFLAC -lWs2_32 -lwinmm
dlltool -D SDL_mixer.dll -d SDL_mixer.def -l libSDL_mixer.dll.a
ranlib libSDL_mixer.dll.a
strip --strip-all SDL_mixer.dll
"""),
Dependency('PORTMIDI', ['portmidi.dll'], """
set -e
cd "$BDWD"
pexports "$BDBIN/portmidi.dll" >portmidi.def
gcc -shared $LDFLAGS -L. -L/usr/local/lib -o portmidi.dll -def portmidi.def \
"$BDLIB/libportmidi.a" -lwinmm
dlltool -D portmidi.dll -d portmidi.def -l portmidi.dll.a
ranlib libSDL_mixer.dll.a
strip --strip-all portmidi.dll
"""),
] # End dependencies = [.
msys_prep = Preparation('/usr/local', """
# Ensure destination directories exists.
mkdir -p "$BDWD"
mkdir -p "$DBMSVCR90"
""")
msvcr90_prep = Preparation('msvcr90.dll linkage', r"""
set -e
#
# msvcr90.dll support
#
if [ ! -f "$DBMSVCR90/libmoldnamed.dll.a" ]; then
OBJS='isascii.o iscsym.o iscsymf.o toascii.o
strcasecmp.o strncasecmp.o wcscmpi.o'
if [ ! -d /tmp/build_deps ]; then mkdir /tmp/build_deps; fi
cd /tmp/build_deps
# These definitions were generated with pexports on msvcr90.dll.
# The C++ stuff at the beginning was removed. _onexit and atexit made
# data entries.
cat > msvcr90.def << 'THE_END'
EXPORTS
_CIacos
_CIasin
_CIatan
_CIatan2
_CIcos
_CIcosh
_CIexp
_CIfmod
_CIlog
_CIlog10
_CIpow
_CIsin
_CIsinh
_CIsqrt
_CItan
_CItanh
_CRT_RTC_INIT
_CRT_RTC_INITW
_CreateFrameInfo
_CxxThrowException
_EH_prolog
_FindAndUnlinkFrame
_Getdays
_Getmonths
_Gettnames
_HUGE DATA
_IsExceptionObjectToBeDestroyed
_NLG_Dispatch2
_NLG_Return
_NLG_Return2
_Strftime
_XcptFilter
__AdjustPointer
__BuildCatchObject
__BuildCatchObjectHelper
__CppXcptFilter
__CxxCallUnwindDelDtor
__CxxCallUnwindDtor
__CxxCallUnwindStdDelDtor
__CxxCallUnwindVecDtor
__CxxDetectRethrow
__CxxExceptionFilter
__CxxFrameHandler
__CxxFrameHandler2
__CxxFrameHandler3
__CxxLongjmpUnwind
__CxxQueryExceptionSize
__CxxRegisterExceptionObject
__CxxUnregisterExceptionObject
__DestructExceptionObject
__FrameUnwindFilter
__RTCastToVoid
__RTDynamicCast
__RTtypeid
__STRINGTOLD
__STRINGTOLD_L
__TypeMatch
___fls_getvalue@4
___fls_setvalue@8
___lc_codepage_func
___lc_collate_cp_func
___lc_handle_func
___mb_cur_max_func
___mb_cur_max_l_func
___setlc_active_func
___unguarded_readlc_active_add_func
__argc DATA
__argv DATA
__badioinfo DATA
__clean_type_info_names_internal
__control87_2
__create_locale
__crtCompareStringA
__crtCompareStringW
__crtGetLocaleInfoW
__crtGetStringTypeW
__crtLCMapStringA
__crtLCMapStringW
__daylight
__dllonexit
__doserrno
__dstbias
__fpecode
__free_locale
__get_app_type
__get_current_locale
__get_flsindex
__get_tlsindex
__getmainargs
__initenv DATA
__iob_func
__isascii
__iscsym
__iscsymf
__iswcsym
__iswcsymf
__lc_clike DATA
__lc_codepage DATA
__lc_collate_cp DATA
__lc_handle DATA
__lconv DATA
__lconv_init
__libm_sse2_acos
__libm_sse2_acosf
__libm_sse2_asin
__libm_sse2_asinf
__libm_sse2_atan
__libm_sse2_atan2
__libm_sse2_atanf
__libm_sse2_cos
__libm_sse2_cosf
__libm_sse2_exp
__libm_sse2_expf
__libm_sse2_log
__libm_sse2_log10
__libm_sse2_log10f
__libm_sse2_logf
__libm_sse2_pow
__libm_sse2_powf
__libm_sse2_sin
__libm_sse2_sinf
__libm_sse2_tan
__libm_sse2_tanf
__mb_cur_max DATA
__p___argc
__p___argv
__p___initenv
__p___mb_cur_max
__p___wargv
__p___winitenv
__p__acmdln
__p__amblksiz
__p__commode
__p__daylight
__p__dstbias
__p__environ
__p__fmode
__p__iob
__p__mbcasemap
__p__mbctype
__p__pctype
__p__pgmptr
__p__pwctype
__p__timezone
__p__tzname
__p__wcmdln
__p__wenviron
__p__wpgmptr
__pctype_func
__pioinfo DATA
__pwctype_func
__pxcptinfoptrs
__report_gsfailure
__set_app_type
__set_flsgetvalue
__setlc_active DATA
__setusermatherr
__strncnt
__swprintf_l
__sys_errlist
__sys_nerr
__threadhandle
__threadid
__timezone
__toascii
__tzname
__unDName
__unDNameEx
__unDNameHelper
__uncaught_exception
__unguarded_readlc_active DATA
__vswprintf_l
__wargv DATA
__wcserror
__wcserror_s
__wcsncnt
__wgetmainargs
__winitenv DATA
_abnormal_termination
_abs64
_access
_access_s
_acmdln DATA
_adj_fdiv_m16i
_adj_fdiv_m32
_adj_fdiv_m32i
_adj_fdiv_m64
_adj_fdiv_r
_adj_fdivr_m16i
_adj_fdivr_m32
_adj_fdivr_m32i
_adj_fdivr_m64
_adj_fpatan
_adj_fprem
_adj_fprem1
_adj_fptan
_adjust_fdiv DATA
_aexit_rtn DATA
_aligned_free
_aligned_malloc
_aligned_msize
_aligned_offset_malloc
_aligned_offset_realloc
_aligned_offset_recalloc
_aligned_realloc
_aligned_recalloc
_amsg_exit
_assert
_atodbl
_atodbl_l
_atof_l
_atoflt
_atoflt_l
_atoi64
_atoi64_l
_atoi_l
_atol_l
_atoldbl
_atoldbl_l
_beep
_beginthread
_beginthreadex
_byteswap_uint64
_byteswap_ulong
_byteswap_ushort
_c_exit
_cabs
_callnewh
_calloc_crt
_cexit
_cgets
_cgets_s
_cgetws
_cgetws_s
_chdir
_chdrive
_chgsign
_chkesp
_chmod
_chsize
_chsize_s
_clearfp
_close
_commit
_commode DATA
_configthreadlocale
_control87
_controlfp
_controlfp_s
_copysign
_cprintf
_cprintf_l
_cprintf_p
_cprintf_p_l
_cprintf_s
_cprintf_s_l
_cputs
_cputws
_creat
_create_locale
_crt_debugger_hook
_cscanf
_cscanf_l
_cscanf_s
_cscanf_s_l
_ctime32
_ctime32_s
_ctime64
_ctime64_s
_cwait
_cwprintf
_cwprintf_l
_cwprintf_p
_cwprintf_p_l
_cwprintf_s
_cwprintf_s_l
_cwscanf
_cwscanf_l
_cwscanf_s
_cwscanf_s_l
_daylight DATA
_decode_pointer
_difftime32
_difftime64
_dosmaperr
_dstbias DATA
_dup
_dup2
_dupenv_s
_ecvt
_ecvt_s
_encode_pointer
_encoded_null
_endthread
_endthreadex
_environ DATA
_eof
_errno
_except_handler2
_except_handler3
_except_handler4_common
_execl
_execle
_execlp
_execlpe
_execv
_execve
_execvp
_execvpe
_exit
_expand
_fclose_nolock
_fcloseall
_fcvt
_fcvt_s
_fdopen
_fflush_nolock
_fgetchar
_fgetwc_nolock
_fgetwchar
_filbuf
_filelength
_filelengthi64
_fileno
_findclose
_findfirst32
_findfirst32i64
_findfirst64
_findfirst64i32
_findnext32
_findnext32i64
_findnext64
_findnext64i32
_finite
_flsbuf
_flushall
_fmode DATA
_fpclass
_fpieee_flt
_fpreset
_fprintf_l
_fprintf_p
_fprintf_p_l
_fprintf_s_l
_fputchar
_fputwc_nolock
_fputwchar
_fread_nolock
_fread_nolock_s
_free_locale
_freea
_freea_s
_freefls
_fscanf_l
_fscanf_s_l
_fseek_nolock
_fseeki64
_fseeki64_nolock
_fsopen
_fstat32
_fstat32i64
_fstat64
_fstat64i32
_ftell_nolock
_ftelli64
_ftelli64_nolock
_ftime32
_ftime32_s
_ftime64
_ftime64_s
_ftol
_fullpath
_futime32
_futime64
_fwprintf_l
_fwprintf_p
_fwprintf_p_l
_fwprintf_s_l
_fwrite_nolock
_fwscanf_l
_fwscanf_s_l
_gcvt
_gcvt_s
_get_amblksiz
_get_current_locale
_get_daylight
_get_doserrno
_get_dstbias
_get_errno
_get_fmode
_get_heap_handle
_get_invalid_parameter_handler
_get_osfhandle
_get_output_format
_get_pgmptr
_get_printf_count_output
_get_purecall_handler
_get_sbh_threshold
_get_terminate
_get_timezone
_get_tzname
_get_unexpected
_get_wpgmptr
_getc_nolock
_getch
_getch_nolock
_getche
_getche_nolock
_getcwd
_getdcwd
_getdcwd_nolock
_getdiskfree
_getdllprocaddr
_getdrive
_getdrives
_getmaxstdio
_getmbcp
_getpid
_getptd
_getsystime
_getw
_getwch
_getwch_nolock
_getwche
_getwche_nolock
_getws
_getws_s
_global_unwind2
_gmtime32
_gmtime32_s
_gmtime64
_gmtime64_s
_heapadd
_heapchk
_heapmin
_heapset
_heapused
_heapwalk
_hypot
_hypotf
_i64toa
_i64toa_s
_i64tow
_i64tow_s
_initptd
_initterm
_initterm_e
_inp
_inpd
_inpw
_invalid_parameter
_invalid_parameter_noinfo
_invoke_watson
_iob DATA
_isalnum_l
_isalpha_l
_isatty
_iscntrl_l
_isctype
_isctype_l
_isdigit_l
_isgraph_l
_isleadbyte_l
_islower_l
_ismbbalnum
_ismbbalnum_l
_ismbbalpha
_ismbbalpha_l
_ismbbgraph
_ismbbgraph_l
_ismbbkalnum
_ismbbkalnum_l
_ismbbkana
_ismbbkana_l
_ismbbkprint
_ismbbkprint_l
_ismbbkpunct
_ismbbkpunct_l
_ismbblead
_ismbblead_l
_ismbbprint
_ismbbprint_l
_ismbbpunct
_ismbbpunct_l
_ismbbtrail
_ismbbtrail_l
_ismbcalnum
_ismbcalnum_l
_ismbcalpha
_ismbcalpha_l
_ismbcdigit
_ismbcdigit_l
_ismbcgraph
_ismbcgraph_l
_ismbchira
_ismbchira_l
_ismbckata
_ismbckata_l
_ismbcl0
_ismbcl0_l
_ismbcl1
_ismbcl1_l
_ismbcl2
_ismbcl2_l
_ismbclegal
_ismbclegal_l
_ismbclower
_ismbclower_l
_ismbcprint
_ismbcprint_l
_ismbcpunct
_ismbcpunct_l
_ismbcspace
_ismbcspace_l
_ismbcsymbol
_ismbcsymbol_l
_ismbcupper
_ismbcupper_l
_ismbslead
_ismbslead_l
_ismbstrail
_ismbstrail_l
_isnan
_isprint_l
_ispunct_l
_isspace_l
_isupper_l
_iswalnum_l
_iswalpha_l
_iswcntrl_l
_iswcsym_l
_iswcsymf_l
_iswctype_l
_iswdigit_l
_iswgraph_l
_iswlower_l
_iswprint_l
_iswpunct_l
_iswspace_l
_iswupper_l
_iswxdigit_l
_isxdigit_l
_itoa
_itoa_s
_itow
_itow_s
_j0
_j1
_jn
_kbhit
_lfind
_lfind_s
_loaddll
_local_unwind2
_local_unwind4
_localtime32
_localtime32_s
_localtime64
_localtime64_s
_lock
_lock_file
_locking
_logb
_longjmpex
_lrotl
_lrotr
_lsearch
_lsearch_s
_lseek
_lseeki64
_ltoa
_ltoa_s
_ltow
_ltow_s
_makepath
_makepath_s
_malloc_crt
_mbbtombc
_mbbtombc_l
_mbbtype
_mbbtype_l
_mbcasemap DATA
_mbccpy
_mbccpy_l
_mbccpy_s
_mbccpy_s_l
_mbcjistojms
_mbcjistojms_l
_mbcjmstojis
_mbcjmstojis_l
_mbclen
_mbclen_l
_mbctohira
_mbctohira_l
_mbctokata
_mbctokata_l
_mbctolower
_mbctolower_l
_mbctombb
_mbctombb_l
_mbctoupper
_mbctoupper_l
_mbctype DATA
_mblen_l
_mbsbtype
_mbsbtype_l
_mbscat_s
_mbscat_s_l
_mbschr
_mbschr_l
_mbscmp
_mbscmp_l
_mbscoll
_mbscoll_l
_mbscpy_s
_mbscpy_s_l
_mbscspn
_mbscspn_l
_mbsdec
_mbsdec_l
_mbsicmp
_mbsicmp_l
_mbsicoll
_mbsicoll_l
_mbsinc
_mbsinc_l
_mbslen
_mbslen_l
_mbslwr
_mbslwr_l
_mbslwr_s
_mbslwr_s_l
_mbsnbcat
_mbsnbcat_l
_mbsnbcat_s
_mbsnbcat_s_l
_mbsnbcmp
_mbsnbcmp_l
_mbsnbcnt
_mbsnbcnt_l
_mbsnbcoll
_mbsnbcoll_l
_mbsnbcpy
_mbsnbcpy_l
_mbsnbcpy_s
_mbsnbcpy_s_l
_mbsnbicmp
_mbsnbicmp_l
_mbsnbicoll
_mbsnbicoll_l
_mbsnbset
_mbsnbset_l
_mbsnbset_s
_mbsnbset_s_l
_mbsncat
_mbsncat_l
_mbsncat_s
_mbsncat_s_l
_mbsnccnt
_mbsnccnt_l
_mbsncmp
_mbsncmp_l
_mbsncoll
_mbsncoll_l
_mbsncpy
_mbsncpy_l
_mbsncpy_s
_mbsncpy_s_l
_mbsnextc
_mbsnextc_l
_mbsnicmp
_mbsnicmp_l
_mbsnicoll
_mbsnicoll_l
_mbsninc
_mbsninc_l
_mbsnlen
_mbsnlen_l
_mbsnset
_mbsnset_l
_mbsnset_s
_mbsnset_s_l
_mbspbrk
_mbspbrk_l
_mbsrchr
_mbsrchr_l
_mbsrev
_mbsrev_l
_mbsset
_mbsset_l
_mbsset_s
_mbsset_s_l
_mbsspn
_mbsspn_l
_mbsspnp
_mbsspnp_l
_mbsstr
_mbsstr_l
_mbstok
_mbstok_l
_mbstok_s
_mbstok_s_l
_mbstowcs_l
_mbstowcs_s_l
_mbstrlen
_mbstrlen_l
_mbstrnlen
_mbstrnlen_l
_mbsupr
_mbsupr_l
_mbsupr_s
_mbsupr_s_l
_mbtowc_l
_memccpy
_memicmp
_memicmp_l
_mkdir
_mkgmtime32
_mkgmtime64
_mktemp
_mktemp_s
_mktime32
_mktime64
_msize
_nextafter
_onexit DATA
_open
_open_osfhandle
_outp
_outpd
_outpw
_pclose
_pctype DATA
_pgmptr DATA
_pipe
_popen
_printf_l
_printf_p
_printf_p_l
_printf_s_l
_purecall
_putch
_putch_nolock
_putenv
_putenv_s
_putw
_putwch
_putwch_nolock
_putws
_pwctype DATA
_read
_realloc_crt
_recalloc
_recalloc_crt
_resetstkoflw
_rmdir
_rmtmp
_rotl
_rotl64
_rotr
_rotr64
_safe_fdiv
_safe_fdivr
_safe_fprem
_safe_fprem1
_scalb
_scanf_l
_scanf_s_l
_scprintf
_scprintf_l
_scprintf_p
_scprintf_p_l
_scwprintf
_scwprintf_l
_scwprintf_p
_scwprintf_p_l
_searchenv
_searchenv_s
_seh_longjmp_unwind
_seh_longjmp_unwind4
_set_SSE2_enable
_set_abort_behavior
_set_amblksiz
_set_controlfp
_set_doserrno
_set_errno
_set_error_mode
_set_fmode
_set_invalid_parameter_handler
_set_malloc_crt_max_wait
_set_output_format
_set_printf_count_output
_set_purecall_handler
_set_sbh_threshold
_seterrormode
_setjmp
_setjmp3
_setmaxstdio
_setmbcp
_setmode
_setsystime
_sleep
_snprintf
_snprintf_c
_snprintf_c_l
_snprintf_l
_snprintf_s
_snprintf_s_l
_snscanf
_snscanf_l
_snscanf_s
_snscanf_s_l
_snwprintf
_snwprintf_l
_snwprintf_s
_snwprintf_s_l
_snwscanf
_snwscanf_l
_snwscanf_s
_snwscanf_s_l
_sopen
_sopen_s
_spawnl
_spawnle
_spawnlp
_spawnlpe
_spawnv
_spawnve
_spawnvp
_spawnvpe
_splitpath
_splitpath_s
_sprintf_l
_sprintf_p
_sprintf_p_l
_sprintf_s_l
_sscanf_l
_sscanf_s_l
_stat32
_stat32i64
_stat64
_stat64i32
_statusfp
_statusfp2
_strcoll_l
_strdate
_strdate_s
_strdup
_strerror
_strerror_s
_strftime_l
_stricmp
_stricmp_l
_stricoll
_stricoll_l
_strlwr
_strlwr_l
_strlwr_s
_strlwr_s_l
_strncoll
_strncoll_l
_strnicmp
_strnicmp_l
_strnicoll
_strnicoll_l
_strnset
_strnset_s
_strrev
_strset
_strset_s
_strtime
_strtime_s
_strtod_l
_strtoi64
_strtoi64_l
_strtol_l
_strtoui64
_strtoui64_l
_strtoul_l
_strupr
_strupr_l
_strupr_s
_strupr_s_l
_strxfrm_l
_swab
_swprintf
_swprintf_c
_swprintf_c_l
_swprintf_p
_swprintf_p_l
_swprintf_s_l
_swscanf_l
_swscanf_s_l
_sys_errlist DATA
_sys_nerr DATA
_tell
_telli64
_tempnam
_time32
_time64
_timezone DATA
_tolower
_tolower_l
_toupper
_toupper_l
_towlower_l
_towupper_l
_tzname DATA
_tzset
_ui64toa
_ui64toa_s
_ui64tow
_ui64tow_s
_ultoa
_ultoa_s
_ultow
_ultow_s
_umask
_umask_s
_ungetc_nolock
_ungetch
_ungetch_nolock
_ungetwc_nolock
_ungetwch
_ungetwch_nolock
_unlink
_unloaddll
_unlock
_unlock_file
_utime32
_utime64
_vcprintf
_vcprintf_l
_vcprintf_p
_vcprintf_p_l
_vcprintf_s
_vcprintf_s_l
_vcwprintf
_vcwprintf_l
_vcwprintf_p
_vcwprintf_p_l
_vcwprintf_s
_vcwprintf_s_l
_vfprintf_l
_vfprintf_p
_vfprintf_p_l
_vfprintf_s_l
_vfwprintf_l
_vfwprintf_p
_vfwprintf_p_l
_vfwprintf_s_l
_vprintf_l
_vprintf_p
_vprintf_p_l
_vprintf_s_l
_vscprintf
_vscprintf_l
_vscprintf_p
_vscprintf_p_l
_vscwprintf
_vscwprintf_l
_vscwprintf_p
_vscwprintf_p_l
_vsnprintf
_vsnprintf_c
_vsnprintf_c_l
_vsnprintf_l
_vsnprintf_s
_vsnprintf_s_l
_vsnwprintf
_vsnwprintf_l
_vsnwprintf_s
_vsnwprintf_s_l
_vsprintf_l
_vsprintf_p
_vsprintf_p_l
_vsprintf_s_l
_vswprintf
_vswprintf_c
_vswprintf_c_l
_vswprintf_l
_vswprintf_p
_vswprintf_p_l
_vswprintf_s_l
_vwprintf_l
_vwprintf_p
_vwprintf_p_l
_vwprintf_s_l
_waccess
_waccess_s
_wasctime
_wasctime_s
_wassert
_wchdir
_wchmod
_wcmdln DATA
_wcreat
_wcscoll_l
_wcsdup
_wcserror
_wcserror_s
_wcsftime_l
_wcsicmp
_wcsicmp_l
_wcsicoll
_wcsicoll_l
_wcslwr
_wcslwr_l
_wcslwr_s
_wcslwr_s_l
_wcsncoll
_wcsncoll_l
_wcsnicmp
_wcsnicmp_l
_wcsnicoll
_wcsnicoll_l
_wcsnset
_wcsnset_s
_wcsrev
_wcsset
_wcsset_s
_wcstod_l
_wcstoi64
_wcstoi64_l
_wcstol_l
_wcstombs_l
_wcstombs_s_l
_wcstoui64
_wcstoui64_l
_wcstoul_l
_wcsupr
_wcsupr_l
_wcsupr_s
_wcsupr_s_l
_wcsxfrm_l
_wctime32
_wctime32_s
_wctime64
_wctime64_s
_wctomb_l
_wctomb_s_l
_wctype
_wdupenv_s
_wenviron DATA
_wexecl
_wexecle
_wexeclp
_wexeclpe
_wexecv
_wexecve
_wexecvp
_wexecvpe
_wfdopen
_wfindfirst32
_wfindfirst32i64
_wfindfirst64
_wfindfirst64i32
_wfindnext32
_wfindnext32i64
_wfindnext64
_wfindnext64i32
_wfopen
_wfopen_s
_wfreopen
_wfreopen_s
_wfsopen
_wfullpath
_wgetcwd
_wgetdcwd
_wgetdcwd_nolock
_wgetenv
_wgetenv_s
_wmakepath
_wmakepath_s
_wmkdir
_wmktemp
_wmktemp_s
_wopen
_wperror
_wpgmptr DATA
_wpopen
_wprintf_l
_wprintf_p
_wprintf_p_l
_wprintf_s_l
_wputenv
_wputenv_s
_wremove
_wrename
_write
_wrmdir
_wscanf_l
_wscanf_s_l
_wsearchenv
_wsearchenv_s
_wsetlocale
_wsopen
_wsopen_s
_wspawnl
_wspawnle
_wspawnlp
_wspawnlpe
_wspawnv
_wspawnve
_wspawnvp
_wspawnvpe
_wsplitpath
_wsplitpath_s
_wstat32
_wstat32i64
_wstat64
_wstat64i32
_wstrdate
_wstrdate_s
_wstrtime
_wstrtime_s
_wsystem
_wtempnam
_wtmpnam
_wtmpnam_s
_wtof
_wtof_l
_wtoi
_wtoi64
_wtoi64_l
_wtoi_l
_wtol
_wtol_l
_wunlink
_wutime32
_wutime64
_y0
_y1
_yn
abort
abs
acos
asctime
asctime_s
asin
atan
atan2
atexit DATA
atof
atoi
atol
bsearch
bsearch_s
btowc
calloc
ceil
clearerr
clearerr_s
clock
cos
cosh
div
exit
exp
fabs
fclose
feof
ferror
fflush
fgetc
fgetpos
fgets
fgetwc
fgetws
floor
fmod
fopen
fopen_s
fprintf
fprintf_s
fputc
fputs
fputwc
fputws
fread
fread_s
free
freopen
freopen_s
frexp
fscanf
fscanf_s
fseek
fsetpos
ftell
fwprintf
fwprintf_s
fwrite
fwscanf
fwscanf_s
getc
getchar
getenv
getenv_s
gets
gets_s
getwc
getwchar
is_wctype
isalnum
isalpha
iscntrl
isdigit
isgraph
isleadbyte
islower
isprint
ispunct
isspace
isupper
iswalnum
iswalpha
iswascii
iswcntrl
iswctype
iswdigit
iswgraph
iswlower
iswprint
iswpunct
iswspace
iswupper
iswxdigit
isxdigit
labs
ldexp
ldiv
localeconv
log
log10
longjmp
malloc
mblen
mbrlen
mbrtowc
mbsrtowcs
mbsrtowcs_s
mbstowcs
mbstowcs_s
mbtowc
memchr
memcmp
memcpy
memcpy_s
memmove
memmove_s
memset
modf
perror
pow
printf
printf_s
putc
putchar
puts
putwc
putwchar
qsort
qsort_s
raise
rand
rand_s
realloc
remove
rename
rewind
scanf
scanf_s
setbuf
setlocale
setvbuf
signal
sin
sinh
sprintf
sprintf_s
sqrt
srand
sscanf
sscanf_s
strcat
strcat_s
strchr
strcmp
strcoll
strcpy
strcpy_s
strcspn
strerror
strerror_s
strftime
strlen
strncat
strncat_s
strncmp
strncpy
strncpy_s
strnlen
strpbrk
strrchr
strspn
strstr
strtod
strtok
strtok_s
strtol
strtoul
strxfrm
swprintf_s
swscanf
swscanf_s
system
tan
tanh
tmpfile
tmpfile_s
tmpnam
tmpnam_s
tolower
toupper
towlower
towupper
ungetc
ungetwc
vfprintf
vfprintf_s
vfwprintf
vfwprintf_s
vprintf
vprintf_s
vsprintf
vsprintf_s
vswprintf_s
vwprintf
vwprintf_s
wcrtomb
wcrtomb_s
wcscat
wcscat_s
wcschr
wcscmp
wcscoll
wcscpy
wcscpy_s
wcscspn
wcsftime
wcslen
wcsncat
wcsncat_s
wcsncmp
wcsncpy
wcsncpy_s
wcsnlen
wcspbrk
wcsrchr
wcsrtombs
wcsrtombs_s
wcsspn
wcsstr
wcstod
wcstok
wcstok_s
wcstol
wcstombs
wcstombs_s
wcstoul
wcsxfrm
wctob
wctomb
wctomb_s
wprintf
wprintf_s
wscanf
wscanf_s
THE_END
# Provide the gmtime stub required by PNG.
cat > gmtime.c << 'THE_END'
/* Stub function for gmtime.
* This is an inline function in Visual C 2008 so is missing from msvcr90.dll
*/
#include
struct tm* _gmtime32(const time_t *timer);
struct tm* gmtime(const time_t *timer)
{
return _gmtime32(timer);
}
THE_END
# Provide the _ftime stub required by numpy.random.mtrand.
cat > _ftime.c << 'THE_END'
/* Stub function for _ftime.
* This is an inline function in Visual C 2008 so is missing from msvcr90.dll
*/
#include
#include
void _ftime32(struct _timeb *timeptr);
void _ftime(struct _timeb *timeptr)
{
_ftime32(timeptr);
}
THE_END
# Provide the time stub required by Numeric.RNG.
cat > time.c << 'THE_END'
/* Stub function for time.
* This is an inline function in Visual C 2008 so is missing from msvcr90.dll
*/
#include
time_t _time32(time_t *timer);
time_t time(time_t *timer)
{
return _time32(timer);
}
THE_END
gcc -c -O2 gmtime.c _ftime.c time.c
dlltool -d msvcr90.def -D msvcr90.dll -l libmsvcr90.dll.a
ar rc libmsvcr90.dll.a gmtime.o _ftime.o time.o
ranlib libmsvcr90.dll.a
cp -f libmsvcr90.dll.a "$DBMSVCR90"
mv -f libmsvcr90.dll.a "$DBMSVCR90/libmsvcrt.dll.a"
gcc -c -g gmtime.c
dlltool -d msvcr90.def -D msvcr90d.dll -l libmsvcr90d.dll.a
ar rc libmsvcr90d.dll.a gmtime.o
ranlib libmsvcr90d.dll.a
cp -f libmsvcr90d.dll.a "$DBMSVCR90"
mv -f libmsvcr90d.dll.a "$DBMSVCR90/libmsvcrtd.dll.a"
# These definitions are taken from mingw-runtime-3.12 .
# The file was generated with the following command:
#
# gcc -DRUNTIME=msvcrt -D__FILENAME__=moldname-msvcrt.def
# -D__MSVCRT__ -C -E -P -xc-header moldname.def.in >moldname-msvcrt.def
# It then had fstat deleted to match with msvcr90.dll.
cat > moldname-msvcrt.def << 'THE_END'
EXPORTS
access
chdir
chmod
chsize
close
creat
cwait
daylight DATA
dup
dup2
ecvt
eof
execl
execle
execlp
execlpe
execv
execve
execvp
execvpe
fcvt
fdopen
fgetchar
fgetwchar
filelength
fileno
; Alias fpreset is set in CRT_fp10,c and CRT_fp8.c.
; fpreset
fputchar
fputwchar
ftime
gcvt
getch
getche
getcwd
getpid
getw
heapwalk
isatty
itoa
kbhit
lfind
lsearch
lseek
ltoa
memccpy
memicmp
mkdir
mktemp
open
pclose
popen
putch
putenv
putw
read
rmdir
rmtmp
searchenv
setmode
sopen
spawnl
spawnle
spawnlp
spawnlpe
spawnv
spawnve
spawnvp
spawnvpe
stat
strcmpi
strdup
stricmp
stricoll
strlwr
strnicmp
strnset
strrev
strset
strupr
swab
tell
tempnam
timezone DATA
; export tzname for both. See
tzname DATA
tzset
umask
ungetch
unlink
utime
wcsdup
wcsicmp
wcsicoll
wcslwr
wcsnicmp
wcsnset
wcsrev
wcsset
wcsupr
wpopen
write
; non-ANSI functions declared in math.h
j0
j1
jn
y0
y1
yn
chgsign
scalb
finite
fpclass
; C99 functions
cabs
hypot
logb
nextafter
THE_END
# Provide the fstat stub required by TIFF.
cat > fstat.c << 'THE_END'
/* Stub function for fstat.
* This is an inlined functions in Visual C 2008 so is missing from msvcr90.dll
*/
#include
int _fstat32(int fd, struct stat *buffer);
int fstat(int fd, struct stat *buffer)
{
return _fstat32(fd, buffer);
}
THE_END
mkdir -p "$DBMSVCR90"
gcc -c -O2 fstat.c
ar x /mingw/lib/libmoldname90.a $OBJS
dlltool --as as -k -U \
--dllname msvcr90.dll \
--def moldname-msvcrt.def \
--output-lib libmoldname.dll.a
ar rc libmoldname.dll.a $OBJS fstat.o
ranlib libmoldname.dll.a
mv -f libmoldname.dll.a "$DBMSVCR90"
gcc -c -g fstat.c
ar x /mingw/lib/libmoldname90d.a $OBJS
dlltool --as as -k -U \
--dllname msvcr90.dll \
--def moldname-msvcrt.def \
--output-lib libmoldnamed.dll.a
ar rc libmoldnamed.dll.a $OBJS fstat.o
ranlib libmoldnamed.dll.a
mv -f libmoldnamed.dll.a "$DBMSVCR90"
rm -f ./*
cd "$OLDPWD"
rmdir /tmp/build_deps
fi
""")
if __name__ == '__main__':
sys.exit(main(dependencies, msvcr90_prep, msys_prep))
pygame-1.9.1release/msys_build_deps.py 0000644 0001750 0001750 00000067724 11227461214 020022 0 ustar vincent vincent #!/usr/bin/env python
# -*- coding: ascii -*-
# Program msys_build_deps.py
# Requires Python 2.4 or later and win32api.
"""Build Pygame dependencies using MinGW and MSYS
Configured for Pygame 1.9.0 and Python 2.4 and up.
The libraries are installed in /usr/local of the MSYS directory structure.
This program can be run from a Windows cmd.exe or MSYS terminal. The current
directory and its outer directory are searched for the library source
directories.
The recognized, and optional, environment variables are:
SHELL - MSYS shell program path - already defined in the MSYS terminal
CFLAGS - compiler options - overrides the defaults used by this program
LDFLAGS - linker options - prepended to flags set by the program
LIBRARY_PATH - library directory paths - appended to those used by this
program
CPATH - C/C++ header file paths - appended to the paths used by this program
To get a list of command line options run
python build_deps.py --help
This program has been tested against the following libraries:
SDL 1.2 (.13) revision 4114 from SVN
SDL_image 1.2.6
SDL_mixer 1.2 (.8) revision 3942 from SVN
SDL_ttf 2.0.9
smpeg revision 370 from SVN
freetype 2.3.7
libogg 1.1.3
libvorbis 1.2.0
FLAC 1.2.1
tiff 3.8.2
libpng 1.2.32
jpeg 6b
zlib 1.2.3
PortMidi release 82
The build environment used:
gcc-core-3.4.5
gcc-c++-3.4.5
binutils-2.17.50
mingwrt-3.15.1
win32api-3.12
mingw32-make-3.81-20080326
MSYS-1.0.10
msysDTK-1.0.1
msys-automake-1.8.2
msys-autocont-2.59
m4-1.4.7-MSYS
nasm-2.05rc6-win32 (SourceForge)
Builds have been performed on Windows 98 and XP.
Build issues:
For pre-2007 computers: MSYS bug "[ 1170716 ] executing a shell scripts
gives a memory leak" (http://sourceforge.net/tracker/
index.php?func=detail&aid=1170716&group_id=2435&atid=102435)
It may not be possible to use the --all option to build all Pygame
dependencies in one session. Instead the job may need to be split into two
or more sessions, with a reboot of the operating system between each. Use
the --help-args option to list the libraries in the their proper build
order.
"""
import msys
from optparse import OptionParser
import os
import sys
from glob import glob
import time
# For Python 2.x/3.x compatibility
def geterror():
return sys.exc_info()[1]
#
# Generic declarations
#
hunt_paths = ['.', '..']
def prompt(p=None):
"""MSYS friendly raw_input
This provides a hook that can be replaced for testing.
"""
msys.msys_raw_input(p)
def print_(*args, **kwds):
msys.msys_print(*args, **kwds)
def confirm(message):
"""Ask a yes/no question, return result"""
reply = prompt("\n%s [Y/n]:" % message)
if reply and reply[0].lower() == 'n':
return 0
return 1
def as_flag(b):
"""Return bool b as a shell script flag '1' or '0'"""
if b:
return '1'
return '0'
def merge_strings(*args, **kwds):
"""Returns non empty string joined by sep
The default separator is an empty string.
"""
sep = kwds.get('sep', '')
return sep.join([s for s in args if s])
class BuildError(Exception):
"""Raised for missing source paths and failed script runs"""
pass
class Dependency(object):
"""Builds a library"""
def __init__(self, name, wildcards, dlls, shell_script):
self.name = name
self.wildcards = wildcards
self.shell_script = shell_script
self.dlls = dlls
def configure(self, hunt_paths):
self.path = None
self.paths = []
self.hunt(hunt_paths)
self.choosepath()
def hunt(self, hunt_paths):
parent = os.path.abspath('..')
for p in hunt_paths:
for w in self.wildcards:
found = glob(os.path.join(p, w))
found.sort() or found.reverse() #reverse sort
for f in found:
if f[:5] == '..'+os.sep+'..' and \
os.path.abspath(f)[:len(parent)] == parent:
continue
if os.path.isdir(f):
self.paths.append(f)
def choosepath(self):
path = None
if not self.paths:
raise BuildError("Path for %s: not found" % self.name)
if len(self.paths) == 1:
path = self.paths[0]
else:
print_("Select path for %s:" % self.name)
for i in range(len(self.paths)):
print_(" %d = %s" % (i+1, self.paths[i]))
print_(" 0 = ")
choice = prompt("Select 0-%d (1=default):" % len(self.paths))
if not choice:
choice = 1
else:
choice = int(choice)
if choice > 0:
path = self.paths[choice-1]
if path is not None:
self.path = os.path.abspath(path)
def build(self, msys):
if self.path is not None:
msys.environ['BDWD'] = msys.windows_to_msys(self.path)
return_code = msys.run_shell_script(self.shell_script)
if return_code != 0:
raise BuildError("The build for %s failed with code %d" %
(self.name, return_code))
else:
raise BuildError("No source directory for %s" % self.name)
class Preparation(object):
"""Perform necessary build environment preperations"""
def __init__(self, name, shell_script):
self.name = name
self.path = ''
self.paths = []
self.dlls = []
self.shell_script = shell_script
def configure(self, hunt_paths):
pass
def build(self, msys):
return_code = msys.run_shell_script(self.shell_script)
if return_code != 0:
raise BuildError("Preparation '%s' failed with code %d" %
(self.name, return_code))
def configure(dependencies):
"""Find source directories of all dependencies"""
success = True
print_("Hunting for source directories...")
for dep in dependencies:
try:
dep.configure(hunt_paths)
except BuildError:
print_(geterror())
success = False
else:
if dep.path:
print_("Source directory for", dep.name, ":", dep.path)
if not success:
raise BuildError("Not all source directories were found")
def build(dependencies, msys):
"""Execute that shell scripts for all dependencies"""
for dep in dependencies:
dep.build(msys)
def command_line():
"""Process the command line and return the options"""
usage = ("usage: %prog [options] --all\n"
" %prog [options] [args]\n"
"\n"
"Build the Pygame dependencies. The args, if given, are\n"
"libraries to include or exclude.\n"
"\n"
"At startup this program may prompt for missing information.\n"
"Be aware of this before redirecting output or leaving the\n"
"program unattended. Once the 'Starting build' message appears\n"
"no more user input is required. The build process will"
"abort on the first error, as library build order is important.\n"
"\n"
"See --include and --help-args.\n"
"\n"
"For more details see the program's document string\n")
parser = OptionParser(usage)
parser.add_option('-a', '--all', action='store_true', dest='build_all',
help="Include all libraries in the build")
parser.set_defaults(build_all=False)
parser.add_option('--no-msvcr71', action='store_false', dest='msvcr71',
help="Do not link to msvcr71.dll")
parser.set_defaults(msvcr71=True)
parser.add_option('--console', action='store_true', dest='console',
help="Link with the console subsystem:"
" defaults to Win32 GUI")
parser.set_defaults(console=False)
parser.add_option('--no-configure', action='store_false', dest='configure',
help="Do not prepare the makefiles")
parser.set_defaults(configure=True)
parser.add_option('--no-compile', action='store_false', dest='compile',
help="Do not compile or install the libraries")
parser.set_defaults(compile=True)
parser.add_option('--no-install', action='store_false', dest='install',
help="Do not install the libraries")
parser.add_option('--no-strip', action='store_false', dest='strip',
help="Do not strip the library")
parser.set_defaults(strip=True)
parser.set_defaults(install=True)
parser.add_option('--clean', action='store_true', dest='clean',
help="Remove generated files (make clean)"
" as a last step")
parser.set_defaults(clean=False)
parser.add_option('--clean-only', action='store_true', dest='clean_only',
help="Perform only a clean")
parser.set_defaults(clean_only=False)
parser.add_option('-e', '--exclude', action='store_true', dest='exclude',
help="Exclude the specified libraries")
parser.set_defaults(exclude=False)
parser.add_option('-m', '--msys-root', action='store',
dest='msys_directory',
help="MSYS directory path, which may include"
" the 1.x subdirectory")
parser.set_defaults(msys_directory='')
parser.add_option('--help-args', action='store_true', dest='arg_help',
help="Show a list of recognised libraries,"
" in build order, and exit")
parser.set_defaults(arg_help=False)
return parser.parse_args()
def set_environment_variables(msys, options):
"""Set the environment variables used by the scripts"""
environ = msys.environ
msys_root = msys.msys_root
environ['BDCONF'] = as_flag(options.configure and
not options.clean_only)
environ['BDCOMP'] = as_flag(options.compile and
not options.clean_only)
environ['BDINST'] = as_flag(options.install and
options.compile and
not options.clean_only)
environ['BDSTRIP'] = as_flag(options.install and
options.strip and
not options.clean_only)
environ['BDCLEAN'] = as_flag(options.clean or options.clean_only)
environ.pop('INCLUDE', None) # INCLUDE causes problems with MIXER.
if 'CFLAGS' not in environ:
environ['CFLAGS'] = '-O2'
ldflags = '-mwindows'
if options.console:
ldflags = '-mconsole'
environ['LDFLAGS'] = merge_strings(environ.get('LDFLAGS', ''), ldflags,
sep=' ')
library_path = os.path.join(msys_root, 'local', 'lib')
msvcr71_path = ''
if options.msvcr71:
# Hide the msvcrt.dll import libraries with those for msvcr71.dll.
# Their subdirectory is in the same directory as the SDL library.
msvcr71_path = os.path.join(library_path, 'msvcr71')
environ['DBMSVCR71'] = msvcr71_path
# For dependency libraries and msvcrt hiding.
environ['LIBRARY_PATH'] = merge_strings(library_path, msvcr71_path,
environ.get('LIBRARY_PATH', ''),
sep=';')
# For dependency headers.
include_path = os.path.join(msys_root, 'local', 'include')
environ['CPATH'] = merge_strings(include_path, environ.get('CPATH', ''),
sep=';')
class ChooseError(Exception):
"""Failer to select dependencies"""
pass
def choose_dependencies(dependencies, options, args):
"""Return the dependencies to actually build"""
if options.build_all:
if args:
raise ChooseError("No library names are accepted"
" for the --all option.")
if options.exclude:
return []
else:
return dependencies
if args:
names = [d.name for d in dependencies]
args = [a.upper() for a in args]
for a in args:
if a not in names:
msg = ["%s is an unknown library; valid choices are:" % a]
msg.extend(names)
raise ChooseError('\n'.join(msg))
if options.exclude:
return [d for d in dependencies if d.name not in args]
return [d for d in dependencies if d.name in args]
return []
def summary(dependencies, msys, start_time, chosen_deps):
"""Display a summary report of new, existing and missing DLLs"""
import datetime
print_("\n\n=== Summary ===")
if start_time is not None:
print_(" Elapse time:",
datetime.timedelta(seconds=time.time()-start_time))
print_()
for dep in chosen_deps:
if dep.path is None:
print_(" ** No source directory found for", dep.name)
elif dep.path:
print_(" Source directory for", dep.name, ":", dep.path)
print_()
msys_root = msys.msys_root
bin_dir = os.path.join(msys_root, 'local', 'bin')
for d in dependencies:
name = d.name
dlls = d.dlls
for dll in dlls:
dll_path = os.path.join(bin_dir, dll)
try:
mod_time = os.path.getmtime(dll_path)
except:
msg = "No DLL"
else:
if mod_time >= start_time:
msg = "Installed new DLL %s" % dll_path
else:
msg = "-- (old DLL %s)" % dll_path
print_(" %-10s: %s" % (name, msg))
def main(dependencies, msvcr71_preparation, msys_preparation):
"""Build the dependencies according to the command line options."""
options, args = command_line()
if options.arg_help:
print_("These are the Pygame library dependencies:")
for dep in dependencies:
print_(" ", dep.name)
return 0
try:
chosen_deps = choose_dependencies(dependencies, options, args)
except ChooseError:
print_(geterror())
return 1
if not chosen_deps:
if not args:
print_("No libraries specified.")
elif options.build_all:
print_("All libraries excluded")
if options.msvcr71:
chosen_deps.insert(0, msvcr71_preparation)
if chosen_deps:
chosen_deps.insert(0, msys_preparation)
try:
m = msys.Msys(options.msys_directory)
except msys.MsysException:
print_(geterror())
return 1
start_time = None
return_code = 1
set_environment_variables(m, options)
try:
configure(chosen_deps)
except BuildError:
print_("Build aborted:", geterror())
else:
print_("\n=== Starting build ===")
start_time = time.time() # For file timestamp checks.
try:
build(chosen_deps, m)
except BuildError:
print_("Build aborted:", geterror())
else:
# A successful build!
return_code = 0
summary(dependencies, m, start_time, chosen_deps)
# MinGW configure file for setup.py (optional).
try:
import mingwcfg
except ImportError:
pass
else:
mingwcfg.write(m.mingw_root)
return return_code
#
# Build specific code
#
# This list includes the MSYS shell scripts to build each library. Each script
# runs in an environment where MINGW_ROOT_DIRECTORY is defined and the MinGW
# bin directory is in PATH. Four other environment variables are defined:
# BDCONF, BDCOMP, BDINST and BDCLEAN. They are either '0' or '1'. They
# represent configure, compile, install and clean respectively. When '1' the
# corresponding action is performed. When '0' it is skipped. A final variable,
# DBWD, is the root directory of the source code. A script will cd to it before
# doing anything else.
#
# None of these scripts end with an "exit". Exit, possibly, leads to Msys
# freezing on some versions of Windows (98).
#
# The list order corresponds to build order. It is critical.
dependencies = [
Dependency('SDL', ['SDL-[1-9].*'], ['SDL.dll'], """
set -e
cd $BDWD
if [ x$BDCONF == x1 ]; then
# Remove NONAMELESSUNION from directx.h headers.
for d in video audio; do
BDDXHDR=src/$d/windx5/directx.h
cp -f $BDDXHDR $BDDXHDR'_'
sed 's/^\\(#define NONAMELESSUNION\\)/\\/*\\1*\\//' $BDDXHDR'_' >$BDDXHDR
if [ x$? != x0 ]; then exit $?; fi
rm $BDDXHDR'_'
BDDXHDR=
done
# This comes straight from SVN so has no configure script
if [ ! -f "./configure" ]; then
./autogen.sh
fi
./configure
fi
if [ x$BDCOMP == x1 ]; then
make
fi
if [ x$BDINST == x1 ]; then
make install
# Make SDL_config_win32.h available for prebuilt and MSVC
cp -f "$BDWD/include/SDL_config_win32.h" "/usr/local/include/SDL"
fi
if [ x$BDSTRIP == x1 ]; then
strip --strip-all /usr/local/bin/SDL.dll
fi
if [ x$BDCLEAN == x1 ]; then
set +e
make clean
fi
"""),
Dependency('Z', ['zlib-[1-9].*'], ['zlib1.dll'], """
set -e
cd $BDWD
if [ x$BDCONF == x1 ]; then
# Use the existing gcc makefile, modified to add linker options.
sed "s/dllwrap/dllwrap $LDFLAGS/" win32/Makefile.gcc >Makefile.gcc
fi
if [ x$BDCOMP == x1 ]; then
# Build with the import library renamed.
make IMPLIB='libz.dll.a' -fMakefile.gcc "CFLAGS=$CFLAGS"
fi
if [ x$BDINST == x1 ]; then
# Have to do own install.
cp -fp *.a /usr/local/lib
cp -fp zlib.h /usr/local/include
cp -fp zconf.h /usr/local/include
cp -fp zlib1.dll /usr/local/bin
fi
if [ x$BDSTRIP == x1 ]; then
strip --strip-all /usr/local/bin/zlib1.dll
fi
if [ x$BDCLEAN == x1 ]; then
set +e
make clean
fi
"""),
Dependency('FREETYPE', ['freetype-[2-9].*'], ['libfreetype-6.dll'], """
set -e
cd $BDWD
if [ x$BDCONF == x1 ]; then
# Need to define inline as freetypes is compiled as -pedentic
# yet stdlib.h is not.
export CPPFLAGS="-Dinline=__inline__ $CPPFLAGS"
./configure
fi
if [ x$BDCOMP == x1 ]; then
make
fi
if [ x$BDINST == x1 ]; then
make install
fi
if [ x$BDSTRIP == x1 ]; then
strip --strip-all /usr/local/bin/libfreetype-6.dll
fi
if [ x$BDCLEAN == x1 ]; then
set +e
make clean
fi
"""),
Dependency('FONT', ['SDL_ttf-[2-9].*'], ['SDL_ttf.dll'], """
set -e
cd $BDWD
if [ x$BDCONF == x1 ]; then
./configure
fi
if [ x$BDCOMP == x1 ]; then
make
fi
if [ x$BDINST == x1 ]; then
make install
fi
if [ x$BDSTRIP == x1 ]; then
strip --strip-all /usr/local/bin/SDL_ttf.dll
fi
if [ x$BDCLEAN == x1 ]; then
set +e
make clean
fi
"""),
Dependency('PNG', ['libpng-[1-9].*'], ['libpng12-0.dll'], """
set -e
cd $BDWD
if [ x$BDCONF == x1 ]; then
# This will only build a static library.
./configure --with-libpng-compat=no
# Remove a duplicate entry in the def file.
BDDEF=scripts/pngw32.def
cp -f "$BDDEF" temp_
sed '222 s/^\\( png_malloc_warn @195\\)/;\\1/' temp_ >"$BDDEF"
rm temp_
fi
if [ x$BDCOMP == x1 ]; then
make
fi
if [ x$BDINST == x1 ]; then
make install
# Sorry, but no one else recognizes png12
cp -f /usr/local/lib/libpng12.dll.a /usr/local/lib/libpng.dll.a
fi
if [ x$BDSTRIP == x1 ]; then
strip --strip-all /usr/local/bin/libpng12-0.dll
fi
if [ x$BDCLEAN == x1 ]; then
set +e
make clean
fi
"""),
Dependency('JPEG', ['jpeg-[6-9]*'], ['jpeg.dll'], """
set -e
cd $BDWD
if [ x$BDCONF == x1 ]; then
# This will only build a static library.
./configure --disable-shared
fi
if [ x$BDCOMP == x1 ]; then
# Build the DLL as a win32 gui.
make
dlltool --export-all-symbols -D jpeg.dll -l libjpeg.dll.a -z in.def libjpeg.a
ranlib libjpeg.dll.a
gcc -shared -s $LDFLAGS -def in.def -o jpeg.dll libjpeg.a
fi
if [ x$BDINST == x1 ]; then
# Only install the headers and import library, otherwise SDL_image will
# statically link to jpeg.
make install-headers
cp -fp libjpeg.a /usr/local/lib
cp -fp libjpeg.dll.a /usr/local/lib
cp -fp jpeg.dll /usr/local/bin
if [ x$? != x0 ]; then exit $?; fi
fi
if [ x$BDSTRIP == x1 ]; then
strip --strip-all /usr/local/bin/jpeg.dll
fi
if [ x$BDCLEAN == x1 ]; then
set +e
make clean
rm -f in.def
rm -f libjpeg.dll.a
rm -f jpeg.dll
fi
"""),
Dependency('TIFF', ['tiff-[3-9].*'], ['libtiff.dll'], """
set -e
cd $BDWD
if [ x$BDCONF == x1 ]; then
# The shared library build does not work
./configure --disable-cxx --prefix=/usr/local --disable-shared
fi
if [ x$BDCOMP == x1 ]; then
make
# Build the DLL as a win32 gui
cd libtiff
gcc -shared -s $LDFLAGS -def libtiff.def -o libtiff.dll .libs/libtiff.a \
-ljpeg -lz
dlltool -D libtiff.dll -d libtiff.def -l libtiff.dll.a
ranlib libtiff.dll.a
cd ..
fi
if [ x$BDINST == x1 ]; then
# Don't install any libtools info files so SDL_image will not
# statically link to jpeg.
cd libtiff
make install-data-am
cp -fp .libs/libtiff.a /usr/local/lib
cp -fp libtiff.dll.a /usr/local/lib
cp -fp libtiff.dll /usr/local/bin
if [ x$? != x0 ]; then exit $?; fi
cd ..
fi
if [ x$BDSTRIP == x1 ]; then
strip --strip-all /usr/local/bin/libtiff.dll
fi
if [ x$BDCLEAN == x1 ]; then
set +e
make clean
rm -f libtiff/libtiff.dll.a
rm -f libtiff/libtiff.dll
fi
"""),
Dependency('IMAGE', ['SDL_image-[1-9].*'], ['SDL_image.dll'], """
set -e
cd $BDWD
if [ x$BDCONF == x1 ]; then
# Disable dynamic loading of image libraries as that uses the wrong DLL
# search path
./configure --disable-jpeg-shared --disable-png-shared --disable-tif-shared
fi
if [ x$BDCOMP == x1 ]; then
make
fi
if [ x$BDINST == x1 ]; then
make install
fi
if [ x$BDSTRIP == x1 ]; then
strip --strip-all /usr/local/bin/SDL_image.dll
fi
if [ x$BDCLEAN == x1 ]; then
set +e
make clean
fi
"""),
Dependency('SMPEG', ['smpeg-[0-9].*', 'smpeg'], ['smpeg.dll'], """
set -e
cd $BDWD
if [ x$BDCONF == x1 ]; then
# This comes straight from SVN so has no configure script
if [ ! -f "./configure" ]; then
./autogen.sh
fi
./configure --disable-gtk-player --disable-opengl-player --disable-gtktest
fi
if [ x$BDCOMP == x1 ]; then
make CXXLD='$(CXX) -no-undefined'
fi
if [ x$BDINST == x1 ]; then
make install
fi
if [ x$BDSTRIP == x1 ]; then
strip --strip-all /usr/local/bin/smpeg.dll
fi
if [ x$BDCLEAN == x1 ]; then
set +e
make clean
fi
"""),
Dependency('OGG', ['libogg-[1-9].*'], ['libogg-0.dll'], """
set -e
cd $BDWD
if [ x$BDCONF == x1 ]; then
./configure
fi
if [ x$BDCOMP == x1 ]; then
make
fi
if [ x$BDINST == x1 ]; then
make install
fi
if [ x$BDSTRIP == x1 ]; then
strip --strip-all /usr/local/bin/libogg-0.dll
fi
if [ x$BDCLEAN == x1 ]; then
set +e
make clean
fi
"""),
Dependency('VORBIS',
['libvorbis-[1-9].*'],
['libvorbis-0.dll', 'libvorbisfile-3.dll'], """
set -e
cd $BDWD
if [ x$BDCONF == x1 ]; then
./configure
fi
if [ x$BDCOMP == x1 ]; then
make LIBS='-logg'
fi
if [ x$BDINST == x1 ]; then
make install
fi
if [ x$BDSTRIP == x1 ]; then
strip --strip-all /usr/local/bin/libvorbis-0.dll
strip --strip-all /usr/local/bin/libvorbisfile-3.dll
fi
if [ x$BDCLEAN == x1 ]; then
set +e
make clean
fi
"""),
Dependency('FLAC', ['flac-[1-9].*'], [], """
set -e
cd $BDWD
if [ x$BDCONF == x1 ]; then
# Add __MINGW32__ to SIZE_T_MAX declaration test in alloc.h header.
BDHDR='include/share/alloc.h'
BDTMP='alloc.h_'
cp -f "$BDHDR" "$BDTMP"
sed 's/^# ifdef _MSC_VER$/# if defined _MSC_VER || defined __MINGW32__/' \
"$BDTMP" >"$BDHDR"
rm "$BDTMP"
# Will only install a static library, but that is all that is needed.
./configure --disable-shared --disable-ogg --disable-cpplibs \
--disable-doxygen-docs
fi
if [ x$BDCOMP == x1 ]; then
make
fi
if [ x$BDINST == x1 ]; then
cp src/libFLAC/.libs/libFLAC.a /usr/local/lib
mkdir -p /usr/local/include/FLAC
cp -f include/FLAC/*.h /usr/local/include/FLAC
fi
if [ x$BDCLEAN == x1 ]; then
set +e
make clean
fi
"""),
Dependency('MIXER', ['SDL_mixer-[1-9].*'], ['SDL_mixer.dll'], """
set -e
cd $BDWD
if [ x$BDCONF == x1 ]; then
# This comes straight from SVN so has no configure script
if [ ! -f "./configure" ]; then
./autogen.sh
fi
# Need to add Ws2_32 library for FLAC.
cp -f configure configure_
sed '
s/\\(EXTRA_LDFLAGS="$EXTRA_LDFLAGS -lFLAC\\)"/\\1 -lWs2_32"/
s/\\(LIBS="-lFLAC\\)\\( $LIBS"\\)/\\1 -lWs2_32\\2/' \
configure_ >configure
rm configure_
# No dynamic loading of dependent libraries.
./configure --disable-music-ogg-shared --disable-music-mp3-shared \
--disable-music-flac-shared
fi
if [ x$BDCOMP == x1 ]; then
make
fi
if [ x$BDINST == x1 ]; then
make install
fi
if [ x$BDSTRIP == x1 ]; then
strip --strip-all /usr/local/bin/SDL_mixer.dll
fi
if [ x$BDCLEAN == x1 ]; then
set +e
make clean
fi
"""),
Dependency('PORTMIDI', ['portmidi', 'portmidi-[1-9].*'], ['portmidi.dll'], """
set -e
cd $BDWD
if [ x$BDCONF == x1 ]; then
cat > GNUmakefile << 'THE_END'
# Makefile for portmidi, generated for Pygame by msys_build_deps.py.
target = /usr/local
pmcom = pm_common
pmwin = pm_win
pt = porttime
pmdll = portmidi.dll
pmlib = libportmidi.a
pmimplib = libportmidi.dll.a
pmcomsrc = $(pmcom)/portmidi.c $(pmcom)/pmutil.c
pmwinsrc = $(pmwin)/pmwin.c $(pmwin)/pmwinmm_.c
pmobj = portmidi.o pmutil.o pmwin.o pmwinmm_.o
pmsrc = $(pmcomsrc) $(pmwinsrc)
pmreqhdr = $(pmcom)/portmidi.h $(pmcom)/pmutil.h
pmhdr = $(pmreqhdr) $(pmcom)/pminternal.h $(pmwin)/pmwinmm.h
ptsrc = $(pt)/porttime.c porttime/ptwinmm.c
ptobj = porttime.o ptwinmm.o
ptreqhdr = $(pt)/porttime.h
pthdr = $(ptreqhdr)
src = $(pmsrc) $(ptsrc)
reqhdr = $(pmreqhdr) $(ptreqhdr)
hdr = $(pmhdr) $(pthdr)
obj = $(pmobj) $(ptobj)
def = portmidi.def
IHDR := -I$(pmcom) -I$(pmwin) -I$(pt)
LIBS := $(LOADLIBES) $(LDLIBS) -lwinmm
all : $(pmdll)
.PHONY : all
$(pmwin)/pmwinmm_.c : $(pmwin)/pmwinmm.c
\tsed 's_#define DEBUG.*$$_/*&*/_' < "$<" > "$@"
$(pmlib) : $(src) $(hdr)
\t$(CC) $(CPPFLAGS) $(IHDR) -c $(CFLAGS) $(src)
\tar rc $(pmlib) $(obj)
\tranlib $(pmlib)
$(pmdll) : $(pmlib) $(def)
\t$(CC) -shared $(LDFLAGS) -def $(def) $(pmlib) $(LIBS) -o $@
\tdlltool -D $(pmdll) -d $(def) -l $(pmimplib)
\tranlib $(pmimplib)
.PHONY : install
install : $(pmdll)
\tcp -f --target-directory=$(target)/bin $<
\tcp -f --target-directory=$(target)/lib $(pmlib)
\tcp -f --target-directory=$(target)/lib $(pmimplib)
\tcp -f --target-directory=$(target)/include $(reqhdr)
.PHONY : clean
clean :
\trm -f $(obj) $(pmdll) $(pmimplib) $(pmlib) $(pmwin)/pmwinmm_.c
THE_END
cat > portmidi.def << 'THE_END'
LIBRARY portmidi.dll
EXPORTS
Pm_Abort
Pm_Close
Pm_CountDevices
Pm_Dequeue
Pm_Enqueue
Pm_GetDefaultInputDeviceID
Pm_GetDefaultOutputDeviceID
Pm_GetDeviceInfo
Pm_GetErrorText
Pm_GetHostErrorText
Pm_HasHostError
Pm_Initialize
Pm_OpenInput
Pm_OpenOutput
Pm_Poll
Pm_QueueCreate
Pm_QueueDestroy
Pm_QueueEmpty
Pm_QueueFull
Pm_QueuePeek
Pm_Read
Pm_SetChannelMask
Pm_SetFilter
Pm_SetOverflow
Pm_Terminate
Pm_Write
Pm_WriteShort
Pm_WriteSysEx
Pt_Sleep
Pt_Start
Pt_Started
Pt_Stop
Pt_Time
pm_add_device
pm_alloc
pm_descriptor_index DATA
pm_descriptor_max DATA
pm_fail_fn
pm_fail_timestamp_fn
pm_free
pm_hosterror DATA
pm_hosterror_text DATA
pm_init
pm_none_dictionary DATA
pm_read_bytes
pm_read_short
pm_success_fn
pm_term
pm_winmm_in_dictionary DATA
pm_winmm_init
pm_winmm_out_dictionary DATA
pm_winmm_term
THE_END
fi
if [ x$BDCOMP == x1 ]; then
make
fi
if [ x$BDINST == x1 ]; then
make install
fi
if [ x$BDSTRIP == x1 ]; then
strip --strip-all /usr/local/bin/portmidi.dll
fi
if [ x$BDCLEAN == x1 ]; then
set +e
make clean
rm -f GNUmakefile portmidi.def
fi
"""),
] # End dependencies = [.
msys_prep = Preparation('/usr/local', """
# Ensure /usr/local and its subdirectories exist.
mkdir -p /usr/local/lib
mkdir -p /usr/local/include
mkdir -p /usr/local/bin
mkdir -p /usr/local/doc
mkdir -p /usr/local/man
mkdir -p /usr/local/share
""")
msvcr71_prep = Preparation('msvcr71.dll linkage', r"""
set -e
#
# msvcr71.dll support
#
if [ ! -f "$DBMSVCR71/libmoldname.a" ]; then
mkdir -p "$DBMSVCR71"
cp -fp /mingw/lib/libmoldname71.a "$DBMSVCR71/libmoldname.a"
cp -fp /mingw/lib/libmoldname71d.a "$DBMSVCR71/libmoldnamed.a"
cp -fp /mingw/lib/libmsvcr71.a "$DBMSVCR71/libmsvcrt.a"
cp -fp /mingw/lib/libmsvcr71d.a "$DBMSVCR71/libmsvcrtd.a"
fi
""")
if __name__ == '__main__':
sys.exit(main(dependencies, msvcr71_prep, msys_prep))
pygame-1.9.1release/msys.py 0000644 0001750 0001750 00000023521 11202451362 015607 0 ustar vincent vincent # module msys.py
# Requires Python 2.4 or better and win32api.
"""MSYS specifics for Msys terminal IO and for running shell scripts
exports msys_raw_input, MsysException, Msys
"""
from msysio import raw_input_ as msys_raw_input, print_ as msys_print
from msysio import is_msys
import os
import time
import subprocess
import re
import glob
try:
import _winreg
except ImportError:
import winreg as _winreg
# For Python 2.x/3.x compatibility
def geterror():
return sys.exc_info()[1]
FSTAB_REGEX = (r'^[ \t]*(?P'
r'([a-zA-Z]:){0,1}([\\/][^\s*^?:%\\/]+)+)'
r'[ \t]+/mingw(\s|$)'
)
def has_drive(path):
"""Return true if the MSYS path strats with a drive letter"""
return re.match('/[A-Z]/', path, re.I) is not None
class MsysException(Exception):
"""Path retrieval problem"""
pass
def find_msys_version_subdir(msys_dir):
"""Return the full MSYS root directory path
If msys_dir path lacks the version subdirectory, e.g. 1.0, then the
path is searched for one. The user will be prompted to choose if more
than one version is found.
"""
regex = r'[\\/][1-9][.][0-9]$'
if re.search(regex, msys_dir) is not None:
return msys_dir
roots = glob.glob(os.path.join(msys_dir, '[1-9].[0-9]'))
roots.sort()
roots.reverse()
if not roots:
raise MsysException("No msys versions found.\n")
else:
if len(roots) == 1:
root = roots[0]
else:
msys_print("Select an Msys version:")
for i, path in enumerate(roots):
msys_print(" %d = %s" % (i+1, os.path.split(path)[1]))
choice = msys_raw_input("Select 1-%d (1 = default):")
if not choice:
root = roots[0]
else:
root = roots[int(choice)-1]
return root
def input_msys_dir():
"""Return user entered MSYS directory path
May raise MsysException."""
while 1:
dir_path = msys_raw_input("Enter the MSYS directory path,\n"
"(or press [Enter] to quit):")
dir_path = dir_path.strip()
if not dir_path:
raise MsysException("Input aborted by user")
dir_path = os.path.abspath(dir_path)
try:
return find_msys_version_subdir(dir_path)
except MsysException:
msys_print(geterror())
def find_msys_registry():
"""Return the MSYS 1.0 directory path stored in the Windows registry
The return value is an encoded ascii str. The registry entry for the
uninstaller is used. Raise a LookupError if not found.
"""
subkey = (
'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\MSYS-1.0_is1')
try:
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, subkey)
try:
return _winreg.QueryValueEx(key, 'Inno Setup: App Path')[0].encode()
finally:
key.Close()
except WindowsError:
raise LookupError("MSYS not found in the registry")
def as_shell(msys_root):
"""Append MSYS shell program to MSYS root directory path"""
return os.path.join(msys_root, 'bin', 'sh.exe')
def check_for_shell(msys_directory=None):
"""Check various locations for MSYS shell or root directory.
May raise MsysException.
"""
if msys_directory is not None:
try:
dir_path = find_msys_version_subdir(msys_directory)
except MsysException:
pass
else:
return as_shell(dir_path)
try:
shell = os.environ['SHELL']
except KeyError:
pass
else:
if is_msys():
return shell + '.exe'
return shell
try:
dir_path = find_msys_registry()
except LookupError:
pass
else:
return as_shell(dir_path)
return as_shell(input_msys_dir())
def find_msys_shell(msys_directory=None):
"""Retrun the MSYS shell program path
MsysException is raised if the shell program is not found. The user
is prompt is prompted as a last resort if no directory is found or
there are multiple choices.
"""
shell = check_for_shell(msys_directory)
while 1:
shell = os.path.abspath(shell.replace('/', os.sep))
if os.path.isfile(shell):
break
msys_print("Directory %s has no MSYS shell." % shell)
shell = as_shell(input_msys_dir())
return shell
def find_mingw_root(msys_directory):
"""Return the Windows equivalent of /mingw"""
# Look it up in the fstabs file.
fstab_path = os.path.join(msys_directory, 'etc', 'fstab')
try:
fstab = open(fstab_path, 'r')
except IOError:
raise MsysException("Unable to open MSYS fstab file %s" % fstab_path)
else:
match = re.search(FSTAB_REGEX, fstab.read(), re.MULTILINE)
if match is None:
raise MsysException(
"The required MinGW path is not in the MSYS fstab file")
dir_path = os.path.abspath(match.groupdict()['path'])
if not os.path.isdir(dir_path):
raise MsysException("%s is not a directory" % dir_path)
return dir_path
class Msys(object):
"""Return a new Msys environment; May raise MsysException
Msys([msys_directory, [require_mingw]])
msys_directory: A string giving the path of the MSYS directory.
Either or both keyword arguments can be omitted. If msys_directory
is not provided then the environment variable SHELL and the Windows
registry are checked. Finally the user is prompted for the directory
path. If require_mingw is True, the default, the mingw directory path
is retrieved from the MSYS fstab file. An MsysException is raised if
the required paths are not found.
"""
_is_msys = is_msys()
def __init__(self, msys_directory=None, require_mingw=None):
"""New environment
May raise MsysException"""
if require_mingw is None:
require_mingw = True
self._environ = os.environ.copy()
self._shell = find_msys_shell(msys_directory)
self._msys_root = os.path.split(os.path.split(self.shell)[0])[0].lower()
try:
self._mingw_root = find_mingw_root(self.msys_root)
except MsysException:
if require_mingw:
raise
self._mingw_root = None
else:
self.environ['MINGW_ROOT_DIRECTORY'] = self._mingw_root
environ = property(lambda self: self._environ,
doc="Environment variables")
shell = property(lambda self: self._shell,
doc="MSYS shell program path")
msys_root = property(lambda self: self._msys_root,
doc="MSYS root directory path")
mingw_root = property(lambda self: self._mingw_root,
doc="MinGW root directory path")
is_msys = property(lambda self: self._is_msys,
doc="True if the execution environment is MSYS")
def windows_to_msys(self, path):
"""Return an MSYS translation of an absolute Windows path"""
msys_root = self.msys_root
mingw_root = self.mingw_root
path_lower = path.lower()
if path_lower.startswith(msys_root.lower()):
return '/usr' + path[len(msys_root):].replace(os.sep, '/')
if mingw_root is not None and path_lower.startswith(mingw_root.lower()):
return '/mingw' + path[len(mingw_root):].replace(os.sep, '/')
drive, tail = os.path.splitdrive(path)
return '/%s%s' % (drive[0], tail.replace(os.sep, '/'))
def msys_to_windows(self, path):
"""Return a Windows translation of an MSYS path
The Unix path separator is uses as it survives the distutils setup
file read process. Raises a ValueError if the path cannot be
translated.
"""
msys_root = self.msys_root
mingw_root = self.mingw_root
if path.startswith('/usr'):
path = msys_root + path[4:]
elif path.startswith('/mingw'):
if mingw_root is None:
raise ValueError('Unable to map the MinGW directory')
path = mingw_root + path[6:]
elif has_drive(path):
path = path[1] + ":" + path[2:]
elif path == '/':
path = msys_root
elif path.startswith('/'):
path = msys_root + path
return path.replace(os.sep, '/')
def run_shell_script(self, script):
"""Run the MSYS shell script and return the shell return code
script is a string representing the contents of the script.
"""
cmd = [self.shell]
if not self._is_msys:
cmd.append('--login')
previous_cwd = os.getcwd()
try:
process = subprocess.Popen(cmd,
stdin=subprocess.PIPE,
env=self.environ)
process.communicate(script)
return process.returncode
finally:
time.sleep(2) # Allow shell subprocesses to terminate.
os.chdir(previous_cwd)
def run_shell_command(self, command):
"""Run the MSYS shell command and return stdout output as a string
command is a list of strings giving the command and its arguments.
The first list entry must be the MSYS path name of a bash shell
script file.
"""
args = [self.shell]
if not self._is_msys:
args.append('--login')
args.extend(command)
previous_cwd = os.getcwd()
try:
return subprocess.Popen(args,
stdout=subprocess.PIPE,
env=self.environ).communicate()[0]
finally:
time.sleep(3) # Allow shell subprocesses to terminate.
os.chdir(previous_cwd)
__all__ = ['Msys', 'msys_raw_input', 'msys_print', 'MsysException']
pygame-1.9.1release/mingwcfg.py 0000644 0001750 0001750 00000001172 11207055754 016425 0 ustar vincent vincent # module mingwcfg.py
"""Manage the MinGW configuration file for setup.py"""
import os
import sys
if sys.version_info >= (3,):
import functools
open_ = functools.partial(open, encoding='utf-8')
else:
open_ = open
directory = os.path.abspath(os.path.split(__file__)[0])
path = os.path.join(directory, 'mingw.cfg')
def write(mingw_root):
cnf = open_(path, 'w')
try:
cnf.write(os.path.abspath(mingw_root))
cnf.write('\n')
finally:
cnf.close()
def read():
cnf = open_(path, 'r')
try:
for ln in cnf:
return ln.strip()
finally:
cnf.close()
pygame-1.9.1release/mingw32distutils.py 0000644 0001750 0001750 00000002617 11207055754 020064 0 ustar vincent vincent # module mingw32distutils.py
# Requires Python 2.1 or better.
"""Enhance distutils mingw32 compilation by adding Win32 GUI/console support."""
from distutils import ccompiler
from distutils.errors import DistutilsModuleError
compilers = ['mingw32', 'mingw32-console']
# Add the compiler classes to the ccompiler table. Unfortunate hacks follow.
compiler_class = ccompiler.compiler_class
value = compiler_class['mingw32']
assert len(value) == 3, "distutils.ccompiler.compiler_class has changed"
compiler_class['mingw32'] = ('', '',
value[2] + ", Win32 GUI shared libraries defaullt")
compiler_class['mingw32-console'] = ('', '',
value[2] + ", console shared libraries")
original_new_compiler = ccompiler.new_compiler
def new_compiler (plat=None,
compiler=None,
verbose=0,
dry_run=0,
force=0):
"""Recognizes replacement mingw32 compiler classes"""
if compiler == 'mingw32':
from mingw32ccompiler import Mingw32DefaultCCompiler
return Mingw32DefaultCCompiler (None, dry_run, force)
if compiler == 'mingw32-console':
from mingw32ccompiler import Mingw32ConsoleCCompiler
return Mingw32ConsoleCCompiler (None, dry_run, force)
return original_new_compiler (plat, compiler, verbose, dry_run, force)
ccompiler.new_compiler = new_compiler
pygame-1.9.1release/mingw32ccompiler.py 0000644 0001750 0001750 00000011520 11207055754 020006 0 ustar vincent vincent # module mingw32ccompiler.py
# Requires Python 2.1 or better.
"""Win32 GUI/console versions of the distutils mingw32 compiler classes."""
from distutils.cygwinccompiler import Mingw32CCompiler
def intersect (sequence_a, sequence_b):
"""Return true if the two sequences contain items in common
If sequence_a is a non-sequence then return false.
"""
try:
for item in sequence_a:
if item in sequence_b:
return 1
except TypeError:
return 0
return 0
def difference (sequence_a, sequence_b):
"""Return a list of items in sequence_a but not in sequence_b
Will raise a ValueError if either argument is not a sequence.
"""
new_sequence = []
for item in sequence_a:
if item not in sequence_b:
new_sequence.append(item)
return new_sequence
subsystem_options = ['-mwindows', '-mconsole'] # Item position is critical.
class Mingw32DefaultCCompiler (Mingw32CCompiler):
"""This mingw32 compiler class builds a Win32 GUI DLL by default.
It is overridden by subsystem options in the linker extras.
"""
def set_executables (self, **args):
"""Has no linker subsystem option for shared libraries"""
Mingw32CCompiler.set_executables(self, **args)
try:
self.linker_so = difference (self.linker_so, subsystem_options)
except TypeError:
pass
def link (self,
target_desc,
objects,
output_filename,
output_dir=None,
libraries=None,
library_dirs=None,
runtime_library_dirs=None,
export_symbols=None,
debug=0,
extra_preargs=None,
extra_postargs=None,
build_temp=None,
target_lang=None):
"""Do a Win32 GUI link if no subsystem option given."""
if (target_desc != self.EXECUTABLE and
not intersect(subsystem_options, extra_preargs) and
not intersect(subsystem_options, extra_postargs)):
try:
extra_preargs = extra_preargs + subsystem_options[0]
except TypeError:
extra_preargs = subsystem_options[0:1]
Mingw32CCompiler.link (self,
target_desc,
objects,
output_filename,
output_dir,
libraries,
library_dirs,
runtime_library_dirs,
export_symbols,
debug,
extra_preargs,
extra_postargs,
build_temp,
target_lang)
class Mingw32ConsoleCCompiler (Mingw32CCompiler):
"""This mingw32 compiler class builds a console DLL.
It is not overridden by subsystem options in the linker extras.
"""
def set_executables (self, **args):
"""Has console subsystem linker option for shared libraries."""
Mingw32CCompiler.set_executables(self, **args)
try:
linker_so = difference(self.linker_so, subsystem_options)
except TypeError:
linker_so = subsystem_options[1:2]
else:
linker_so.append(subsystem_options[1])
self.linker_so = linker_so
def link (self,
target_desc,
objects,
output_filename,
output_dir=None,
libraries=None,
library_dirs=None,
runtime_library_dirs=None,
export_symbols=None,
debug=0,
extra_preargs=None,
extra_postargs=None,
build_temp=None,
target_lang=None):
"""Do a console link."""
if target_desc != self.EXECUTABLE:
try:
extra_preargs = difference(extra_preargs, subsystem_options)
except TypeError:
pass
try:
extra_postargs = difference(extra_postargs, subsystem_options)
except TypeError:
pass
Mingw32CCompiler.link (self,
target_desc,
objects,
output_filename,
output_dir,
libraries,
library_dirs,
runtime_library_dirs,
export_symbols,
debug,
extra_preargs,
extra_postargs,
build_temp,
target_lang)
pygame-1.9.1release/MANIFEST.in 0000644 0001750 0001750 00000000406 11236507623 016006 0 ustar vincent vincent include Setup.in Setup_Darwin.in Setup_Win_Common.in *.py WHATSNEW readme.txt install.html readme.html LGPL
recursive-include docs *
recursive-include lib *
recursive-include src *
recursive-include examples *
recursive-include test *
prune */CVS
prune */*/CVS
pygame-1.9.1release/makeref.py 0000644 0001750 0001750 00000030224 11202644537 016234 0 ustar vincent vincent #!/usr/bin/env python
import os, glob
def sortkey(x):
return os.path.basename(x).lower()
def sort_list_by_keyfunc(alist, akey):
""" sort(key=sortkey) is only in python2.4.
this is not inplace like list.sort()
"""
# make a list of tupples with the key as the first.
keys_and_list = list( zip(map(akey, alist), alist) )
keys_and_list.sort()
alist = list( map(lambda x:x[1], keys_and_list) )
return alist
def collect_doc_files():
# ABSPATH ONLY WORKS FOR docs_as_dict
#
# if __name__ == '__main__': Run()
# must be ran from in trunk dir
# get files and shuffle ordering
trunk_dir = os.path.abspath(os.path.dirname(__file__))
src_dir = os.path.join(trunk_dir, 'src')
lib_dir = os.path.join(trunk_dir, 'lib')
pygame_doc = os.path.join(src_dir, "pygame.doc")
files = (
glob.glob(os.path.join(src_dir,'*.doc')) +
glob.glob(os.path.join(lib_dir,'*.doc'))
)
files.remove(pygame_doc)
#XXX: sort(key=) is only available in >= python2.4
# files.sort(key=sortkey)
files = sort_list_by_keyfunc(files, sortkey)
files.insert(0, pygame_doc)
return files
def Run():
from optparse import OptionParser
parser = OptionParser()
parser.add_option("", "--no-code-docs", dest="have_code_docs",
action="store_false", default=True,
help="No python documentation in code.")
(options, args) = parser.parse_args()
files = collect_doc_files()
for file in files:
# print file
print (os.path.basename(file))
docs = []
pages = []
for f in files:
name = os.path.splitext(os.path.basename(f))[0]
pages.append(name)
d = name, Doc('', open(f, "U"))
docs.append(d)
#pages.sort(key=str.lower)
pages = sort_list_by_keyfunc(pages, str.lower)
pages.insert(0, "index")
index = {}
justDocs = []
for name, doc in docs:
justDocs.append(doc)
MakeIndex(name, doc, index)
for name, doc in docs:
fullname = os.path.join("docs","ref","%s.html") % name
outFile = open(fullname, "w")
outFile.write(HTMLHeader % name)
WritePageLinks(outFile, pages)
outFile.write(HTMLMid)
HtmlOut(doc, index, outFile)
outFile.write(HTMLFinish)
outFile.close()
outFile = open(os.path.join("src", "pygamedocs.h"), "w")
outFile.write("/* Auto generated file: with makeref.py . Docs go in src/ *.doc . */\n")
for doc in justDocs:
WriteDocHeader(outFile, doc, options.have_code_docs)
outFile.write("\n\n/* Docs in a comments... slightly easier to read. */\n\n\n/*")
# add the docs as comments to the header file.
for doc in justDocs:
WriteDocHeaderComments(outFile, doc)
outFile.write("\n\n*/\n\n")
topDoc = LayoutDocs(justDocs)
outFile = open(os.path.join("docs","ref","index.html"), "w")
outFile.write(HTMLHeader % "Index")
WritePageLinks(outFile, pages)
outFile.write(HTMLMid)
outFile.write("\n\n")
WriteIndex(outFile, index, topDoc)
outFile.write("\n\n
\n")
outFile.write(HTMLFinish)
outFile.close()
def HtmlOut(doc, index, f):
f.write('\n\n\n' % doc.fullname)
f.write("%s
\n" % doc.fullname)
if doc.descr:
f.write(" %s
\n" % doc.descr)
if doc.protos:
for p in doc.protos:
f.write(" %s
\n" % p)
if doc.kids:
f.write("\n")
for kid in doc.kids:
f.write(" %s | %s |
\n"
% (index.get(kid.fullname + "()"), kid.descr or ""))
f.write("
\n")
if doc.docs:
pre = False
for d in doc.docs:
if d[0] == '*':
f.write("\n")
for li in d[1:].split('*'):
txt = HtmlPrettyWord(li)
f.write(" - %s
\n" % txt)
f.write("
\n")
else:
txt, pre = HtmlPrettyLine(d, index, pre)
f.write(txt)
if pre:
f.write("\n")
else:
f.write("
\n")
f.write("")
f.write("
\n")
if doc.kids:
for k in doc.kids:
HtmlOut(k, index, f)
f.write("
\n")
def HtmlPrettyWord(word):
if "." in word[:-1] or word.isupper():
return "%s" % word
return word
def HtmlPrettyLine(line, index, pre):
pretty = ""
if line[0].isspace():
if not pre:
pretty += ""
pre = True
elif pre:
pre = False
pretty += "
"
if not pre:
pretty += ""
for word in line.split():
if word[-1] in ",.":
finish = word[-1]
word = word[:-1]
else:
finish = ""
link = index.get(word)
if link:
pretty += "%s%s " % (link, finish)
elif word.isupper() or "." in word[1:-1]:
pretty += "%s%s " % (word, finish)
else:
pretty += "%s%s " % (word, finish)
pretty += "
\n"
else:
pretty += line + "\n"
return pretty, pre
def WritePageLinks(outFile, pages):
links = []
for page in pages[1:]:
link = '%s' % (page, page.title())
links.append(link)
outFile.write(" || \n".join(links))
#outFile.write("\n\n\n")
def MakeIndex(name, doc, index):
if doc.fullname:
link = '%s - %s' % (name, doc.fullname, doc.fullname, doc.descr)
index[doc.fullname + "()"] = link
if doc.kids:
for kid in doc.kids:
MakeIndex(name, kid, index)
def LayoutDocs(docs):
levels = {}
for doc in docs:
if doc.fullname:
topName = doc.fullname.split(".")[-1]
levels[topName] = doc
top = levels["pygame"]
for doc in docs:
if doc is top:
continue
#print (doc)
if doc.fullname:
parentName = doc.fullname.split(".")[-2]
else:
parentName = ""
parent = levels.get(parentName)
if parent is not None:
parent.kids.append(doc)
return top
def WriteIndex(outFile, index, doc):
link = index.get(doc.fullname + "()", doc.fullname)
outFile.write("%s\n" % link)
if doc.kids:
outFile.write("\n")
sortKids = list(doc.kids)
#print(sortKids)
sortKids = sort_list_by_keyfunc(sortKids, lambda x: x.fullname)
#sortKids = sorted( sortKids )
for kid in sortKids:
WriteIndex(outFile, index, kid)
outFile.write("
\n")
def WriteDocHeader(f, doc, have_code_docs ):
name = doc.fullname.replace(".", "")
name = name.replace("_", "")
name = name.upper()
defineName = "DOC_" + name
text = ""
if have_code_docs:
if doc.protos:
text = "\\n".join(doc.protos)
if doc.descr:
if text:
text += "\\n"
text += doc.descr
f.write('#define %s "%s"\n\n' % (defineName, text))
if doc.kids:
for kid in doc.kids:
WriteDocHeader(f, kid, have_code_docs)
def WriteDocHeaderComments(f, doc):
name = doc.fullname
defineName = name
text = ""
if doc.protos:
text = "\n".join(doc.protos)
if doc.descr:
if text:
text += "\n"
text += doc.descr
text = text.replace("\\n", "\n")
#f.write('\n\n/*\n%s\n %s\n\n*/' % (defineName, text))
f.write('\n\n%s\n %s\n\n' % (defineName, text))
if doc.kids:
for kid in doc.kids:
WriteDocHeaderComments(f, kid)
class Doc(object):
def __init__(self, parentname, f):
self.kids = None
self.protos = []
self.docs = None
self.descr = ""
self.name = ""
self.fullname = ""
self.finished = False
curdocline = ""
while True:
line = f.readline()
if not line:
break
line = line.rstrip()
if line == "":
if curdocline:
self.docs.append(curdocline)
curdocline = ""
self.finished = True
break
if self.kids is not None:
kid = Doc(self.fullname, f)
if kid:
self.kids.append(kid)
if line == "":
if curdocline:
self.docs.append(curdocline)
curdocline = ""
self.kids = []
continue
if line:
if self.docs is not None:
if line[0].isspace():
if curdocline:
self.docs.append(curdocline)
curdocline = ""
self.docs.append(line)
else:
curdocline += line + " "
elif not self.name:
self.name = line
if len(line) > 1 and line[0] == '"' and line[-1] == '"':
self.fullname = line[1:-1]
elif parentname:
splitparent = parentname.split(".")
if splitparent[-1][0].isupper():
self.fullname = splitparent[-1] + "." + line
else:
self.fullname = parentname + "." + line
else:
self.fullname = line
elif not self.descr:
self.descr = line
else:
self.protos.append(line)
else:
if self.docs is not None:
if curdocline:
self.docs.append(curdocline)
curdocline = ""
elif self.name and self.kids is None:
self.docs = []
def __repr__(self):
return "" % self.name
def __nonzero__(self):
return self.finished
def __cmp__(self, b):
return cmp(self.name.lower(), b.name.lower())
def docs_as_dict():
"""
Dict Format:
{'pygame.rect.Rect.center': 'Rect.center: ...' ...}
Generally works, has some workarounds, inspect results manually.
"""
import pygame
files = collect_doc_files()
def make_mapping(doc, parent_name):
docs = {}
for k in doc.kids:
if k.docs:
kid_name = k.fullname
if parent_name == 'pygame':
if hasattr(pygame.base, k.name):
kid_name = '%s.%s' % ('pygame.base', k.name)
elif not kid_name.startswith(parent_name):
kid_name = '%s.%s' % (parent_name, kid_name)
docs[kid_name] = '\n'.join(k.docs)
if k.kids:
docs.update(make_mapping(k, parent_name))
return docs
mapping = {}
for f in files:
doc = Doc('', open(f, "U"))
mapping.update(make_mapping(doc, doc.name.lower()))
return mapping
HTMLHeader = """
%s - Pygame Documentation
"""
HTMLFinish = """
"""
if __name__ == '__main__':
Run()
pygame-1.9.1release/make_prebuilt.py 0000644 0001750 0001750 00000017726 11227461214 017455 0 ustar vincent vincent import msys
from distutils.extension import read_setup_file
import os
import re
import sys
prebuilt_dir = 'prebuilt'
lib_subdir = 'lib'
class MakePrebuiltError(Exception):
pass
def file_copy(src, dest):
if os.path.isdir(dest):
dest = os.path.join(dest, os.path.split(src)[1])
s = open(src, 'rb')
try:
d = open(dest, 'wb')
try:
d.write(s.read())
print "%s => %s" % (src, dest)
finally:
d.close()
finally:
s.close()
def find_import_libraries(path, roots):
match = re.compile(r'lib(%s)\.dll\.a$' % '|'.join(roots)).match
return [name for name in os.listdir(path) if match(name) is not None]
def copy_dir(src, dest):
if dest == '.':
ignore, dest = os.path.split(src)
if src == dest:
raise IOError("%s: Source and destination are identical" % src)
mkdir(dest)
for name in os.listdir(src):
src_path = os.path.join(src, name)
if os.path.isfile(src_path):
file_copy(src_path, os.path.join(dest, name))
def confirm(message):
"ask a yes/no question, return result"
reply = msys.msys_raw_input("\n%s [Y/n]:" % message)
if reply and reply[0].lower() == 'n':
return 0
return 1
created_dirs = set()
def mkdir(path):
path = os.path.abspath(path)
if path in created_dirs:
pass
elif not os.path.exists(path):
os.mkdir(path)
created_dirs.add(path)
elif not os.path.isdir(path):
raise MakePrebuiltError("%s is not a directory" % path)
def main(dest_dir=None):
# Top level directories.
if dest_dir is None:
dest_dir = prebuilt_dir
if re.match(r'([A-Za-z]:){0,1}[^"<>:|?*]+$', dest_dir) is None:
print "Invalid directory path name %s" % dest_dir
return 1
dest_dir = os.path.abspath(dest_dir)
if os.path.isdir(dest_dir):
if not confirm("Directory %s already exists;\ncontinue" % dest_dir):
return 1
mkdir(dest_dir)
m = msys.Msys()
src_dir = os.path.join(m.msys_root, 'local')
prebuilt_template = os.path.abspath('prebuilt-template')
dest_lib_dir = os.path.join(dest_dir, lib_subdir)
# Read setup file.
src_file = os.path.join(prebuilt_template, 'Setup_Win.in')
file_copy(src_file, dest_dir)
deps = read_setup_file(src_file)
setup_in = open(src_file)
match = re.compile('[A-Z_][A-Z0-9_]* *=(.*)').match
header_dir_pat = re.compile(' -I([^ ]+)')
lib_pat = re.compile(' -l([^ ]+)')
macros = []
for line in setup_in:
matches = match(line)
if matches is not None:
flags = matches.group(1)
header_dirs = header_dir_pat.findall(flags)
libs = lib_pat.findall(flags)
macros.append((header_dirs, libs))
# Copy DLLs.
src_bin_dir = os.path.join(src_dir, 'bin')
have_dlls = set()
for dep in deps:
path_elements = dep.library_dirs[0].split('/') # / required by setup.
dll_name = path_elements[-1]
src_dll_path = os.path.join(src_bin_dir, dll_name)
if os.path.exists(src_dll_path):
if path_elements[0] == '.':
path_elements = path_elements[2:]
else:
path_elements = path_elements[1:]
dest_dll_dir = dest_dir
for dir_name in path_elements[:-1]:
dest_dll_dir = os.path.join(dest_dll_dir, dir_name)
mkdir(dest_dll_dir)
file_copy(os.path.join(src_bin_dir, dll_name),
os.path.join(dest_dll_dir, dll_name))
have_dlls.add(dep.name[8:])
# Copy required import libraries only.
copied_files = set()
src_lib_dir = os.path.join(src_dir, 'lib')
mkdir(dest_lib_dir)
for ignore, libs in macros:
use = False
for lib in libs:
if lib in have_dlls:
use = True
break
if use and lib not in copied_files:
copied_files.add(lib)
lib_name = 'lib%s.dll.a' % lib
src_lib_path = os.path.join(src_lib_dir, lib_name)
if not os.path.exists(src_lib_path):
print "Missing import library %s" % lib_name
return 1
file_copy(src_lib_path, os.path.join(dest_lib_dir, lib_name))
# Copy required header directories only.
copied_dirs = set()
for header_dirs, libs in macros:
use = False
for lib in libs:
if lib in have_dlls:
use = True
break
if use:
for header_dir in header_dirs:
path_elements = header_dir.split('/')
if path_elements[0] == '.':
path_elements = path_elements[2:]
else:
path_elements = path_elements[1:]
src_header_dir = os.path.join(src_dir, *path_elements)
if not os.path.exists(src_header_dir):
print "Missing include directory %s" % src_header_dir
return 1
dest_header_dir = dest_dir
for dir_name in path_elements:
dest_header_dir = os.path.join(dest_header_dir, dir_name)
mkdir(dest_header_dir)
if not src_header_dir in copied_dirs:
copy_dir(src_header_dir, dest_header_dir)
copied_dirs.add(src_header_dir)
if 'SDL' in have_dlls:
# For MSVC use SDL_config_win32.h in place of configure
# generated SDL_config.h.
file_copy(
os.path.join(src_dir, 'include', 'SDL', 'SDL_config_win32.h'),
os.path.join(dest_dir, 'include', 'SDL', 'SDL_config.h'))
# msvcr71.dll linking support.
src_msvcr71_dir = os.path.join(src_dir, 'lib', 'msvcr71')
dest_msvcr71_dir = os.path.join(dest_dir, 'lib', 'msvcr71')
copy_dir(src_msvcr71_dir, dest_msvcr71_dir)
# Def file bat.
make_defs = open(os.path.join(dest_lib_dir, 'MakeDefs.bat'), 'w')
try:
make_defs.write('@echo off\n'
'rem Make .def files needed for .lib file creation.\n'
'rem Requires pexports.exe on the search path\n'
'rem (found in altbinutils-pe as SourceForge,\n'
'rem http://sourceforge.net/projects/mingwrep/).\n\n')
for dep in deps:
dll_name = os.path.split(dep.library_dirs[0])[1]
lib = dep.name[8:]
lib_name = 'lib%s.dll.a' % lib
if os.path.exists(os.path.join(dest_lib_dir, lib_name)):
start = ''
else:
start = 'rem '
make_defs.write('%spexports %s >%s.def\n' %
(start, dll_name, lib))
finally:
make_defs.close()
# Lib import files bat.
make_libs = open(os.path.join(dest_lib_dir, 'MakeLibs.bat'), 'w')
try:
make_libs.write('@echo off\n'
'rem Make .lib import libraries.\n'
'rem Requires Visual C++ Studio or Toolkit.\n'
'rem VCVARS32.BAT (VCVARS64.BAT (?) for 64 bit build)\n'
'rem must be run first to use LIB.EXE.\n\n')
for dep in deps:
dll_name = os.path.split(dep.library_dirs[0])[1]
lib = dep.name[8:]
lib_name = 'lib%s.dll.a' % lib
if os.path.exists(os.path.join(dest_lib_dir, lib_name)):
start = ''
else:
start = 'rem '
make_libs.write('%sLIB.EXE /NOLOGO /DEF:%s.def /MACHINE:IX86 /OUT:%s.lib\n' %
(start, lib, lib))
finally:
make_libs.close()
# Top level make batch file for 32 bit build.
file_copy(os.path.join(prebuilt_template, 'Make32.bat'), dest_lib_dir)
return 0
if __name__ =='__main__':
dest_dir = None
if len(sys.argv) > 1:
dest_dir = sys.argv[1]
try:
sys.exit(main(dest_dir))
except MakePrebuiltError, e:
print "*** %s; execution halted" % e
sys.exit(1)
pygame-1.9.1release/LGPL 0000644 0001750 0001750 00000063476 10767613027 014755 0 ustar vincent vincent GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
Copyright (C)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!
pygame-1.9.1release/install.html 0000644 0001750 0001750 00000020363 10777531062 016613 0 ustar vincent vincent Pygame Installation
Pygame Installation
Python can be built from source, but the easiest way is to
get a binary package for your type of system and version of Python.
This document will give you information on either type of installation.
Windows Binary Installer
This is probably the most popular method of installation. If you are
running on windows, it is highly recommended you use this form
of installing. The installers come with with nearly everything
you need, and have an easy point and click installers.
The first thing you will need is an installation of Python. Python
binary installers make it easy to get this done. Pygame binaries
usually come for the latest 2 releases of Python, so you'll want to be fairly
up to date.
Once that is in place, you want to download the appropriate
windows binary. From the pygame downloads page you can find the .EXE
file you need. This will automatically install all of pygame and all the SDL
dependencies. The windows binaries have filenames like this; "http://www3.telus.net/len_l/pygame-1.8.0release.win32-py2.5.msi".
This would be the installer for pygame version 1.8.0, for Python version 2.5. You
shouldn't have trouble finding the correct binary from the "Windows" section
of the download page.
http://www.pygame.org/download.shtml.
You will also probably want to install the windows documentation and
installation package. This will add easy links to the different documentation
and games that come with pygame. The installer for this is found
next to the other windows binary downloads. The filename looks like this;
"pygame-docs-1.8.0.exe". And this would install the documentation and
examples for pygame-1.8.0
One other thing the windows binaries are missing is the Numeric or numpy Python
packages. You can easily install this separately and it will allow you to use
the pygame "surfarray" module. This module is optional, so there is no need
to do this. A Numeric for Windows python 2.5 can be found on the download page: http://www.pygame.org/download.shtml. There are older binary installers from the Numeric download page.
http://sourceforge.net/project/showfiles.php?group_id=1369.
PixelArray, which is built into pygame 1.8+, and is usually quite a lot faster is the recommended array implementation to use. Numpy is newer than Numeric, however both are not entirely compatible.
Unix Binary Packages
For many unix systems, the easiest way to install pygame is
from source. Still, there are binary packages available for
different distributions.
There are several binary RPM packages for linux machines. These are
actually a little bit of work to install, since you will also need several
RPM packages for the dependencies. There is a good chance
your linux distribution came with the needed dependencies (like Python
and SDL). There are binary RPMs available from the website for each dependency.
For debian systems, pygame is actively maintained in the debian
archives. Visit the debian pygame page for more information.
http://packages.qa.debian.org/p/pygame.html
FreeBSD also has an active pygame package. While techinicaly it
isn't binary, it is automatically built and installed by the
ports manager. See the FreeBSD package page for more information.
http://www.freebsdports.info/ports/devel/py-game.html
Gentoo has a builtin package for pygame. This is compiled for
your system as it installs, similar to BSD,
http://packages.gentoo.org/package/dev-python/pygame
Mac OS X Binaries
For Mac OS X 10.3 and above, binary packages are available from
http://www.pygame.org/download.shtml
This package includes almost of the dependencies required for pygame
(SDL, SDL_image, etc.), but you need PyObjC 1.2 or later, and may
also want to get Numeric, numpy and PyOpenGL. A PyObjC 1.4 installer is also made available on the download page.
If you want to use the Apple system python, you will need to compile from source at this time - since most people prefer to leave the system python alone, and use the python downloaded from python.org. See http://pygame.org/wiki/MacCompile for current instructions for compiling from source on Mac OSX.
pygame is also available from the fink, and macports distributions.
To build self-contained pygame applications, you should use py2app.
There is an example in:
/Developer/Python/pygame/Examples/macosx/aliens_app_example
Installing From Source
Compiling and installing pygame is handled by Python's distutils.
Pygame also comes with some scripts to automatically configure
the flags needed to build pygame. Use the "setup.py" script to
start the installation.
The first time you run the setup script, it will call the
"config.py" script. This will build a "Setup" file which
stores all the information needed to compile. The "config.py"
will do a good job of detecting what dependencies are available
and where they are located. If it isn't perfect, it is easy to
build your own, or edit the created "Setup" text file. This
"Setup" file is a simple Makefile-like text file. It defines
variables needed to use each dependency, and then enables
all the pygame modules with found dependencies. If you have
trouble compiling, you should be able to easily fix any problems
inside the "Setup" file.
Running the "setup.py" script will call distutils to build and
install the pygame package. Distutils actually supports a wide
variety of compile and install options. running "python setup.py help"
will start to show you the different options available. You can
change many things like install locations, compiler to use, and more.
Calling the "setup.py" script with no arguments and it will just
ask you if you want the default flags needed to compile and install.
Windows Compiling Info
You can compile pygame on windows with mingw (gcc for windows) and also with visual studio.
Up to date details can be found here:
http://pygame.org/wiki/CompileWindows
Unix Compiling Info
Compiling from linux shouldn't give you any problems. One thing
you must keep in mind is that most linux RPM packages separate the
actual library from the "dev" files needed to compile. To build you
will need to make sure the packages like "SDL-dev" are
installed.
You can check to see if SDL is ready to be built from by running
the command sdl-config and seeing if it is found. If the
sdl-config script is not on the path (or you have more than
one?) Set the environment variable SDL_CONFIG to its location.
Sometimes you will have the SDL libraries installed in once
location, and the other SDL libraries in another. This tricks the
pygame config scripts, but you can help it out by setting the
environment LOCALBASE to a path prefix where the other libraries
are. The common case for this is SDL installed in /usr and other
SDL libs installed in /usr/local. The command for this situation
is "LOCALBASE=/usr/local python setup.py install".
Mac OS X Compiling Info
Up to date instructions for compiling on Mac OS X can be found here:
http://pygame.org/wiki/MacCompile
pygame-1.9.1release/dll.py 0000644 0001750 0001750 00000004441 11202451362 015367 0 ustar vincent vincent # dll.py module
"""DLL specifics
Configured for the Pygame 1.9.0 dependencies as built by msys_build_deps.py.
"""
# Some definitions:
# Library name (name): An internal identifier, a string, for a library.
# e.g. FONT
# Library file root (root): The library root used in linker -l options.
# e.g. SDL_mixer
import re
# Table of dependencies.
# name, root, File regex, Dependency list of names
libraries = [
('MIXER', 'SDL_mixer', r'SDL_mixer\.dll$',
['SDL', 'VORBISFILE', 'SMPEG']),
('VORBISFILE', 'vorbisfile', r'libvorbisfile-3\.dll$',
['VORBIS']),
('VORBIS', 'vorbis', r'libvorbis-0\.dll$', ['OGG']),
('OGG', 'ogg', r'libogg-0\.dll$', []),
('SMPEG', 'smpeg', r'smpeg\.dll$', ['SDL']),
('IMAGE', 'SDL_image', r'SDL_image\.dll$',
['SDL', 'JPEG', 'PNG', 'TIFF']),
('TIFF', 'tiff', r'libtiff\.dll$', ['JPEG', 'Z']),
('JPEG', 'jpeg', r'jpeg\.dll$', []),
('PNG', 'png12', r'libpng12-0\.dll$', ['Z']),
('FONT', 'SDL_ttf', r'SDL_ttf\.dll$', ['SDL']),
('FREETYPE', 'freetype', r'libfreetype-6\.dll$', ['Z']),
('Z', 'z', r'zlib1\.dll$', []),
('SDL', 'SDL', r'SDL\.dll$', []),
('PORTMIDI', 'portmidi', r'portmidi\.dll', []),
('PORTTIME', 'portmidi', r'portmidi\.dll', []),
]
# regexs: Maps name to DLL file name regex.
# lib_dependencies: Maps name to list of dependencies.
# file_root_names: Maps name to root.
regexs = {}
lib_dependencies = {}
file_root_names = {}
for name, root, ignore1, ignore2 in libraries:
file_root_names[name] = root
for name, root, regex, deps in libraries:
regexs[name] = regex
lib_dependencies[root] = [file_root_names[d] for d in deps]
del name, root, regex, deps, ignore1, ignore2
def tester(name):
"""For a library name return a function which tests dll file names"""
def test(file_name):
"""Return true if file name f is a valid DLL name"""
return match(file_name) is not None
match = re.compile(regexs[name], re.I).match
test.library_name = name # Available for debugging.
return test
def name_to_root(name):
"""Return the library file root for the library name"""
return file_root_names[name]
def libraries(name):
"""Return the library file roots this library links too"""
return lib_dependencies[name_to_root(name)]
pygame-1.9.1release/distutils_mods.py 0000644 0001750 0001750 00000003407 10227340532 017665 0 ustar vincent vincent #purpose: a few changes to distutils to build betterer.
# - fixes up paths when using msys.
#
#
import os
import distutils.cygwinccompiler
distutils.cygwinccompiler.oldMingw32CCompiler= distutils.cygwinccompiler.Mingw32CCompiler
"""
Should put the above imports at the top of your file.
and after them put
import distutils_mods
distutils.cygwinccompiler.Mingw32 = distutils_mods.mingcomp
"""
from distutils.errors import DistutilsExecError
class mingcomp(distutils.cygwinccompiler.oldMingw32CCompiler):
def spawn(self, cmd):
""" Because spawn uses a straight call to the systems underlying
shell, bypassing the string handling goodness of mingw/msys
something gets fubared. So this little hack method was put
in its place.
"""
self.verbose = 1
if self.verbose:
print "cmd :%s:" % cmd
cmpl = " ".join(cmd)
cmpl = cmpl.replace("\\", "/")
cmpl = cmpl.replace("c:", "/c")
cmpl = cmpl.replace("C:", "/c")
cmpl = cmpl.replace("gcc", "gcc -g ")
if self.verbose:
print "cmpl is :%s:" % cmpl
if not self.dry_run:
import tempfile
tmpfn = tempfile.mktemp(suffix='run_compiler')
tmpf = open(tmpfn, "w+b")
tmpf.write(cmpl)
tmpf.close()
r = os.system("sh %s" % tmpfn)
os.remove(tmpfn)
if r != 0:
raise DistutilsExecError, \
"command '%s' failed with exit status :%d: command was :%s:. " % (cmd[0], r, cmpl)
if self.verbose:
print "return value of the compile command is :%s:" % r
distutils.cygwinccompiler.Mingw32CCompiler= mingcomp
pygame-1.9.1release/config_win.py 0000644 0001750 0001750 00000022217 11207055754 016751 0 ustar vincent vincent """Config on Windows"""
# **** The search part is broken. For instance, the png Visual Studio project
# places to dll in a directory not checked by this module.
from setup_win_common import get_definitions
import os, sys
import re
from glob import glob
from distutils.sysconfig import get_python_inc
try:
raw_input
except NameError:
raw_input = input
huntpaths = ['..', '..\\..', '..\\*', '..\\..\\*']
class Dependency(object):
inc_hunt = ['include']
lib_hunt = ['VisualC\\SDL\\Release', 'VisualC\\Release', 'Release', 'lib']
def __init__(self, name, wildcards, libs=None, required = 0):
if libs is None:
libs = []
self.name = name
self.wildcards = wildcards
self.required = required
self.paths = []
self.path = None
self.inc_dir = None
self.lib_dir = None
self.libs = libs
self.found = False
self.cflags = ''
def hunt(self):
parent = os.path.abspath('..')
for p in huntpaths:
for w in self.wildcards:
found = glob(os.path.join(p, w))
found.sort() or found.reverse() #reverse sort
for f in found:
if f[:5] == '..'+os.sep+'..' and \
os.path.abspath(f)[:len(parent)] == parent:
continue
if os.path.isdir(f):
self.paths.append(f)
def choosepath(self):
if not self.paths:
print ("Path for %s not found." % self.name)
if self.required:
print ('Too bad that is a requirement! Hand-fix the "Setup"')
elif len(self.paths) == 1:
self.path = self.paths[0]
print ("Path for %s:' % self.name")
else:
print ("Select path for %s:" % self.name)
for i in range(len(self.paths)):
print (" %i=%s" % (i + 1, self.paths[i]))
print (" %i = " % 0)
choice = raw_input("Select 0-%i (1=default):" % len(self.paths))
if not choice: choice = 1
else: choice = int(choice)
if(choice):
self.path = self.paths[choice-1]
def findhunt(self, base, paths):
for h in paths:
hh = os.path.join(base, h)
if os.path.isdir(hh):
return hh.replace('\\', '/')
return base.replace('\\', '/')
def configure(self):
self.hunt()
self.choosepath()
if self.path:
self.found = True
self.inc_dir = self.findhunt(self.path, Dependency.inc_hunt)
self.lib_dir = self.findhunt(self.path, Dependency.lib_hunt)
class DependencyPython(object):
def __init__(self, name, module, header):
self.name = name
self.lib_dir = ''
self.inc_dir = ''
self.libs = []
self.cflags = ''
self.found = False
self.ver = '0'
self.module = module
self.header = header
def configure(self):
self.found = True
if self.module:
try:
self.ver = __import__(self.module).__version__
except ImportError:
self.found = False
if self.found and self.header:
fullpath = os.path.join(get_python_inc(0), self.header)
if not os.path.isfile(fullpath):
found = 0
else:
self.inc_dir = os.path.split(fullpath)[0]
if self.found:
print ("%-8.8s: found %s" % (self.name, self.ver))
else:
print ("%-8.8s: not found" % self.name)
class DependencyDLL(Dependency):
def __init__(self, dll_regex, lib=None, wildcards=None, libs=None, link=None):
if lib is None:
lib = link.libs[0]
Dependency.__init__(self, 'COPYLIB_' + lib, wildcards, libs)
self.lib_name = lib
self.test = re.compile(dll_regex, re.I).match
self.lib_dir = '_'
self.found = True
self.link = link
def configure(self):
if self.link is None and self.wildcards:
self.hunt()
self.choosepath()
else:
self.path = self.link.path
if self.path is not None:
self.hunt_dll()
def hunt_dll(self):
for dir in self.lib_hunt:
path = os.path.join(self.path, dir)
try:
entries = os.listdir(path)
except:
pass
else:
for e in entries:
if self.test(e) and os.path.isfile(os.path.join(path, e)):
# Found
self.lib_dir = os.path.join(path, e).replace('\\', '/')
print ("DLL for %s is %s" % (self.lib_name, self.lib_dir))
return
print ("DLL for %s not found" % self.lib_name)
class DependencyWin(object):
def __init__(self, name, cflags):
self.name = name
self.inc_dir = None
self.lib_dir = None
self.libs = []
self.found = True
self.cflags = cflags
def configure(self):
pass
class DependencyGroup(object):
def __init__(self):
self.dependencies =[]
self.dlls = []
def add(self, name, lib, wildcards, dll_regex, libs=None, required=0):
if libs is None:
libs = []
dep = Dependency(name, wildcards, [lib], required)
self.dependencies.append(dep)
self.dlls.append(DependencyDLL(dll_regex, link=dep, libs=libs))
def add_win(self, name, cflags):
self.dependencies.append(DependencyWin(name, cflags))
def add_dll(self, dll_regex, lib=None, wildcards=None, libs=None, link_lib=None):
link = None
if link_lib is not None:
name = 'COPYLIB_' + link_lib
for d in self.dlls:
if d.name == name:
link = d
break
else:
raise KeyError("Link lib %s not found" % link_lib)
self.dlls.append(DependencyDLL(dll_regex, lib, wildcards, libs, link))
def configure(self):
for d in self:
d.configure()
def __iter__(self):
for d in self.dependencies:
yield d
for d in self.dlls:
yield d
DEPS = DependencyGroup()
DEPS.add('SDL', 'SDL', ['SDL-[1-9].*'], r'(lib){0,1}SDL\.dll$', required=1)
DEPS.add('FONT', 'SDL_ttf', ['SDL_ttf-[2-9].*'], r'(lib){0,1}SDL_ttf\.dll$', ['SDL', 'z'])
DEPS.add('IMAGE', 'SDL_image', ['SDL_image-[1-9].*'], r'(lib){0,1}SDL_image\.dll$',
['SDL', 'jpeg', 'png', 'tiff'], 0),
DEPS.add('MIXER', 'SDL_mixer', ['SDL_mixer-[1-9].*'], r'(lib){0,1}SDL_mixer\.dll$',
['SDL', 'vorbisfile', 'smpeg'])
DEPS.add('SMPEG', 'smpeg', ['smpeg-[0-9].*', 'smpeg'], r'smpeg\.dll$', ['SDL'])
DEPS.add('PNG', 'png', ['libpng-[1-9].*'], r'(png|libpng13)\.dll$', ['z'])
DEPS.add('JPEG', 'jpeg', ['jpeg-[6-9]*'], r'(lib){0,1}jpeg\.dll$')
DEPS.add('PORTMIDI', 'portmidi', ['portmidi'], r'portmidi\.dll$')
#DEPS.add('PORTTIME', 'porttime', ['porttime'], r'porttime\.dll$')
DEPS.add_dll(r'(lib){0,1}tiff\.dll$', 'tiff', ['tiff-[3-9].*'], ['jpeg', 'z'])
DEPS.add_dll(r'(z|zlib1)\.dll$', 'z', ['zlib-[1-9].*'])
DEPS.add_dll(r'(libvorbis-0|vorbis)\.dll$', 'vorbis', ['libvorbis-[1-9].*'],
['ogg'])
DEPS.add_dll(r'(libvorbisfile-3|vorbisfile)\.dll$', 'vorbisfile',
link_lib='vorbis', libs=['vorbis'])
DEPS.add_dll(r'(libogg-0|ogg)\.dll$', 'ogg', ['libogg-[1-9].*'])
for d in get_definitions():
DEPS.add_win(d.name, d.value)
def setup_prebuilt():
setup = open('Setup', 'w')
try:
try:
setup_win_in = open(os.path.join('prebuilt', 'Setup_Win.in'))
except IOError:
raise IOError("prebuilt missing required Setup_Win.in")
# Copy Setup.in to Setup, replacing the BeginConfig/EndConfig
# block with prebuilt\Setup_Win.in .
setup_in = open('Setup.in')
try:
do_copy = True
for line in setup_in:
if line.startswith('#--StartConfig'):
do_copy = False
setup.write(setup_win_in.read())
try:
setup_win_common_in = open('Setup_Win_Common.in')
except:
pass
else:
try:
setup.write(setup_win_common_in.read())
finally:
setup_win_common_in.close()
elif line.startswith('#--EndConfig'):
do_copy = True
elif do_copy:
setup.write(line)
finally:
setup_in.close()
finally:
setup.close()
def main():
if os.path.isdir('prebuilt'):
reply = raw_input('\nUse the SDL libraries in "prebuilt"? [Y/n]')
if not reply or reply[0].lower() != 'n':
setup_prebuilt()
raise SystemExit()
global DEPS
DEPS.configure()
return list(DEPS)
if __name__ == '__main__':
print ("""This is the configuration subscript for Windows.
Please run "config.py" for full configuration.""")
pygame-1.9.1release/config_unix.py 0000644 0001750 0001750 00000015037 11207055754 017141 0 ustar vincent vincent """Config on Unix"""
import os, sys
from glob import glob
from distutils.sysconfig import get_python_inc
# Python 2.x/3.x compatibility
try:
raw_input
except NameError:
raw_input = input
configcommand = os.environ.get('SDL_CONFIG', 'sdl-config',)
configcommand = configcommand + ' --version --cflags --libs'
localbase = os.environ.get('LOCALBASE', '')
#these get prefixes with '/usr' and '/usr/local' or the $LOCALBASE
origincdirs = ['/include', '/include/SDL', '/include/SDL',
'/include/smpeg' ]
origlibdirs = ['/lib','/lib64','/X11R6/lib']
def confirm(message):
"ask a yes/no question, return result"
reply = raw_input('\n' + message + ' [Y/n]:')
if reply and (reply[0].lower()) == 'n':
return 0
return 1
class DependencyProg:
def __init__(self, name, envname, exename, minver, defaultlibs):
self.name = name
command = os.environ.get(envname, exename)
self.lib_dir = ''
self.inc_dir = ''
self.libs = []
self.cflags = ''
try:
config = os.popen(command + ' --version --cflags --libs').readlines()
flags = ' '.join(config[1:]).split()
# remove this GNU_SOURCE if there... since python has it already,
# it causes a warning.
if '-D_GNU_SOURCE=1' in flags:
flags.remove('-D_GNU_SOURCE=1')
self.ver = config[0].strip()
if minver and self.ver < minver:
err= 'WARNING: requires %s version %s (%s found)' % (self.name, self.ver, minver)
raise ValueError(err)
self.found = 1
self.cflags = ''
for f in flags:
if f[:2] in ('-l', '-D', '-I', '-L'):
self.cflags += f + ' '
elif f[:3] == '-Wl':
self.cflags += '-Xlinker ' + f + ' '
if self.name == 'SDL':
inc = '-I' + '/usr/X11R6/include'
self.cflags = inc + ' ' + self.cflags
except:
print ('WARNING: "%s" failed!' % command)
self.found = 0
self.ver = '0'
self.libs = defaultlibs
def configure(self, incdirs, libdir):
if self.found:
print (self.name + ' '[len(self.name):] + ': found ' + self.ver)
self.found = 1
else:
print (self.name + ' '[len(self.name):] + ': not found')
class Dependency:
def __init__(self, name, checkhead, checklib, libs):
self.name = name
self.inc_dir = None
self.lib_dir = None
self.libs = libs
self.found = 0
self.checklib = checklib
self.checkhead = checkhead
self.cflags = ''
def configure(self, incdirs, libdirs):
incname = self.checkhead
libnames = self.checklib, self.name.lower()
if incname:
for dir in incdirs:
path = os.path.join(dir, incname)
if os.path.isfile(path):
self.inc_dir = dir
for dir in libdirs:
for name in libnames:
path = os.path.join(dir, name)
if filter(os.path.isfile, glob(path+'*')):
self.lib_dir = dir
if (incname and self.lib_dir and self.inc_dir) or (not incname and self.lib_dir):
print (self.name + ' '[len(self.name):] + ': found')
self.found = 1
else:
print (self.name + ' '[len(self.name):] + ': not found')
class DependencyPython:
def __init__(self, name, module, header):
self.name = name
self.lib_dir = ''
self.inc_dir = ''
self.libs = []
self.cflags = ''
self.found = 0
self.ver = '0'
self.module = module
self.header = header
def configure(self, incdirs, libdirs):
self.found = 1
if self.module:
try:
self.ver = __import__(self.module).__version__
except ImportError:
self.found = 0
if self.found and self.header:
fullpath = os.path.join(get_python_inc(0), self.header)
if not os.path.isfile(fullpath):
self.found = 0
else:
self.inc_dir = os.path.split(fullpath)[0]
if self.found:
print (self.name + ' '[len(self.name):] + ': found', self.ver)
else:
print (self.name + ' '[len(self.name):] + ': not found')
sdl_lib_name = 'SDL'
def main():
print ('\nHunting dependencies...')
DEPS = [
DependencyProg('SDL', 'SDL_CONFIG', 'sdl-config', '1.2', ['sdl']),
Dependency('FONT', 'SDL_ttf.h', 'libSDL_ttf.so', ['SDL_ttf']),
Dependency('IMAGE', 'SDL_image.h', 'libSDL_image.so', ['SDL_image']),
Dependency('MIXER', 'SDL_mixer.h', 'libSDL_mixer.so', ['SDL_mixer']),
DependencyProg('SMPEG', 'SMPEG_CONFIG', 'smpeg-config', '0.4.3', ['smpeg']),
Dependency('PNG', 'png.h', 'libpng', ['png']),
Dependency('JPEG', 'jpeglib.h', 'libjpeg', ['jpeg']),
Dependency('SCRAP', '', 'libX11', ['X11']),
Dependency('PORTMIDI', 'portmidi.h', 'libportmidi.so', ['portmidi']),
Dependency('PORTTIME', 'porttime.h', 'libporttime.so', ['porttime']),
#Dependency('GFX', 'SDL_gfxPrimitives.h', 'libSDL_gfx.so', ['SDL_gfx']),
]
if not DEPS[0].found:
print ('Unable to run "sdl-config". Please make sure a development version of SDL is installed.')
raise SystemExit
if localbase:
incdirs = [localbase+d for d in origincdirs]
libdirs = [localbase+d for d in origlibdirs]
else:
incdirs = []
libdirs = []
incdirs += ["/usr"+d for d in origincdirs]
libdirs += ["/usr"+d for d in origlibdirs]
incdirs += ["/usr/local"+d for d in origincdirs]
libdirs += ["/usr/local"+d for d in origlibdirs]
for arg in DEPS[0].cflags.split():
if arg[:2] == '-I':
incdirs.append(arg[2:])
elif arg[:2] == '-L':
libdirs.append(arg[2:])
for d in DEPS:
d.configure(incdirs, libdirs)
for d in DEPS[1:]:
if not d.found:
if not confirm("""
Warning, some of the pygame dependencies were not found. Pygame can still
compile and install, but games that depend on those missing dependencies
will not run. Would you like to continue the configuration?"""):
raise SystemExit
break
return DEPS
if __name__ == '__main__':
print ("""This is the configuration subscript for Unix.
Please run "config.py" for full configuration.""")
pygame-1.9.1release/config_msys.py 0000644 0001750 0001750 00000023076 11201733045 017141 0 ustar vincent vincent # Requires Python 2.4 or better and win32api.
"""Config on Msys mingw
This version expects the Pygame 1.9.0 dependencies as built by
msys_build_deps.py
"""
import dll
from setup_win_common import get_definitions
import msys
import os, sys, string
from glob import glob
from distutils.sysconfig import get_python_inc
configcommand = os.environ.get('SDL_CONFIG', 'sdl-config',)
configcommand = configcommand + ' --version --cflags --libs'
localbase = os.environ.get('LOCALBASE', '')
#these get prefixes with '/usr/local' and /mingw or the $LOCALBASE
origincdirs = ['/include', '/include/SDL', '/include/SDL11',
'/include/smpeg', '/include/libpng12', ]
origlibdirs = ['/lib']
class ConfigError(Exception):
pass
def path_join(a, *p):
return os.path.join(a, *p).replace(os.sep, '/')
path_split = os.path.split
def print_(*args, **kwds):
return msys.msys_print(*args, **kwds)
def confirm(message):
"ask a yes/no question, return result"
reply = msys.msys_raw_input("\n%s [Y/n]:" % message)
if reply and string.lower(reply[0]) == 'n':
return 0
return 1
class DependencyProg:
needs_dll = True
def __init__(self, name, envname, exename, minver, msys, defaultlibs=None):
if defaultlibs is None:
defaultlibs = [dll.name_to_root(name)]
self.name = name
try:
command = os.environ[envname]
except KeyError:
command = exename
else:
drv, pth = os.path.splitdrive(command)
if drv:
command = '/' + drv[0] + pth
self.lib_dir = ''
self.inc_dir = ''
self.libs = []
self.cflags = ''
try:
config = msys.run_shell_command([command, '--version', '--cflags', '--libs'])
ver, flags = config.split('\n', 1)
self.ver = ver.strip()
flags = flags.split()
if minver and self.ver < minver:
err= 'WARNING: requires %s version %s (%s found)' % (self.name, self.ver, minver)
raise ValueError, err
self.found = 1
self.cflags = ''
for f in flags:
if f[:2] in ('-I', '-L'):
self.cflags += f[:2] + msys.msys_to_windows(f[2:]) + ' '
elif f[:2] in ('-l', '-D'):
self.cflags += f + ' '
elif f[:3] == '-Wl':
self.cflags += '-Xlinker ' + f + ' '
except:
print_('WARNING: "%s" failed!' % command)
self.found = 0
self.ver = '0'
self.libs = defaultlibs
def configure(self, incdirs, libdir):
if self.found:
print_(self.name + ' '[len(self.name):] + ': found ' + self.ver)
self.found = 1
else:
print_(self.name + ' '[len(self.name):] + ': not found')
class Dependency:
needs_dll = True
def __init__(self, name, checkhead, checklib, libs=None):
if libs is None:
libs = [dll.name_to_root(name)]
self.name = name
self.inc_dir = None
self.lib_dir = None
self.libs = libs
self.found = 0
self.checklib = checklib
self.checkhead = checkhead
self.cflags = ''
def configure(self, incdirs, libdirs):
self.find_inc_dir(incdirs)
self.find_lib_dir(libdirs)
if self.lib_dir and self.inc_dir:
print_(self.name + ' '[len(self.name):] + ': found')
self.found = 1
else:
print_(self.name + ' '[len(self.name):] + ': not found')
def find_inc_dir(self, incdirs):
incname = self.checkhead
for dir in incdirs:
path = path_join(dir, incname)
if os.path.isfile(path):
self.inc_dir = dir
return
def find_lib_dir(self, libdirs):
libname = self.checklib
for dir in libdirs:
path = path_join(dir, libname)
if filter(os.path.isfile, glob(path+'*')):
self.lib_dir = dir
return
class DependencyPython:
needs_dll = False
def __init__(self, name, module, header):
self.name = name
self.lib_dir = ''
self.inc_dir = ''
self.libs = []
self.cflags = ''
self.found = 0
self.ver = '0'
self.module = module
self.header = header
def configure(self, incdirs, libdirs):
self.found = 1
if self.module:
try:
self.ver = __import__(self.module).__version__
except ImportError:
self.found = 0
if self.found and self.header:
fullpath = path_join(get_python_inc(0), self.header)
if not os.path.isfile(fullpath):
self.found = 0
else:
self.inc_dir = os.path.split(fullpath)[0]
if self.found:
print_(self.name + ' '[len(self.name):] + ': found', self.ver)
else:
print_(self.name + ' '[len(self.name):] + ': not found')
class DependencyDLL:
needs_dll = False
def __init__(self, name, libs=None):
if libs is None:
libs = dll.libraries(name)
self.name = 'COPYLIB_' + dll.name_to_root(name)
self.inc_dir = None
self.lib_dir = '_'
self.libs = libs
self.found = 1 # Alway found to make its COPYLIB work
self.cflags = ''
self.lib_name = name
self.file_name_test = dll.tester(name)
def configure(self, incdirs, libdirs, start=None):
omit = []
if start is not None:
if self.set_path(start):
return
omit.append(start)
p, f = path_split(start)
if f == 'lib' and self.set_path(path_join(p, 'bin')):
return
omit.append(start)
# Search other directories
for dir in libdirs:
if dir not in omit:
if self.set_path(dir):
return
p, f = path_split(dir)
if f == 'lib' and self.set_path(path_join(p, 'bin')): # cond. and
return
def set_path(self, wdir):
test = self.file_name_test
try:
files = os.listdir(wdir)
except:
pass
else:
for f in files:
if test(f) and os.path.isfile(path_join(wdir, f)):
# Found
self.lib_dir = path_join(wdir, f)
return True
# Not found
return False
class DependencyWin:
needs_dll = False
def __init__(self, name, cflags):
self.name = name
self.inc_dir = None
self.lib_dir = None
self.libs = []
self.found = 1
self.cflags = cflags
def configure(self, incdirs, libdirs):
pass
def main():
m = msys.Msys(require_mingw=False)
print_('\nHunting dependencies...')
DEPS = [
DependencyProg('SDL', 'SDL_CONFIG', 'sdl-config', '1.2.13', m),
Dependency('FONT', 'SDL_ttf.h', 'libSDL_ttf.dll.a'),
Dependency('IMAGE', 'SDL_image.h', 'libSDL_image.dll.a'),
Dependency('MIXER', 'SDL_mixer.h', 'libSDL_mixer.dll.a'),
DependencyProg('SMPEG', 'SMPEG_CONFIG', 'smpeg-config', '0.4.3', m),
Dependency('PNG', 'png.h', 'libpng12.dll.a'),
Dependency('JPEG', 'jpeglib.h', 'libjpeg.dll.a'),
Dependency('PORTMIDI', 'portmidi.h', 'libportmidi.dll.a'),
Dependency('PORTTIME', 'portmidi.h', 'libportmidi.dll.a'),
DependencyDLL('TIFF'),
DependencyDLL('VORBISFILE'),
DependencyDLL('VORBIS'),
DependencyDLL('OGG'),
DependencyDLL('FREETYPE'),
DependencyDLL('Z'),
]
if not DEPS[0].found:
print_('Unable to run "sdl-config". Please make sure a development version of SDL is installed.')
sys.exit(1)
if localbase:
incdirs = [localbase+d for d in origincdirs]
libdirs = [localbase+d for d in origlibdirs]
else:
incdirs = []
libdirs = []
incdirs += [m.msys_to_windows("/usr/local"+d) for d in origincdirs]
libdirs += [m.msys_to_windows("/usr/local"+d) for d in origlibdirs]
if m.mingw_root is not None:
incdirs += [m.msys_to_windows("/mingw"+d) for d in origincdirs]
libdirs += [m.msys_to_windows("/mingw"+d) for d in origlibdirs]
for arg in string.split(DEPS[0].cflags):
if arg[:2] == '-I':
incdirs.append(arg[2:])
elif arg[:2] == '-L':
libdirs.append(arg[2:])
dll_deps = []
for d in DEPS:
d.configure(incdirs, libdirs)
if d.needs_dll:
dll_dep = DependencyDLL(d.name)
dll_dep.configure(incdirs, libdirs, d.lib_dir)
dll_deps.append(dll_dep)
DEPS += dll_deps
for d in get_definitions():
DEPS.append(DependencyWin(d.name, d.value))
for d in DEPS:
if isinstance(d, DependencyDLL):
if d.lib_dir == '':
print_("DLL for %-12s: not found" % d.lib_name)
else:
print_("DLL for %-12s: %s" % (d.lib_name, d.lib_dir))
for d in DEPS[1:]:
if not d.found:
if not confirm("""
Warning, some of the pygame dependencies were not found. Pygame can still
compile and install, but games that depend on those missing dependencies
will not run. Would you like to continue the configuration?"""):
raise SystemExit()
break
return DEPS
if __name__ == '__main__':
print_("""This is the configuration subscript for MSYS.
Please run "config.py" for full configuration.""")
pygame-1.9.1release/config_darwin.py 0000644 0001750 0001750 00000007770 11225305200 017427 0 ustar vincent vincent """Config on Darwin w/ frameworks"""
import os, sys, string
from glob import glob
from distutils.sysconfig import get_python_inc
class Dependency:
libext = '.a'
def __init__(self, name, checkhead, checklib, libs):
self.name = name
self.inc_dir = None
self.lib_dir = None
self.libs = libs
self.found = 0
self.checklib = checklib + self.libext
self.checkhead = checkhead
self.cflags = ''
def configure(self, incdirs, libdirs):
incname = self.checkhead
libnames = self.checklib, self.name.lower()
for dir in incdirs:
path = os.path.join(dir, incname)
if os.path.isfile(path):
self.inc_dir = dir
break
for dir in libdirs:
for name in libnames:
path = os.path.join(dir, name)
if os.path.isfile(path):
self.lib_dir = dir
break
if self.lib_dir and self.inc_dir:
print (self.name + ' '[len(self.name):] + ': found')
self.found = 1
else:
print (self.name + ' '[len(self.name):] + ': not found')
class FrameworkDependency(Dependency):
def configure(self, incdirs, libdirs):
BASE_DIRS = '/', os.path.expanduser('~/'), '/System/'
for n in BASE_DIRS:
n += 'Library/Frameworks/'
fmwk = n + self.libs + '.framework/Versions/Current/'
if os.path.isfile(fmwk + self.libs):
print ('Framework ' + self.libs + ' found')
self.found = 1
self.inc_dir = fmwk + 'Headers'
self.cflags = (
'-Xlinker "-framework" -Xlinker "' + self.libs + '"' +
' -Xlinker "-F' + n + '"')
self.origlib = self.libs
self.libs = ''
return
print ('Framework ' + self.libs + ' not found')
class DependencyPython:
def __init__(self, name, module, header):
self.name = name
self.lib_dir = ''
self.inc_dir = ''
self.libs = []
self.cflags = ''
self.found = 0
self.ver = '0'
self.module = module
self.header = header
def configure(self, incdirs, libdirs):
self.found = 1
if self.module:
try:
self.ver = __import__(self.module).__version__
except ImportError:
self.found = 0
if self.found and self.header:
fullpath = os.path.join(get_python_inc(0), self.header)
if not os.path.isfile(fullpath):
found = 0
else:
self.inc_dir = os.path.split(fullpath)[0]
if self.found:
print (self.name + ' '[len(self.name):] + ': found', self.ver)
else:
print (self.name + ' '[len(self.name):] + ': not found')
DEPS = [
FrameworkDependency('SDL', 'SDL.h', 'libSDL', 'SDL'),
FrameworkDependency('FONT', 'SDL_ttf.h', 'libSDL_ttf', 'SDL_ttf'),
FrameworkDependency('IMAGE', 'SDL_image.h', 'libSDL_image', 'SDL_image'),
FrameworkDependency('MIXER', 'SDL_mixer.h', 'libSDL_mixer', 'SDL_mixer'),
FrameworkDependency('SMPEG', 'smpeg.h', 'libsmpeg', 'smpeg'),
Dependency('PNG', 'png.h', 'libpng', ['png']),
Dependency('JPEG', 'jpeglib.h', 'libjpeg', ['jpeg']),
Dependency('SCRAP', '','',[]),
Dependency('PORTMIDI', 'portmidi.h', 'libportmidi', ['portmidi']),
FrameworkDependency('PORTTIME', 'CoreMidi.h', 'CoreMidi', 'CoreMidi'),
]
def main():
global DEPS
print ('Hunting dependencies...')
incdirs = ['/usr/local/include','/opt/local/include']
libdirs = ['/usr/local/lib','/opt/local/lib']
newconfig = []
for d in DEPS:
d.configure(incdirs, libdirs)
DEPS[0].cflags = '-Ddarwin '+ DEPS[0].cflags
return DEPS
if __name__ == '__main__':
print ("""This is the configuration subscript for OSX Darwin.
Please run "config.py" for full configuration.""")
pygame-1.9.1release/config.py 0000644 0001750 0001750 00000011511 11225305200 016047 0 ustar vincent vincent #!/usr/bin/env python
# For MinGW build requires Python 2.4 or better and win32api.
"""Quick tool to help setup the needed paths and flags
in your Setup file. This will call the appropriate sub-config
scripts automatically.
each platform config file only needs a "main" routine
that returns a list of instances. the instances must
contain the following variables.
name: name of the dependency, as references in Setup (SDL, FONT, etc)
inc_dir: path to include
lib_dir: library directory
lib: name of library to be linked to
found: true if the dep is available
cflags: extra compile flags
"""
import msysio
import mingwcfg
import sys, os, shutil
def print_(*args, **kwds):
"""Simular to the Python 3.0 print function"""
# This not only supports MSYS but is also a head start on the move to
# Python 3.0. Also, this function can be overridden for testing.
msysio.print_(*args, **kwds)
def confirm(message):
"ask a yes/no question, return result"
reply = msysio.raw_input_("\n%s [Y/n]:" % message)
if reply and reply[0].lower() == 'n':
return False
return True
def is_msys_mingw():
"""Return true if this in an MinGW/MSYS build
The user may prompted for confirmation so only call this function
once.
"""
if msysio.is_msys():
return 1
if ('MINGW_ROOT_DIRECTORY' in os.environ or
os.path.isfile(mingwcfg.path)):
return confirm("Is this an mingw/msys build")
return 0
def prepdep(dep, basepath):
"add some vars to a dep"
if dep.libs:
dep.line = dep.name + ' ='
for lib in dep.libs:
dep.line += ' -l' + lib
else:
dep.line = dep.name + ' = -I.'
dep.varname = '$('+dep.name+')'
if not dep.found:
if dep.name == 'SDL': #fudge if this is unfound SDL
dep.line = 'SDL = -I/NEED_INC_PATH_FIX -L/NEED_LIB_PATH_FIX -lSDL'
dep.varname = '$('+dep.name+')'
dep.found = 1
return
inc = lid = lib = ""
if basepath:
if dep.inc_dir: inc = ' -I$(BASE)'+dep.inc_dir[len(basepath):]
if dep.lib_dir: lid = ' -L$(BASE)'+dep.lib_dir[len(basepath):]
else:
if dep.inc_dir: inc = ' -I' + dep.inc_dir
if dep.lib_dir: lid = ' -L' + dep.lib_dir
libs = ''
for lib in dep.libs:
libs += ' -l' + lib
if dep.name.startswith('COPYLIB_'):
dep.line = dep.name + libs + lid
else:
dep.line = dep.name+' =' + inc + lid + ' ' + dep.cflags + libs
def writesetupfile(deps, basepath, additional_lines):
"create a modified copy of Setup.in"
origsetup = open('Setup.in', 'r')
newsetup = open('Setup', 'w')
line = ''
while line.find('#--StartConfig') == -1:
newsetup.write(line)
line = origsetup.readline()
while line.find('#--EndConfig') == -1:
line = origsetup.readline()
if basepath:
newsetup.write('BASE = ' + basepath + '\n')
for d in deps:
newsetup.write(d.line + '\n')
lines = origsetup.readlines()
lines.extend(additional_lines)
for line in lines:
useit = 1
if not line.startswith('COPYLIB'):
for d in deps:
if line.find(d.varname)!=-1 and not d.found:
useit = 0
newsetup.write('#'+line)
break
if useit:
newsetup.write(line)
def main():
additional_platform_setup = []
if (sys.platform == 'win32' and
# Note that msys builds supported for 2.6 and greater. Use prebuilt.
(sys.version_info >= (2, 6) or not is_msys_mingw())):
print_('Using WINDOWS configuration...\n')
import config_win as CFG
elif sys.platform == 'win32':
print_('Using WINDOWS mingw/msys configuration...\n')
import config_msys as CFG
elif sys.platform == 'darwin':
print_('Using Darwin configuration...\n')
import config_darwin as CFG
additional_platform_setup = open("Setup_Darwin.in", "r").readlines()
else:
print_('Using UNIX configuration...\n')
import config_unix as CFG
if os.path.isfile('Setup'):
if "-auto" in sys.argv or confirm('Backup existing "Setup" file'):
shutil.copyfile('Setup', 'Setup.bak')
if not "-auto" in sys.argv and os.path.isdir('build'):
if confirm('Remove old build directory (force recompile)'):
shutil.rmtree('build', 0)
deps = CFG.main()
if deps:
basepath = None
for d in deps:
prepdep(d, basepath)
writesetupfile(deps, basepath, additional_platform_setup)
print_("""\nIf you get compiler errors during install, doublecheck
the compiler flags in the "Setup" file.\n""")
else:
print_("""\nThere was an error creating the Setup file, check for errors
or make a copy of "Setup.in" and edit by hand.""")
if __name__ == '__main__': main()
pygame-1.9.1release/check_test.py 0000644 0001750 0001750 00000002061 11131725456 016735 0 ustar vincent vincent # Program check_test.py
# Requires Python 2.4
"""A program for listing the modules accessed by a Pygame unit test module
Usage:
python check_test.py
e.g.
python check_test.py surface_test.py
The returned list will show which Pygame modules were imported and accessed.
Each module name is followed by a list of attributes accessed.
"""
import sys
import os
import trackmod
trackmod.begin(pattern=['pygame', 'pygame.*'],
continuous=True,
submodule_accesses=False)
skip = set(['pygame.locals', 'pygame.constants',
'pygame.base', 'pygame.threads'])
os.chdir('test')
test_file = sys.argv[1]
del sys.argv[1]
try:
execfile(test_file)
finally:
trackmod.end()
print "=== Pygame package submodule accesses ==="
print
accesses = [(n, a) for n, a in trackmod.get_accesses().iteritems()
if n not in skip]
accesses.sort(key=lambda t: t[0])
for name, attributes in accesses:
print "%s (%s)" % (name, ', '.join(attributes))
pygame-1.9.1release/bundle_docs.py 0000644 0001750 0001750 00000003673 10770024204 017103 0 ustar vincent vincent #! /usr/bin/env python
"""Tar-zip the Pygame documents and examples
Run this script from the Pygame source root directory.
"""
import os
import tarfile
import re
def add_files(bundle, root, alias, file_names):
for file_name in file_names:
file_alias = os.path.join(alias, file_name)
print " ", file_name, "-->", file_alias
bundle.add(os.path.join(root, file_name), file_alias)
def add_directory(bundle, root, alias):
reject_dirs = re.compile(r'(.svn)$')
# Since it is the file extension that is of interest the reversed
# file name is checked.
reject_files_reversed = re.compile(r'((~.*)|(cyp\..*))')
for sub_root, directories, files in os.walk(root):
directories[:] = [d for d in directories if reject_dirs.match(d) is None]
files[:] = [f for f in files if reject_files_reversed.match(f[-1::-1]) is None]
sub_alias = os.path.join(alias, sub_root[len(root)+1:])
add_files(bundle, sub_root, sub_alias, files)
def main():
bundle_name_elements = ['pygame', 'docs']
setup = open('setup.py', 'r')
try:
match = re.search(r'"version":[ \t]+"([0-9]+\.[0-9]+)\.[^"]+"', setup.read())
finally:
setup.close()
if match is None:
print "*** Unable to find Pygame version in setup.py"
version = ''
else:
version = '-%s' % match.group(1)
bundle_name = 'pygame%s-docs-and-examples.tar.gz' % version
print "Creating bundle", bundle_name
bundle = tarfile.open(bundle_name, 'w:gz')
try:
root = os.path.abspath('.')
alias = 'pygame'
add_files(bundle, root, alias, ['LGPL', 'readme.html', 'install.html'])
add_directory(bundle, os.path.join(root, 'docs'), os.path.join(alias, 'docs'))
add_directory(bundle, os.path.join(root, 'examples'), os.path.join(alias, 'examples'))
print "\nFinished", bundle_name
finally:
bundle.close()
if __name__ == '__main__':
main()
pygame-1.9.1release/bdist_mpkg_support.py 0000644 0001750 0001750 00000002007 11176715722 020544 0 ustar vincent vincent # only enable bdist_mpkg if it's installed already
import pkg_resources
try:
pkg_resources.require('bdist_mpkg>=0.4.2')
except pkg_resources.DistributionNotFound:
raise ImportError
try:
unicode
except NameError:
def unicode(s):
return s
FRAMEWORKS = ['SDL', 'SDL_ttf', 'SDL_image', 'SDL_mixer', 'smpeg']
CUSTOM_SCHEMES = dict(
examples=dict(
description=unicode('(Optional) pygame example code'),
prefix='/Developer/Python/pygame/Examples',
source='examples',
),
docs=dict(
description=unicode('(Optional) pygame documentation'),
prefix='/Developer/Python/pygame/Documentation',
source='docs',
),
)
for framework in FRAMEWORKS:
CUSTOM_SCHEMES[framework] = dict(
description=unicode('(Required) %s.framework') % (framework,),
prefix='/Library/Frameworks/%s.framework' % (framework,),
source='/Library/Frameworks/%s.framework' % (framework,),
)
options = dict(bdist_mpkg=dict(custom_schemes=CUSTOM_SCHEMES))
pygame-1.9.1release/test/transform_test.py 0000644 0001750 0001750 00000060476 11207055754 020671 0 ustar vincent vincent if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests import test_utils
from pygame.tests.test_utils import test_not_implemented, unittest
else:
from test import test_utils
from test.test_utils import test_not_implemented, unittest
import pygame
import pygame.transform
from pygame.locals import *
import platform
def show_image(s, images = []):
#pygame.display.init()
size = s.get_rect()[2:]
screen = pygame.display.set_mode(size)
screen.blit(s, (0,0))
pygame.display.flip()
pygame.event.pump()
going = True
idx = 0
while going:
events = pygame.event.get()
for e in events:
if e.type == QUIT:
going = False
if e.type == KEYDOWN:
if e.key in [K_s, K_a]:
if e.key == K_s: idx += 1
if e.key == K_a: idx -= 1
s = images[idx]
screen.blit(s, (0,0))
pygame.display.flip()
pygame.event.pump()
else:
going = False
pygame.display.quit()
pygame.display.init()
def threshold(return_surf, surf, color, threshold = (0,0,0), diff_color = (0,0,0), change_return = True ):
""" given the color it makes return_surf only have areas with the given colour.
"""
width, height =surf.get_width(), surf.get_height()
if change_return:
return_surf.fill(diff_color)
try:
r, g, b = color
except ValueError:
r, g, b, a = color
try:
tr, tg, tb = color
except ValueError:
tr, tg, tb, ta = color
similar = 0
for y in xrange(height):
for x in xrange(width):
c1 = surf.get_at((x,y))
if ( (abs(c1[0] - r) < tr) &
(abs(c1[1] - g) < tg) &
(abs(c1[2] - b) < tb) ):
# this pixel is within the threshold.
if change_return:
return_surf.set_at((x,y), c1)
similar += 1
#else:
# print c1, c2
return similar
class TransformModuleTest( unittest.TestCase ):
#class TransformModuleTest( object ):
#def assertEqual(self, x,x2):
# print x,x2
def test_scale__alpha( self ):
""" see if set_alpha information is kept.
"""
s = pygame.Surface((32,32))
s.set_alpha(55)
self.assertEqual(s.get_alpha(),55)
s = pygame.Surface((32,32))
s.set_alpha(55)
s2 = pygame.transform.scale(s, (64,64))
s3 = s.copy()
self.assertEqual(s.get_alpha(),s3.get_alpha())
self.assertEqual(s.get_alpha(),s2.get_alpha())
def test_scale__destination( self ):
""" see if the destination surface can be passed in to use.
"""
s = pygame.Surface((32,32))
s2 = pygame.transform.scale(s, (64,64))
s3 = s2.copy()
s3 = pygame.transform.scale(s, (64,64), s3)
pygame.transform.scale(s, (64,64), s2)
# the wrong size surface is past in. Should raise an error.
self.assertRaises(ValueError, pygame.transform.scale, s, (33,64), s3)
if 1:
s = pygame.Surface((32,32))
s2 = pygame.transform.smoothscale(s, (64,64))
s3 = s2.copy()
s3 = pygame.transform.smoothscale(s, (64,64), s3)
pygame.transform.smoothscale(s, (64,64), s2)
# the wrong size surface is past in. Should raise an error.
self.assertRaises(ValueError, pygame.transform.smoothscale, s, (33,64), s3)
def test_threshold__honors_third_surface(self):
# __doc__ for threshold as of Tue 07/15/2008
# pygame.transform.threshold(DestSurface, Surface, color, threshold =
# (0,0,0,0), diff_color = (0,0,0,0), change_return = True, Surface =
# None): return num_threshold_pixels
# When given the optional third
# surface, it would use the colors in that rather than the "color"
# specified in the function to check against.
# New in pygame 1.8
################################################################
# Sizes
(w, h) = size = (32, 32)
# the original_color is within the threshold of the threshold_color
threshold = (20, 20, 20, 20)
original_color = (25,25,25,25)
threshold_color = (10, 10, 10, 10)
# Surfaces
original_surface = pygame.Surface(size, pygame.SRCALPHA, 32)
dest_surface = pygame.Surface(size, pygame.SRCALPHA, 32)
# Third surface is used in lieu of 3rd position arg color
third_surface = pygame.Surface(size, pygame.SRCALPHA, 32)
# Color filling
original_surface.fill(original_color)
third_surface.fill(threshold_color)
################################################################
# All pixels for color should be within threshold
#
pixels_within_threshold = pygame.transform.threshold (
dest_surface, original_surface, threshold_color,
threshold,
0, # diff_color
0 # change_return
)
self.assertEqual(w*h, pixels_within_threshold)
################################################################
# This should respect third_surface colors in place of 3rd arg
# color Should be the same as: surface.fill(threshold_color)
# all within threshold
pixels_within_threshold = pygame.transform.threshold (
dest_surface,
original_surface,
0, # color (would fail if honored)
threshold,
0, # diff_color
0, # change_return
third_surface,
)
self.assertEqual(w*h, pixels_within_threshold)
################################################################
# Change dest_surface on return (not expected)
change_color = (255, 10, 10, 10)
pixels_within_threshold = pygame.transform.threshold (
dest_surface,
original_surface,
0, # color
threshold,
change_color, # diff_color
1, # change_return
third_surface,
)
# Return, of pixels within threshold is correct
self.assertEqual(w*h, pixels_within_threshold)
# Size of dest surface is correct
dest_rect = dest_surface.get_rect()
dest_size = dest_rect.size
self.assertEqual(size, dest_size)
# The color is not the change_color specified for every pixel As all
# pixels are within threshold
for pt in test_utils.rect_area_pts(dest_rect):
self.assert_(dest_surface.get_at(pt) != change_color)
################################################################
# Lowering the threshold, expecting changed surface
pixels_within_threshold = pygame.transform.threshold (
dest_surface,
original_surface,
0, # color
0, # threshold
change_color, # diff_color
1, # change_return
third_surface,
)
# Return, of pixels within threshold is correct
self.assertEqual(0, pixels_within_threshold)
# Size of dest surface is correct
dest_rect = dest_surface.get_rect()
dest_size = dest_rect.size
self.assertEqual(size, dest_size)
# The color is the change_color specified for every pixel As all
# pixels are not within threshold
for pt in test_utils.rect_area_pts(dest_rect):
self.assertEqual(dest_surface.get_at(pt), change_color)
#XXX
def test_threshold_non_src_alpha(self):
result = pygame.Surface((10,10))
s1 = pygame.Surface((10,10))
s2 = pygame.Surface((10,10))
s3 = pygame.Surface((10,10))
s4 = pygame.Surface((10,10))
result = pygame.Surface((10,10))
x = s1.fill((0,0,0))
x = s2.fill((0,20,0))
x = s3.fill((0,0,0))
x = s4.fill((0,0,0))
s1.set_at((0,0), (32, 20, 0 ))
s2.set_at((0,0), (33, 21, 0 ))
s2.set_at((3,0), (63, 61, 0 ))
s3.set_at((0,0), (112, 31, 0 ))
s4.set_at((0,0), (11, 31, 0 ))
s4.set_at((1,1), (12, 31, 0 ))
self.assertEqual( s1.get_at((0,0)), (32, 20, 0, 255) )
self.assertEqual( s2.get_at((0,0)), (33, 21, 0, 255) )
self.assertEqual( (0,0), (s1.get_flags(), s2.get_flags()))
#All one hundred of the pixels should be within the threshold.
#>>> object_tracking.diff_image(result, s1, s2, threshold = 20)
#100
similar_color = (255, 255, 255,255)
diff_color=(222,0,0,255)
threshold_color = (20,20,20,255)
rr = pygame.transform.threshold(result, s1, similar_color, threshold_color, diff_color, 1, s2)
self.assertEqual(rr, 99)
self.assertEqual( result.get_at((0,0)), (255,255,255, 255) )
rr = pygame.transform.threshold(result, s1, similar_color,
threshold_color, diff_color, 2, s2)
self.assertEqual(rr, 99)
self.assertEqual( result.get_at((0,0)), (32, 20, 0, 255) )
# this is within the threshold,
# so the color is copied from the s1 surface.
self.assertEqual( result.get_at((1,0)), (0, 0, 0, 255) )
# this color was not in the threshold so it has been set to diff_color
self.assertEqual( result.get_at((3,0)), (222, 0, 0, 255) )
def test_threshold__uneven_colors(self):
(w,h) = size = (16, 16)
original_surface = pygame.Surface(size, pygame.SRCALPHA, 32)
dest_surface = pygame.Surface(size, pygame.SRCALPHA, 32)
original_surface.fill(0)
threshold_color_template = [5, 5, 5, 5]
threshold_template = [6, 6, 6, 6]
################################################################
for pos in range(len('rgb')):
threshold_color = threshold_color_template[:]
threshold = threshold_template[:]
threshold_color[pos] = 45
threshold[pos] = 50
pixels_within_threshold = pygame.transform.threshold (
dest_surface, original_surface, threshold_color,
threshold,
0, # diff_color
0 # change_return
)
self.assertEqual(w*h, pixels_within_threshold)
################################################################
def test_threshold__surface(self):
"""
"""
#pygame.transform.threshold(DestSurface, Surface, color, threshold = (0,0,0,0), diff_color = (0,0,0,0), change_return = True): return num_threshold_pixels
threshold = pygame.transform.threshold
s1 = pygame.Surface((32,32), SRCALPHA, 32)
s2 = pygame.Surface((32,32), SRCALPHA, 32)
s3 = pygame.Surface((1,1), SRCALPHA, 32)
s1.fill((40,40,40))
s2.fill((255,255,255))
dest_surface = s2
surface1 = s1
color = (30,30,30)
the_threshold = (11,11,11)
diff_color = (255,0,0)
change_return = 2
# set the similar pixels in destination surface to the color
# in the first surface.
num_threshold_pixels = threshold(dest_surface, surface1, color,
the_threshold, diff_color,
change_return)
#num_threshold_pixels = threshold(s2, s1, (30,30,30))
self.assertEqual(num_threshold_pixels, s1.get_height() * s1.get_width())
self.assertEqual(s2.get_at((0,0)), (40, 40, 40, 255))
if 1:
# only one pixel should not be changed.
s1.fill((40,40,40))
s2.fill((255,255,255))
s1.set_at( (0,0), (170, 170, 170) )
# set the similar pixels in destination surface to the color
# in the first surface.
num_threshold_pixels = threshold(s2, s1, (30,30,30), (11,11,11),
(0,0,0), 2)
#num_threshold_pixels = threshold(s2, s1, (30,30,30))
self.assertEqual(num_threshold_pixels, (s1.get_height() * s1.get_width()) -1)
self.assertEqual(s2.get_at((0,0)), (0,0,0, 255))
self.assertEqual(s2.get_at((0,1)), (40, 40, 40, 255))
self.assertEqual(s2.get_at((17,1)), (40, 40, 40, 255))
# abs(40 - 255) < 100
#(abs(c1[0] - r) < tr)
if 1:
s1.fill((160,160,160))
s2.fill((255,255,255))
num_threshold_pixels = threshold(s2, s1, (255,255,255), (100,100,100), (0,0,0), True)
self.assertEqual(num_threshold_pixels, (s1.get_height() * s1.get_width()))
if 1:
# only one pixel should not be changed.
s1.fill((40,40,40))
s2.fill((255,255,255))
s1.set_at( (0,0), (170, 170, 170) )
num_threshold_pixels = threshold(s3, s1, (30,30,30), (11,11,11), (0,0,0), False)
#num_threshold_pixels = threshold(s2, s1, (30,30,30))
self.assertEqual(num_threshold_pixels, (s1.get_height() * s1.get_width()) -1)
if 1:
# test end markers. 0, and 255
# the pixels are different by 1.
s1.fill((254,254,254))
s2.fill((255,255,255))
s3.fill((255,255,255))
s1.set_at( (0,0), (170, 170, 170) )
num_threshold_pixels = threshold(s3, s1, (254,254,254), (1,1,1),
(44,44,44,255), False)
self.assertEqual(num_threshold_pixels, (s1.get_height() * s1.get_width()) -1)
# compare the two surfaces. Should be all but one matching.
num_threshold_pixels = threshold(s3, s1, 0, (1,1,1),
(44,44,44,255), False, s2)
self.assertEqual(num_threshold_pixels, (s1.get_height() * s1.get_width()) -1)
# within (0,0,0) threshold? Should match no pixels.
num_threshold_pixels = threshold(s3, s1, (253,253,253), (0,0,0),
(44,44,44,255), False)
self.assertEqual(num_threshold_pixels, 0)
# other surface within (0,0,0) threshold? Should match no pixels.
num_threshold_pixels = threshold(s3, s1, 0, (0,0,0),
(44,44,44,255), False, s2)
self.assertEqual(num_threshold_pixels, 0)
def test_laplacian(self):
"""
"""
SIZE = 32
s1 = pygame.Surface((SIZE, SIZE))
s2 = pygame.Surface((SIZE, SIZE))
s1.fill((10,10,70))
pygame.draw.line(s1, (255,0,0), (3,10), (20,20))
# a line at the last row of the image.
pygame.draw.line(s1, (255,0,0), (0,31), (31,31))
pygame.transform.laplacian(s1,s2)
#show_image(s1)
#show_image(s2)
self.assertEqual(s2.get_at((0,0)), (0, 0, 0, 255))
self.assertEqual(s2.get_at((3,10)), (255,0,0,255))
self.assertEqual(s2.get_at((0,31)), (255,0,0,255))
self.assertEqual(s2.get_at((31,31)), (255,0,0,255))
# here we create the return surface.
s2 = pygame.transform.laplacian(s1)
self.assertEqual(s2.get_at((0,0)), (0, 0, 0, 255))
self.assertEqual(s2.get_at((3,10)), (255,0,0,255))
self.assertEqual(s2.get_at((0,31)), (255,0,0,255))
self.assertEqual(s2.get_at((31,31)), (255,0,0,255))
def test_average_surfaces(self):
"""
"""
SIZE = 32
s1 = pygame.Surface((SIZE, SIZE))
s2 = pygame.Surface((SIZE, SIZE))
s3 = pygame.Surface((SIZE, SIZE))
s1.fill((10,10,70))
s2.fill((10,20,70))
s3.fill((10,130,10))
surfaces = [s1, s2, s3]
surfaces = [s1, s2]
sr = pygame.transform.average_surfaces(surfaces)
self.assertEqual(sr.get_at((0,0)), (10,15,70,255))
self.assertRaises(TypeError, pygame.transform.average_surfaces, 1)
self.assertRaises(TypeError, pygame.transform.average_surfaces, [])
self.assertRaises(TypeError, pygame.transform.average_surfaces, [1])
self.assertRaises(TypeError, pygame.transform.average_surfaces, [s1, 1])
self.assertRaises(TypeError, pygame.transform.average_surfaces, [1, s1])
self.assertRaises(TypeError, pygame.transform.average_surfaces, [s1, s2, 1])
self.assertRaises(TypeError, pygame.transform.average_surfaces, (s for s in [s1, s2,s3] ))
def test_average_surfaces__24(self):
SIZE = 32
depth = 24
s1 = pygame.Surface((SIZE, SIZE), 0, depth)
s2 = pygame.Surface((SIZE, SIZE), 0, depth)
s3 = pygame.Surface((SIZE, SIZE), 0, depth)
s1.fill((10,10,70, 255))
s2.fill((10,20,70, 255))
s3.fill((10,130,10, 255))
surfaces = [s1, s2, s3]
sr = pygame.transform.average_surfaces(surfaces)
self.assertEqual( sr.get_masks(), s1.get_masks() )
self.assertEqual( sr.get_flags(), s1.get_flags() )
self.assertEqual( sr.get_losses(), s1.get_losses() )
if 0:
print ( sr, s1 )
print ( sr.get_masks(), s1.get_masks() )
print ( sr.get_flags(), s1.get_flags() )
print ( sr.get_losses(), s1.get_losses() )
print ( sr.get_shifts(), s1.get_shifts() )
self.assertEqual(sr.get_at((0,0)), (10,53,50,255))
def test_average_color(self):
"""
"""
a = [24, 32]
for i in a:
s = pygame.Surface((32,32), 0, i)
s.fill((0,100,200))
s.fill((10,50,100), (0,0,16,32))
self.assertEqual(pygame.transform.average_color(s),(5,75,150,0))
self.assertEqual(pygame.transform.average_color(s, (16,0,16,32)), (0,100,200,0))
def todo_test_rotate(self):
# __doc__ (as of 2008-06-25) for pygame.transform.rotate:
# pygame.transform.rotate(Surface, angle): return Surface
# rotate an image
# color = (128, 128, 128, 255)
# s = pygame.Surface((3, 3))
# s.set_at((2, 0), color)
# self.assert_(s.get_at((0, 0)) != color)
# s = pygame.transform.rotate(s, 90)
# self.assert_(s.get_at((0, 0)) == color)
self.fail()
def test_rotate__lossless_at_90_degrees(self):
w, h = 32, 32
s = pygame.Surface((w, h), pygame.SRCALPHA)
gradient = list(test_utils.gradient(w, h))
for pt, color in gradient: s.set_at(pt, color)
for rotation in (90, -90):
s = pygame.transform.rotate(s,rotation)
for pt, color in gradient:
self.assert_(s.get_at(pt) == color)
def test_scale2x(self):
# __doc__ (as of 2008-06-25) for pygame.transform.scale2x:
# pygame.transform.scale2x(Surface, DestSurface = None): Surface
# specialized image doubler
w, h = 32, 32
s = pygame.Surface((w, h), pygame.SRCALPHA, 32)
# s.set_at((0,0), (20, 20, 20, 255))
s2 = pygame.transform.scale2x(s)
self.assertEquals(s2.get_rect().size, (64, 64))
def test_get_smoothscale_backend(self):
filter_type = pygame.transform.get_smoothscale_backend()
self.failUnless(filter_type in ['GENERIC', 'MMX', 'SSE'])
# It would be nice to test if a non-generic type corresponds to an x86
# processor. But there is no simple test for this. platform.machine()
# returns process version specific information, like 'i686'.
def test_set_smoothscale_backend(self):
# All machines should allow 'GENERIC'.
original_type = pygame.transform.get_smoothscale_backend()
pygame.transform.set_smoothscale_backend('GENERIC')
filter_type = pygame.transform.get_smoothscale_backend()
self.failUnlessEqual(filter_type, 'GENERIC')
# All machines should allow returning to original value.
# Also check that keyword argument works.
pygame.transform.set_smoothscale_backend(type=original_type)
# Something invalid.
def change():
pygame.transform.set_smoothscale_backend('mmx')
self.failUnlessRaises(ValueError, change)
# Invalid argument keyword.
def change():
pygame.transform.set_smoothscale_backend(t='GENERIC')
self.failUnlessRaises(TypeError, change)
# Invalid argument type.
def change():
pygame.transform.set_smoothscale_backend(1)
self.failUnlessRaises(TypeError, change)
# Unsupported type, if possible.
if original_type != 'SSE':
def change():
pygame.transform.set_smoothscale_backend('SSE')
self.failUnlessRaises(ValueError, change)
# Should be back where we started.
filter_type = pygame.transform.get_smoothscale_backend()
self.failUnlessEqual(filter_type, original_type)
def todo_test_chop(self):
# __doc__ (as of 2008-08-02) for pygame.transform.chop:
# pygame.transform.chop(Surface, rect): return Surface
# gets a copy of an image with an interior area removed
#
# Extracts a portion of an image. All vertical and horizontal pixels
# surrounding the given rectangle area are removed. The corner areas
# (diagonal to the rect) are then brought together. (The original
# image is not altered by this operation.)
#
# NOTE: If you want a "crop" that returns the part of an image within
# a rect, you can blit with a rect to a new surface or copy a
# subsurface.
self.fail()
def todo_test_flip(self):
# __doc__ (as of 2008-08-02) for pygame.transform.flip:
# pygame.transform.flip(Surface, xbool, ybool): return Surface
# flip vertically and horizontally
#
# This can flip a Surface either vertically, horizontally, or both.
# Flipping a Surface is nondestructive and returns a new Surface with
# the same dimensions.
self.fail()
def todo_test_rotozoom(self):
# __doc__ (as of 2008-08-02) for pygame.transform.rotozoom:
# pygame.transform.rotozoom(Surface, angle, scale): return Surface
# filtered scale and rotation
#
# This is a combined scale and rotation transform. The resulting
# Surface will be a filtered 32-bit Surface. The scale argument is a
# floating point value that will be multiplied by the current
# resolution. The angle argument is a floating point value that
# represents the counterclockwise degrees to rotate. A negative
# rotation angle will rotate clockwise.
self.fail()
def todo_test_smoothscale(self):
# __doc__ (as of 2008-08-02) for pygame.transform.smoothscale:
# pygame.transform.smoothscale(Surface, (width, height), DestSurface =
# None): return Surface
#
# scale a surface to an arbitrary size smoothly
#
# Uses one of two different algorithms for scaling each dimension of
# the input surface as required. For shrinkage, the output pixels are
# area averages of the colors they cover. For expansion, a bilinear
# filter is used. For the amd64 and i686 architectures, optimized MMX
# routines are included and will run much faster than other machine
# types. The size is a 2 number sequence for (width, height). This
# function only works for 24-bit or 32-bit surfaces. An exception
# will be thrown if the input surface bit depth is less than 24.
#
# New in pygame 1.8
self.fail()
if __name__ == '__main__':
#tt = TransformModuleTest()
#tt.test_threshold_non_src_alpha()
unittest.main()
pygame-1.9.1release/test/time_test.py 0000644 0001750 0001750 00000017264 11207055754 017611 0 ustar vincent vincent #################################### IMPORTS ###################################
if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils import test_not_implemented, unittest
else:
from test.test_utils import test_not_implemented, unittest
import pygame
import time
Clock = pygame.time.Clock
################################################################################
class ClockTypeTest(unittest.TestCase):
def test_construction(self):
c = Clock()
self.assert_(c, "Clock can be constructed")
def todo_test_get_fps(self):
# __doc__ (as of 2008-08-02) for pygame.time.Clock.get_fps:
# Clock.get_fps(): return float
# compute the clock framerate
#
# Compute your game's framerate (in frames per second). It is computed
# by averaging the last few calls to Clock.tick().
#
self.fail()
# delay_per_frame = 1 / 100.0
#
# c = Clock()
#
# for f in range(100):
# c.tick()
# time.sleep(delay_per_frame)
#
# self.assert_(99.0 < c.get_fps() < 101.0)
def todo_test_get_rawtime(self):
# __doc__ (as of 2008-08-02) for pygame.time.Clock.get_rawtime:
# Clock.get_rawtime(): return milliseconds
# actual time used in the previous tick
#
# Similar to Clock.get_time(), but this does not include any time used
# while Clock.tick() was delaying to limit the framerate.
#
self.fail()
def todo_test_get_time(self):
# __doc__ (as of 2008-08-02) for pygame.time.Clock.get_time:
# Clock.get_time(): return milliseconds
# time used in the previous tick
#
# Returns the parameter passed to the last call to Clock.tick(). It is
# the number of milliseconds passed between the previous two calls to
# Pygame.tick().
#
self.fail()
# c = Clock()
# c.tick() #between here
# time.sleep(0.02)
# #get_time()
# c.tick() # here
#
# time.sleep(0.02)
#
# self.assert_(20 <= c.get_time() <= 30)
def todo_test_tick(self):
# __doc__ (as of 2008-08-02) for pygame.time.Clock.tick:
# Clock.tick(framerate=0): return milliseconds
# control timer events
# update the clock
#
# This method should be called once per frame. It will compute how
# many milliseconds have passed since the previous call.
#
# If you pass the optional framerate argument the function will delay
# to keep the game running slower than the given ticks per second.
# This can be used to help limit the runtime speed of a game. By
# calling Clock.tick(40) once per frame, the program will never run at
# more than 40 frames per second.
#
# Note that this function uses SDL_Delay function which is not
# accurate on every platform, but does not use much cpu. Use
# tick_busy_loop if you want an accurate timer, and don't mind chewing
# cpu.
#
self.fail()
# collection = []
# c = Clock()
#
# c.tick()
# for i in range(100):
# time.sleep(0.005)
# collection.append(c.tick())
#
# for outlier in [min(collection), max(collection)]:
# if outlier != 5: collection.remove(outlier)
#
# self.assert_(sum(collection) / len(collection) == 5)
def todo_test_tick_busy_loop(self):
# __doc__ (as of 2008-08-02) for pygame.time.Clock.tick_busy_loop:
# Clock.tick_busy_loop(framerate=0): return milliseconds
# control timer events
# update the clock
#
# This method should be called once per frame. It will compute how
# many milliseconds have passed since the previous call.
#
# If you pass the optional framerate argument the function will delay
# to keep the game running slower than the given ticks per second.
# This can be used to help limit the runtime speed of a game. By
# calling Clock.tick(40) once per frame, the program will never run at
# more than 40 frames per second.
#
# Note that this function uses pygame.time.delay, which uses lots of
# cpu in a busy loop to make sure that timing is more acurate.
#
# New in pygame 1.8.0.
self.fail()
class TimeModuleTest(unittest.TestCase):
def todo_test_delay(self):
# __doc__ (as of 2008-08-02) for pygame.time.delay:
# pygame.time.delay(milliseconds): return time
# pause the program for an amount of time
#
# Will pause for a given number of milliseconds. This function will
# use the processor (rather than sleeping) in order to make the delay
# more accurate than pygame.time.wait().
#
# This returns the actual number of milliseconds used.
self.fail()
def todo_test_get_ticks(self):
# __doc__ (as of 2008-08-02) for pygame.time.get_ticks:
# pygame.time.get_ticks(): return milliseconds
# get the time in milliseconds
#
# Return the number of millisconds since pygame.init() was called.
# Before pygame is initialized this will always be 0.
#
self.fail()
def todo_test_set_timer(self):
# __doc__ (as of 2008-08-02) for pygame.time.set_timer:
# pygame.time.set_timer(eventid, milliseconds): return None
# repeatedly create an event on the event queue
#
# Set an event type to appear on the event queue every given number of
# milliseconds. The first event will not appear until the amount of
# time has passed.
#
# Every event type can have a separate timer attached to it. It is
# best to use the value between pygame.USEREVENT and pygame.NUMEVENTS.
#
# To disable the timer for an event, set the milliseconds argument to 0.
self.fail()
def todo_test_wait(self):
# __doc__ (as of 2008-08-02) for pygame.time.wait:
# pygame.time.wait(milliseconds): return time
# pause the program for an amount of time
#
# Will pause for a given number of milliseconds. This function sleeps
# the process to share the processor with other programs. A program
# that waits for even a few milliseconds will consume very little
# processor time. It is slightly less accurate than the
# pygame.time.delay() function.
#
# This returns the actual number of milliseconds used.
self.fail()
################################################################################
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/threads_test.py 0000644 0001750 0001750 00000015256 11131725456 020303 0 ustar vincent vincent #################################### IMPORTS ###################################
if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils import test_not_implemented, unittest
else:
from test.test_utils import test_not_implemented, unittest
from pygame.threads import FuncResult, tmap, WorkerQueue, Empty, STOP
from pygame import threads
import time
################################################################################
class WorkerQueueTypeTest(unittest.TestCase):
def test_usage_with_different_functions(self):
def f(x):
return x+1
def f2(x):
return x+2
wq = WorkerQueue()
fr = FuncResult(f)
fr2 = FuncResult(f2)
wq.do(fr, 1)
wq.do(fr2, 1)
wq.wait()
wq.stop()
self.assert_(fr.result == 2)
self.assert_(fr2.result == 3)
def test_do(self):
# __doc__ (as of 2008-06-28) for pygame.threads.WorkerQueue.do:
# puts a function on a queue for running later.
#
return
def test_stop(self):
# __doc__ (as of 2008-06-28) for pygame.threads.WorkerQueue.stop:
# Stops the WorkerQueue, waits for all of the threads to finish up.
#
wq = WorkerQueue()
self.assert_(len(wq.pool) > 0)
for t in wq.pool: self.assert_(t.isAlive())
for i in xrange(200): wq.do(lambda x: x+1, i)
wq.stop()
for t in wq.pool: self.assert_(not t.isAlive())
self.assert_(wq.queue.get() is STOP)
def todo_test_threadloop(self):
# __doc__ (as of 2008-06-28) for pygame.threads.WorkerQueue.threadloop:
# Loops until all of the tasks are finished.
self.fail()
def test_wait(self):
# __doc__ (as of 2008-06-28) for pygame.threads.WorkerQueue.wait:
# waits until all tasks are complete.
wq = WorkerQueue()
for i in xrange(2000): wq.do(lambda x: x+1, i)
wq.wait()
self.assertRaises(Empty, wq.queue.get_nowait)
wq.stop()
class ThreadsModuleTest(unittest.TestCase):
def todo_test_benchmark_workers(self):
"tags:long_running"
# __doc__ (as of 2008-06-28) for pygame.threads.benchmark_workers:
# does a little test to see if workers are at all faster.
# Returns the number of workers which works best.
# Takes a little bit of time to run, so you should only really call
# it once.
# You can pass in benchmark data, and functions if you want.
# a_bench_func - f(data)
# the_data - data to work on.
self.fail()
def test_init(self):
# __doc__ (as of 2008-06-28) for pygame.threads.init:
# Does a little test to see if threading is worth it.
# Sets up a global worker queue if it's worth it.
#
# Calling init() is not required, but is generally better to do.
threads.init(8)
self.assert_(isinstance(threads._wq, WorkerQueue))
threads.quit()
def test_quit(self):
# __doc__ (as of 2008-06-28) for pygame.threads.quit:
# cleans up everything.
#
threads.init(8)
threads.quit()
self.assert_(threads._wq is None)
def test_tmap(self):
# __doc__ (as of 2008-06-28) for pygame.threads.tmap:
# like map, but uses a thread pool to execute.
# num_workers - the number of worker threads that will be used. If pool
# is passed in, then the num_workers arg is ignored.
# worker_queue - you can optionally pass in an existing WorkerQueue.
# wait - True means that the results are returned when everything is finished.
# False means that we return the [worker_queue, results] right away instead.
# results, is returned as a list of FuncResult instances.
# stop_on_error -
func, data = lambda x:x+1, xrange(100)
tmapped = tmap(func, data)
mapped = map(func, data)
self.assert_(tmapped == mapped)
def test_tmap__None_func_and_multiple_sequences(self):
return #TODO
""" Using a None as func and multiple seqences """
res = tmap(None, [1,2,3,4])
res2 = tmap(None, [1,2,3,4], [22, 33, 44, 55])
res3 = tmap(None, [1,2,3,4], [22, 33, 44, 55, 66])
res4 = tmap(None, [1,2,3,4,5], [22, 33, 44, 55])
self.assertEqual([1, 2, 3, 4], res)
self.assertEqual([(1, 22), (2, 33), (3, 44), (4, 55)], res2)
self.assertEqual([(1, 22), (2, 33), (3, 44), (4, 55), (None, 66)], res3)
self.assertEqual([(1, 22), (2, 33), (3, 44), (4, 55), (5,None)], res4)
def test_tmap__wait(self):
r = range(1000)
wq, results = tmap(lambda x:x, r, num_workers = 5, wait=False)
wq.wait()
r2 = map(lambda x:x.result, results)
self.assert_(r == r2)
def test_FuncResult(self):
# as of 2008-06-28
# FuncResult(f, callback = None, errback = None)
# Used for wrapping up a function call so that the results are stored
# inside the instances result attribute.
# f - is the function we that we call
# callback(result) - this is called when the function(f) returns
# errback(exception) - this is called when the function(f) raises
# an exception.
# Results are stored in result attribute
fr = FuncResult(lambda x:x+1)
fr(2)
self.assert_(fr.result == 3)
# Exceptions are store in exception attribute
self.assert_(fr.exception is None, "when no exception raised")
exception = ValueError('rast')
def x(sdf):
raise exception
fr = FuncResult(x)
fr(None)
self.assert_(fr.exception is exception)
################################################################################
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/threads_tags.py 0000644 0001750 0001750 00000000162 11207055754 020251 0 ustar vincent vincent __tags__ = []
import sys
if sys.version_info >= (3, 0, 0):
__tags__.extend(('ignore', 'subprocess_ignore'))
pygame-1.9.1release/test/test_test_.py 0000644 0001750 0001750 00000000033 11032334512 017737 0 ustar vincent vincent while True:
pass
pygame-1.9.1release/test/sysfont_test.py 0000644 0001750 0001750 00000003304 11207055754 020346 0 ustar vincent vincent #################################### IMPORTS ###################################
if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils import test_not_implemented, unittest
else:
from test.test_utils import test_not_implemented, unittest
################################################################################
class SysfontModuleTest(unittest.TestCase):
def todo_test_create_aliases(self):
# __doc__ (as of 2008-08-02) for pygame.sysfont.create_aliases:
#
self.fail()
def todo_test_initsysfonts(self):
# __doc__ (as of 2008-08-02) for pygame.sysfont.initsysfonts:
#
self.fail()
def todo_test_initsysfonts_darwin(self):
# __doc__ (as of 2008-08-02) for pygame.sysfont.initsysfonts_darwin:
#
self.fail()
def todo_test_initsysfonts_unix(self):
# __doc__ (as of 2008-08-02) for pygame.sysfont.initsysfonts_unix:
#
self.fail()
def todo_test_initsysfonts_win32(self):
# __doc__ (as of 2008-08-02) for pygame.sysfont.initsysfonts_win32:
#
self.fail()
################################################################################
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/surflock_test.py 0000644 0001750 0001750 00000012553 11207055754 020477 0 ustar vincent vincent if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils import test_not_implemented, unittest
else:
from test.test_utils import test_not_implemented, unittest
import pygame
import sys
class SurfaceLockTest (unittest.TestCase):
def test_lock (self):
sf = pygame.Surface ((5, 5))
sf.lock ()
self.assertEquals (sf.get_locked (), True)
self.assertEquals (sf.get_locks (), (sf,))
sf.lock ()
self.assertEquals (sf.get_locked (), True)
self.assertEquals (sf.get_locks (), (sf, sf))
sf.unlock ()
self.assertEquals (sf.get_locked (), True)
self.assertEquals (sf.get_locks (), (sf,))
sf.unlock ()
self.assertEquals (sf.get_locked (), False)
self.assertEquals (sf.get_locks (), ())
def test_subsurface_lock (self):
sf = pygame.Surface ((5, 5))
subsf = sf.subsurface ((1, 1, 2, 2))
sf2 = pygame.Surface ((5, 5))
# Simple blits, nothing should happen here.
sf2.blit (subsf, (0, 0))
sf2.blit (sf, (0, 0))
# Test blitting on self:
self.assertRaises (pygame.error, sf.blit, subsf, (0, 0))
#self.assertRaises (pygame.error, subsf.blit, sf, (0, 0))
# ^ Fails although it should not in my opinion. If I cannot
# blit the subsurface to the surface, it should not be allowed
# the other way around as well.
# Test additional locks.
sf.lock ()
sf2.blit (subsf, (0, 0))
self.assertRaises (pygame.error, sf2.blit, sf, (0, 0))
subsf.lock ()
self.assertRaises (pygame.error, sf2.blit, subsf, (0, 0))
self.assertRaises (pygame.error, sf2.blit, sf, (0, 0))
# sf and subsf are now explicitly locked. Unlock sf, so we can
# (assume) to blit it.
# It will fail though as the subsurface still has a lock around,
# which is okay and correct behaviour.
sf.unlock ()
self.assertRaises (pygame.error, sf2.blit, subsf, (0, 0))
self.assertRaises (pygame.error, sf2.blit, sf, (0, 0))
# Run a second unlock on the surface. This should ideally have
# no effect as the subsurface is the locking reason!
sf.unlock ()
self.assertRaises (pygame.error, sf2.blit, sf, (0, 0))
self.assertRaises (pygame.error, sf2.blit, subsf, (0, 0))
subsf.unlock ()
sf.lock ()
self.assertEquals (sf.get_locked (), True)
self.assertEquals (sf.get_locks (), (sf,))
self.assertEquals (subsf.get_locked (), False)
self.assertEquals (subsf.get_locks (), ())
subsf.lock ()
self.assertEquals (sf.get_locked (), True)
self.assertEquals (sf.get_locks (), (sf, subsf))
self.assertEquals (subsf.get_locked (), True)
self.assertEquals (subsf.get_locks (), (subsf,))
sf.unlock ()
self.assertEquals (sf.get_locked (), True)
self.assertEquals (sf.get_locks (), (subsf,))
self.assertEquals (subsf.get_locked (), True)
self.assertEquals (subsf.get_locks (), (subsf,))
subsf.unlock ()
self.assertEquals (sf.get_locked (), False)
self.assertEquals (sf.get_locks (), ())
self.assertEquals (subsf.get_locked (), False)
self.assertEquals (subsf.get_locks (), ())
subsf.lock ()
self.assertEquals (sf.get_locked (), True)
self.assertEquals (sf.get_locks (), (subsf,))
self.assertEquals (subsf.get_locked (), True)
self.assertEquals (subsf.get_locks (), (subsf,))
subsf.lock ()
self.assertEquals (sf.get_locked (), True)
self.assertEquals (sf.get_locks (), (subsf, subsf))
self.assertEquals (subsf.get_locked (), True)
self.assertEquals (subsf.get_locks (), (subsf, subsf))
def test_pxarray_ref (self):
sf = pygame.Surface ((5, 5))
ar = pygame.PixelArray (sf)
ar2 = pygame.PixelArray (sf)
self.assertEquals (sf.get_locked (), True)
self.assertEquals (sf.get_locks (), (ar, ar2))
del ar
self.assertEquals (sf.get_locked (), True)
self.assertEquals (sf.get_locks (), (ar2,))
ar = ar2[:]
self.assertEquals (sf.get_locked (), True)
self.assertEquals (sf.get_locks (), (ar2,))
del ar
self.assertEquals (sf.get_locked (), True)
self.assertEquals (len (sf.get_locks ()), 1)
def test_buffer (self):
sf = pygame.Surface ((5, 5))
buf = sf.get_buffer ()
self.assertEquals (sf.get_locked (), True)
self.assertEquals (sf.get_locks (), (buf,))
sf.unlock ()
self.assertEquals (sf.get_locked (), True)
self.assertEquals (sf.get_locks (), (buf,))
del buf
self.assertEquals (sf.get_locked (), False)
self.assertEquals (sf.get_locks (), ())
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/surfarray_test.py 0000644 0001750 0001750 00000065317 11201706427 020665 0 ustar vincent vincent if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils import test_not_implemented, unittest
else:
from test.test_utils import test_not_implemented, unittest
import pygame
from pygame.locals import *
arraytype = ""
try:
import pygame.surfarray
except ImportError:
pass
else:
arraytype = pygame.surfarray.get_arraytype()
if arraytype == 'numpy':
from numpy import \
uint8, uint16, uint32, uint64, zeros, float64, alltrue
elif arraytype == 'numeric':
from Numeric import \
UInt8 as uint8, UInt16 as uint16, UInt32 as uint32, zeros, \
Float64 as float64, alltrue
else:
print ("Unknown array type %s; tests skipped" %
pygame.surfarray.get_arraytype())
arraytype = ""
class SurfarrayModuleTest (unittest.TestCase):
pixels2d = {8: True, 16: True, 24: False, 32: True}
pixels3d = {8: False, 16: False, 24: True, 32: True}
array2d = {8: True, 16: True, 24: True, 32: True}
array3d = {8: False, 16: False, 24: True, 32: True}
test_palette = [(0, 0, 0, 255),
(10, 30, 60, 255),
(25, 75, 100, 255),
(100, 150, 200, 255),
(0, 100, 200, 255)]
surf_size = (10, 12)
test_points = [((0, 0), 1), ((4, 5), 1), ((9, 0), 2),
((5, 5), 2), ((0, 11), 3), ((4, 6), 3),
((9, 11), 4), ((5, 6), 4)]
def _make_surface(self, bitsize, srcalpha=False, palette=None):
if palette is None:
palette = self.test_palette
flags = 0
if srcalpha:
flags |= SRCALPHA
surf = pygame.Surface(self.surf_size, flags, bitsize)
if bitsize == 8:
surf.set_palette([c[:3] for c in palette])
return surf
def _fill_surface(self, surf, palette=None):
if palette is None:
palette = self.test_palette
surf.fill(palette[1], (0, 0, 5, 6))
surf.fill(palette[2], (5, 0, 5, 6))
surf.fill(palette[3], (0, 6, 5, 6))
surf.fill(palette[4], (5, 6, 5, 6))
def _make_src_surface(self, bitsize, srcalpha=False, palette=None):
surf = self._make_surface(bitsize, srcalpha, palette)
self._fill_surface(surf, palette)
return surf
def _assert_surface(self, surf, palette=None, msg=""):
if palette is None:
palette = self.test_palette
if surf.get_bitsize() == 16:
palette = [surf.unmap_rgb(surf.map_rgb(c)) for c in palette]
for posn, i in self.test_points:
self.failUnlessEqual(surf.get_at(posn), palette[i],
"%s != %s: flags: %i, bpp: %i, posn: %s%s" %
(surf.get_at(posn),
palette[i], surf.get_flags(),
surf.get_bitsize(), posn, msg))
def _make_array3d(self, dtype):
return zeros((self.surf_size[0], self.surf_size[1], 3), dtype)
def _fill_array2d(self, arr, surf):
palette = self.test_palette
arr[:5,:6] = surf.map_rgb(palette[1])
arr[5:,:6] = surf.map_rgb(palette[2])
arr[:5,6:] = surf.map_rgb(palette[3])
arr[5:,6:] = surf.map_rgb(palette[4])
def _fill_array3d(self, arr):
palette = self.test_palette
arr[:5,:6] = palette[1][:3]
arr[5:,:6] = palette[2][:3]
arr[:5,6:] = palette[3][:3]
arr[5:,6:] = palette[4][:3]
def _make_src_array3d(self, dtype):
arr = self._make_array3d(dtype)
self._fill_array3d(arr)
return arr
def _make_array2d(self, dtype):
return zeros(self.surf_size, dtype)
def setUp(self):
# Needed for 8 bits-per-pixel color palette surface tests.
pygame.init()
# Makes sure the same array package is used each time.
if arraytype:
pygame.surfarray.use_arraytype(arraytype)
def tearDown(self):
pygame.quit()
def test_array2d(self):
if not arraytype:
self.fail("no array package installed")
if arraytype == 'numeric':
# This is known to fail with Numeric (incompatible
# get_rgb and array element types).
return
sources = [self._make_src_surface(8),
self._make_src_surface(16),
self._make_src_surface(16, srcalpha=True),
self._make_src_surface(24),
self._make_src_surface(32),
self._make_src_surface(32, srcalpha=True)]
palette = self.test_palette
alpha_color = (0, 0, 0, 128)
for surf in sources:
arr = pygame.surfarray.array2d(surf)
map_rgb = surf.map_rgb
for (x, y), i in self.test_points:
self.failUnlessEqual(arr[x, y], map_rgb(palette[i]),
"%s != %s: flags: %i, bpp: %i, posn: %s" %
(arr[x, y],
map_rgb(palette[i]),
surf.get_flags(), surf.get_bitsize(),
(x, y)))
if surf.get_masks()[3]:
surf.fill(alpha_color)
arr = pygame.surfarray.array2d(surf)
self.failUnlessEqual(arr[0, 0], map_rgb(alpha_color),
"%s != %s: bpp: %i" %
(arr[0, 0],
map_rgb(alpha_color),
surf.get_bitsize()))
def test_array3d(self):
if not arraytype:
self.fail("no array package installed")
if arraytype == 'numeric':
# This is known to fail with Numeric (wrong color element
# values for 16 bit surfaces).
return
sources = [self._make_src_surface(16),
self._make_src_surface(16, srcalpha=True),
self._make_src_surface(24),
self._make_src_surface(32),
self._make_src_surface(32, srcalpha=True)]
palette = self.test_palette
for surf in sources:
arr = pygame.surfarray.array3d(surf)
map_rgb = surf.map_rgb
unmap_rgb = surf.unmap_rgb
def same_color(ac, sc):
sc = unmap_rgb(map_rgb(sc))
return (ac[0] == sc[0] and
ac[1] == sc[1] and
ac[2] == sc[2])
for (x, y), i in self.test_points:
self.failUnless(same_color(arr[x, y], palette[i]),
"%s != %s: flags: %i, bpp: %i, posn: %s" %
(tuple(arr[x, y]),
unmap_rgb(map_rgb(palette[i])),
surf.get_flags(), surf.get_bitsize(),
(x, y)))
def test_array_alpha(self):
if not arraytype:
self.fail("no array package installed")
if arraytype == 'numeric':
# This is known to fail with Numeric (differing values for
# get_rgb and array element for 16 bit surfaces).
return
palette = [(0, 0, 0, 0),
(10, 50, 100, 255),
(60, 120, 240, 130),
(64, 128, 255, 0),
(255, 128, 0, 65)]
targets = [self._make_src_surface(8, palette=palette),
self._make_src_surface(16, palette=palette),
self._make_src_surface(16, palette=palette, srcalpha=True),
self._make_src_surface(24, palette=palette),
self._make_src_surface(32, palette=palette),
self._make_src_surface(32, palette=palette, srcalpha=True)]
for surf in targets:
p = palette
if surf.get_bitsize() == 16:
p = [surf.unmap_rgb(surf.map_rgb(c)) for c in p]
arr = pygame.surfarray.array_alpha(surf)
if surf.get_masks()[3]:
for (x, y), i in self.test_points:
self.failUnlessEqual(arr[x, y], p[i][3],
("%i != %i, posn: (%i, %i), "
"bitsize: %i" %
(arr[x, y], p[i][3],
x, y,
surf.get_bitsize())))
else:
self.failUnless(alltrue(arr == 255))
# No per-pixel alpha when blanket alpha is None.
for surf in targets:
blacket_alpha = surf.get_alpha()
surf.set_alpha(None)
arr = pygame.surfarray.array_alpha(surf)
self.failUnless(alltrue(arr == 255),
"bitsize: %i, flags: %i" %
(surf.get_bitsize(), surf.get_flags()))
surf.set_alpha(blacket_alpha)
# Bug for per-pixel alpha surface when blanket alpha 0.
for surf in targets:
blanket_alpha = surf.get_alpha()
surf.set_alpha(0)
arr = pygame.surfarray.array_alpha(surf)
if surf.get_masks()[3]:
self.failIf(alltrue(arr == 255),
"bitsize: %i, flags: %i" %
(surf.get_bitsize(), surf.get_flags()))
else:
self.failUnless(alltrue(arr == 255),
"bitsize: %i, flags: %i" %
(surf.get_bitsize(), surf.get_flags()))
surf.set_alpha(blanket_alpha)
def test_array_colorkey(self):
if not arraytype:
self.fail("no array package installed")
palette = [(0, 0, 0, 0),
(10, 50, 100, 255),
(60, 120, 240, 130),
(64, 128, 255, 0),
(255, 128, 0, 65)]
targets = [self._make_src_surface(8, palette=palette),
self._make_src_surface(16, palette=palette),
self._make_src_surface(16, palette=palette, srcalpha=True),
self._make_src_surface(24, palette=palette),
self._make_src_surface(32, palette=palette),
self._make_src_surface(32, palette=palette, srcalpha=True)]
for surf in targets:
p = palette
if surf.get_bitsize() == 16:
p = [surf.unmap_rgb(surf.map_rgb(c)) for c in p]
surf.set_colorkey(None)
arr = pygame.surfarray.array_colorkey(surf)
self.failUnless(alltrue(arr == 255))
for i in range(1, len(palette)):
surf.set_colorkey(p[i])
alphas = [255] * len(p)
alphas[i] = 0
arr = pygame.surfarray.array_colorkey(surf)
for (x, y), j in self.test_points:
self.failUnlessEqual(arr[x, y], alphas[j],
("%i != %i, posn: (%i, %i), "
"bitsize: %i" %
(arr[x, y], alphas[j],
x, y,
surf.get_bitsize())))
def test_blit_array(self):
if not arraytype:
self.fail("no array package installed")
# bug 24 at http://pygame.motherhamster.org/bugzilla/
if 'numpy' in pygame.surfarray.get_arraytypes():
prev = pygame.surfarray.get_arraytype()
# This would raise exception:
# File "[...]\pygame\_numpysurfarray.py", line 381, in blit_array
# (array[:,:,1::3] >> losses[1] << shifts[1]) | \
# TypeError: unsupported operand type(s) for >>: 'float' and 'int'
pygame.surfarray.use_arraytype('numpy')
s = pygame.Surface((10,10), 0, 24)
a = pygame.surfarray.array3d(s)
pygame.surfarray.blit_array(s, a)
prev = pygame.surfarray.use_arraytype(prev)
# target surfaces
targets = [self._make_surface(8),
self._make_surface(16),
self._make_surface(16, srcalpha=True),
self._make_surface(24),
self._make_surface(32),
self._make_surface(32, srcalpha=True),
]
# source arrays
arrays3d = []
dtypes = [(8, uint8), (16, uint16), (32, uint32)]
try:
dtypes.append((64, uint64))
except NameError:
pass
arrays3d = [(self._make_src_array3d(dtype), None)
for __, dtype in dtypes]
for bitsize in [8, 16, 24, 32]:
palette = None
if bitsize == 16:
s = pygame.Surface((1,1), 0, 16)
palette = [s.unmap_rgb(s.map_rgb(c))
for c in self.test_palette]
if self.pixels3d[bitsize]:
surf = self._make_src_surface(bitsize)
arr = pygame.surfarray.pixels3d(surf)
arrays3d.append((arr, palette))
if self.array3d[bitsize]:
surf = self._make_src_surface(bitsize)
arr = pygame.surfarray.array3d(surf)
arrays3d.append((arr, palette))
for sz, dtype in dtypes:
arrays3d.append((arr.astype(dtype), palette))
# tests on arrays
def do_blit(surf, arr):
pygame.surfarray.blit_array(surf, arr)
for surf in targets:
bitsize = surf.get_bitsize()
for arr, palette in arrays3d:
surf.fill((0, 0, 0, 0))
if bitsize == 8:
self.failUnlessRaises(ValueError, do_blit, surf, arr)
else:
pygame.surfarray.blit_array(surf, arr)
self._assert_surface(surf, palette)
if self.pixels2d[bitsize]:
surf.fill((0, 0, 0, 0))
s = self._make_src_surface(bitsize, surf.get_flags() & SRCALPHA)
arr = pygame.surfarray.pixels2d(s)
pygame.surfarray.blit_array(surf, arr)
self._assert_surface(surf)
if self.array2d[bitsize]:
s = self._make_src_surface(bitsize, surf.get_flags() & SRCALPHA)
arr = pygame.surfarray.array2d(s)
for sz, dtype in dtypes:
surf.fill((0, 0, 0, 0))
if sz >= bitsize:
pygame.surfarray.blit_array(surf, arr.astype(dtype))
self._assert_surface(surf)
else:
self.failUnlessRaises(ValueError, do_blit,
surf, self._make_array2d(dtype))
# Check alpha for 2D arrays
surf = self._make_surface(16, srcalpha=True)
arr = zeros(surf.get_size(), uint16)
arr[...] = surf.map_rgb((0, 128, 255, 64))
color = surf.unmap_rgb(arr[0, 0])
pygame.surfarray.blit_array(surf, arr)
self.failUnlessEqual(surf.get_at((5, 5)), color)
surf = self._make_surface(32, srcalpha=True)
arr = zeros(surf.get_size(), uint32)
color = (0, 111, 255, 63)
arr[...] = surf.map_rgb(color)
pygame.surfarray.blit_array(surf, arr)
self.failUnlessEqual(surf.get_at((5, 5)), color)
# Check shifts
arr3d = self._make_src_array3d(uint8)
shift_tests = [(16,
[12, 0, 8, 4],
[0xf000, 0xf, 0xf00, 0xf0]),
(24,
[16, 0, 8, 0],
[0xff0000, 0xff, 0xff00, 0]),
(32,
[0, 16, 24, 8],
[0xff, 0xff0000, 0xff000000, 0xff00])]
for bitsize, shifts, masks in shift_tests:
surf = self._make_surface(bitsize, srcalpha=(shifts[3] != 0))
palette = None
if bitsize == 16:
palette = [surf.unmap_rgb(surf.map_rgb(c))
for c in self.test_palette]
surf.set_shifts(shifts)
surf.set_masks(masks)
pygame.surfarray.blit_array(surf, arr3d)
self._assert_surface(surf, palette)
# Invalid arrays
surf = pygame.Surface((1,1), 0, 32)
t = 'abcd'
self.failUnlessRaises(ValueError, do_blit, surf, t)
surf_size = self.surf_size
surf = pygame.Surface(surf_size, 0, 32)
arr = zeros([surf_size[0], surf_size[1] + 1, 3], uint32)
self.failUnlessRaises(ValueError, do_blit, surf, arr)
arr = zeros([surf_size[0] + 1, surf_size[1], 3], uint32)
self.failUnlessRaises(ValueError, do_blit, surf, arr)
surf = pygame.Surface((1, 4), 0, 32)
arr = zeros((4,), uint32)
self.failUnlessRaises(ValueError, do_blit, surf, arr)
arr.shape = (1, 1, 1, 4)
self.failUnlessRaises(ValueError, do_blit, surf, arr)
arr = zeros((10, 10), float64)
surf = pygame.Surface((10, 10), 0, 32)
self.failUnlessRaises(ValueError, do_blit, surf, arr)
def test_get_arraytype(self):
if not arraytype:
self.fail("no array package installed")
self.failUnless((pygame.surfarray.get_arraytype() in
['numpy', 'numeric']),
("unknown array type %s" %
pygame.surfarray.get_arraytype()))
def test_get_arraytypes(self):
if not arraytype:
self.fail("no array package installed")
arraytypes = pygame.surfarray.get_arraytypes()
try:
import numpy
except ImportError:
self.failIf('numpy' in arraytypes)
else:
self.failUnless('numpy' in arraytypes)
try:
import Numeric
except ImportError:
self.failIf('numeric' in arraytypes)
else:
self.failUnless('numeric' in arraytypes)
for atype in arraytypes:
self.failUnless(atype in ['numpy', 'numeric'],
"unknown array type %s" % atype)
def test_make_surface(self):
if not arraytype:
self.fail("no array package installed")
# How does one properly test this with 2d arrays. It makes no sense
# since the pixel format is not entirely dependent on element size.
# Just make sure the surface pixel size is at least as large as the
# array element size I guess.
#
for bitsize, dtype in [(8, uint8), (16, uint16), (24, uint32)]:
## Even this simple assertion fails for 2d arrays. Where's the problem?
## surf = pygame.surfarray.make_surface(self._make_array2d(dtype))
## self.failUnless(surf.get_bitsize() >= bitsize,
## "not %i >= %i)" % (surf.get_bitsize(), bitsize))
##
surf = pygame.surfarray.make_surface(self._make_src_array3d(dtype))
self._assert_surface(surf)
def test_map_array(self):
if not arraytype:
self.fail("no array package installed")
if not arraytype == 'numpy':
# This test would probably fail for Numeric
# (incompatible get_rgb and array element types
# and zero alpha for SRCALPHA surfaces).
return
arr3d = self._make_src_array3d(uint8)
targets = [self._make_surface(16),
self._make_surface(16, srcalpha=True),
self._make_surface(24),
self._make_surface(32),
self._make_surface(32, srcalpha=True)]
palette = self.test_palette
for surf in targets:
arr2d = pygame.surfarray.map_array(surf, arr3d)
for (x, y), i in self.test_points:
self.failUnlessEqual(arr2d[x, y], surf.map_rgb(palette[i]),
"%i != %i, bitsize: %i, flags: %i" %
(arr2d[x, y], surf.map_rgb(palette[i]),
surf.get_bitsize(), surf.get_flags()))
# Exception checks
def do_map_array(surf, arr):
pygame.surfarray.map_array(surf, arr)
self.failUnlessRaises(ValueError, do_map_array,
self._make_surface(32),
self._make_array2d(uint8))
def test_pixels2d(self):
if not arraytype:
self.fail("no array package installed")
if arraytype == 'numeric':
# This is known to fail with Numeric
# (incompatible get_rgb and array element types).
return
sources = [self._make_surface(8),
self._make_surface(16, srcalpha=True),
self._make_surface(32, srcalpha=True)]
for surf in sources:
self.failIf(surf.get_locked())
arr = pygame.surfarray.pixels2d(surf)
self.failUnless(surf.get_locked())
# Numpy uses the surface's buffer.
if arraytype == "numeric":
self.failUnlessEqual(surf.get_locks(), (ar,))
self._fill_array2d(arr, surf)
surf.unlock()
self.failUnless(surf.get_locked())
del arr
self.failIf(surf.get_locked())
self.failUnlessEqual(surf.get_locks(), ())
self._assert_surface(surf)
# Error checks
def do_pixels2d(surf):
pygame.surfarray.pixels2d(surf)
self.failUnlessRaises(ValueError,
do_pixels2d,
self._make_surface(24))
def test_pixels3d(self):
if not arraytype:
self.fail("no array package installed")
sources = [self._make_surface(24),
self._make_surface(32)]
for surf in sources:
self.failIf(surf.get_locked())
arr = pygame.surfarray.pixels3d(surf)
self.failUnless(surf.get_locked())
# Numpy uses the surface's buffer.
if arraytype == "numeric":
self.failUnlessEqual(surf.get_locks(), (arr,))
self._fill_array3d(arr)
surf.unlock()
self.failUnless(surf.get_locked())
del arr
self.failIf(surf.get_locked())
self.failUnlessEqual(surf.get_locks(), ())
self._assert_surface(surf)
# Alpha check
color = (1, 2, 3, 0)
surf = self._make_surface(32, srcalpha=True)
arr = pygame.surfarray.pixels3d(surf)
arr[0,0] = color[:3]
self.failUnlessEqual(surf.get_at((0, 0)), color)
# Error checks
def do_pixels3d(surf):
pygame.surfarray.pixels3d(surf)
self.failUnlessRaises(ValueError,
do_pixels3d,
self._make_surface(8))
self.failUnlessRaises(ValueError,
do_pixels3d,
self._make_surface(16))
def test_pixels_alpha(self):
if not arraytype:
self.fail("no array package installed")
palette = [(0, 0, 0, 0),
(127, 127, 127, 0),
(127, 127, 127, 85),
(127, 127, 127, 170),
(127, 127, 127, 255)]
alphas = [0, 45, 86, 99, 180]
surf = self._make_src_surface(32, srcalpha=True, palette=palette)
self.failIf(surf.get_locked())
arr = pygame.surfarray.pixels_alpha(surf)
self.failUnless(surf.get_locked())
# Numpy uses the surface's buffer.
if arraytype == 'numeric':
self.failUnlessEqual(surf.get_locks(), (arr,))
surf.unlock()
self.failUnless(surf.get_locked())
for (x, y), i in self.test_points:
self.failUnlessEqual(arr[x, y], palette[i][3])
for (x, y), i in self.test_points:
alpha = alphas[i]
arr[x, y] = alpha
color = (127, 127, 127, alpha)
self.failUnlessEqual(surf.get_at((x, y)), color,
"posn: (%i, %i)" % (x, y))
del arr
self.failIf(surf.get_locked())
self.failUnlessEqual(surf.get_locks(), ())
# Check exceptions.
def do_pixels_alpha(surf):
pygame.surfarray.pixels_alpha(surf)
targets = [(8, False),
(16, False),
(16, True),
(24, False),
(32, False)]
for bitsize, srcalpha in targets:
self.failUnlessRaises(ValueError, do_pixels_alpha,
self._make_surface(bitsize, srcalpha))
def test_use_arraytype(self):
if not arraytype:
self.fail("no array package installed")
def do_use_arraytype(atype):
pygame.surfarray.use_arraytype(atype)
try:
import numpy
except ImportError:
self.failUnlessRaises(ValueError, do_use_arraytype, 'numpy')
self.failIfEqual(pygame.surfarray.get_arraytype(), 'numpy')
else:
pygame.surfarray.use_arraytype('numpy')
self.failUnlessEqual(pygame.surfarray.get_arraytype(), 'numpy')
try:
import Numeric
except ImportError:
self.failUnlessRaises(ValueError, do_use_arraytype, 'numeric')
self.failIfEqual(pygame.surfarray.get_arraytype(), 'numeric')
else:
pygame.surfarray.use_arraytype('numeric')
self.failUnlessEqual(pygame.surfarray.get_arraytype(), 'numeric')
self.failUnlessRaises(ValueError, do_use_arraytype, 'not an option')
def test_surf_lock (self):
if not arraytype:
self.fail("no array package installed")
sf = pygame.Surface ((5, 5), 0, 32)
for atype in pygame.surfarray.get_arraytypes ():
pygame.surfarray.use_arraytype (atype)
ar = pygame.surfarray.pixels2d (sf)
self.assertEquals (sf.get_locked (), True)
# Numpy uses the Surface's buffer.
if atype == "numeric":
self.assertEquals (sf.get_locks (), (ar,))
sf.unlock ()
self.assertEquals (sf.get_locked (), True)
del ar
self.assertEquals (sf.get_locked (), False)
self.assertEquals (sf.get_locks (), ())
#print ("test_surf_lock - end")
if __name__ == '__main__':
if not arraytype:
print ("No array package is installed. Cannot run unit tests.")
else:
unittest.main()
pygame-1.9.1release/test/surfarray_tags.py 0000644 0001750 0001750 00000000624 11207055754 020640 0 ustar vincent vincent __tags__ = ['array']
exclude = False
try:
import numpy
except ImportError:
try:
import Numeric
import pygame._numericsurfarray
import pygame._arraysurfarray
except ImportError:
exclude = True
else:
try:
import pygame._arraysurfarray
except ImportError:
exclude = True
if exclude:
__tags__.extend(('ignore', 'subprocess_ignore'))
pygame-1.9.1release/test/surface_test.py 0000644 0001750 0001750 00000165576 11224767753 020325 0 ustar vincent vincent if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests import test_utils
from pygame.tests.test_utils import test_not_implemented, unittest
else:
from test import test_utils
from test.test_utils import test_not_implemented, unittest
import pygame
from pygame.locals import *
from pygame.compat import xrange_
def intify(i):
"""If i is a long, cast to an int while preserving the bits"""
if 0x80000000 & i:
return int((0xFFFFFFFF & i))
return i
def longify(i):
"""If i is an int, cast to a long while preserving the bits"""
if i < 0:
return 0xFFFFFFFF & i
return long(i)
class SurfaceTypeTest(unittest.TestCase):
def test_set_clip( self ):
""" see if surface.set_clip(None) works correctly.
"""
s = pygame.Surface((800, 600))
r = pygame.Rect(10, 10, 10, 10)
s.set_clip(r)
r.move_ip(10, 0)
s.set_clip(None)
res = s.get_clip()
# this was garbled before.
self.assertEqual(res[0], 0)
self.assertEqual(res[2], 800)
def test_print(self):
surf = pygame.Surface((70,70), 0, 32)
self.assertEqual(repr(surf), '')
def test_keyword_arguments(self):
surf = pygame.Surface((70,70), flags=SRCALPHA, depth=32)
self.assertEqual(surf.get_flags() & SRCALPHA, SRCALPHA)
self.assertEqual(surf.get_bitsize(), 32)
# sanity check to make sure the check below is valid
surf_16 = pygame.Surface((70,70), 0, 16)
self.assertEqual(surf_16.get_bytesize(), 2)
# try again with an argument list
surf_16 = pygame.Surface((70,70), depth=16)
self.assertEqual(surf_16.get_bytesize(), 2)
def test_set_at(self):
#24bit surfaces
s = pygame.Surface( (100, 100), 0, 24)
s.fill((0,0,0))
# set it with a tuple.
s.set_at((0,0), (10,10,10, 255))
r = s.get_at((0,0))
self.failUnless(isinstance(r, pygame.Color))
self.assertEqual(r, (10,10,10, 255))
# try setting a color with a single integer.
s.fill((0,0,0,255))
s.set_at ((10, 1), 0x0000FF)
r = s.get_at((10,1))
self.assertEqual(r, (0,0,255, 255))
def test_SRCALPHA(self):
# has the flag been passed in ok?
surf = pygame.Surface((70,70), SRCALPHA, 32)
self.assertEqual(surf.get_flags() & SRCALPHA, SRCALPHA)
#24bit surfaces can not have SRCALPHA.
self.assertRaises(ValueError, pygame.Surface, (100, 100), pygame.SRCALPHA, 24)
# if we have a 32 bit surface, the SRCALPHA should have worked too.
surf2 = pygame.Surface((70,70), SRCALPHA)
if surf2.get_bitsize() == 32:
self.assertEqual(surf2.get_flags() & SRCALPHA, SRCALPHA)
def test_masks(self):
def make_surf(bpp, flags, masks):
pygame.Surface((10, 10), flags, bpp, masks)
# With some masks SDL_CreateRGBSurface does not work properly.
masks = (0xFF000000, 0xFF0000, 0xFF00, 0)
self.assertEqual(make_surf(32, 0, masks), None)
# For 24 and 32 bit surfaces Pygame assumes no losses.
masks = (0x7F0000, 0xFF00, 0xFF, 0)
self.failUnlessRaises(ValueError, make_surf, 24, 0, masks)
self.failUnlessRaises(ValueError, make_surf, 32, 0, masks)
# What contiguous bits in a mask.
masks = (0x6F0000, 0xFF00, 0xFF, 0)
self.failUnlessRaises(ValueError, make_surf, 32, 0, masks)
def test_get_buffer (self):
surf = pygame.Surface ((70, 70), 0, 32)
buf = surf.get_buffer ()
# 70*70*4 bytes = 19600
self.assertEqual (repr (buf), "")
def test_get_bounding_rect (self):
surf = pygame.Surface ((70, 70), SRCALPHA, 32)
surf.fill((0,0,0,0))
bound_rect = surf.get_bounding_rect()
self.assertEqual(bound_rect.width, 0)
self.assertEqual(bound_rect.height, 0)
surf.set_at((30,30),(255,255,255,1))
bound_rect = surf.get_bounding_rect()
self.assertEqual(bound_rect.left, 30)
self.assertEqual(bound_rect.top, 30)
self.assertEqual(bound_rect.width, 1)
self.assertEqual(bound_rect.height, 1)
surf.set_at((29,29),(255,255,255,1))
bound_rect = surf.get_bounding_rect()
self.assertEqual(bound_rect.left, 29)
self.assertEqual(bound_rect.top, 29)
self.assertEqual(bound_rect.width, 2)
self.assertEqual(bound_rect.height, 2)
surf = pygame.Surface ((70, 70), 0, 24)
surf.fill((0,0,0))
bound_rect = surf.get_bounding_rect()
self.assertEqual(bound_rect.width, surf.get_width())
self.assertEqual(bound_rect.height, surf.get_height())
surf.set_colorkey((0,0,0))
bound_rect = surf.get_bounding_rect()
self.assertEqual(bound_rect.width, 0)
self.assertEqual(bound_rect.height, 0)
surf.set_at((30,30),(255,255,255))
bound_rect = surf.get_bounding_rect()
self.assertEqual(bound_rect.left, 30)
self.assertEqual(bound_rect.top, 30)
self.assertEqual(bound_rect.width, 1)
self.assertEqual(bound_rect.height, 1)
surf.set_at((60,60),(255,255,255))
bound_rect = surf.get_bounding_rect()
self.assertEqual(bound_rect.left, 30)
self.assertEqual(bound_rect.top, 30)
self.assertEqual(bound_rect.width, 31)
self.assertEqual(bound_rect.height, 31)
def test_copy(self):
# __doc__ (as of 2008-06-25) for pygame.surface.Surface.copy:
# Surface.copy(): return Surface
# create a new copy of a Surface
color = (25, 25, 25, 25)
s1 = pygame.Surface((32,32), pygame.SRCALPHA, 32)
s1.fill(color)
s2 = s1.copy()
s1rect = s1.get_rect()
s2rect = s2.get_rect()
self.assert_(s1rect.size == s2rect.size)
self.assert_(s2.get_at((10,10)) == color)
def test_fill(self):
# __doc__ (as of 2008-06-25) for pygame.surface.Surface.fill:
# Surface.fill(color, rect=None, special_flags=0): return Rect
# fill Surface with a solid color
color = (25, 25, 25, 25)
fill_rect = pygame.Rect(0, 0, 16, 16)
s1 = pygame.Surface((32,32), pygame.SRCALPHA, 32)
s1.fill(color, fill_rect)
for pt in test_utils.rect_area_pts(fill_rect):
self.assert_(s1.get_at(pt) == color )
for pt in test_utils.rect_outer_bounds(fill_rect):
self.assert_(s1.get_at(pt) != color )
def test_fill_keyword_args(self):
color = (1, 2, 3, 255)
area = (1, 1, 2, 2)
s1 = pygame.Surface((4, 4), 0, 32)
s1.fill(special_flags=pygame.BLEND_ADD, color=color, rect=area)
self.assert_(s1.get_at((0, 0)) == (0, 0, 0, 255))
self.assert_(s1.get_at((1, 1)) == color)
########################################################################
def test_get_alpha(self):
# __doc__ (as of 2008-06-25) for pygame.surface.Surface.get_alpha:
# Surface.get_alpha(): return int_value or None
# get the current Surface transparency value
s1 = pygame.Surface((32,32), pygame.SRCALPHA, 32)
self.assert_(s1.get_alpha() == 255)
for alpha in (0, 32, 127, 255):
s1.set_alpha(alpha)
for t in range(4): s1.set_alpha(s1.get_alpha())
self.assert_(s1.get_alpha() == alpha)
########################################################################
def test_get_bytesize(self):
# __doc__ (as of 2008-06-25) for pygame.surface.Surface.get_bytesize:
# Surface.get_bytesize(): return int
# get the bytes used per Surface pixel
s1 = pygame.Surface((32,32), pygame.SRCALPHA, 32)
self.assert_(s1.get_bytesize() == 4)
self.assert_(s1.get_bitsize() == 32)
########################################################################
def test_get_flags(self):
# __doc__ (as of 2008-06-25) for pygame.surface.Surface.get_flags:
# Surface.get_flags(): return int
# get the additional flags used for the Surface
s1 = pygame.Surface((32,32), pygame.SRCALPHA, 32)
self.assert_(s1.get_flags() == pygame.SRCALPHA)
########################################################################
def test_get_parent(self):
# __doc__ (as of 2008-06-25) for pygame.surface.Surface.get_parent:
# Surface.get_parent(): return Surface
# find the parent of a subsurface
parent = pygame.Surface((16, 16))
child = parent.subsurface((0,0,5,5))
self.assert_(child.get_parent() is parent)
########################################################################
def test_get_rect(self):
# __doc__ (as of 2008-06-25) for pygame.surface.Surface.get_rect:
# Surface.get_rect(**kwargs): return Rect
# get the rectangular area of the Surface
surf = pygame.Surface((16, 16))
rect = surf.get_rect()
self.assert_(rect.size == (16, 16))
########################################################################
def test_get_width__size_and_height(self):
# __doc__ (as of 2008-06-25) for pygame.surface.Surface.get_width:
# Surface.get_width(): return width
# get the width of the Surface
for w in xrange_(0, 255, 32):
for h in xrange_(0, 127, 15):
s = pygame.Surface((w, h))
self.assertEquals(s.get_width(), w)
self.assertEquals(s.get_height(), h)
self.assertEquals(s.get_size(), (w, h))
def test_set_colorkey(self):
# __doc__ (as of 2008-06-25) for pygame.surface.Surface.set_colorkey:
# Surface.set_colorkey(Color, flags=0): return None
# Surface.set_colorkey(None): return None
# Set the transparent colorkey
s = pygame.Surface((16,16), pygame.SRCALPHA, 32)
colorkeys = ((20,189,20, 255),(128,50,50,255), (23, 21, 255,255))
for colorkey in colorkeys:
s.set_colorkey(colorkey)
for t in range(4): s.set_colorkey(s.get_colorkey())
self.assertEquals(s.get_colorkey(), colorkey)
def test_set_masks(self):
s = pygame.Surface((32,32))
r,g,b,a = s.get_masks()
s.set_masks((b,g,r,a))
r2,g2,b2,a2 = s.get_masks()
self.assertEqual((r,g,b,a), (b2,g2,r2,a2))
def test_set_shifts(self):
s = pygame.Surface((32,32))
r,g,b,a = s.get_shifts()
s.set_shifts((b,g,r,a))
r2,g2,b2,a2 = s.get_shifts()
self.assertEqual((r,g,b,a), (b2,g2,r2,a2))
def test_blit_keyword_args(self):
color = (1, 2, 3, 255)
s1 = pygame.Surface((4, 4), 0, 32)
s2 = pygame.Surface((2, 2), 0, 32)
s2.fill((1, 2, 3))
s1.blit(special_flags=BLEND_ADD, source=s2,
dest=(1, 1), area=s2.get_rect())
self.assertEqual(s1.get_at((0, 0)), (0, 0, 0, 255))
self.assertEqual(s1.get_at((1, 1)), color)
def todo_test_blit(self):
# __doc__ (as of 2008-08-02) for pygame.surface.Surface.blit:
# Surface.blit(source, dest, area=None, special_flags = 0): return Rect
# draw one image onto another
#
# Draws a source Surface onto this Surface. The draw can be positioned
# with the dest argument. Dest can either be pair of coordinates
# representing the upper left corner of the source. A Rect can also be
# passed as the destination and the topleft corner of the rectangle
# will be used as the position for the blit. The size of the
# destination rectangle does not effect the blit.
#
# An optional area rectangle can be passed as well. This represents a
# smaller portion of the source Surface to draw.
#
# An optional special flags is for passing in new in 1.8.0: BLEND_ADD,
# BLEND_SUB, BLEND_MULT, BLEND_MIN, BLEND_MAX new in 1.8.1:
# BLEND_RGBA_ADD, BLEND_RGBA_SUB, BLEND_RGBA_MULT, BLEND_RGBA_MIN,
# BLEND_RGBA_MAX BLEND_RGB_ADD, BLEND_RGB_SUB, BLEND_RGB_MULT,
# BLEND_RGB_MIN, BLEND_RGB_MAX With other special blitting flags
# perhaps added in the future.
#
# The return rectangle is the area of the affected pixels, excluding
# any pixels outside the destination Surface, or outside the clipping
# area.
#
# Pixel alphas will be ignored when blitting to an 8 bit Surface.
# special_flags new in pygame 1.8.
self.fail()
def test_blit__SRCALPHA_opaque_source(self):
src = pygame.Surface( (256,256), SRCALPHA ,32)
dst = src.copy()
for i, j in test_utils.rect_area_pts(src.get_rect()):
dst.set_at( (i,j), (i,0,0,j) )
src.set_at( (i,j), (0,i,0,255) )
dst.blit(src, (0,0))
for pt in test_utils.rect_area_pts(src.get_rect()):
self.assertEquals ( dst.get_at(pt)[1], src.get_at(pt)[1] )
def todo_test_blit__blit_to_self(self): #TODO
src = pygame.Surface( (256,256), SRCALPHA, 32)
rect = src.get_rect()
for pt, color in test_utils.gradient(rect.width, rect.height):
src.set_at(pt, color)
src.blit(src, (0, 0))
def todo_test_blit__SRCALPHA_to_SRCALPHA_non_zero(self): #TODO
# " There is no unit test for blitting a SRCALPHA source with non-zero
# alpha to a SRCALPHA destination with non-zero alpha " LL
w,h = size = 32,32
s = pygame.Surface(size, pygame.SRCALPHA, 32)
s2 = s.copy()
s.fill((32,32,32,111))
s2.fill((32,32,32,31))
s.blit(s2, (0,0))
# TODO:
# what is the correct behaviour ?? should it blend? what algorithm?
self.assertEquals(s.get_at((0,0)), (32,32,32,31))
def todo_test_convert(self):
# __doc__ (as of 2008-08-02) for pygame.surface.Surface.convert:
# Surface.convert(Surface): return Surface
# Surface.convert(depth, flags=0): return Surface
# Surface.convert(masks, flags=0): return Surface
# Surface.convert(): return Surface
# change the pixel format of an image
#
# Creates a new copy of the Surface with the pixel format changed. The
# new pixel format can be determined from another existing Surface.
# Otherwise depth, flags, and masks arguments can be used, similar to
# the pygame.Surface() call.
#
# If no arguments are passed the new Surface will have the same pixel
# format as the display Surface. This is always the fastest format for
# blitting. It is a good idea to convert all Surfaces before they are
# blitted many times.
#
# The converted Surface will have no pixel alphas. They will be
# stripped if the original had them. See Surface.convert_alpha() for
# preserving or creating per-pixel alphas.
#
self.fail()
def todo_test_convert_alpha(self):
# __doc__ (as of 2008-08-02) for pygame.surface.Surface.convert_alpha:
# Surface.convert_alpha(Surface): return Surface
# Surface.convert_alpha(): return Surface
# change the pixel format of an image including per pixel alphas
#
# Creates a new copy of the surface with the desired pixel format. The
# new surface will be in a format suited for quick blitting to the
# given format with per pixel alpha. If no surface is given, the new
# surface will be optimized for blitting to the current display.
#
# Unlike the Surface.convert() method, the pixel format for the new
# image will not be exactly the same as the requested source, but it
# will be optimized for fast alpha blitting to the destination.
#
self.fail()
def todo_test_get_abs_offset(self):
# __doc__ (as of 2008-08-02) for pygame.surface.Surface.get_abs_offset:
# Surface.get_abs_offset(): return (x, y)
# find the absolute position of a child subsurface inside its top level parent
#
# Get the offset position of a child subsurface inside of its top
# level parent Surface. If the Surface is not a subsurface this will
# return (0, 0).
#
self.fail()
def todo_test_get_abs_parent(self):
# __doc__ (as of 2008-08-02) for pygame.surface.Surface.get_abs_parent:
# Surface.get_abs_parent(): return Surface
# find the top level parent of a subsurface
#
# Returns the parent Surface of a subsurface. If this is not a
# subsurface then this surface will be returned.
#
self.fail()
def todo_test_get_at(self):
surf = pygame.Surface((2, 2), 0, 24)
c00 = pygame.Color((1, 2, 3))
c01 = pygame.Color((5, 10, 15))
c10 = pygame.Color((100, 50, 0))
c11 = pygame.Color((4, 5, 6))
surf.set_at((0, 0), c00)
surf.set_at((0, 1), c01)
surf.set_at((1, 0), c10)
surf.set_at((1, 1), c11)
c = surf.get_at((0, 0))
self.failUnless(isinstance(c, pygame.Color))
self.failUnlessEqual(c, c00)
self.failUnlessEqual(surf.get_at((0, 1)), c01)
self.failUnlessEqual(surf.get_at((1, 0)), c10)
self.failUnlessEqual(surf.get_at((1, 1)), c11)
for p in [(-1, 0), (0, -1), (2, 0), (0, 2)]:
self.failUnlessRaises(IndexError, surf.get_at, p, "%s" % (p,))
def todo_test_get_bitsize(self):
# __doc__ (as of 2008-08-02) for pygame.surface.Surface.get_bitsize:
# Surface.get_bitsize(): return int
# get the bit depth of the Surface pixel format
#
# Returns the number of bits used to represent each pixel. This value
# may not exactly fill the number of bytes used per pixel. For example
# a 15 bit Surface still requires a full 2 bytes.
#
self.fail()
def todo_test_get_clip(self):
# __doc__ (as of 2008-08-02) for pygame.surface.Surface.get_clip:
# Surface.get_clip(): return Rect
# get the current clipping area of the Surface
#
# Return a rectangle of the current clipping area. The Surface will
# always return a valid rectangle that will never be outside the
# bounds of the image. If the Surface has had None set for the
# clipping area, the Surface will return a rectangle with the full
# area of the Surface.
#
self.fail()
def todo_test_get_colorkey(self):
surf = pygame.surface((2, 2), 0, 24)
self.failUnless(surf.get_colorykey() is None)
colorkey = pygame.Color(20, 40, 60)
surf.set_colorkey(colorkey)
ck = surf.get_colorkey()
self.failUnless(isinstance(ck, pygame.Color))
self.failUnlessEqual(ck, colorkey)
def todo_test_get_height(self):
# __doc__ (as of 2008-08-02) for pygame.surface.Surface.get_height:
# Surface.get_height(): return height
# get the height of the Surface
#
# Return the height of the Surface in pixels.
self.fail()
def todo_test_get_locked(self):
# __doc__ (as of 2008-08-02) for pygame.surface.Surface.get_locked:
# Surface.get_locked(): return bool
# test if the Surface is current locked
#
# Returns True when the Surface is locked. It doesn't matter how many
# times the Surface is locked.
#
self.fail()
def todo_test_get_locks(self):
# __doc__ (as of 2008-08-02) for pygame.surface.Surface.get_locks:
# Surface.get_locks(): return tuple
# Gets the locks for the Surface
#
# Returns the currently existing locks for the Surface.
self.fail()
def todo_test_get_losses(self):
# __doc__ (as of 2008-08-02) for pygame.surface.Surface.get_losses:
# Surface.get_losses(): return (R, G, B, A)
# the significant bits used to convert between a color and a mapped integer
#
# Return the least significant number of bits stripped from each color
# in a mapped integer.
#
# This value is not needed for normal Pygame usage.
self.fail()
def todo_test_get_masks(self):
# __doc__ (as of 2008-08-02) for pygame.surface.Surface.get_masks:
# Surface.get_masks(): return (R, G, B, A)
# the bitmasks needed to convert between a color and a mapped integer
#
# Returns the bitmasks used to isolate each color in a mapped integer.
# This value is not needed for normal Pygame usage.
self.fail()
def todo_test_get_offset(self):
# __doc__ (as of 2008-08-02) for pygame.surface.Surface.get_offset:
# Surface.get_offset(): return (x, y)
# find the position of a child subsurface inside a parent
#
# Get the offset position of a child subsurface inside of a parent. If
# the Surface is not a subsurface this will return (0, 0).
#
self.fail()
def test_get_palette(self):
pygame.init()
try:
palette = [Color(i, i, i) for i in range(256)]
pygame.display.set_mode((100, 50))
surf = pygame.Surface((2, 2), 0, 8)
surf.set_palette(palette)
palette2 = surf.get_palette()
r,g,b = palette2[0]
self.failUnlessEqual(len(palette2), len(palette))
for c2, c in zip(palette2, palette):
self.failUnlessEqual(c2, c)
for c in palette2:
self.failUnless(isinstance(c, pygame.Color))
finally:
pygame.quit()
def test_get_palette_at(self):
# See also test_get_palette
pygame.init()
try:
pygame.display.set_mode((100, 50))
surf = pygame.Surface((2, 2), 0, 8)
color = pygame.Color(1, 2, 3, 255)
surf.set_palette_at(0, color)
color2 = surf.get_palette_at(0)
self.failUnless(isinstance(color2, pygame.Color))
self.failUnlessEqual(color2, color)
self.failUnlessRaises(IndexError, surf.get_palette_at, -1)
self.failUnlessRaises(IndexError, surf.get_palette_at, 256)
finally:
pygame.quit()
def todo_test_get_pitch(self):
# __doc__ (as of 2008-08-02) for pygame.surface.Surface.get_pitch:
# Surface.get_pitch(): return int
# get the number of bytes used per Surface row
#
# Return the number of bytes separating each row in the Surface.
# Surfaces in video memory are not always linearly packed. Subsurfaces
# will also have a larger pitch than their real width.
#
# This value is not needed for normal Pygame usage.
self.fail()
def todo_test_get_shifts(self):
# __doc__ (as of 2008-08-02) for pygame.surface.Surface.get_shifts:
# Surface.get_shifts(): return (R, G, B, A)
# the bit shifts needed to convert between a color and a mapped integer
#
# Returns the pixel shifts need to convert between each color and a
# mapped integer.
#
# This value is not needed for normal Pygame usage.
self.fail()
def todo_test_get_size(self):
# __doc__ (as of 2008-08-02) for pygame.surface.Surface.get_size:
# Surface.get_size(): return (width, height)
# get the dimensions of the Surface
#
# Return the width and height of the Surface in pixels.
self.fail()
def todo_test_lock(self):
# __doc__ (as of 2008-08-02) for pygame.surface.Surface.lock:
# Surface.lock(): return None
# lock the Surface memory for pixel access
#
# Lock the pixel data of a Surface for access. On accelerated
# Surfaces, the pixel data may be stored in volatile video memory or
# nonlinear compressed forms. When a Surface is locked the pixel
# memory becomes available to access by regular software. Code that
# reads or writes pixel values will need the Surface to be locked.
#
# Surfaces should not remain locked for more than necessary. A locked
# Surface can often not be displayed or managed by Pygame.
#
# Not all Surfaces require locking. The Surface.mustlock() method can
# determine if it is actually required. There is no performance
# penalty for locking and unlocking a Surface that does not need it.
#
# All pygame functions will automatically lock and unlock the Surface
# data as needed. If a section of code is going to make calls that
# will repeatedly lock and unlock the Surface many times, it can be
# helpful to wrap the block inside a lock and unlock pair.
#
# It is safe to nest locking and unlocking calls. The surface will
# only be unlocked after the final lock is released.
#
self.fail()
def test_map_rgb(self):
color = Color(0, 128, 255, 64)
surf = pygame.Surface((5, 5), SRCALPHA, 32)
c = surf.map_rgb(color)
self.failUnlessEqual(surf.unmap_rgb(c), color)
self.failUnlessEqual(surf.get_at((0, 0)), (0, 0, 0, 0))
surf.fill(c)
self.failUnlessEqual(surf.get_at((0, 0)), color)
surf.fill((0, 0, 0, 0))
self.failUnlessEqual(surf.get_at((0, 0)), (0, 0, 0, 0))
surf.set_at((0, 0), c)
self.failUnlessEqual(surf.get_at((0, 0)), color)
def todo_test_mustlock(self):
# __doc__ (as of 2008-08-02) for pygame.surface.Surface.mustlock:
# Surface.mustlock(): return bool
# test if the Surface requires locking
#
# Returns True if the Surface is required to be locked to access pixel
# data. Usually pure software Surfaces do not require locking. This
# method is rarely needed, since it is safe and quickest to just lock
# all Surfaces as needed.
#
# All pygame functions will automatically lock and unlock the Surface
# data as needed. If a section of code is going to make calls that
# will repeatedly lock and unlock the Surface many times, it can be
# helpful to wrap the block inside a lock and unlock pair.
#
self.fail()
def todo_test_set_alpha(self):
# __doc__ (as of 2008-08-02) for pygame.surface.Surface.set_alpha:
# Surface.set_alpha(value, flags=0): return None
# Surface.set_alpha(None): return None
# set the alpha value for the full Surface image
#
# Set the current alpha value fo r the Surface. When blitting this
# Surface onto a destination, the pixels will be drawn slightly
# transparent. The alpha value is an integer from 0 to 255, 0 is fully
# transparent and 255 is fully opaque. If None is passed for the alpha
# value, then the Surface alpha will be disabled.
#
# This value is different than the per pixel Surface alpha. If the
# Surface format contains per pixel alphas, then this alpha value will
# be ignored. If the Surface contains per pixel alphas, setting the
# alpha value to None will disable the per pixel transparency.
#
# The optional flags argument can be set to pygame.RLEACCEL to provide
# better performance on non accelerated displays. An RLEACCEL Surface
# will be slower to modify, but quicker to blit as a source.
#
s = pygame.Surface((1,1), SRCALHPA, 32)
s.fill((1, 2, 3, 4))
s.set_alpha(None)
self.failUnlessEqual(s.get_at((0, 0)), (1, 2, 3, 255))
self.fail()
def test_set_palette(self):
palette = [pygame.Color(i, i, i) for i in range(256)]
palette[10] = tuple(palette[10]) # 4 element tuple
palette[11] = tuple(palette[11])[0:3] # 3 element tuple
surf = pygame.Surface((2, 2), 0, 8)
pygame.init()
try:
pygame.display.set_mode((100, 50))
surf.set_palette(palette)
for i in range(256):
self.failUnlessEqual(surf.map_rgb(palette[i]), i,
"palette color %i" % (i,))
c = palette[i]
surf.fill(c)
self.failUnlessEqual(surf.get_at((0, 0)), c,
"palette color %i" % (i,))
for i in range(10):
palette[i] = pygame.Color(255 - i, 0, 0)
surf.set_palette(palette[0:10])
for i in range(256):
self.failUnlessEqual(surf.map_rgb(palette[i]), i,
"palette color %i" % (i,))
c = palette[i]
surf.fill(c)
self.failUnlessEqual(surf.get_at((0, 0)), c,
"palette color %i" % (i,))
self.failUnlessRaises(ValueError, surf.set_palette,
[Color(1, 2, 3, 254)])
self.failUnlessRaises(ValueError, surf.set_palette,
(1, 2, 3, 254))
finally:
pygame.quit()
def test_set_palette_at(self):
pygame.init()
try:
pygame.display.set_mode((100, 50))
surf = pygame.Surface((2, 2), 0, 8)
original = surf.get_palette_at(10)
replacement = Color(1, 1, 1, 255)
if replacement == original:
replacement = Color(2, 2, 2, 255)
surf.set_palette_at(10, replacement)
self.failUnlessEqual(surf.get_palette_at(10), replacement)
next = tuple(original)
surf.set_palette_at(10, next)
self.failUnlessEqual(surf.get_palette_at(10), next)
next = tuple(original)[0:3]
surf.set_palette_at(10, next)
self.failUnlessEqual(surf.get_palette_at(10), next)
self.failUnlessRaises(IndexError,
surf.set_palette_at,
256, replacement)
self.failUnlessRaises(IndexError,
surf.set_palette_at,
-1, replacement)
finally:
pygame.quit()
def test_subsurface(self):
# __doc__ (as of 2008-08-02) for pygame.surface.Surface.subsurface:
# Surface.subsurface(Rect): return Surface
# create a new surface that references its parent
#
# Returns a new Surface that shares its pixels with its new parent.
# The new Surface is considered a child of the original. Modifications
# to either Surface pixels will effect each other. Surface information
# like clipping area and color keys are unique to each Surface.
#
# The new Surface will inherit the palette, color key, and alpha
# settings from its parent.
#
# It is possible to have any number of subsurfaces and subsubsurfaces
# on the parent. It is also possible to subsurface the display Surface
# if the display mode is not hardware accelerated.
#
# See the Surface.get_offset(), Surface.get_parent() to learn more
# about the state of a subsurface.
#
surf = pygame.Surface((16, 16))
s = surf.subsurface(0,0,1,1)
s = surf.subsurface((0,0,1,1))
#s = surf.subsurface((0,0,1,1), 1)
# This form is not acceptable.
#s = surf.subsurface(0,0,10,10, 1)
self.assertRaises(ValueError, surf.subsurface, (0,0,1,1,666))
self.assertEquals(s.get_shifts(), surf.get_shifts())
self.assertEquals(s.get_masks(), surf.get_masks())
self.assertEquals(s.get_losses(), surf.get_losses())
def todo_test_unlock(self):
# __doc__ (as of 2008-08-02) for pygame.surface.Surface.unlock:
# Surface.unlock(): return None
# unlock the Surface memory from pixel access
#
# Unlock the Surface pixel data after it has been locked. The unlocked
# Surface can once again be drawn and managed by Pygame. See the
# Surface.lock() documentation for more details.
#
# All pygame functions will automatically lock and unlock the Surface
# data as needed. If a section of code is going to make calls that
# will repeatedly lock and unlock the Surface many times, it can be
# helpful to wrap the block inside a lock and unlock pair.
#
# It is safe to nest locking and unlocking calls. The surface will
# only be unlocked after the final lock is released.
#
self.fail()
def test_unmap_rgb(self):
# Special case, 8 bit-per-pixel surface (has a palette).
surf = pygame.Surface((2, 2), 0, 8)
c = (1, 1, 1) # Unlikely to be in a default palette.
i = 67
pygame.init()
try:
pygame.display.set_mode((100, 50))
surf.set_palette_at(i, c)
unmapped_c = surf.unmap_rgb(i)
self.failUnlessEqual(unmapped_c, c)
# Confirm it is a Color instance
self.failUnless(isinstance(unmapped_c, pygame.Color))
finally:
pygame.quit()
# Remaining, non-pallete, cases.
c = (128, 64, 12, 255)
formats = [(0, 16), (0, 24), (0, 32),
(SRCALPHA, 16), (SRCALPHA, 32)]
for flags, bitsize in formats:
surf = pygame.Surface((2, 2), flags, bitsize)
unmapped_c = surf.unmap_rgb(surf.map_rgb(c))
surf.fill(c)
comparison_c = surf.get_at((0, 0))
self.failUnlessEqual(unmapped_c, comparison_c,
"%s != %s, flags: %i, bitsize: %i" %
(unmapped_c, comparison_c, flags, bitsize))
# Confirm it is a Color instance
self.failUnless(isinstance(unmapped_c, pygame.Color))
def test_scroll(self):
scrolls = [(8, 2, 3),
(16, 2, 3),
(24, 2, 3),
(32, 2, 3),
(32, -1, -3),
(32, 0, 0),
(32, 11, 0),
(32, 0, 11),
(32, -11, 0),
(32, 0, -11),
(32, -11, 2),
(32, 2, -11)]
for bitsize, dx, dy in scrolls:
surf = pygame.Surface((10, 10), 0, bitsize)
surf.fill((255, 0, 0))
surf.fill((0, 255, 0), (2, 2, 2, 2,))
comp = surf.copy()
comp.blit(surf, (dx, dy))
surf.scroll(dx, dy)
w, h = surf.get_size()
for x in range(w):
for y in range(h):
self.failUnlessEqual(surf.get_at((x, y)),
comp.get_at((x, y)),
"%s != %s, bpp:, %i, x: %i, y: %i" %
(surf.get_at((x, y)),
comp.get_at((x, y)),
bitsize, dx, dy))
# Confirm clip rect containment
surf = pygame.Surface((20, 13), 0, 32)
surf.fill((255, 0, 0))
surf.fill((0, 255, 0), (7, 1, 6, 6))
comp = surf.copy()
clip = Rect(3, 1, 8, 14)
surf.set_clip(clip)
comp.set_clip(clip)
comp.blit(surf, (clip.x + 2, clip.y + 3), surf.get_clip())
surf.scroll(2, 3)
w, h = surf.get_size()
for x in range(w):
for y in range(h):
self.failUnlessEqual(surf.get_at((x, y)),
comp.get_at((x, y)))
# Confirm keyword arguments and per-pixel alpha
spot_color = (0, 255, 0, 128)
surf = pygame.Surface((4, 4), pygame.SRCALPHA, 32)
surf.fill((255, 0, 0, 255))
surf.set_at((1, 1), spot_color)
surf.scroll(dx=1)
self.failUnlessEqual(surf.get_at((2, 1)), spot_color)
surf.scroll(dy=1)
self.failUnlessEqual(surf.get_at((2, 2)), spot_color)
surf.scroll(dy=1, dx=1)
self.failUnlessEqual(surf.get_at((3, 3)), spot_color)
surf.scroll(dx=-3, dy=-3)
self.failUnlessEqual(surf.get_at((0, 0)), spot_color)
class SurfaceBlendTest (unittest.TestCase):
test_palette = [(0, 0, 0, 255),
(10, 30, 60, 0),
(25, 75, 100, 128),
(200, 150, 100, 200),
(0, 100, 200, 255)]
surf_size = (10, 12)
test_points = [((0, 0), 1), ((4, 5), 1), ((9, 0), 2),
((5, 5), 2), ((0, 11), 3), ((4, 6), 3),
((9, 11), 4), ((5, 6), 4)]
def _make_surface(self, bitsize, srcalpha=False, palette=None):
if palette is None:
palette = self.test_palette
flags = 0
if srcalpha:
flags |= SRCALPHA
surf = pygame.Surface(self.surf_size, flags, bitsize)
if bitsize == 8:
surf.set_palette([c[:3] for c in palette])
return surf
def _fill_surface(self, surf, palette=None):
if palette is None:
palette = self.test_palette
surf.fill(palette[1], (0, 0, 5, 6))
surf.fill(palette[2], (5, 0, 5, 6))
surf.fill(palette[3], (0, 6, 5, 6))
surf.fill(palette[4], (5, 6, 5, 6))
def _make_src_surface(self, bitsize, srcalpha=False, palette=None):
surf = self._make_surface(bitsize, srcalpha, palette)
self._fill_surface(surf, palette)
return surf
def _assert_surface(self, surf, palette=None, msg=""):
if palette is None:
palette = self.test_palette
if surf.get_bitsize() == 16:
palette = [surf.unmap_rgb(surf.map_rgb(c)) for c in palette]
for posn, i in self.test_points:
self.failUnlessEqual(surf.get_at(posn), palette[i],
"%s != %s: flags: %i, bpp: %i, posn: %s%s" %
(surf.get_at(posn),
palette[i], surf.get_flags(),
surf.get_bitsize(), posn, msg))
def setUp(self):
# Needed for 8 bits-per-pixel color palette surface tests.
pygame.init()
def tearDown(self):
pygame.quit()
def test_blit_blend(self):
sources = [self._make_src_surface(8),
self._make_src_surface(16),
self._make_src_surface(16, srcalpha=True),
self._make_src_surface(24),
self._make_src_surface(32),
self._make_src_surface(32, srcalpha=True)]
destinations = [self._make_surface(8),
self._make_surface(16),
self._make_surface(16, srcalpha=True),
self._make_surface(24),
self._make_surface(32),
self._make_surface(32, srcalpha=True)]
blend = [('BLEND_ADD', (0, 25, 100, 255),
lambda a, b: min(a + b, 255)),
('BLEND_SUB', (100, 25, 0, 100),
lambda a, b: max(a - b, 0)),
('BLEND_MULT', (100, 200, 0, 0),
lambda a, b: (a * b) // 256),
('BLEND_MIN', (255, 0, 0, 255), min),
('BLEND_MAX', (0, 255, 0, 255), max)]
for src in sources:
src_palette = [src.unmap_rgb(src.map_rgb(c))
for c in self.test_palette]
for dst in destinations:
for blend_name, dst_color, op in blend:
dc = dst.unmap_rgb(dst.map_rgb(dst_color))
p = []
for sc in src_palette:
c = [op(dc[i], sc[i]) for i in range(3)]
if dst.get_masks()[3]:
c.append(dc[3])
else:
c.append(255)
c = dst.unmap_rgb(dst.map_rgb(c))
p.append(c)
dst.fill(dst_color)
dst.blit(src,
(0, 0),
special_flags=getattr(pygame, blend_name))
self._assert_surface(dst, p,
(", op: %s, src bpp: %i"
", src flags: %i" %
(blend_name,
src.get_bitsize(),
src.get_flags())))
src = self._make_src_surface(32)
masks = src.get_masks()
dst = pygame.Surface(src.get_size(), 0, 32,
[masks[1], masks[2], masks[0], masks[3]])
for blend_name, dst_color, op in blend:
p = []
for src_color in self.test_palette:
c = [op(dst_color[i], src_color[i]) for i in range(3)]
c.append(255)
p.append(tuple(c))
dst.fill(dst_color)
dst.blit(src,
(0, 0),
special_flags=getattr(pygame, blend_name))
self._assert_surface(dst, p, ", %s" % blend_name)
# Blend blits are special cased for 32 to 32 bit surfaces.
#
# Confirm that it works when the rgb bytes are not the
# least significant bytes.
pat = self._make_src_surface(32)
masks = pat.get_masks()
if min(masks) == intify(0xFF000000):
masks = [longify(m) >> 8 for m in masks]
else:
masks = [intify(m << 8) for m in masks]
src = pygame.Surface(pat.get_size(), 0, 32, masks)
self._fill_surface(src)
dst = pygame.Surface(src.get_size(), 0, 32, masks)
for blend_name, dst_color, op in blend:
p = []
for src_color in self.test_palette:
c = [op(dst_color[i], src_color[i]) for i in range(3)]
c.append(255)
p.append(tuple(c))
dst.fill(dst_color)
dst.blit(src,
(0, 0),
special_flags=getattr(pygame, blend_name))
self._assert_surface(dst, p, ", %s" % blend_name)
def test_blit_blend_rgba(self):
sources = [self._make_src_surface(8),
self._make_src_surface(16),
self._make_src_surface(16, srcalpha=True),
self._make_src_surface(24),
self._make_src_surface(32),
self._make_src_surface(32, srcalpha=True)]
destinations = [self._make_surface(8),
self._make_surface(16),
self._make_surface(16, srcalpha=True),
self._make_surface(24),
self._make_surface(32),
self._make_surface(32, srcalpha=True)]
blend = [('BLEND_RGBA_ADD', (0, 25, 100, 255),
lambda a, b: min(a + b, 255)),
('BLEND_RGBA_SUB', (0, 25, 100, 255),
lambda a, b: max(a - b, 0)),
('BLEND_RGBA_MULT', (0, 7, 100, 255),
lambda a, b: (a * b) // 256),
('BLEND_RGBA_MIN', (0, 255, 0, 255), min),
('BLEND_RGBA_MAX', (0, 255, 0, 255), max)]
for src in sources:
src_palette = [src.unmap_rgb(src.map_rgb(c))
for c in self.test_palette]
for dst in destinations:
for blend_name, dst_color, op in blend:
dc = dst.unmap_rgb(dst.map_rgb(dst_color))
p = []
for sc in src_palette:
c = [op(dc[i], sc[i]) for i in range(4)]
if not dst.get_masks()[3]:
c[3] = 255
c = dst.unmap_rgb(dst.map_rgb(c))
p.append(c)
dst.fill(dst_color)
dst.blit(src,
(0, 0),
special_flags=getattr(pygame, blend_name))
self._assert_surface(dst, p,
(", op: %s, src bpp: %i"
", src flags: %i" %
(blend_name,
src.get_bitsize(),
src.get_flags())))
# Blend blits are special cased for 32 to 32 bit surfaces
# with per-pixel alpha.
#
# Confirm the general case is used instead when the formats differ.
src = self._make_src_surface(32, srcalpha=True)
masks = src.get_masks()
dst = pygame.Surface(src.get_size(), SRCALPHA, 32,
(masks[1], masks[2], masks[3], masks[0]))
for blend_name, dst_color, op in blend:
p = [tuple([op(dst_color[i], src_color[i]) for i in range(4)])
for src_color in self.test_palette]
dst.fill(dst_color)
dst.blit(src,
(0, 0),
special_flags=getattr(pygame, blend_name))
self._assert_surface(dst, p, ", %s" % blend_name)
# Confirm this special case handles subsurfaces.
src = pygame.Surface((8, 10), SRCALPHA, 32)
dst = pygame.Surface((8, 10), SRCALPHA, 32)
tst = pygame.Surface((8, 10), SRCALPHA, 32)
src.fill((1, 2, 3, 4))
dst.fill((40, 30, 20, 10))
subsrc = src.subsurface((2, 3, 4, 4))
try:
subdst = dst.subsurface((2, 3, 4, 4))
try:
subdst.blit(subsrc, (0, 0), special_flags=BLEND_RGBA_ADD)
finally:
del subdst
finally:
del subsrc
tst.fill((40, 30, 20, 10))
tst.fill((41, 32, 23, 14), (2, 3, 4, 4))
for x in range(8):
for y in range(10):
self.failUnlessEqual(dst.get_at((x, y)), tst.get_at((x, y)),
"%s != %s at (%i, %i)" %
(dst.get_at((x, y)), tst.get_at((x, y)),
x, y))
def test_GET_PIXELVALS(self):
# surface.h GET_PIXELVALS bug regarding whether of not
# a surface has per-pixel alpha. Looking at the Amask
# is not enough. The surface's SRCALPHA flag must also
# be considered. Fix rev. 1923.
src = self._make_surface(32, srcalpha=True)
src.fill((0, 0, 0, 128))
src.set_alpha(None) # Clear SRCALPHA flag.
dst = self._make_surface(32, srcalpha=True)
dst.blit(src, (0, 0), special_flags=BLEND_RGBA_ADD)
self.failUnlessEqual(dst.get_at((0, 0)), (0, 0, 0, 255))
def test_fill_blend(self):
destinations = [self._make_surface(8),
self._make_surface(16),
self._make_surface(16, srcalpha=True),
self._make_surface(24),
self._make_surface(32),
self._make_surface(32, srcalpha=True)]
blend = [('BLEND_ADD', (0, 25, 100, 255),
lambda a, b: min(a + b, 255)),
('BLEND_SUB', (0, 25, 100, 255),
lambda a, b: max(a - b, 0)),
('BLEND_MULT', (0, 7, 100, 255),
lambda a, b: (a * b) // 256),
('BLEND_MIN', (0, 255, 0, 255), min),
('BLEND_MAX', (0, 255, 0, 255), max)]
for dst in destinations:
dst_palette = [dst.unmap_rgb(dst.map_rgb(c))
for c in self.test_palette]
for blend_name, fill_color, op in blend:
fc = dst.unmap_rgb(dst.map_rgb(fill_color))
self._fill_surface(dst)
p = []
for dc in dst_palette:
c = [op(dc[i], fc[i]) for i in range(3)]
if dst.get_masks()[3]:
c.append(dc[3])
else:
c.append(255)
c = dst.unmap_rgb(dst.map_rgb(c))
p.append(c)
dst.fill(fill_color, special_flags=getattr(pygame, blend_name))
self._assert_surface(dst, p, ", %s" % blend_name)
def test_fill_blend_rgba(self):
destinations = [self._make_surface(8),
self._make_surface(16),
self._make_surface(16, srcalpha=True),
self._make_surface(24),
self._make_surface(32),
self._make_surface(32, srcalpha=True)]
blend = [('BLEND_RGBA_ADD', (0, 25, 100, 255),
lambda a, b: min(a + b, 255)),
('BLEND_RGBA_SUB', (0, 25, 100, 255),
lambda a, b: max(a - b, 0)),
('BLEND_RGBA_MULT', (0, 7, 100, 255),
lambda a, b: (a * b) // 256),
('BLEND_RGBA_MIN', (0, 255, 0, 255), min),
('BLEND_RGBA_MAX', (0, 255, 0, 255), max)]
for dst in destinations:
dst_palette = [dst.unmap_rgb(dst.map_rgb(c))
for c in self.test_palette]
for blend_name, fill_color, op in blend:
fc = dst.unmap_rgb(dst.map_rgb(fill_color))
self._fill_surface(dst)
p = []
for dc in dst_palette:
c = [op(dc[i], fc[i]) for i in range(4)]
if not dst.get_masks()[3]:
c[3] = 255
c = dst.unmap_rgb(dst.map_rgb(c))
p.append(c)
dst.fill(fill_color, special_flags=getattr(pygame, blend_name))
self._assert_surface(dst, p, ", %s" % blend_name)
class SurfaceSelfBlitTest(unittest.TestCase):
"""Blit to self tests.
This test case is in response to MotherHamster Bugzilla Bug 19.
"""
test_palette = [(0, 0, 0, 255),
(255, 0, 0, 0),
(0, 255, 0, 255)]
surf_size = (9, 6)
def _fill_surface(self, surf, palette=None):
if palette is None:
palette = self.test_palette
surf.fill(palette[1])
surf.fill(palette[2], (1, 2, 1, 2))
def _make_surface(self, bitsize, srcalpha=False, palette=None):
if palette is None:
palette = self.test_palette
flags = 0
if srcalpha:
flags |= SRCALPHA
surf = pygame.Surface(self.surf_size, flags, bitsize)
if bitsize == 8:
surf.set_palette([c[:3] for c in palette])
self._fill_surface(surf, palette)
return surf
def _assert_same(self, a, b):
w, h = a.get_size()
for x in range(w):
for y in range(h):
self.failUnlessEqual(a.get_at((x, y)), b.get_at((x, y)),
("%s != %s, bpp: %i" %
(a.get_at((x, y)), b.get_at((x, y)),
a.get_bitsize())))
def setUp(self):
# Needed for 8 bits-per-pixel color palette surface tests.
pygame.init()
def tearDown(self):
pygame.quit()
def test_overlap_check(self):
# Ensure overlapping blits are properly detected. There are two
# places where this is done, within SoftBlitPyGame() in alphablit.c
# and PySurface_Blit() in surface.c. SoftBlitPyGame should catch the
# per-pixel alpha surface, PySurface_Blit the colorkey and blanket
# alpha surface. per-pixel alpha and blanket alpha self blits are
# not properly handled by SDL 1.2.13, so Pygame does them.
bgc = (0, 0, 0, 255)
rectc_left = (128, 64, 32, 255)
rectc_right = (255, 255, 255, 255)
colors = [(255, 255, 255, 255), (128, 64, 32, 255)]
overlaps = [(0, 0, 1, 0, (50, 0)),
(0, 0, 49, 1, (98, 2)),
(0, 0, 49, 49, (98, 98)),
(49, 0, 0, 1, (0, 2)),
(49, 0, 0, 49, (0, 98))]
surfs = [pygame.Surface((100, 100), SRCALPHA, 32)]
surf = pygame.Surface((100, 100), 0, 32)
surf.set_alpha(255)
surfs.append(surf)
surf = pygame.Surface((100, 100), 0, 32)
surf.set_colorkey((0, 1, 0))
surfs.append(surf)
for surf in surfs:
for s_x, s_y, d_x, d_y, test_posn in overlaps:
surf.fill(bgc)
surf.fill(rectc_right, (25, 0, 25, 50))
surf.fill(rectc_left, (0, 0, 25, 50))
surf.blit(surf, (d_x, d_y), (s_x, s_y, 50, 50))
self.failUnlessEqual(surf.get_at(test_posn), rectc_right)
def test_colorkey(self):
# Check a workaround for an SDL 1.2.13 surface self-blit problem
# (MotherHamster Bugzilla bug 19).
pygame.display.set_mode((100, 50)) # Needed for 8bit surface
bitsizes = [8, 16, 24, 32]
for bitsize in bitsizes:
surf = self._make_surface(bitsize)
surf.set_colorkey(self.test_palette[1])
surf.blit(surf, (3, 0))
p = []
for c in self.test_palette:
c = surf.unmap_rgb(surf.map_rgb(c))
p.append(c)
p[1] = (p[1][0], p[1][1], p[1][2], 0)
tmp = self._make_surface(32, srcalpha=True, palette=p)
tmp.blit(tmp, (3, 0))
tmp.set_alpha(None)
comp = self._make_surface(bitsize)
comp.blit(tmp, (0, 0))
self._assert_same(surf, comp)
def test_blanket_alpha(self):
# Check a workaround for an SDL 1.2.13 surface self-blit problem
# (MotherHamster Bugzilla bug 19).
pygame.display.set_mode((100, 50)) # Needed for 8bit surface
bitsizes = [8, 16, 24, 32]
for bitsize in bitsizes:
surf = self._make_surface(bitsize)
surf.set_alpha(128)
surf.blit(surf, (3, 0))
p = []
for c in self.test_palette:
c = surf.unmap_rgb(surf.map_rgb(c))
p.append((c[0], c[1], c[2], 128))
tmp = self._make_surface(32, srcalpha=True, palette=p)
tmp.blit(tmp, (3, 0))
tmp.set_alpha(None)
comp = self._make_surface(bitsize)
comp.blit(tmp, (0, 0))
self._assert_same(surf, comp)
def test_pixel_alpha(self):
bitsizes = [16, 32]
for bitsize in bitsizes:
surf = self._make_surface(bitsize, srcalpha=True)
comp = self._make_surface(bitsize, srcalpha=True)
comp.blit(surf, (3, 0))
surf.blit(surf, (3, 0))
self._assert_same(surf, comp)
def test_blend(self):
bitsizes = [8, 16, 24, 32]
blends = ['BLEND_ADD',
'BLEND_SUB',
'BLEND_MULT',
'BLEND_MIN',
'BLEND_MAX']
for bitsize in bitsizes:
surf = self._make_surface(bitsize)
comp = self._make_surface(bitsize)
for blend in blends:
self._fill_surface(surf)
self._fill_surface(comp)
comp.blit(surf, (3, 0),
special_flags=getattr(pygame, blend))
surf.blit(surf, (3, 0),
special_flags=getattr(pygame, blend))
self._assert_same(surf, comp)
def test_blend_rgba(self):
bitsizes = [16, 32]
blends = ['BLEND_RGBA_ADD',
'BLEND_RGBA_SUB',
'BLEND_RGBA_MULT',
'BLEND_RGBA_MIN',
'BLEND_RGBA_MAX']
for bitsize in bitsizes:
surf = self._make_surface(bitsize, srcalpha=True)
comp = self._make_surface(bitsize, srcalpha=True)
for blend in blends:
self._fill_surface(surf)
self._fill_surface(comp)
comp.blit(surf, (3, 0),
special_flags=getattr(pygame, blend))
surf.blit(surf, (3, 0),
special_flags=getattr(pygame, blend))
self._assert_same(surf, comp)
def test_subsurface(self):
# Blitting a surface to its subsurface is allowed.
surf = self._make_surface(32, srcalpha=True)
comp = surf.copy()
comp.blit(surf, (3, 0))
sub = surf.subsurface((3, 0, 6, 6))
sub.blit(surf, (0, 0))
del sub
self._assert_same(surf, comp)
# Blitting a subsurface to its owner is forbidden because of
# lock conficts. This limitation allows the overlap check
# in PySurface_Blit of alphablit.c to be simplified.
def do_blit(d, s):
d.blit(s, (0, 0))
sub = surf.subsurface((1, 1, 2, 2))
self.failUnlessRaises(pygame.error, do_blit, surf, sub)
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/sprite_test.py 0000644 0001750 0001750 00000074112 11207055754 020154 0 ustar vincent vincent #################################### IMPORTS ###################################
if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils \
import test_not_implemented, unordered_equality, unittest
else:
from test.test_utils \
import test_not_implemented, unordered_equality, unittest
import pygame
from pygame import sprite
################################# MODULE LEVEL #################################
class SpriteModuleTest( unittest.TestCase ):
pass
######################### SPRITECOLLIDE FUNCTIONS TEST #########################
class SpriteCollideTest( unittest.TestCase ):
def setUp(self):
self.ag = sprite.AbstractGroup()
self.ag2 = sprite.AbstractGroup()
self.s1 = sprite.Sprite(self.ag)
self.s2 = sprite.Sprite(self.ag2)
self.s3 = sprite.Sprite(self.ag2)
self.s1.image = pygame.Surface((50,10), pygame.SRCALPHA, 32)
self.s2.image = pygame.Surface((10,10), pygame.SRCALPHA, 32)
self.s3.image = pygame.Surface((10,10), pygame.SRCALPHA, 32)
self.s1.rect = self.s1.image.get_rect()
self.s2.rect = self.s2.image.get_rect()
self.s3.rect = self.s3.image.get_rect()
self.s2.rect.move_ip(40, 0)
self.s3.rect.move_ip(100, 100)
def test_spritecollide__works_if_collided_cb_is_None(self):
# Test that sprites collide without collided function.
self.assertEqual (
sprite.spritecollide (
self.s1, self.ag2, dokill = False, collided = None
),
[self.s2]
)
def test_spritecollide__works_if_collided_cb_not_passed(self):
# Should also work when collided function isn't passed at all.
self.assertEqual(sprite.spritecollide (
self.s1, self.ag2, dokill = False),
[self.s2]
)
def test_spritecollide__collided_must_be_a_callable(self):
# Need to pass a callable.
self.assertRaises (
TypeError,
sprite.spritecollide, self.s1, self.ag2, dokill = False, collided = 1
)
def test_spritecollide__collided_defaults_to_collide_rect(self):
# collide_rect should behave the same as default.
self.assertEqual (
sprite.spritecollide (
self.s1, self.ag2, dokill = False, collided = sprite.collide_rect
),
[self.s2]
)
def test_collide_rect_ratio__ratio_of_one_like_default(self):
# collide_rect_ratio should behave the same as default at a 1.0 ratio.
self.assertEqual (
sprite.spritecollide (
self.s1, self.ag2, dokill = False,
collided = sprite.collide_rect_ratio(1.0)
),
[self.s2]
)
def test_collide_rect_ratio__collides_all_at_ratio_of_twenty(self):
# collide_rect_ratio should collide all at a 20.0 ratio.
self.assert_ (
unordered_equality (
sprite.spritecollide (
self.s1, self.ag2, dokill = False,
collided = sprite.collide_rect_ratio(20.0)
),
[self.s2, self.s3]
)
)
def test_collide_circle__no_radius_set(self):
# collide_circle with no radius set.
self.assertEqual (
sprite.spritecollide (
self.s1, self.ag2, dokill = False, collided = sprite.collide_circle
),
[self.s2]
)
def test_collide_circle_ratio__no_radius_and_ratio_of_one(self):
# collide_circle_ratio with no radius set, at a 1.0 ratio.
self.assertEqual (
sprite.spritecollide (
self.s1, self.ag2, dokill = False,
collided = sprite.collide_circle_ratio(1.0)
),
[self.s2]
)
def test_collide_circle_ratio__no_radius_and_ratio_of_twenty(self):
# collide_circle_ratio with no radius set, at a 20.0 ratio.
self.assert_ (
unordered_equality (
sprite.spritecollide (
self.s1, self.ag2, dokill = False,
collided = sprite.collide_circle_ratio(20.0)
),
[self.s2, self.s3]
)
)
def test_collide_circle__with_radii_set(self):
# collide_circle with a radius set.
self.s1.radius = 50
self.s2.radius = 10
self.s3.radius = 400
self.assert_ (
unordered_equality (
sprite.spritecollide (
self.s1, self.ag2, dokill = False,
collided = sprite.collide_circle
),
[self.s2, self.s3]
)
)
def test_collide_circle_ratio__with_radii_set(self):
self.s1.radius = 50
self.s2.radius = 10
self.s3.radius = 400
# collide_circle_ratio with a radius set.
self.assert_ (
unordered_equality (
sprite.spritecollide (
self.s1, self.ag2, dokill = False,
collided = sprite.collide_circle_ratio(0.5)
),
[self.s2, self.s3]
)
)
def test_collide_mask(self):
# make some fully opaque sprites that will collide with masks.
self.s1.image.fill((255,255,255,255))
self.s2.image.fill((255,255,255,255))
self.s3.image.fill((255,255,255,255))
# masks should be autogenerated from image if they don't exist.
self.assertEqual (
sprite.spritecollide (
self.s1, self.ag2, dokill = False,
collided = sprite.collide_mask
),
[self.s2]
)
self.s1.mask = pygame.mask.from_surface(self.s1.image)
self.s2.mask = pygame.mask.from_surface(self.s2.image)
self.s3.mask = pygame.mask.from_surface(self.s3.image)
# with set masks.
self.assertEqual (
sprite.spritecollide (
self.s1, self.ag2, dokill = False,
collided = sprite.collide_mask
),
[self.s2]
)
def test_collide_mask(self):
# make some sprites that are fully transparent, so they won't collide.
self.s1.image.fill((255,255,255,0))
self.s2.image.fill((255,255,255,0))
self.s3.image.fill((255,255,255,0))
self.s1.mask = pygame.mask.from_surface(self.s1.image, 255)
self.s2.mask = pygame.mask.from_surface(self.s2.image, 255)
self.s3.mask = pygame.mask.from_surface(self.s3.image, 255)
self.assertFalse (
sprite.spritecollide (
self.s1, self.ag2, dokill = False, collided = sprite.collide_mask
)
)
def todo_test_spritecollideany(self):
# __doc__ (as of 2008-08-02) for pygame.sprite.spritecollideany:
# pygame.sprite.spritecollideany(sprite, group) -> sprite
# finds any sprites that collide
#
# given a sprite and a group of sprites, this will
# return return any single sprite that collides with
# with the given sprite. If there are no collisions
# this returns None.
#
# if you don't need all the features of the
# spritecollide function, this function will be a
# bit quicker.
#
# collided is a callback function used to calculate if
# two sprites are colliding. it should take two sprites
# as values, and return a bool value indicating if
# they are colliding. if collided is not passed, all
# sprites must have a "rect" value, which is a
# rectangle of the sprite area, which will be used
# to calculate the collision.
#
# Test if the given Sprite intersects with any Sprites in a Group.
# Intersection is determined by comparing of the Sprite.rect attribute
# of each Sprite.
#
# This collision test can be faster than pygame.sprite.spritecollide()
# since it has less work to do.
self.fail()
def todo_test_groupcollide(self):
# __doc__ (as of 2008-08-02) for pygame.sprite.groupcollide:
# pygame.sprite.groupcollide(groupa, groupb, dokilla, dokillb) -> dict
# collision detection between group and group
#
# given two groups, this will find the intersections
# between all sprites in each group. it returns a
# dictionary of all sprites in the first group that
# collide. the value for each item in the dictionary
# is a list of the sprites in the second group it
# collides with. the two dokill arguments control if
# the sprites from either group will be automatically
# removed from all groups.
# collided is a callback function used to calculate if
# two sprites are colliding. it should take two sprites
# as values, and return a bool value indicating if
# they are colliding. if collided is not passed, all
# sprites must have a "rect" value, which is a
# rectangle of the sprite area, which will be used
# to calculate the collision.
#
# This will find intersections between all the Sprites in two groups.
# Intersection is determined by comparing the Sprite.rect attribute of
# each Sprite.
#
# Every Sprite inside group1 is added to the return dictionary. The
# value for each item is the list of Sprites in group2 that intersect.
#
# If either dokill argument is True, the intersecting Sprites will be
# removed from their respective Group.
self.fail()
def todo_test_collide_rect(self):
# __doc__ (as of 2008-08-02) for pygame.sprite.collide_rect:
# collision detection between two sprites, using rects.
# pygame.sprite.collide_rect(left, right): return bool
#
# Tests for collision between two sprites. Uses the
# pygame rect colliderect function to calculate the
# collision. Intended to be passed as a collided
# callback function to the *collide functions.
# Sprites must have a "rect" attributes.
#
# New in pygame 1.8.0
#
# Tests for collision between two sprites. Uses the pygame rect
# colliderect function to calculate the collision. Intended to be
# passed as a collided callback function to the *collide functions.
# Sprites must have a "rect" attributes.
#
# New in pygame 1.8.0
self.fail()
################################################################################
class AbstractGroupTypeTest( unittest.TestCase ):
def test_has( self ):
" See if AbstractGroup.has() works as expected. "
ag = sprite.AbstractGroup()
ag2 = sprite.AbstractGroup()
s1 = sprite.Sprite(ag)
s2 = sprite.Sprite(ag)
s3 = sprite.Sprite(ag2)
s4 = sprite.Sprite(ag2)
self.assertEqual(True, s1 in ag )
self.assertEqual(True, ag.has(s1) )
self.assertEqual(True, ag.has([s1, s2]) )
# see if one of them not being in there.
self.assertNotEqual(True, ag.has([s1, s2, s3]) )
# see if a second AbstractGroup works.
self.assertEqual(True, ag2.has(s3) )
def todo_test_add(self):
# __doc__ (as of 2008-08-02) for pygame.sprite.AbstractGroup.add:
# add(sprite, list, or group, ...)
# add sprite to group
#
# Add a sprite or sequence of sprites to a group.
self.fail()
def todo_test_add_internal(self):
# __doc__ (as of 2008-08-02) for pygame.sprite.AbstractGroup.add_internal:
#
self.fail()
def todo_test_clear(self):
# __doc__ (as of 2008-08-02) for pygame.sprite.AbstractGroup.clear:
# clear(surface, bgd)
# erase the previous position of all sprites
#
# Clears the area of all drawn sprites. the bgd
# argument should be Surface which is the same
# dimensions as the surface. The bgd can also be
# a function which gets called with the passed
# surface and the area to be cleared.
self.fail()
def todo_test_copy(self):
# __doc__ (as of 2008-08-02) for pygame.sprite.AbstractGroup.copy:
# copy()
# copy a group with all the same sprites
#
# Returns a copy of the group that is the same class
# type, and has the same sprites in it.
self.fail()
def todo_test_draw(self):
# __doc__ (as of 2008-08-02) for pygame.sprite.AbstractGroup.draw:
# draw(surface)
# draw all sprites onto the surface
#
# Draws all the sprites onto the given surface.
self.fail()
def todo_test_empty(self):
# __doc__ (as of 2008-08-02) for pygame.sprite.AbstractGroup.empty:
# empty()
# remove all sprites
#
# Removes all the sprites from the group.
self.fail()
def todo_test_has_internal(self):
# __doc__ (as of 2008-08-02) for pygame.sprite.AbstractGroup.has_internal:
#
self.fail()
def todo_test_remove(self):
# __doc__ (as of 2008-08-02) for pygame.sprite.AbstractGroup.remove:
# remove(sprite, list, or group, ...)
# remove sprite from group
#
# Remove a sprite or sequence of sprites from a group.
self.fail()
def todo_test_remove_internal(self):
# __doc__ (as of 2008-08-02) for pygame.sprite.AbstractGroup.remove_internal:
self.fail()
def todo_test_sprites(self):
# __doc__ (as of 2008-08-02) for pygame.sprite.AbstractGroup.sprites:
# sprites()
# get a list of sprites in the group
#
# Returns an object that can be looped over with a 'for' loop.
# (For now it is always a list, but newer version of Python
# could return different iterators.) You can also iterate directly
# over the sprite group.
self.fail()
def todo_test_update(self):
# __doc__ (as of 2008-08-02) for pygame.sprite.AbstractGroup.update:
# update(*args)
# call update for all member sprites
#
# calls the update method for all sprites in the group.
# Passes all arguments on to the Sprite update function.
self.fail()
################################################################################
# A base class to share tests between similar classes
class LayeredGroupBase:
def test_get_layer_of_sprite(self):
self.assert_(len(self.LG._spritelist)==0)
spr = self.sprite()
self.LG.add(spr, layer=666)
self.assert_(len(self.LG._spritelist)==1)
self.assert_(self.LG.get_layer_of_sprite(spr)==666)
self.assert_(self.LG.get_layer_of_sprite(spr)==self.LG._spritelayers[spr])
def test_add(self):
self.assert_(len(self.LG._spritelist)==0)
spr = self.sprite()
self.LG.add(spr)
self.assert_(len(self.LG._spritelist)==1)
self.assert_(self.LG.get_layer_of_sprite(spr)==self.LG._default_layer)
def test_add__sprite_with_layer_attribute(self):
#test_add_sprite_with_layer_attribute
self.assert_(len(self.LG._spritelist)==0)
spr = self.sprite()
spr._layer = 100
self.LG.add(spr)
self.assert_(len(self.LG._spritelist)==1)
self.assert_(self.LG.get_layer_of_sprite(spr)==100)
def test_add__passing_layer_keyword(self):
# test_add_sprite_passing_layer
self.assert_(len(self.LG._spritelist)==0)
spr = self.sprite()
self.LG.add(spr, layer=100)
self.assert_(len(self.LG._spritelist)==1)
self.assert_(self.LG.get_layer_of_sprite(spr)==100)
def test_add__overriding_sprite_layer_attr(self):
# test_add_sprite_overriding_layer_attr
self.assert_(len(self.LG._spritelist)==0)
spr = self.sprite()
spr._layer = 100
self.LG.add(spr, layer=200)
self.assert_(len(self.LG._spritelist)==1)
self.assert_(self.LG.get_layer_of_sprite(spr)==200)
def test_add__adding_sprite_on_init(self):
# test_add_sprite_init
spr = self.sprite()
lrg2 = sprite.LayeredUpdates(spr)
self.assert_(len(lrg2._spritelist)==1)
self.assert_(lrg2._spritelayers[spr]==lrg2._default_layer)
def test_add__sprite_init_layer_attr(self):
# test_add_sprite_init_layer_attr
spr = self.sprite()
spr._layer = 20
lrg2 = sprite.LayeredUpdates(spr)
self.assert_(len(lrg2._spritelist)==1)
self.assert_(lrg2._spritelayers[spr]==20)
def test_add__sprite_init_passing_layer(self):
# test_add_sprite_init_passing_layer
spr = self.sprite()
lrg2 = sprite.LayeredUpdates(spr, layer=33)
self.assert_(len(lrg2._spritelist)==1)
self.assert_(lrg2._spritelayers[spr]==33)
def test_add__sprite_init_overiding_layer(self):
# test_add_sprite_init_overiding_layer
spr = self.sprite()
spr._layer = 55
lrg2 = sprite.LayeredUpdates(spr, layer=33)
self.assert_(len(lrg2._spritelist)==1)
self.assert_(lrg2._spritelayers[spr]==33)
def test_add__spritelist(self):
# test_add_spritelist
self.assert_(len(self.LG._spritelist)==0)
sprites = []
for i in range(10):
sprites.append(self.sprite())
self.LG.add(sprites)
self.assert_(len(self.LG._spritelist)==10)
for i in range(10):
self.assert_(self.LG.get_layer_of_sprite(sprites[i])==self.LG._default_layer)
def test_add__spritelist_with_layer_attr(self):
# test_add_spritelist_with_layer_attr
self.assert_(len(self.LG._spritelist)==0)
sprites = []
for i in range(10):
sprites.append(self.sprite())
sprites[-1]._layer = i
self.LG.add(sprites)
self.assert_(len(self.LG._spritelist)==10)
for i in range(10):
self.assert_(self.LG.get_layer_of_sprite(sprites[i])==i)
def test_add__spritelist_passing_layer(self):
# test_add_spritelist_passing_layer
self.assert_(len(self.LG._spritelist)==0)
sprites = []
for i in range(10):
sprites.append(self.sprite())
self.LG.add(sprites, layer=33)
self.assert_(len(self.LG._spritelist)==10)
for i in range(10):
self.assert_(self.LG.get_layer_of_sprite(sprites[i])==33)
def test_add__spritelist_overriding_layer(self):
# test_add_spritelist_overriding_layer
self.assert_(len(self.LG._spritelist)==0)
sprites = []
for i in range(10):
sprites.append(self.sprite())
sprites[-1].layer = i
self.LG.add(sprites, layer=33)
self.assert_(len(self.LG._spritelist)==10)
for i in range(10):
self.assert_(self.LG.get_layer_of_sprite(sprites[i])==33)
def test_add__spritelist_init(self):
# test_add_spritelist_init
self.assert_(len(self.LG._spritelist)==0)
sprites = []
for i in range(10):
sprites.append(self.sprite())
lrg2 = sprite.LayeredUpdates(sprites)
self.assert_(len(lrg2._spritelist)==10)
for i in range(10):
self.assert_(lrg2.get_layer_of_sprite(sprites[i])==self.LG._default_layer)
def test_remove__sprite(self):
# test_remove_sprite
self.assert_(len(self.LG._spritelist)==0)
sprites = []
for i in range(10):
sprites.append(self.sprite())
sprites[-1].rect = 0
self.LG.add(sprites)
self.assert_(len(self.LG._spritelist)==10)
for i in range(10):
self.LG.remove(sprites[i])
self.assert_(len(self.LG._spritelist)==0)
def test_sprites(self):
# test_sprites
self.assert_(len(self.LG._spritelist)==0)
sprites = []
for i in range(10):
sprites.append(self.sprite())
sprites[-1]._layer = 10-i
self.LG.add(sprites)
self.assert_(len(self.LG._spritelist)==10)
for idx,spr in enumerate(self.LG.sprites()):
self.assert_(spr == sprites[9-idx])
def test_layers(self):
# test_layers
self.assert_(len(self.LG._spritelist)==0)
sprites = []
for i in range(10):
for j in range(5):
sprites.append(self.sprite())
sprites[-1]._layer = i
self.LG.add(sprites)
lays = self.LG.layers()
for i in range(10):
self.assert_(lays[i] == i)
def test_add__layers_are_correct(self): #TODO
# test_layers2
self.assert_(len(self.LG)==0)
layers = [1,4,6,8,3,6,2,6,4,5,6,1,0,9,7,6,54,8,2,43,6,1]
for lay in layers:
self.LG.add(self.sprite(), layer=lay)
layers.sort()
for idx, spr in enumerate(self.LG.sprites()):
self.assert_(self.LG.get_layer_of_sprite(spr)==layers[idx])
def test_change_layer(self):
# test_change_layer
self.assert_(len(self.LG._spritelist)==0)
spr = self.sprite()
self.LG.add(spr, layer=99)
self.assert_(self.LG._spritelayers[spr] == 99)
self.LG.change_layer(spr, 44)
self.assert_(self.LG._spritelayers[spr] == 44)
spr2 = self.sprite()
spr2.layer = 55
self.LG.add(spr2)
self.LG.change_layer(spr2, 77)
self.assert_(spr2.layer == 77)
def test_get_top_layer(self):
# test_get_top_layer
layers = [1,5,2,8,4,5,3,88,23,0]
for i in layers:
self.LG.add(self.sprite(), layer=i)
self.assert_(self.LG.get_top_layer()==max(layers))
self.assert_(self.LG.get_top_layer()==max(self.LG._spritelayers.values()))
self.assert_(self.LG.get_top_layer()==self.LG._spritelayers[self.LG._spritelist[-1]])
def test_get_bottom_layer(self):
# test_get_bottom_layer
layers = [1,5,2,8,4,5,3,88,23,0]
for i in layers:
self.LG.add(self.sprite(), layer=i)
self.assert_(self.LG.get_bottom_layer()==min(layers))
self.assert_(self.LG.get_bottom_layer()==min(self.LG._spritelayers.values()))
self.assert_(self.LG.get_bottom_layer()==self.LG._spritelayers[self.LG._spritelist[0]])
def test_move_to_front(self):
# test_move_to_front
layers = [1,5,2,8,4,5,3,88,23,0]
for i in layers:
self.LG.add(self.sprite(), layer=i)
spr = self.sprite()
self.LG.add(spr, layer=3)
self.assert_(spr != self.LG._spritelist[-1])
self.LG.move_to_front(spr)
self.assert_(spr == self.LG._spritelist[-1])
def test_move_to_back(self):
# test_move_to_back
layers = [1,5,2,8,4,5,3,88,23,0]
for i in layers:
self.LG.add(self.sprite(), layer=i)
spr = self.sprite()
self.LG.add(spr, layer=55)
self.assert_(spr != self.LG._spritelist[0])
self.LG.move_to_back(spr)
self.assert_(spr == self.LG._spritelist[0])
def test_get_top_sprite(self):
# test_get_top_sprite
layers = [1,5,2,8,4,5,3,88,23,0]
for i in layers:
self.LG.add(self.sprite(), layer=i)
self.assert_(self.LG.get_layer_of_sprite(self.LG.get_top_sprite())== self.LG.get_top_layer())
def test_get_sprites_from_layer(self):
# test_get_sprites_from_layer
self.assert_(len(self.LG)==0)
sprites = {}
layers = [1,4,5,6,3,7,8,2,1,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,0,1,6,5,4,3,2]
for lay in layers:
spr = self.sprite()
spr._layer = lay
self.LG.add(spr)
if lay not in sprites:
sprites[lay] = []
sprites[lay].append(spr)
for lay in self.LG.layers():
for spr in self.LG.get_sprites_from_layer(lay):
self.assert_(spr in sprites[lay])
sprites[lay].remove(spr)
if len(sprites[lay]) == 0:
del sprites[lay]
self.assert_(len(sprites.values())==0)
def test_switch_layer(self):
# test_switch_layer
self.assert_(len(self.LG)==0)
sprites1 = []
sprites2 = []
layers = [3,2,3,2,3,3,2,2,3,2,3,2,3,2,3,2,3,3,2,2,3,2,3]
for lay in layers:
spr = self.sprite()
spr._layer = lay
self.LG.add(spr)
if lay==2:
sprites1.append(spr)
else:
sprites2.append(spr)
for spr in sprites1:
self.assert_(spr in self.LG.get_sprites_from_layer(2))
for spr in sprites2:
self.assert_(spr in self.LG.get_sprites_from_layer(3))
self.assert_(len(self.LG)==len(sprites1)+len(sprites2))
self.LG.switch_layer(2,3)
for spr in sprites1:
self.assert_(spr in self.LG.get_sprites_from_layer(3))
for spr in sprites2:
self.assert_(spr in self.LG.get_sprites_from_layer(2))
self.assert_(len(self.LG)==len(sprites1)+len(sprites2))
########################## LAYERED RENDER GROUP TESTS ##########################
class LayeredUpdatesTypeTest__SpriteTest(LayeredGroupBase, unittest.TestCase):
sprite = sprite.Sprite
def setUp(self):
self.LG = sprite.LayeredUpdates()
class LayeredUpdatesTypeTest__DirtySprite(LayeredGroupBase, unittest.TestCase):
sprite = sprite.DirtySprite
def setUp(self):
self.LG = sprite.LayeredUpdates()
class LayeredDirtyTypeTest__DirtySprite(LayeredGroupBase, unittest.TestCase):
sprite = sprite.DirtySprite
def setUp(self):
self.LG = sprite.LayeredDirty()
############################### SPRITE BASE CLASS ##############################
#
# tests common between sprite classes
class SpriteBase:
def setUp(self):
self.groups = []
for Group in self.Groups:
self.groups.append(Group())
self.sprite = self.Sprite()
def todo_test_add_internal(self):
# __doc__ (as of 2008-08-02) for pygame.sprite.Sprite.add_internal:
self.fail()
def todo_test_remove_internal(self):
# __doc__ (as of 2008-08-02) for pygame.sprite.Sprite.remove_internal:
self.fail()
def todo_test_update(self):
# __doc__ (as of 2008-08-02) for pygame.sprite.Sprite.update:
# method to control sprite behavior
# Sprite.update(*args):
#
# The default implementation of this method does nothing; it's just a
# convenient "hook" that you can override. This method is called by
# Group.update() with whatever arguments you give it.
#
# There is no need to use this method if not using the convenience
# method by the same name in the Group class.
#
# The default implementation of this method does nothing; it's just a
# convenient "hook" that you can override. This method is called by
# Group.update() with whatever arguments you give it.
#
# There is no need to use this method if not using the convenience
# method by the same name in the Group class.
self.fail()
def test___init____added_to_groups_passed(self):
self.sprite = self.Sprite(self.groups)
self.assert_(unordered_equality(
self.sprite.groups(),
self.groups
))
def test_add(self):
self.sprite.add(self.groups)
self.assert_(unordered_equality(
self.sprite.groups(),
self.groups
))
def test_alive(self):
self.assert_(
not self.sprite.alive(),
"Sprite should not be alive if in no groups"
)
self.sprite.add(self.groups)
self.assert_(self.sprite.alive())
def test_groups(self):
for i, g in enumerate(self.groups):
self.sprite.add(g)
groups = self.sprite.groups()
self.assert_( unordered_equality (
groups,
self.groups[:i+1],
))
def test_kill(self):
self.sprite.add(self.groups)
self.assert_(self.sprite.alive())
self.sprite.kill()
self.assert_(not self.sprite.groups() and not self.sprite.alive() )
def test_remove(self):
self.sprite.add(self.groups)
self.sprite.remove(self.groups)
self.assert_(not self.sprite.groups())
############################## SPRITE CLASS TESTS ##############################
class SpriteTypeTest(SpriteBase, unittest.TestCase):
Sprite = sprite.Sprite
Groups = [ sprite.Group,
sprite.LayeredUpdates,
sprite.RenderUpdates,
sprite.OrderedUpdates, ]
class DirtySpriteTypeTest(SpriteBase, unittest.TestCase):
Sprite = sprite.DirtySprite
Groups = [ sprite.Group,
sprite.LayeredUpdates,
sprite.RenderUpdates,
sprite.OrderedUpdates,
sprite.LayeredDirty, ]
################################################################################
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/sndarray_test.py 0000644 0001750 0001750 00000020761 11205604523 020462 0 ustar vincent vincent if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils import test_not_implemented, unittest
else:
from test.test_utils import test_not_implemented, unittest
import pygame
arraytype = ""
try:
import pygame.sndarray
except ImportError:
pass
else:
arraytype = pygame.sndarray.get_arraytype()
if arraytype == 'numpy':
from numpy import \
int8, int16, uint8, uint16, array, alltrue
elif arraytype == 'numeric':
from Numeric import \
Int8 as int8, Int16 as int16, UInt8 as uint8, UInt16 as uint16, \
array, alltrue
else:
print ("Unknown array type %s; tests skipped" %
(pygame.sndarray.get_arraytype(),))
arraytype = ""
class SndarrayTest (unittest.TestCase):
if arraytype:
array_dtypes = {8: uint8, -8: int8, 16: uint16, -16: int16}
def _assert_compatible(self, arr, size):
dtype = self.array_dtypes[size]
if arraytype == 'numpy':
self.failUnlessEqual(arr.dtype, dtype)
else:
self.failUnlessEqual(arr.typecode(), dtype)
def test_import(self):
'does it import'
if not arraytype:
self.fail("no array package installed")
import pygame.sndarray
def test_array(self):
if not arraytype:
self.fail("no array package installed")
def check_array(size, channels, test_data):
try:
pygame.mixer.init(22050, size, channels)
except pygame.error:
# Not all sizes are supported on all systems.
return
try:
__, sz, __ = pygame.mixer.get_init()
if sz == size:
srcarr = array(test_data, self.array_dtypes[size])
snd = pygame.sndarray.make_sound(srcarr)
arr = pygame.sndarray.array(snd)
self._assert_compatible(arr, size)
self.failUnless(alltrue(arr == srcarr),
"size: %i\n%s\n%s" %
(size, arr, test_data))
finally:
pygame.mixer.quit()
check_array(8, 1, [0, 0x0f, 0xf0, 0xff])
check_array(8, 2,
[[0, 0x80], [0x2D, 0x41], [0x64, 0xA1], [0xff, 0x40]])
check_array(16, 1, [0, 0x00ff, 0xff00, 0xffff])
check_array(16, 2, [[0, 0xffff], [0xffff, 0],
[0x00ff, 0xff00], [0x0f0f, 0xf0f0]])
check_array(-8, 1, [0, -0x80, 0x7f, 0x64])
check_array(-8, 2,
[[0, -0x80], [-0x64, 0x64], [0x25, -0x50], [0xff, 0]])
check_array(-16, 1, [0, 0x7fff, -0x7fff, -1])
check_array(-16, 2, [[0, -0x7fff], [-0x7fff, 0],
[0x7fff, 0], [0, 0x7fff]])
def test_get_arraytype(self):
if not arraytype:
self.fail("no array package installed")
self.failUnless((pygame.sndarray.get_arraytype() in
['numpy', 'numeric']),
("unknown array type %s" %
pygame.sndarray.get_arraytype()))
def test_get_arraytypes(self):
if not arraytype:
self.fail("no array package installed")
arraytypes = pygame.sndarray.get_arraytypes()
try:
import numpy
except ImportError:
self.failIf('numpy' in arraytypes)
else:
self.failUnless('numpy' in arraytypes)
try:
import Numeric
except ImportError:
self.failIf('numeric' in arraytypes)
else:
self.failUnless('numeric' in arraytypes)
for atype in arraytypes:
self.failUnless(atype in ['numpy', 'numeric'],
"unknown array type %s" % atype)
def test_make_sound(self):
if not arraytype:
self.fail("no array package installed")
def check_sound(size, channels, test_data):
try:
pygame.mixer.init(22050, size, channels)
except pygame.error:
# Not all sizes are supported on all systems.
return
try:
__, sz, __ = pygame.mixer.get_init()
if sz == size:
srcarr = array(test_data, self.array_dtypes[size])
snd = pygame.sndarray.make_sound(srcarr)
arr = pygame.sndarray.samples(snd)
self.failUnless(alltrue(arr == srcarr),
"size: %i\n%s\n%s" %
(size, arr, test_data))
finally:
pygame.mixer.quit()
check_sound(8, 1, [0, 0x0f, 0xf0, 0xff])
check_sound(8, 2,
[[0, 0x80], [0x2D, 0x41], [0x64, 0xA1], [0xff, 0x40]])
check_sound(16, 1, [0, 0x00ff, 0xff00, 0xffff])
check_sound(16, 2, [[0, 0xffff], [0xffff, 0],
[0x00ff, 0xff00], [0x0f0f, 0xf0f0]])
check_sound(-8, 1, [0, -0x80, 0x7f, 0x64])
check_sound(-8, 2,
[[0, -0x80], [-0x64, 0x64], [0x25, -0x50], [0xff, 0]])
check_sound(-16, 1, [0, 0x7fff, -0x7fff, -1])
check_sound(-16, 2, [[0, -0x7fff], [-0x7fff, 0],
[0x7fff, 0], [0, 0x7fff]])
def test_samples(self):
if not arraytype:
self.fail("no array package installed")
def check_sample(size, channels, test_data):
try:
pygame.mixer.init(22050, size, channels)
except pygame.error:
# Not all sizes are supported on all systems.
return
try:
__, sz, __ = pygame.mixer.get_init()
if sz == size:
zeroed = '\0' * ((abs(size) // 8) *
len(test_data) *
channels)
snd = pygame.mixer.Sound(buffer(zeroed))
samples = pygame.sndarray.samples(snd)
self._assert_compatible(samples, size)
print ('X %s' % (samples.shape,))
print ('Y %s' % (test_data,))
samples[...] = test_data
arr = pygame.sndarray.array(snd)
self.failUnless(alltrue(samples == arr),
"size: %i\n%s\n%s" %
(size, arr, test_data))
finally:
pygame.mixer.quit()
check_sample(8, 1, [0, 0x0f, 0xf0, 0xff])
check_sample(8, 2,
[[0, 0x80], [0x2D, 0x41], [0x64, 0xA1], [0xff, 0x40]])
check_sample(16, 1, [0, 0x00ff, 0xff00, 0xffff])
check_sample(16, 2, [[0, 0xffff], [0xffff, 0],
[0x00ff, 0xff00], [0x0f0f, 0xf0f0]])
check_sample(-8, 1, [0, -0x80, 0x7f, 0x64])
check_sample(-8, 2,
[[0, -0x80], [-0x64, 0x64], [0x25, -0x50], [0xff, 0]])
check_sample(-16, 1, [0, 0x7fff, -0x7fff, -1])
check_sample(-16, 2, [[0, -0x7fff], [-0x7fff, 0],
[0x7fff, 0], [0, 0x7fff]])
def test_use_arraytype(self):
if not arraytype:
self.fail("no array package installed")
def do_use_arraytype(atype):
pygame.sndarray.use_arraytype(atype)
try:
import numpy
except ImportError:
self.failUnlessRaises(ValueError, do_use_arraytype, 'numpy')
self.failIfEqual(pygame.sndarray.get_arraytype(), 'numpy')
else:
pygame.sndarray.use_arraytype('numpy')
self.failUnlessEqual(pygame.sndarray.get_arraytype(), 'numpy')
try:
import Numeric
except ImportError:
self.failUnlessRaises(ValueError, do_use_arraytype, 'numeric')
self.failIfEqual(pygame.sndarray.get_arraytype(), 'numeric')
else:
pygame.sndarray.use_arraytype('numeric')
self.failUnlessEqual(pygame.sndarray.get_arraytype(), 'numeric')
self.failUnlessRaises(ValueError, do_use_arraytype, 'not an option')
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/sndarray_tags.py 0000644 0001750 0001750 00000000411 11207055754 020437 0 ustar vincent vincent __tags__ = ['array']
exclude = False
try:
import numpy
except ImportError:
try:
import Numeric
import pygame._numericsndarray
except ImportError:
exclude = True
if exclude:
__tags__.extend(('ignore', 'subprocess_ignore'))
pygame-1.9.1release/test/scrap_test.py 0000644 0001750 0001750 00000012052 11201706427 017743 0 ustar vincent vincent if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils \
import test_not_implemented, trunk_relative_path, unittest
else:
from test.test_utils \
import test_not_implemented, trunk_relative_path, unittest
import pygame
from pygame import scrap
class ScrapModuleTest(unittest.TestCase):
not_initialized = True
def setUp(self):
if self.not_initialized:
pygame.init ()
pygame.display.set_mode ((1, 1))
scrap.init ()
self.not_initialized = False
def todo_test_contains(self):
# __doc__ (as of 2008-08-02) for pygame.scrap.contains:
# scrap.contains (type) -> bool
# Checks, whether a certain type is available in the clipboard.
#
# Returns True, if data for the passed type is available in the
# clipboard, False otherwise.
#
# if pygame.scrap.contains (SCRAP_TEXT):
# print "There is text in the clipboard."
# if pygame.scrap.contains ("own_data_type"):
# print "There is stuff in the clipboard."
self.fail()
def todo_test_get(self):
# __doc__ (as of 2008-08-02) for pygame.scrap.get:
# scrap.get (type) -> string
# Gets the data for the specified type from the clipboard.
#
# Returns the data for the specified type from the clipboard. The data
# is returned as string and might need further processing. If no data
# for the passed type is available, None is returned.
#
# text = pygame.scrap.get (SCRAP_TEXT)
# if text:
# # Do stuff with it.
# else:
# print "There does not seem to be text in the clipboard."
self.fail()
def todo_test_get_types(self):
# __doc__ (as of 2008-08-02) for pygame.scrap.get_types:
# scrap.get_types () -> list
# Gets a list of the available clipboard types.
#
# Gets a list of strings with the identifiers for the available
# clipboard types. Each identifier can be used in the scrap.get()
# method to get the clipboard content of the specific type. If there
# is no data in the clipboard, an empty list is returned.
#
# types = pygame.scrap.get_types ()
# for t in types:
# if "text" in t:
# # There is some content with the word "text" in it. It's
# # possibly text, so print it.
# print pygame.scrap.get (t)
self.fail()
def todo_test_init(self):
# __doc__ (as of 2008-08-02) for pygame.scrap.init:
# scrap.init () -> None
# Initializes the scrap module.
#
# Tries to initialize the scrap module and raises an exception, if it
# fails. Note that this module requires a set display surface, so you
# have to make sure, you acquired one earlier using
# pygame.display.set_mode().
#
self.fail()
def todo_test_lost(self):
# __doc__ (as of 2008-08-02) for pygame.scrap.lost:
# scrap.lost() -> bool
# Checks whether the clipboard is currently owned by the application.
#
# Returns True, if the clipboard is currently owned by the pygame
# application, False otherwise.
#
# if pygame.scrap.lost ():
# print "No content from me anymore. The clipboard is used by someone else."
self.fail()
def test_set_mode (self):
scrap.set_mode (pygame.SCRAP_SELECTION)
scrap.set_mode (pygame.SCRAP_CLIPBOARD)
self.assertRaises (ValueError, scrap.set_mode, 1099)
def test_scrap_put_text (self):
scrap.put (pygame.SCRAP_TEXT, "Hello world")
self.assertEquals (scrap.get (pygame.SCRAP_TEXT), "Hello world")
scrap.put (pygame.SCRAP_TEXT, "Another String")
self.assertEquals (scrap.get (pygame.SCRAP_TEXT), "Another String")
def test_scrap_put_image (self):
sf = pygame.image.load (
trunk_relative_path("examples/data/asprite.bmp")
)
string = pygame.image.tostring (sf, "RGBA")
scrap.put (pygame.SCRAP_BMP, string)
self.assertEquals (scrap.get(pygame.SCRAP_BMP), string)
def test_put (self):
scrap.put ("arbitrary buffer", "buf")
r = scrap.get ("arbitrary buffer")
self.assertEquals (r, "buf")
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/scrap_tags.py 0000644 0001750 0001750 00000000573 11207055754 017735 0 ustar vincent vincent __tags__ = []
import sys
exclude = False
if ((sys.platform == 'win32' or sys.platform == 'linux2') and
sys.version_info < (3, 0, 0)):
try:
import pygame
pygame.scrap._NOT_IMPLEMENTED_
except AttributeError:
pass
else:
exclude = True
else:
exclude = True
if exclude:
__tags__.extend(['ignore', 'subprocess_ignore'])
pygame-1.9.1release/test/rect_test.py 0000644 0001750 0001750 00000056401 11207055754 017604 0 ustar vincent vincent if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils import test_not_implemented, unittest
else:
from test.test_utils import test_not_implemented, unittest
from pygame import Rect
class RectTypeTest( unittest.TestCase ):
def testConstructionXYWidthHeight( self ):
r = Rect(1,2,3,4)
self.assertEqual( 1, r.left )
self.assertEqual( 2, r.top )
self.assertEqual( 3, r.width )
self.assertEqual( 4, r.height )
def testConstructionTopLeftSize( self ):
r = Rect( (1,2), (3,4) )
self.assertEqual( 1, r.left )
self.assertEqual( 2, r.top )
self.assertEqual( 3, r.width )
self.assertEqual( 4, r.height )
def testCalculatedAttributes( self ):
r = Rect( 1, 2, 3, 4 )
self.assertEqual( r.left+r.width, r.right )
self.assertEqual( r.top+r.height, r.bottom )
self.assertEqual( (r.width,r.height), r.size )
self.assertEqual( (r.left,r.top), r.topleft )
self.assertEqual( (r.right,r.top), r.topright )
self.assertEqual( (r.left,r.bottom), r.bottomleft )
self.assertEqual( (r.right,r.bottom), r.bottomright )
midx = r.left + r.width // 2
midy = r.top + r.height // 2
self.assertEqual( midx, r.centerx )
self.assertEqual( midy, r.centery )
self.assertEqual( (r.centerx,r.centery), r.center )
self.assertEqual( (r.centerx,r.top), r.midtop )
self.assertEqual( (r.centerx,r.bottom), r.midbottom )
self.assertEqual( (r.left,r.centery), r.midleft )
self.assertEqual( (r.right,r.centery), r.midright )
def test_normalize( self ):
r = Rect( 1, 2, -3, -6 )
r2 = Rect(r)
r2.normalize()
self.failUnless( r2.width >= 0 )
self.failUnless( r2.height >= 0 )
self.assertEqual( (abs(r.width),abs(r.height)), r2.size )
self.assertEqual( (-2,-4), r2.topleft )
def test_left( self ):
"""Changing the left attribute moves the rect and does not change
the rect's width
"""
r = Rect( 1, 2, 3, 4 )
new_left = 10
r.left = new_left
self.assertEqual( new_left, r.left )
self.assertEqual( Rect(new_left,2,3,4), r )
def test_right( self ):
"""Changing the right attribute moves the rect and does not change
the rect's width
"""
r = Rect( 1, 2, 3, 4 )
new_right = r.right + 20
expected_left = r.left + 20
old_width = r.width
r.right = new_right
self.assertEqual( new_right, r.right )
self.assertEqual( expected_left, r.left )
self.assertEqual( old_width, r.width )
def test_top( self ):
"""Changing the top attribute moves the rect and does not change
the rect's width
"""
r = Rect( 1, 2, 3, 4 )
new_top = 10
r.top = new_top
self.assertEqual( Rect(1,new_top,3,4), r )
self.assertEqual( new_top, r.top )
def test_bottom( self ):
"""Changing the bottom attribute moves the rect and does not change
the rect's height
"""
r = Rect( 1, 2, 3, 4 )
new_bottom = r.bottom + 20
expected_top = r.top + 20
old_height = r.height
r.bottom = new_bottom
self.assertEqual( new_bottom, r.bottom )
self.assertEqual( expected_top, r.top )
self.assertEqual( old_height, r.height )
def test_centerx( self ):
"""Changing the centerx attribute moves the rect and does not change
the rect's width
"""
r = Rect( 1, 2, 3, 4 )
new_centerx = r.centerx + 20
expected_left = r.left + 20
old_width = r.width
r.centerx = new_centerx
self.assertEqual( new_centerx, r.centerx )
self.assertEqual( expected_left, r.left )
self.assertEqual( old_width, r.width )
def test_centery( self ):
"""Changing the centerx attribute moves the rect and does not change
the rect's width
"""
r = Rect( 1, 2, 3, 4 )
new_centery = r.centery + 20
expected_top = r.top + 20
old_height = r.height
r.centery = new_centery
self.assertEqual( new_centery, r.centery )
self.assertEqual( expected_top, r.top )
self.assertEqual( old_height, r.height )
def test_topleft( self ):
"""Changing the topleft attribute moves the rect and does not change
the rect's size
"""
r = Rect( 1, 2, 3, 4 )
new_topleft = (r.left+20,r.top+30)
old_size = r.size
r.topleft = new_topleft
self.assertEqual( new_topleft, r.topleft )
self.assertEqual( old_size, r.size )
def test_bottomleft( self ):
"""Changing the bottomleft attribute moves the rect and does not change
the rect's size
"""
r = Rect( 1, 2, 3, 4 )
new_bottomleft = (r.left+20,r.bottom+30)
expected_topleft = (r.left+20,r.top+30)
old_size = r.size
r.bottomleft = new_bottomleft
self.assertEqual( new_bottomleft, r.bottomleft )
self.assertEqual( expected_topleft, r.topleft )
self.assertEqual( old_size, r.size )
def test_topright( self ):
"""Changing the bottomleft attribute moves the rect and does not change
the rect's size
"""
r = Rect( 1, 2, 3, 4 )
new_topright = (r.right+20,r.top+30)
expected_topleft = (r.left+20,r.top+30)
old_size = r.size
r.topright = new_topright
self.assertEqual( new_topright, r.topright )
self.assertEqual( expected_topleft, r.topleft )
self.assertEqual( old_size, r.size )
def test_bottomright( self ):
"""Changing the bottomright attribute moves the rect and does not change
the rect's size
"""
r = Rect( 1, 2, 3, 4 )
new_bottomright = (r.right+20,r.bottom+30)
expected_topleft = (r.left+20,r.top+30)
old_size = r.size
r.bottomright = new_bottomright
self.assertEqual( new_bottomright, r.bottomright )
self.assertEqual( expected_topleft, r.topleft )
self.assertEqual( old_size, r.size )
def test_center( self ):
"""Changing the center attribute moves the rect and does not change
the rect's size
"""
r = Rect( 1, 2, 3, 4 )
new_center = (r.centerx+20,r.centery+30)
expected_topleft = (r.left+20,r.top+30)
old_size = r.size
r.center = new_center
self.assertEqual( new_center, r.center )
self.assertEqual( expected_topleft, r.topleft )
self.assertEqual( old_size, r.size )
def test_midleft( self ):
"""Changing the midleft attribute moves the rect and does not change
the rect's size
"""
r = Rect( 1, 2, 3, 4 )
new_midleft = (r.left+20,r.centery+30)
expected_topleft = (r.left+20,r.top+30)
old_size = r.size
r.midleft = new_midleft
self.assertEqual( new_midleft, r.midleft )
self.assertEqual( expected_topleft, r.topleft )
self.assertEqual( old_size, r.size )
def test_midright( self ):
"""Changing the midright attribute moves the rect and does not change
the rect's size
"""
r = Rect( 1, 2, 3, 4 )
new_midright= (r.right+20,r.centery+30)
expected_topleft = (r.left+20,r.top+30)
old_size = r.size
r.midright = new_midright
self.assertEqual( new_midright, r.midright )
self.assertEqual( expected_topleft, r.topleft )
self.assertEqual( old_size, r.size )
def test_midtop( self ):
"""Changing the midtop attribute moves the rect and does not change
the rect's size
"""
r = Rect( 1, 2, 3, 4 )
new_midtop= (r.centerx+20,r.top+30)
expected_topleft = (r.left+20,r.top+30)
old_size = r.size
r.midtop = new_midtop
self.assertEqual( new_midtop, r.midtop )
self.assertEqual( expected_topleft, r.topleft )
self.assertEqual( old_size, r.size )
def test_midbottom( self ):
"""Changing the midbottom attribute moves the rect and does not change
the rect's size
"""
r = Rect( 1, 2, 3, 4 )
new_midbottom = (r.centerx+20,r.bottom+30)
expected_topleft = (r.left+20,r.top+30)
old_size = r.size
r.midbottom = new_midbottom
self.assertEqual( new_midbottom, r.midbottom )
self.assertEqual( expected_topleft, r.topleft )
self.assertEqual( old_size, r.size )
def test_width( self ):
"Changing the width resizes the rect from the top-left corner"
r = Rect( 1, 2, 3, 4 )
new_width = 10
old_topleft = r.topleft
old_height = r.height
r.width = new_width
self.assertEqual( new_width, r.width )
self.assertEqual( old_height, r.height )
self.assertEqual( old_topleft, r.topleft )
def test_height( self ):
"Changing the height resizes the rect from the top-left corner"
r = Rect( 1, 2, 3, 4 )
new_height = 10
old_topleft = r.topleft
old_width = r.width
r.height = new_height
self.assertEqual( new_height, r.height )
self.assertEqual( old_width, r.width )
self.assertEqual( old_topleft, r.topleft )
def test_size( self ):
"Changing the size resizes the rect from the top-left corner"
r = Rect( 1, 2, 3, 4 )
new_size = (10,20)
old_topleft = r.topleft
r.size = new_size
self.assertEqual( new_size, r.size )
self.assertEqual( old_topleft, r.topleft )
def test_contains( self ):
r = Rect( 1, 2, 3, 4 )
self.failUnless( r.contains( Rect( 2, 3, 1, 1 ) ),
"r does not contain Rect(2,3,1,1)" )
self.failUnless( r.contains( Rect(r) ),
"r does not contain the same rect as itself" )
self.failUnless( r.contains( Rect(2,3,0,0) ),
"r does not contain an empty rect within its bounds" )
self.failIf( r.contains( Rect(0,0,1,2) ),
"r contains Rect(0,0,1,2)" )
self.failIf( r.contains( Rect(4,6,1,1) ),
"r contains Rect(4,6,1,1)" )
self.failIf( r.contains( Rect(4,6,0,0) ),
"r contains Rect(4,6,0,0)" )
def test_collidepoint( self ):
r = Rect( 1, 2, 3, 4 )
self.failUnless( r.collidepoint( r.left, r.top ),
"r does not collide with point (left,top)" )
self.failIf( r.collidepoint( r.left-1, r.top ),
"r collides with point (left-1,top)" )
self.failIf( r.collidepoint( r.left, r.top-1 ),
"r collides with point (left,top-1)" )
self.failIf( r.collidepoint( r.left-1,r.top-1 ),
"r collides with point (left-1,top-1)" )
self.failUnless( r.collidepoint( r.right-1, r.bottom-1 ),
"r does not collide with point (right-1,bottom-1)")
self.failIf( r.collidepoint( r.right, r.bottom ),
"r collides with point (right,bottom)" )
self.failIf( r.collidepoint( r.right-1, r.bottom ),
"r collides with point (right-1,bottom)" )
self.failIf( r.collidepoint( r.right, r.bottom-1 ),
"r collides with point (right,bottom-1)" )
def test_inflate__larger( self ):
"The inflate method inflates around the center of the rectangle"
r = Rect( 2, 4, 6, 8 )
r2 = r.inflate( 4, 6 )
self.assertEqual( r.center, r2.center )
self.assertEqual( r.left-2, r2.left )
self.assertEqual( r.top-3, r2.top )
self.assertEqual( r.right+2, r2.right )
self.assertEqual( r.bottom+3, r2.bottom )
self.assertEqual( r.width+4, r2.width )
self.assertEqual( r.height+6, r2.height )
def test_inflate__smaller( self ):
"The inflate method inflates around the center of the rectangle"
r = Rect( 2, 4, 6, 8 )
r2 = r.inflate( -4, -6 )
self.assertEqual( r.center, r2.center )
self.assertEqual( r.left+2, r2.left )
self.assertEqual( r.top+3, r2.top )
self.assertEqual( r.right-2, r2.right )
self.assertEqual( r.bottom-3, r2.bottom )
self.assertEqual( r.width-4, r2.width )
self.assertEqual( r.height-6, r2.height )
def test_inflate_ip__larger( self ):
"The inflate_ip method inflates around the center of the rectangle"
r = Rect( 2, 4, 6, 8 )
r2 = Rect( r )
r2.inflate_ip( -4, -6 )
self.assertEqual( r.center, r2.center )
self.assertEqual( r.left+2, r2.left )
self.assertEqual( r.top+3, r2.top )
self.assertEqual( r.right-2, r2.right )
self.assertEqual( r.bottom-3, r2.bottom )
self.assertEqual( r.width-4, r2.width )
self.assertEqual( r.height-6, r2.height )
def test_inflate_ip__smaller( self ):
"The inflate method inflates around the center of the rectangle"
r = Rect( 2, 4, 6, 8 )
r2 = Rect( r )
r2.inflate_ip( -4, -6 )
self.assertEqual( r.center, r2.center )
self.assertEqual( r.left+2, r2.left )
self.assertEqual( r.top+3, r2.top )
self.assertEqual( r.right-2, r2.right )
self.assertEqual( r.bottom-3, r2.bottom )
self.assertEqual( r.width-4, r2.width )
self.assertEqual( r.height-6, r2.height )
def test_clamp( self ):
r = Rect(10, 10, 10, 10)
c = Rect(19, 12, 5, 5).clamp(r)
self.assertEqual(c.right, r.right)
self.assertEqual(c.top, 12)
c = Rect(1, 2, 3, 4).clamp(r)
self.assertEqual(c.topleft, r.topleft)
c = Rect(5, 500, 22, 33).clamp(r)
self.assertEqual(c.center, r.center)
def test_clamp_ip( self ):
r = Rect(10, 10, 10, 10)
c = Rect(19, 12, 5, 5)
c.clamp_ip(r)
self.assertEqual(c.right, r.right)
self.assertEqual(c.top, 12)
c = Rect(1, 2, 3, 4)
c.clamp_ip(r)
self.assertEqual(c.topleft, r.topleft)
c = Rect(5, 500, 22, 33)
c.clamp_ip(r)
self.assertEqual(c.center, r.center)
def test_clip( self ):
r1 = Rect( 1, 2, 3, 4 )
self.assertEqual( Rect( 1, 2, 2, 2 ), r1.clip( Rect(0,0,3,4) ) )
self.assertEqual( Rect( 2, 2, 2, 4 ), r1.clip( Rect(2,2,10,20) ) )
self.assertEqual( Rect(2,3,1,2), r1.clip( Rect(2,3,1,2) ) )
self.assertEqual( (0,0), r1.clip(20,30,5,6).size )
self.assertEqual( r1, r1.clip( Rect(r1) ),
"r1 does not clip an identical rect to itself" )
def test_move( self ):
r = Rect( 1, 2, 3, 4 )
move_x = 10
move_y = 20
r2 = r.move( move_x, move_y )
expected_r2 = Rect(r.left+move_x,r.top+move_y,r.width,r.height)
self.assertEqual( expected_r2, r2 )
def test_move_ip( self ):
r = Rect( 1, 2, 3, 4 )
r2 = Rect( r )
move_x = 10
move_y = 20
r2.move_ip( move_x, move_y )
expected_r2 = Rect(r.left+move_x,r.top+move_y,r.width,r.height)
self.assertEqual( expected_r2, r2 )
def test_union( self ):
r1 = Rect( 1, 1, 1, 2 )
r2 = Rect( -2, -2, 1, 2 )
self.assertEqual( Rect( -2, -2, 4, 5 ), r1.union(r2) )
def test_union__with_identical_Rect( self ):
r1 = Rect( 1, 2, 3, 4 )
self.assertEqual( r1, r1.union( Rect(r1) ) )
def test_union_ip( self ):
r1 = Rect( 1, 1, 1, 2 )
r2 = Rect( -2, -2, 1, 2 )
r1.union_ip(r2)
self.assertEqual( Rect( -2, -2, 4, 5 ), r1 )
def test_unionall( self ):
r1 = Rect( 0, 0, 1, 1 )
r2 = Rect( -2, -2, 1, 1 )
r3 = Rect( 2, 2, 1, 1 )
r4 = r1.unionall( [r2,r3] )
self.assertEqual( Rect(-2, -2, 5, 5), r4 )
def test_unionall_ip( self ):
r1 = Rect( 0, 0, 1, 1 )
r2 = Rect( -2, -2, 1, 1 )
r3 = Rect( 2, 2, 1, 1 )
r1.unionall_ip( [r2,r3] )
self.assertEqual( Rect(-2, -2, 5, 5), r1 )
def test_colliderect( self ):
r1 = Rect(1,2,3,4)
self.failUnless( r1.colliderect( Rect(0,0,2,3) ),
"r1 does not collide with Rect(0,0,2,3)" )
self.failIf( r1.colliderect( Rect(0,0,1,2) ),
"r1 collides with Rect(0,0,1,2)" )
self.failIf( r1.colliderect( Rect(r1.right,r1.bottom,2,2) ),
"r1 collides with Rect(r1.right,r1.bottom,2,2)" )
self.failUnless( r1.colliderect( Rect(r1.left+1,r1.top+1,
r1.width-2,r1.height-2) ),
"r1 does not collide with Rect(r1.left+1,r1.top+1,"+
"r1.width-2,r1.height-2)" )
self.failUnless( r1.colliderect( Rect(r1.left-1,r1.top-1,
r1.width+2,r1.height+2) ),
"r1 does not collide with Rect(r1.left-1,r1.top-1,"+
"r1.width+2,r1.height+2)" )
self.failUnless( r1.colliderect( Rect(r1) ),
"r1 does not collide with an identical rect" )
self.failIf( r1.colliderect( Rect(r1.right,r1.bottom,0,0) ),
"r1 collides with Rect(r1.right,r1.bottom,0,0)" )
self.failIf( r1.colliderect( Rect(r1.right,r1.bottom,1,1) ),
"r1 collides with Rect(r1.right,r1.bottom,1,1)" )
def testEquals( self ):
""" check to see how the rect uses __eq__
"""
r1 = Rect(1,2,3,4)
r2 = Rect(10,20,30,40)
r3 = (10,20,30,40)
r4 = Rect(10,20,30,40)
class foo (Rect):
def __eq__(self,other):
return id(self) == id(other);
class foo2 (Rect):
pass
r5 = foo(10,20,30,40)
r6 = foo2(10,20,30,40)
self.assertNotEqual(r5, r2)
# because we define equality differently for this subclass.
self.assertEqual(r6, r2)
rect_list = [r1,r2,r3,r4,r6]
# see if we can remove 4 of these.
rect_list.remove(r2)
rect_list.remove(r2)
rect_list.remove(r2)
rect_list.remove(r2)
self.assertRaises(ValueError, rect_list.remove, r2)
def test_collidedict(self):
# __doc__ (as of 2008-08-02) for pygame.rect.Rect.collidedict:
# Rect.collidedict(dict): return (key, value)
# test if one rectangle in a dictionary intersects
#
# Returns the key and value of the first dictionary value that
# collides with the Rect. If no collisions are found, None is
# returned.
#
# Rect objects are not hashable and cannot be used as keys in a
# dictionary, only as values.
r = Rect(1, 1, 10, 10)
r1 = Rect(1, 1, 10, 10)
r2 = Rect(50, 50, 10, 10)
r3 = Rect(70, 70, 10, 10)
r4 = Rect(61, 61, 10, 10)
d = {1: r1, 2: r2, 3: r3}
rects_values = 1
val = r.collidedict(d, rects_values)
self.assertTrue(val)
self.assertEqual(len(val), 2)
self.assertEqual(val[0], 1)
self.assertEqual(val[1], r1)
none_d = {2: r2, 3: r3}
none_val = r.collidedict(none_d, rects_values)
self.assertFalse(none_val)
barely_d = {1: r1, 2: r2, 3: r3}
k3, v3 = r4.collidedict(barely_d, rects_values)
self.assertEqual(k3, 3)
self.assertEqual(v3, r3)
def test_collidedictall(self):
# __doc__ (as of 2008-08-02) for pygame.rect.Rect.collidedictall:
# Rect.collidedictall(dict): return [(key, value), ...]
# test if all rectangles in a dictionary intersect
#
# Returns a list of all the key and value pairs that intersect with
# the Rect. If no collisions are found an empty dictionary is
# returned.
#
# Rect objects are not hashable and cannot be used as keys in a
# dictionary, only as values.
r = Rect(1, 1, 10, 10)
r2 = Rect(1, 1, 10, 10)
r3 = Rect(5, 5, 10, 10)
r4 = Rect(10, 10, 10, 10)
r5 = Rect(50, 50, 10, 10)
rects_values = 1
d = {2: r2}
l = r.collidedictall(d, rects_values)
self.assertEqual(l, [(2, r2)])
d2 = {2: r2, 3: r3, 4: r4, 5: r5}
l2 = r.collidedictall(d2, rects_values)
self.assertEqual(l2, [(2, r2), (3, r3), (4, r4)])
def test_collidelist(self):
# __doc__ (as of 2008-08-02) for pygame.rect.Rect.collidelist:
# Rect.collidelist(list): return index
# test if one rectangle in a list intersects
#
# Test whether the rectangle collides with any in a sequence of
# rectangles. The index of the first collision found is returned. If
# no collisions are found an index of -1 is returned.
r = Rect(1, 1, 10, 10)
l = [Rect(50, 50, 1, 1), Rect(5, 5, 10, 10), Rect(15, 15, 1, 1)]
self.assertEqual(r.collidelist(l), 1)
f = [Rect(50, 50, 1, 1), (100, 100, 4, 4)]
self.assertEqual(r.collidelist(f), -1)
def test_collidelistall(self):
# __doc__ (as of 2008-08-02) for pygame.rect.Rect.collidelistall:
# Rect.collidelistall(list): return indices
# test if all rectangles in a list intersect
#
# Returns a list of all the indices that contain rectangles that
# collide with the Rect. If no intersecting rectangles are found, an
# empty list is returned.
r = Rect(1, 1, 10, 10)
l = [
Rect(1, 1, 10, 10),
Rect(5, 5, 10, 10),
Rect(15, 15, 1, 1),
Rect(2, 2, 1, 1),
]
self.assertEqual(r.collidelistall(l), [0, 1, 3])
f = [Rect(50, 50, 1, 1), Rect(20, 20, 5, 5)]
self.assertFalse(r.collidelistall(f))
def test_fit(self):
# __doc__ (as of 2008-08-02) for pygame.rect.Rect.fit:
# Rect.fit(Rect): return Rect
# resize and move a rectangle with aspect ratio
#
# Returns a new rectangle that is moved and resized to fit another.
# The aspect ratio of the original Rect is preserved, so the new
# rectangle may be smaller than the target in either width or height.
r = Rect(10, 10, 30, 30)
r2 = Rect(30, 30, 15, 10)
f = r.fit(r2)
self.assertTrue(r2.contains(f))
f2 = r2.fit(r)
self.assertTrue(r.contains(f2))
def test_copy(self):
r = Rect(1, 2, 10, 20)
c = r.copy()
self.failUnlessEqual(c, r)
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/README.TXT 0000644 0001750 0001750 00000013060 11210740174 016555 0 ustar vincent vincent ================================================================================
= README FOR PYGAME TESTS =
===========================
================================================================================
= run_tests.py =
================
The test runner for PyGame was developed for these purposes:
* Per process isolation of test modules
* Ability to tag tests for exclusion (interactive tests etc)
* Record timings of tests
It does this by altering the behaviour of unittest at run time. As much as
possible each individual module was left to be fully compatible with the
standard unittest. At one point it was discovered that the run time patching of
unittest was incompatible with the 2.4 version so a copy of the 2.5 version now
is included in the pygame test directory. The test directory was made a
package.
If an individual module is run, eg ``python test/color_test.py``, then it will
run an unmodified version of unittest. ( unittest.main() )
================================================================================
= Creating New Test Modules =
=============================
*** NOTE ***
Be sure to import test_utils first at the top of your file, this will set the
sys.path required for test.unittest to run, otherwise run_tests.py will not work
properly
import test_utils
import test.unittest as unittest
================================================================================
= Writing New Tests =
=====================
See test/util/gen_stubs.py for automatic creation of test stubs
Follow the naming convention
================================================================================
= gen_stubs.py =
================
trunk/test/util/gen_stubs.py
The gen_stubs.py utility will inspect pygame, and compile stubs of each of the
module's callables (funcs, methods, getter/setters). It will include in the
test's comment the __doc__ and the documentation found in the relevant xxxx.doc
files. There is a naming convention in place that maps test names to callables
in a one to one manner. If there are no untested (or unstubbed) callables then
gen_stubs.py will output nothing.
gen_stubs.py --help
gen_stubs.py module -d >> ../test_module_to_append_to.py
You will need to manually merge the stubs into relevant TestCases.
================================================================================
= Test Naming Convention =
==========================
This convention is in place so the stub generator can tell what has already been
tested and for other introspection purposes.
Each module in the pygame package has a corresponding test module in the
trunk/test directory.
pygame.color : color_test.py
Each class has corresponding TestCase[s] in form of $Class + "Type"
# TC[:TC.rindex('Type')]
pygame.color.Color : color_test.ColorTypeTest
pygame.color.Color : color_test.ColorTypeTestOtherAspect
*** NOTE ***
Use the names of the instantiator helper functions:
eg pygame.cdrom.CD and not pygame.cdrom.CDType
Each test should be named in the form, test_$funcname__$comment
Surface.blit : test_blit__raises_exception_if_locked
================================================================================
= Tagging =
===========
There are three levels of tagging available, module level, TestCase level and
individual test level.
For class and module level tagging assign a tag attribute __tags__ = []
Module Level Tags
-----------------
Include the module level tags in: 'some_module_tags.py'
Where the module name is 'some_module' which has its tests in some_module_test.py
This allows some modules to be excluded without loading some code in the first place.
# some_module_test.py
__tags__ = ['display', 'interactive']
Tags are inherited by children, so all TestCases, and thus tests will inherit
these module level tags.
Class Level Tags
----------------
If you want to override a specifig tag then you can use negation.
class SomeTest(unittest.TestCase):
__tags__ = ['-interactive']
Test Level Tags
---------------
The tags for individual tests are specified in the __doc__ for the test.
format : |Tags:comma,separated,tags|
def test_something__about_something(self):
"""
|Tags:interactive,some_other_tag|
"""
*** NOTE ***
By default 'interactive' tags are not run
run_tests.py --exclude display,slow for exclusion of tags
However if you do python test/some_module_test.py all of the tests will run.
See run_tests.py --help for more details.
================================================================================
= test_utils.py =
=================
This contains utility routines for common testing needs as well as sets the
sys.path required for test.unittest to work.
some convenience functions:
question(q)
Will ask q and return True if they answered yes
prompt(p)
Will notify the user of p and then prompt them to "press enter to continue"
trunk_relative_path(pth)
Will return a normalized relative path, relative to the test_module
eg trunk_relative_path('examples\\data\\alien.jpg') will work on linux
This is so the test module can be run from anywhere with working paths
eg ../test/color_test.py
fixture_path(pth)
Likewise but paths are relative to trunk\test\fixtures
example_path(pth)
Likewise but paths are relative to trunk\examples
================================================================================
pygame-1.9.1release/test/pixelarray_test.py 0000644 0001750 0001750 00000047013 11207055754 021026 0 ustar vincent vincent import sys
if __name__ == '__main__':
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils import test_not_implemented, unittest
else:
from test.test_utils import test_not_implemented, unittest
import pygame
from pygame.compat import xrange_
PY3 = sys.version_info >= (3, 0, 0)
class PixelArrayTypeTest (unittest.TestCase):
def todo_test_compare(self):
# __doc__ (as of 2008-06-25) for pygame.pixelarray.PixelArray.compare:
# PixelArray.compare (array, distance=0, weights=(0.299, 0.587, 0.114)): Return PixelArray
# Compares the PixelArray with another one.
self.fail()
def test_pixel_array (self):
for bpp in (8, 16, 24, 32):
sf = pygame.Surface ((10, 20), 0, bpp)
sf.fill ((0, 0, 0))
ar = pygame.PixelArray (sf)
if sf.mustlock():
self.assertTrue (sf.get_locked ())
self.assertEqual (len (ar), 10)
del ar
if sf.mustlock():
self.assertFalse (sf.get_locked ())
# Sequence interfaces
def test_get_column (self):
for bpp in (8, 16, 24, 32):
sf = pygame.Surface ((6, 8), 0, bpp)
sf.fill ((0, 0, 255))
val = sf.map_rgb ((0, 0, 255))
ar = pygame.PixelArray (sf)
ar2 = ar.__getitem__ (1)
self.assertEqual (len(ar2), 8)
self.assertEqual (ar2.__getitem__ (0), val)
self.assertEqual (ar2.__getitem__ (1), val)
self.assertEqual (ar2.__getitem__ (2), val)
ar2 = ar.__getitem__ (-1)
self.assertEqual (len(ar2), 8)
self.assertEqual (ar2.__getitem__ (0), val)
self.assertEqual (ar2.__getitem__ (1), val)
self.assertEqual (ar2.__getitem__ (2), val)
def test_get_pixel (self):
for bpp in (8, 16, 24, 32):
sf = pygame.Surface ((10, 20), 0, bpp)
sf.fill ((0, 0, 255))
for x in xrange_ (20):
sf.set_at ((1, x), (0, 0, 11))
for x in xrange_ (10):
sf.set_at ((x, 1), (0, 0, 11))
ar = pygame.PixelArray (sf)
ar2 = ar.__getitem__ (0).__getitem__ (0)
self.assertEqual (ar2, sf.map_rgb ((0, 0, 255)))
ar2 = ar.__getitem__ (1).__getitem__ (0)
self.assertEqual (ar2, sf.map_rgb ((0, 0, 11)))
ar2 = ar.__getitem__ (-4).__getitem__ (1)
self.assertEqual (ar2, sf.map_rgb ((0, 0, 11)))
ar2 = ar.__getitem__ (-4).__getitem__ (5)
self.assertEqual (ar2, sf.map_rgb ((0, 0, 255)))
def test_set_pixel (self):
for bpp in (8, 16, 24, 32):
sf = pygame.Surface ((10, 20), 0, bpp)
sf.fill ((0, 0, 0))
ar = pygame.PixelArray (sf)
ar.__getitem__ (0).__setitem__ (0, (0, 255, 0))
self.assertEqual (ar[0][0], sf.map_rgb ((0, 255, 0)))
ar.__getitem__ (1).__setitem__ (1, (128, 128, 128))
self.assertEqual (ar[1][1], sf.map_rgb ((128, 128, 128)))
ar.__getitem__(-1).__setitem__ (-1, (128, 128, 128))
self.assertEqual (ar[9][19], sf.map_rgb ((128, 128, 128)))
ar.__getitem__ (-2).__setitem__ (-2, (128, 128, 128))
self.assertEqual (ar[8][-2], sf.map_rgb ((128, 128, 128)))
def test_set_column (self):
for bpp in (8, 16, 24, 32):
sf = pygame.Surface ((6, 8), 0, bpp)
sf.fill ((0, 0, 0))
ar = pygame.PixelArray (sf)
sf2 = pygame.Surface ((6, 8), 0, bpp)
sf2.fill ((0, 255, 255))
ar2 = pygame.PixelArray (sf2)
# Test single value assignment
ar.__setitem__ (2, (128, 128, 128))
self.assertEqual (ar[2][0], sf.map_rgb ((128, 128, 128)))
self.assertEqual (ar[2][1], sf.map_rgb ((128, 128, 128)))
ar.__setitem__ (-1, (0, 255, 255))
self.assertEqual (ar[5][0], sf.map_rgb ((0, 255, 255)))
self.assertEqual (ar[-1][1], sf.map_rgb ((0, 255, 255)))
ar.__setitem__ (-2, (255, 255, 0))
self.assertEqual (ar[4][0], sf.map_rgb ((255, 255, 0)))
self.assertEqual (ar[-2][1], sf.map_rgb ((255, 255, 0)))
# Test list assignment.
ar.__setitem__ (0, [(255, 255, 255)] * 8)
self.assertEqual (ar[0][0], sf.map_rgb ((255, 255, 255)))
self.assertEqual (ar[0][1], sf.map_rgb ((255, 255, 255)))
# Test tuple assignment.
ar.__setitem__ (1, ((204, 0, 204), (17, 17, 17), (204, 0, 204),
(17, 17, 17), (204, 0, 204), (17, 17, 17),
(204, 0, 204), (17, 17, 17)))
self.assertEqual (ar[1][0], sf.map_rgb ((204, 0, 204)))
self.assertEqual (ar[1][1], sf.map_rgb ((17, 17, 17)))
self.assertEqual (ar[1][2], sf.map_rgb ((204, 0, 204)))
# Test pixel array assignment.
ar.__setitem__ (1, ar2.__getitem__ (3))
self.assertEqual (ar[1][0], sf.map_rgb ((0, 255, 255)))
self.assertEqual (ar[1][1], sf.map_rgb ((0, 255, 255)))
def test_get_slice (self):
for bpp in (8, 16, 24, 32):
sf = pygame.Surface ((10, 20), 0, bpp)
sf.fill ((0, 0, 0))
ar = pygame.PixelArray (sf)
if PY3:
self.assertEqual (len (ar[0:2]), 2)
self.assertEqual (len (ar[3:7][3]), 20)
self.assertEqual (ar[0:0], None)
self.assertEqual (ar[5:5], None)
self.assertEqual (ar[9:9], None)
else:
self.assertEqual (len (ar.__getslice__ (0, 2)), 2)
self.assertEqual (len (ar.__getslice__ (3, 7)[3]), 20)
self.assertEqual (ar.__getslice__ (0, 0), None)
self.assertEqual (ar.__getslice__ (5, 5), None)
self.assertEqual (ar.__getslice__ (9, 9), None)
# Has to resolve to ar[7:8]
self.assertEqual (len (ar[-3:-2]), 20)
# Try assignments.
# 2D assignment.
if PY3:
ar[2:5] = (255, 255, 255)
else:
ar.__setslice__ (2, 5, (255, 255, 255))
self.assertEqual (ar[3][3], sf.map_rgb ((255, 255, 255)))
# 1D assignment
if PY3:
ar[3][3:7] = (10, 10, 10)
else:
ar[3].__setslice__ (3, 7, (10, 10, 10))
self.assertEqual (ar[3][5], sf.map_rgb ((10, 10, 10)))
self.assertEqual (ar[3][6], sf.map_rgb ((10, 10, 10)))
def test_contains (self):
for bpp in (8, 16, 24, 32):
sf = pygame.Surface ((10, 20), 0, bpp)
sf.fill ((0, 0, 0))
sf.set_at ((8, 8), (255, 255, 255))
ar = pygame.PixelArray (sf)
self.assertTrue ((0, 0, 0) in ar)
self.assertTrue ((255, 255, 255) in ar)
self.assertFalse ((255, 255, 0) in ar)
self.assertFalse (0x0000ff in ar)
# Test sliced array
self.assertTrue ((0, 0, 0) in ar[8])
self.assertTrue ((255, 255, 255) in ar[8])
self.assertFalse ((255, 255, 0) in ar[8])
self.assertFalse (0x0000ff in ar[8])
def test_get_surface (self):
for bpp in (8, 16, 24, 32):
sf = pygame.Surface ((10, 20), 0, bpp)
sf.fill ((0, 0, 0))
ar = pygame.PixelArray (sf)
self.assertEqual (sf, ar.surface)
def test_set_slice (self):
for bpp in (8, 16, 24, 32):
sf = pygame.Surface ((6, 8), 0, bpp)
sf.fill ((0, 0, 0))
ar = pygame.PixelArray (sf)
# Test single value assignment
val = sf.map_rgb ((128, 128, 128))
if PY3:
ar[0:2] = val
else:
ar.__setslice__ (0, 2, val)
self.assertEqual (ar[0][0], val)
self.assertEqual (ar[0][1], val)
self.assertEqual (ar[1][0], val)
self.assertEqual (ar[1][1], val)
val = sf.map_rgb ((0, 255, 255))
ar[-3:-1] = val
self.assertEqual (ar[3][0], val)
self.assertEqual (ar[-2][1], val)
val = sf.map_rgb ((255, 255, 255))
ar[-3:] = (255, 255, 255)
self.assertEqual (ar[4][0], val)
self.assertEqual (ar[-1][1], val)
# Test list assignment, this is a vertical assignment.
val = sf.map_rgb ((0, 255, 0))
if PY3:
ar[2:4] = [val] * 8
else:
ar.__setslice__ (2, 4, [val] * 8)
self.assertEqual (ar[2][0], val)
self.assertEqual (ar[2][1], val)
self.assertEqual (ar[2][4], val)
self.assertEqual (ar[2][5], val)
self.assertEqual (ar[3][0], val)
self.assertEqual (ar[3][1], val)
self.assertEqual (ar[3][4], val)
self.assertEqual (ar[3][5], val)
# And the horizontal assignment.
val = sf.map_rgb ((255, 0, 0))
val2 = sf.map_rgb ((128, 0, 255))
if PY3:
ar[0:2] = [val, val2]
else:
ar.__setslice__ (0, 2, [val, val2])
self.assertEqual (ar[0][0], val)
self.assertEqual (ar[1][0], val2)
self.assertEqual (ar[0][1], val)
self.assertEqual (ar[1][1], val2)
self.assertEqual (ar[0][4], val)
self.assertEqual (ar[1][4], val2)
self.assertEqual (ar[0][5], val)
self.assertEqual (ar[1][5], val2)
# Test pixelarray assignment.
ar[:] = (0, 0, 0)
sf2 = pygame.Surface ((6, 8), 0, bpp)
sf2.fill ((255, 0, 255))
val = sf.map_rgb ((255, 0, 255))
ar2 = pygame.PixelArray (sf2)
ar[:] = ar2[:]
self.assertEqual (ar[0][0], val)
self.assertEqual (ar[5][7], val)
def test_subscript (self):
# By default we do not need to work with any special __***__
# methods as map subscripts are the first looked up by the
# object system.
for bpp in (8, 16, 24, 32):
sf = pygame.Surface ((6, 8), 0, bpp)
sf.set_at ((1, 3), (0, 255, 0))
sf.set_at ((0, 0), (0, 255, 0))
sf.set_at ((4, 4), (0, 255, 0))
val = sf.map_rgb ((0, 255, 0))
ar = pygame.PixelArray (sf)
# Test single value requests.
self.assertEqual (ar[1,3], val)
self.assertEqual (ar[0,0], val)
self.assertEqual (ar[4,4], val)
self.assertEqual (ar[1][3], val)
self.assertEqual (ar[0][0], val)
self.assertEqual (ar[4][4], val)
# Test ellipse working.
self.assertEqual (len (ar[...,...]), 6)
self.assertEqual (len (ar[1,...]), 8)
self.assertEqual (len (ar[...,3]), 6)
# Test simple slicing
self.assertEqual (len (ar[:,:]), 6)
self.assertEqual (len (ar[:,]), 6)
self.assertEqual (len (ar[1,:]), 8)
self.assertEqual (len (ar[:,2]), 6)
# Empty slices
self.assertEqual (ar[4:4,], None)
self.assertEqual (ar[4:4,...], None)
self.assertEqual (ar[4:4,2:2], None)
self.assertEqual (ar[4:4,1:4], None)
self.assertEqual (ar[4:4:2,], None)
self.assertEqual (ar[4:4:-2,], None)
self.assertEqual (ar[4:4:1,...], None)
self.assertEqual (ar[4:4:-1,...], None)
self.assertEqual (ar[4:4:1,2:2], None)
self.assertEqual (ar[4:4:-1,1:4], None)
self.assertEqual (ar[...,4:4], None)
self.assertEqual (ar[1:4,4:4], None)
self.assertEqual (ar[...,4:4:1], None)
self.assertEqual (ar[...,4:4:-1], None)
self.assertEqual (ar[2:2,4:4:1], None)
self.assertEqual (ar[1:4,4:4:-1], None)
# Test advanced slicing
ar[0] = 0
ar[1] = 1
ar[2] = 2
ar[3] = 3
ar[4] = 4
ar[5] = 5
# We should receive something like [0,2,4]
self.assertEqual (ar[::2,1][0], 0)
self.assertEqual (ar[::2,1][1], 2)
self.assertEqual (ar[::2,1][2], 4)
# We should receive something like [2,2,2]
self.assertEqual (ar[2,::2][0], 2)
self.assertEqual (ar[2,::2][1], 2)
self.assertEqual (ar[2,::2][2], 2)
# Should create a 3x3 array of [0,2,4]
ar2 = ar[::2,::2]
self.assertEqual (len (ar2), 3)
self.assertEqual (ar2[0][0], 0)
self.assertEqual (ar2[0][1], 0)
self.assertEqual (ar2[0][2], 0)
self.assertEqual (ar2[2][0], 4)
self.assertEqual (ar2[2][1], 4)
self.assertEqual (ar2[2][2], 4)
self.assertEqual (ar2[1][0], 2)
self.assertEqual (ar2[2][0], 4)
self.assertEqual (ar2[1][1], 2)
# Should create a reversed 3x8 array over X of [1,2,3] -> [3,2,1]
ar2 = ar[3:0:-1]
self.assertEqual (len (ar2), 3)
self.assertEqual (ar2[0][0], 3)
self.assertEqual (ar2[0][1], 3)
self.assertEqual (ar2[0][2], 3)
self.assertEqual (ar2[0][7], 3)
self.assertEqual (ar2[2][0], 1)
self.assertEqual (ar2[2][1], 1)
self.assertEqual (ar2[2][2], 1)
self.assertEqual (ar2[2][7], 1)
self.assertEqual (ar2[1][0], 2)
self.assertEqual (ar2[1][1], 2)
# Should completely reverse the array over X -> [5,4,3,2,1,0]
ar2 = ar[::-1]
self.assertEqual (len (ar2), 6)
self.assertEqual (ar2[0][0], 5)
self.assertEqual (ar2[0][1], 5)
self.assertEqual (ar2[0][3], 5)
self.assertEqual (ar2[0][-1], 5)
self.assertEqual (ar2[1][0], 4)
self.assertEqual (ar2[1][1], 4)
self.assertEqual (ar2[1][3], 4)
self.assertEqual (ar2[1][-1], 4)
self.assertEqual (ar2[-1][-1], 0)
self.assertEqual (ar2[-2][-2], 1)
self.assertEqual (ar2[-3][-1], 2)
# Test advanced slicing
ar[:] = 0
ar2 = ar[:,1]
ar2[:] = [99] * len(ar2)
self.assertEqual (ar2[0], 99)
self.assertEqual (ar2[-1], 99)
self.assertEqual (ar2[-2], 99)
self.assertEqual (ar2[2], 99)
self.assertEqual (ar[0,1], 99)
self.assertEqual (ar[1,1], 99)
self.assertEqual (ar[2,1], 99)
self.assertEqual (ar[-1,1], 99)
self.assertEqual (ar[-2,1], 99)
def test_ass_subscript (self):
for bpp in (8, 16, 24, 32):
sf = pygame.Surface ((6, 8), 0, bpp)
sf.fill ((255, 255, 255))
ar = pygame.PixelArray (sf)
# Test ellipse working
ar[...,...] = (0, 0, 0)
self.assertEqual (ar[0,0], 0)
self.assertEqual (ar[1,0], 0)
self.assertEqual (ar[-1,-1], 0)
ar[...,] = (0, 0, 255)
self.assertEqual (ar[0,0], sf.map_rgb ((0, 0, 255)))
self.assertEqual (ar[1,0], sf.map_rgb ((0, 0, 255)))
self.assertEqual (ar[-1,-1], sf.map_rgb ((0, 0, 255)))
ar[:,...] = (255, 0, 0)
self.assertEqual (ar[0,0], sf.map_rgb ((255, 0, 0)))
self.assertEqual (ar[1,0], sf.map_rgb ((255, 0, 0)))
self.assertEqual (ar[-1,-1], sf.map_rgb ((255, 0, 0)))
def test_make_surface (self):
for bpp in (8, 16, 24, 32):
sf = pygame.Surface ((10, 20), 0, bpp)
sf.fill ((255, 255, 255))
ar = pygame.PixelArray (sf)
newsf = ar[::2,::2].make_surface ()
rect = newsf.get_rect ()
self.assertEqual (rect.width, 5)
self.assertEqual (rect.height, 10)
def test_iter (self):
for bpp in (8, 16, 24, 32):
sf = pygame.Surface ((5, 10), 0, bpp)
ar = pygame.PixelArray (sf)
iterations = 0
for col in ar:
self.assertEqual (len (col), 10)
iterations += 1
self.assertEqual (iterations, 5)
def test_replace (self):
#print "replace start"
for bpp in (8, 16, 24, 32):
sf = pygame.Surface ((10, 10), 0, bpp)
sf.fill ((255, 0, 0))
rval = sf.map_rgb ((0, 0, 255))
oval = sf.map_rgb ((255, 0, 0))
ar = pygame.PixelArray (sf)
ar[::2].replace ((255, 0, 0), (0, 0, 255))
self.assertEqual (ar[0][0], rval)
self.assertEqual (ar[1][0], oval)
self.assertEqual (ar[2][3], rval)
self.assertEqual (ar[3][6], oval)
self.assertEqual (ar[8][9], rval)
self.assertEqual (ar[9][9], oval)
ar[::2].replace ((0, 0, 255), (255, 0, 0), weights=(10, 20, 50))
self.assertEqual (ar[0][0], oval)
self.assertEqual (ar[2][3], oval)
self.assertEqual (ar[3][6], oval)
self.assertEqual (ar[8][9], oval)
self.assertEqual (ar[9][9], oval)
#print "replace end"
def test_extract (self):
#print "extract start"
for bpp in (8, 16, 24, 32):
sf = pygame.Surface ((10, 10), 0, bpp)
sf.fill ((0, 0, 255))
sf.fill ((255, 0, 0), (2, 2, 6, 6))
white = sf.map_rgb ((255, 255, 255))
black = sf.map_rgb ((0, 0, 0))
ar = pygame.PixelArray (sf)
newar = ar.extract ((255, 0, 0))
self.assertEqual (newar[0][0], black)
self.assertEqual (newar[1][0], black)
self.assertEqual (newar[2][3], white)
self.assertEqual (newar[3][6], white)
self.assertEqual (newar[8][9], black)
self.assertEqual (newar[9][9], black)
newar = ar.extract ((255, 0, 0), weights=(10, 0.1, 50))
self.assertEqual (newar[0][0], black)
self.assertEqual (newar[1][0], black)
self.assertEqual (newar[2][3], white)
self.assertEqual (newar[3][6], white)
self.assertEqual (newar[8][9], black)
self.assertEqual (newar[9][9], black)
#print "extract end"
def todo_test_surface(self):
# __doc__ (as of 2008-08-02) for pygame.pixelarray.PixelArray.surface:
# PixelArray.surface: Return Surface
# Gets the Surface the PixelArray uses.
#
# The Surface, the PixelArray was created for.
self.fail()
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/overlay_test.py 0000644 0001750 0001750 00000003252 11207055754 020324 0 ustar vincent vincent #################################### IMPORTS ###################################
if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils import test_not_implemented, unittest
else:
from test.test_utils import test_not_implemented, unittest
################################################################################
class OverlayTypeTest(unittest.TestCase):
def todo_test_display(self):
# __doc__ (as of 2008-08-02) for pygame.overlay.overlay.display:
# Overlay.display((y, u, v)): return None
# Overlay.display(): return None
# set the overlay pixel data
self.fail()
def todo_test_get_hardware(self):
# __doc__ (as of 2008-08-02) for pygame.overlay.overlay.get_hardware:
# Overlay.get_hardware(rect): return int
# test if the Overlay is hardware accelerated
self.fail()
def todo_test_set_location(self):
# __doc__ (as of 2008-08-02) for pygame.overlay.overlay.set_location:
# Overlay.set_location(rect): return None
# control where the overlay is displayed
self.fail()
################################################################################
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/movie_test.py 0000644 0001750 0001750 00000021613 11207055754 017763 0 ustar vincent vincent if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests import test_utils
from pygame.tests.test_utils import test_not_implemented, unittest
else:
from test import test_utils
from test.test_utils import test_not_implemented, unittest
import pygame
import pygame.movie
from pygame.locals import *
import os
import sys
import time
def within(a,b, error_range):
return abs(a - b) < error_range
def within_seq(a,b,error_range):
for x,y in zip(a,b):
#print x,y
if not within(x,y,error_range):
return 0
return 1
class MovieTypeTest( unittest.TestCase ):
def test_render_frame__off_screen(self):
# __doc__ (as of 2008-06-25) for pygame.movie.Movie:
# pygame.movie.Movie(filename): return Movie
# pygame.movie.Movie(object): return Movie
# load an mpeg movie file
# pygame accepts only MPEG program stream containers,
# with MPEG1 video and MPEG2 audio. I found
# that the command
# mencoder -of mpeg -ovc lavc -oac lavc -lavcopts \
# acodec=mp2:vcodec=mpeg1video:vbitrate=1000 -o new.mpg old.avi
# os.environ.update({"SDL_VIDEODRIVER":'windib'})
movie_file = test_utils.trunk_relative_path('examples/data/blue.mpg')
# Need to init display before using it.
self.assertRaises(Exception, (pygame.movie.Movie, movie_file))
pygame.display.init() # Needs to be init
movie = pygame.movie.Movie(movie_file)
movie_dimensions = movie.get_size()
screen = pygame.display.set_mode(movie_dimensions)
self.assertEqual(movie_dimensions, (320, 240))
off_screen = pygame.Surface(movie_dimensions).convert()
movie.set_display(off_screen)
frame_number = movie.render_frame(5)
#self.assertEqual(off_screen.get_at((10,10)), (16, 16, 255, 255))
#self.assert_(off_screen.get_at((10,10)) in [(16, 16, 255, 255), (18, 13, 238, 255)])
self.assert_(within_seq( off_screen.get_at((10,10)), (16, 16, 255, 255), 20 ))
pygame.display.quit()
def dont_test_render_frame__on_screen(self):
pygame.display.init() # Needs to be init or will segfault
movie_file = test_utils.trunk_relative_path('examples/data/blue.mpg')
movie = pygame.movie.Movie(movie_file)
movie_dimensions = movie.get_size()
self.assertEqual(movie_dimensions, (320, 240))
screen = pygame.display.set_mode(movie_dimensions)
movie.set_display(screen)
movie.render_frame(5)
#self.assertEqual(screen.get_at((10,10)), (16, 16, 255, 255))
#self.assert_(screen.get_at((10,10)) in [(16, 16, 255, 255), (18, 13, 238, 255)])
self.assert_(within_seq( screen.get_at((10,10)), (16, 16, 255, 255), 20 ))
pygame.display.quit()
def todo_test_get_busy(self):
# __doc__ (as of 2008-08-02) for pygame.movie.Movie.get_busy:
# Movie.get_busy(): return bool
# check if the movie is currently playing
#
# Returns true if the movie is currently being played.
self.fail()
def todo_test_get_frame(self):
# __doc__ (as of 2008-08-02) for pygame.movie.Movie.get_frame:
# Movie.get_frame(): return frame_number
# get the current video frame
#
# Returns the integer frame number of the current video frame.
self.fail()
def todo_test_get_length(self):
# __doc__ (as of 2008-08-02) for pygame.movie.Movie.get_length:
# Movie.get_length(): return seconds
# the total length of the movie in seconds
#
# Returns the length of the movie in seconds as a floating point value.
self.fail()
def todo_test_get_size(self):
# __doc__ (as of 2008-08-02) for pygame.movie.Movie.get_size:
# Movie.get_size(): return (width, height)
# get the resolution of the video
#
# Gets the resolution of the movie video. The movie will be stretched
# to the size of any Surface, but this will report the natural video
# size.
self.fail()
def todo_test_get_time(self):
# __doc__ (as of 2008-08-02) for pygame.movie.Movie.get_time:
# Movie.get_time(): return seconds
# get the current vide playback time
#
# Return the current playback time as a floating point value in
# seconds. This method currently seems broken and always returns 0.0.
self.fail()
def todo_test_has_audio(self):
# __doc__ (as of 2008-08-02) for pygame.movie.Movie.has_audio:
# Movie.get_audio(): return bool
# check if the movie file contains audio
#
# True when the opened movie file contains an audio stream.
self.fail()
def todo_test_has_video(self):
# __doc__ (as of 2008-08-02) for pygame.movie.Movie.has_video:
# Movie.get_video(): return bool
# check if the movie file contains video
#
# True when the opened movie file contains a video stream.
self.fail()
def todo_test_pause(self):
# __doc__ (as of 2008-08-02) for pygame.movie.Movie.pause:
# Movie.pause(): return None
# temporarily stop and resume playback
#
# This will temporarily stop or restart movie playback.
self.fail()
def todo_test_play(self):
# __doc__ (as of 2008-08-02) for pygame.movie.Movie.play:
# Movie.play(loops=0): return None
# start playback of a movie
#
# Starts playback of the movie. Sound and video will begin playing if
# they are not disabled. The optional loops argument controls how many
# times the movie will be repeated. A loop value of -1 means the movie
# will repeat forever.
self.fail()
def todo_test_rewind(self):
# __doc__ (as of 2008-08-02) for pygame.movie.Movie.rewind:
# Movie.rewind(): return None
# restart the movie playback
#
# Sets the movie playback position to the start of the movie. The
# movie will automatically begin playing even if it stopped.
#
# The can raise a ValueError if the movie cannot be rewound. If the
# rewind fails the movie object is considered invalid.
self.fail()
def todo_test_set_display(self):
# __doc__ (as of 2008-08-02) for pygame.movie.Movie.set_display:
# Movie.set_display(Surface, rect=None): return None
# set the video target Surface
#
# Set the output target Surface for the movie video. You may also pass
# a rectangle argument for the position, which will move and stretch
# the video into the given area.
#
# If None is passed as the target Surface, the video decoding will be disabled.
self.fail()
def todo_test_set_volume(self):
# __doc__ (as of 2008-08-02) for pygame.movie.Movie.set_volume:
# Movie.set_volume(value): return None
# set the audio playback volume
#
# Set the playback volume for this movie. The argument is a value
# between 0.0 and 1.0. If the volume is set to 0 the movie audio will
# not be decoded.
self.fail()
def todo_test_skip(self):
# __doc__ (as of 2008-08-02) for pygame.movie.Movie.skip:
# Movie.skip(seconds): return None
# advance the movie playback position
#
# Advance the movie playback time in seconds. This can be called
# before the movie is played to set the starting playback time. This
# can only skip the movie forward, not backwards. The argument is a
# floating point number.
self.fail()
def todo_test_stop(self):
# __doc__ (as of 2008-08-02) for pygame.movie.Movie.stop:
# Movie.stop(): return None
# stop movie playback
#
# Stops the playback of a movie. The video and audio playback will be
# stopped at their current position.
self.fail()
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/movie_tags.py 0000644 0001750 0001750 00000000240 11207055754 017733 0 ustar vincent vincent __tags__ = []
import pygame
try:
pygame.movie._NOT_IMPLEMENTED_
except AttributeError:
pass
else:
__tags__.extend(('ignore', 'subprocess_ignore'))
pygame-1.9.1release/test/mouse_test.py 0000644 0001750 0001750 00000014561 11207055754 020000 0 ustar vincent vincent #################################### IMPORTS ###################################
if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils import test_not_implemented, unittest
else:
from test.test_utils import test_not_implemented, unittest
################################################################################
class MouseModuleTest(unittest.TestCase):
def todo_test_get_cursor(self):
# __doc__ (as of 2008-08-02) for pygame.mouse.get_cursor:
# pygame.mouse.get_cursor(): return (size, hotspot, xormasks, andmasks)
# get the image for the system mouse cursor
#
# Get the information about the mouse system cursor. The return value
# is the same data as the arguments passed into
# pygame.mouse.set_cursor().
#
self.fail()
def todo_test_get_focused(self):
# __doc__ (as of 2008-08-02) for pygame.mouse.get_focused:
# pygame.mouse.get_focused(): return bool
# check if the display is receiving mouse input
#
# Returns true when pygame is receiving mouse input events (or, in
# windowing terminology, is "active" or has the "focus").
#
# This method is most useful when working in a window. By contrast, in
# full-screen mode, this method always returns true.
#
# Note: under MS Windows, the window that has the mouse focus also has
# the keyboard focus. But under X-Windows, one window can receive
# mouse events and another receive keyboard events.
# pygame.mouse.get_focused() indicates whether the pygame window
# receives mouse events.
#
self.fail()
def todo_test_get_pos(self):
# __doc__ (as of 2008-08-02) for pygame.mouse.get_pos:
# pygame.mouse.get_pos(): return (x, y)
# get the mouse cursor position
#
# Returns the X and Y position of the mouse cursor. The position is
# relative the the top-left corner of the display. The cursor position
# can be located outside of the display window, but is always
# constrained to the screen.
#
self.fail()
def todo_test_get_pressed(self):
# __doc__ (as of 2008-08-02) for pygame.mouse.get_pressed:
# pygame.moouse.get_pressed(): return (button1, button2, button3)
# get the state of the mouse buttons
#
# Returns a sequence of booleans representing the state of all the
# mouse buttons. A true value means the mouse is currently being
# pressed at the time of the call.
#
# Note, to get all of the mouse events it is better to use either
# pygame.event.wait() or pygame.event.get() and check all of those events
# to see if they are MOUSEBUTTONDOWN, MOUSEBUTTONUP, or MOUSEMOTION.
# Note, that on X11 some XServers use middle button emulation. When
# you click both buttons 1 and 3 at the same time a 2 button event can
# be emitted.
#
# Note, remember to call pygame.event.get() before this function.
# Otherwise it will not work.
#
self.fail()
def todo_test_get_rel(self):
# __doc__ (as of 2008-08-02) for pygame.mouse.get_rel:
# pygame.mouse.get_rel(): return (x, y)
# get the amount of mouse movement
#
# Returns the amount of movement in X and Y since the previous call to
# this function. The relative movement of the mouse cursor is
# constrained to the edges of the screen, but see the virtual input
# mouse mode for a way around this. Virtual input mode is described
# at the top of the page.
#
self.fail()
def todo_test_set_cursor(self):
# __doc__ (as of 2008-08-02) for pygame.mouse.set_cursor:
# pygame.mouse.set_cursor(size, hotspot, xormasks, andmasks): return None
# set the image for the system mouse cursor
#
# When the mouse cursor is visible, it will be displayed as a black
# and white bitmap using the given bitmask arrays. The size is a
# sequence containing the cursor width and height. Hotspot is a
# sequence containing the cursor hotspot position. xormasks is a
# sequence of bytes containing the cursor xor data masks. Lastly is
# andmasks, a sequence of bytes containting the cursor bitmask data.
#
# Width must be a multiple of 8, and the mask arrays must be the
# correct size for the given width and height. Otherwise an exception
# is raised.
#
# See the pygame.cursor module for help creating default and custom
# masks for the system cursor.
#
self.fail()
def todo_test_set_pos(self):
# __doc__ (as of 2008-08-02) for pygame.mouse.set_pos:
# pygame.mouse.set_pos([x, y]): return None
# set the mouse cursor position
#
# Set the current mouse position to arguments given. If the mouse
# cursor is visible it will jump to the new coordinates. Moving the
# mouse will generate a new pygaqme.MOUSEMOTION event.
#
self.fail()
def todo_test_set_visible(self):
# __doc__ (as of 2008-08-02) for pygame.mouse.set_visible:
# pygame.mouse.set_visible(bool): return bool
# hide or show the mouse cursor
#
# If the bool argument is true, the mouse cursor will be visible. This
# will return the previous visible state of the cursor.
#
self.fail()
################################################################################
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/mixer_test.py 0000644 0001750 0001750 00000061434 11207055754 017775 0 ustar vincent vincent #################################### IMPORTS ###################################
if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils import test_not_implemented, unittest
else:
from test.test_utils import test_not_implemented, unittest
import pygame
from pygame import mixer
from pygame.compat import xrange_
import os
################################### CONSTANTS ##################################
FREQUENCIES = [11025, 22050, 44100, 48000]
SIZES = [-16, -8, 8, 16]
CHANNELS = [1, 2]
BUFFERS = [3024]
############################## MODULE LEVEL TESTS ##############################
class MixerModuleTest(unittest.TestCase):
def test_init__keyword_args(self):
# Fails on a Mac; probably older SDL_mixer
## Probably don't need to be so exhaustive. Besides being slow the repeated
## init/quit calls may be causing problems on the Mac.
## configs = ( {'frequency' : f, 'size' : s, 'channels': c }
## for f in FREQUENCIES
## for s in SIZES
## for c in CHANNELS )
#### configs = [{'frequency' : 44100, 'size' : 16, 'channels' : 1}]
configs = [{'frequency' : 22050, 'size' : -16, 'channels' : 2}]
for kw_conf in configs:
mixer.init(**kw_conf)
mixer_conf = mixer.get_init()
self.assertEquals(
# Not all "sizes" are supported on all systems.
(mixer_conf[0], abs(mixer_conf[1]), mixer_conf[2]),
(kw_conf['frequency'],
abs(kw_conf['size']),
kw_conf['channels'])
)
mixer.quit()
def todo_test_pre_init__keyword_args(self):
# Fails on Mac; probably older SDL_mixer
## Probably don't need to be so exhaustive. Besides being slow the repeated
## init/quit calls may be causing problems on the Mac.
## configs = ( {'frequency' : f, 'size' : s, 'channels': c }
## for f in FREQUENCIES
## for s in SIZES
## for c in CHANNELS )
configs = [{'frequency' : 44100, 'size' : 16, 'channels' : 1}]
for kw_conf in configs:
mixer.pre_init(**kw_conf)
mixer.init()
mixer_conf = mixer.get_init()
self.assertEquals(
# Not all "sizes" are supported on all systems.
(mixer_conf[0], abs(mixer_conf[1]), mixer_conf[2]),
(kw_conf['frequency'],
abs(kw_conf['size']),
kw_conf['channels'])
)
mixer.quit()
def todo_test_pre_init__zero_values(self):
# Ensure that argument values of 0 are replaced with
# default values. No way to check buffer size though.
mixer.pre_init(44100, -8, 1) # Non default values
mixer.pre_init(0, 0, 0) # Should reset to default values
mixer.init()
try:
self.failUnlessEqual(mixer.get_init(), (22050, -16, 2))
finally:
mixer.quit()
def todo_test_init__zero_values(self):
# Ensure that argument values of 0 are replaced with
# preset values. No way to check buffer size though.
mixer.pre_init(44100, 8, 1) # None default values
mixer.init(0, 0, 0)
try:
self.failUnlessEqual(mixer.get_init(), (44100, 8, 1))
finally:
mixer.quit()
mixer.pre_init(0, 0, 0, 0)
def test_get_init__returns_exact_values_used_for_init(self):
return
# fix in 1.9 - I think it's a SDL_mixer bug.
# TODO: When this bug is fixed, testing through every combination
# will be too slow so adjust as necessary, at the moment it
# breaks the loop after first failure
configs = []
for f in FREQUENCIES:
for s in SIZES:
for c in CHANNELS:
configs.append ((f,s,c))
print (configs)
for init_conf in configs:
print (init_conf)
f,s,c = init_conf
if (f,s) == (22050,16):continue
mixer.init(f,s,c)
mixer_conf = mixer.get_init()
import time
time.sleep(0.1)
mixer.quit()
time.sleep(0.1)
if init_conf != mixer_conf:
continue
self.assertEquals(init_conf, mixer_conf)
def test_get_init__returns_None_if_mixer_not_initialized(self):
self.assert_(mixer.get_init() is None)
def test_get_num_channels__defaults_eight_after_init(self):
mixer.init()
num_channels = mixer.get_num_channels()
self.assert_(num_channels == 8)
mixer.quit()
def test_set_num_channels(self):
mixer.init()
for i in xrange_(1, mixer.get_num_channels() + 1):
mixer.set_num_channels(i)
self.assert_(mixer.get_num_channels() == i)
mixer.quit()
def test_quit(self):
""" get_num_channels() Should throw pygame.error if uninitialized
after mixer.quit() """
mixer.init()
mixer.quit()
self.assertRaises (
pygame.error, mixer.get_num_channels,
)
def todo_test_fadeout(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.fadeout:
# pygame.mixer.fadeout(time): return None
# fade out the volume on all sounds before stopping
#
# This will fade out the volume on all active channels over the time
# argument in milliseconds. After the sound is muted the playback will
# stop.
#
self.fail()
def todo_test_find_channel(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.find_channel:
# pygame.mixer.find_channel(force=False): return Channel
# find an unused channel
#
# This will find and return an inactive Channel object. If there are
# no inactive Channels this function will return None. If there are no
# inactive channels and the force argument is True, this will find the
# Channel with the longest running Sound and return it.
#
# If the mixer has reserved channels from pygame.mixer.set_reserved()
# then those channels will not be returned here.
#
self.fail()
def todo_test_get_busy(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.get_busy:
# pygame.mixer.get_busy(): return bool
# test if any sound is being mixed
#
# Returns True if the mixer is busy mixing any channels. If the mixer
# is idle then this return False.
#
self.fail()
def todo_test_init(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.init:
# pygame.mixer.init(frequency=22050, size=-16, channels=2,
# buffer=3072): return None
#
# initialize the mixer module
#
# Initialize the mixer module for Sound loading and playback. The
# default arguments can be overridden to provide specific audio
# mixing. The size argument represents how many bits are used for each
# audio sample. If the value is negative then signed sample values
# will be used. Positive values mean unsigned audio samples will be
# used.
#
# The channels argument is used to specify whether to use mono or
# stereo. 1 for mono and 2 for stereo. No other values are supported.
#
# The buffer argument controls the number of internal samples used in
# the sound mixer. The default value should work for most cases. It
# can be lowered to reduce latency, but sound dropout may occur. It
# can be raised to larger values to ensure playback never skips, but
# it will impose latency on sound playback. The buffer size must be a
# power of two.
#
# Some platforms require the pygame.mixer module to be initialized
# after the display modules have initialized. The top level
# pygame.init() takes care of this automatically, but cannot pass any
# arguments to the mixer init. To solve this, mixer has a function
# pygame.mixer.pre_init() to set the proper defaults before the
# toplevel init is used.
#
# It is safe to call this more than once, but after the mixer is
# initialized you cannot change the playback arguments without first
# calling pygame.mixer.quit().
#
self.fail()
def todo_test_pause(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.pause:
# pygame.mixer.pause(): return None
# temporarily stop playback of all sound channels
#
# This will temporarily stop all playback on the active mixer
# channels. The playback can later be resumed with
# pygame.mixer.unpause()
#
self.fail()
def todo_test_pre_init(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.pre_init:
# pygame.mixer.pre_init(frequency=0, size=0, channels=0,
# buffersize=0): return None
#
# preset the mixer init arguments
#
# Any nonzero arguments change the default values used when the real
# pygame.mixer.init() is called. The best way to set custom mixer
# playback values is to call pygame.mixer.pre_init() before calling
# the top level pygame.init().
#
self.fail()
def todo_test_set_reserved(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.set_reserved:
# pygame.mixer.set_reserved(count): return None
# reserve channels from being automatically used
#
# The mixer can reserve any number of channels that will not be
# automatically selected for playback by Sounds. If sounds are
# currently playing on the reserved channels they will not be stopped.
#
# This allows the application to reserve a specific number of channels
# for important sounds that must not be dropped or have a guaranteed
# channel to play on.
#
self.fail()
def todo_test_stop(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.stop:
# pygame.mixer.stop(): return None
# stop playback of all sound channels
#
# This will stop all playback of all active mixer channels.
self.fail()
def todo_test_unpause(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.unpause:
# pygame.mixer.unpause(): return None
# resume paused playback of sound channels
#
# This will resume all active sound channels after they have been paused.
self.fail()
############################## CHANNEL CLASS TESTS #############################
class ChannelTypeTest(unittest.TestCase):
def todo_test_Channel(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.Channel:
# pygame.mixer.Channel(id): return Channel
# Create a Channel object for controlling playback
#
# Return a Channel object for one of the current channels. The id must
# be a value from 0 to the value of pygame.mixer.get_num_channels().
#
# The Channel object can be used to get fine control over the playback
# of Sounds. A channel can only playback a single Sound at time. Using
# channels is entirely optional since pygame can manage them by
# default.
#
self.fail()
def todo_test_fadeout(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.Channel.fadeout:
# Channel.fadeout(time): return None
# stop playback after fading channel out
#
# Stop playback of a channel after fading out the sound over the given
# time argument in milliseconds.
#
self.fail()
def todo_test_get_busy(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.Channel.get_busy:
# Channel.get_busy(): return bool
# check if the channel is active
#
# Returns true if the channel is activily mixing sound. If the channel
# is idle this returns False.
#
self.fail()
def todo_test_get_endevent(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.Channel.get_endevent:
# Channel.get_endevent(): return type
# get the event a channel sends when playback stops
#
# Returns the event type to be sent every time the Channel finishes
# playback of a Sound. If there is no endevent the function returns
# pygame.NOEVENT.
#
self.fail()
def todo_test_get_queue(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.Channel.get_queue:
# Channel.get_queue(): return Sound
# return any Sound that is queued
#
# If a Sound is already queued on this channel it will be returned.
# Once the queued sound begins playback it will no longer be on the
# queue.
#
self.fail()
def todo_test_get_sound(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.Channel.get_sound:
# Channel.get_sound(): return Sound
# get the currently playing Sound
#
# Return the actual Sound object currently playing on this channel. If
# the channel is idle None is returned.
#
self.fail()
def todo_test_get_volume(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.Channel.get_volume:
# Channel.get_volume(): return value
# get the volume of the playing channel
#
# Return the volume of the channel for the current playing sound. This
# does not take into account stereo separation used by
# Channel.set_volume. The Sound object also has its own volume which
# is mixed with the channel.
#
self.fail()
def todo_test_pause(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.Channel.pause:
# Channel.pause(): return None
# temporarily stop playback of a channel
#
# Temporarily stop the playback of sound on a channel. It can be
# resumed at a later time with Channel.unpause()
#
self.fail()
def todo_test_play(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.Channel.play:
# Channel.play(Sound, loops=0, maxtime=0, fade_ms=0): return None
# play a Sound on a specific Channel
#
# This will begin playback of a Sound on a specific Channel. If the
# Channel is currently playing any other Sound it will be stopped.
#
# The loops argument has the same meaning as in Sound.play(): it is
# the number of times to repeat the sound after the first time. If it
# is 3, the sound will be played 4 times (the first time, then three
# more). If loops is -1 then the playback will repeat indefinitely.
#
# As in Sound.play(), the maxtime argument can be used to stop
# playback of the Sound after a given number of milliseconds.
#
# As in Sound.play(), the fade_ms argument can be used fade in the sound.
self.fail()
def todo_test_queue(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.Channel.queue:
# Channel.queue(Sound): return None
# queue a Sound object to follow the current
#
# When a Sound is queued on a Channel, it will begin playing
# immediately after the current Sound is finished. Each channel can
# only have a single Sound queued at a time. The queued Sound will
# only play if the current playback finished automatically. It is
# cleared on any other call to Channel.stop() or Channel.play().
#
# If there is no sound actively playing on the Channel then the Sound
# will begin playing immediately.
#
self.fail()
def todo_test_set_endevent(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.Channel.set_endevent:
# Channel.set_endevent(): return None
# Channel.set_endevent(type): return None
# have the channel send an event when playback stops
#
# When an endevent is set for a channel, it will send an event to the
# pygame queue every time a sound finishes playing on that channel
# (not just the first time). Use pygame.event.get() to retrieve the
# endevent once it's sent.
#
# Note that if you called Sound.play(n) or Channel.play(sound,n), the
# end event is sent only once: after the sound has been played "n+1"
# times (see the documentation of Sound.play).
#
# If Channel.stop() or Channel.play() is called while the sound was
# still playing, the event will be posted immediately.
#
# The type argument will be the event id sent to the queue. This can
# be any valid event type, but a good choice would be a value between
# pygame.locals.USEREVENT and pygame.locals.NUMEVENTS. If no type
# argument is given then the Channel will stop sending endevents.
#
self.fail()
def todo_test_set_volume(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.Channel.set_volume:
# Channel.set_volume(value): return None
# Channel.set_volume(left, right): return None
# set the volume of a playing channel
#
# Set the volume (loudness) of a playing sound. When a channel starts
# to play its volume value is reset. This only affects the current
# sound. The value argument is between 0.0 and 1.0.
#
# If one argument is passed, it will be the volume of both speakers.
# If two arguments are passed and the mixer is in stereo mode, the
# first argument will be the volume of the left speaker and the second
# will be the volume of the right speaker. (If the second argument is
# None, the first argument will be the volume of both speakers.)
#
# If the channel is playing a Sound on which set_volume() has also
# been called, both calls are taken into account. For example:
#
# sound = pygame.mixer.Sound("s.wav")
# channel = s.play() # Sound plays at full volume by default
# sound.set_volume(0.9) # Now plays at 90% of full volume.
# sound.set_volume(0.6) # Now plays at 60% (previous value replaced).
# channel.set_volume(0.5) # Now plays at 30% (0.6 * 0.5).
self.fail()
def todo_test_stop(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.Channel.stop:
# Channel.stop(): return None
# stop playback on a Channel
#
# Stop sound playback on a channel. After playback is stopped the
# channel becomes available for new Sounds to play on it.
#
self.fail()
def todo_test_unpause(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.Channel.unpause:
# Channel.unpause(): return None
# resume pause playback of a channel
#
# Resume the playback on a paused channel.
self.fail()
############################### SOUND CLASS TESTS ##############################
class SoundTypeTest(unittest.TestCase):
def todo_test_fadeout(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.Sound.fadeout:
# Sound.fadeout(time): return None
# stop sound playback after fading out
#
# This will stop playback of the sound after fading it out over the
# time argument in milliseconds. The Sound will fade and stop on all
# actively playing channels.
#
self.fail()
def todo_test_get_buffer(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.Sound.get_buffer:
# Sound.get_buffer(): return BufferProxy
# acquires a buffer object for the sameples of the Sound.
#
# Return a buffer object for the Sound samples. The buffer can be used
# for direct access and manipulation.
#
# New in pygame 1.8.
self.fail()
def todo_test_get_length(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.Sound.get_length:
# Sound.get_length(): return seconds
# get the length of the Sound
#
# Return the length of this Sound in seconds.
self.fail()
def todo_test_get_num_channels(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.Sound.get_num_channels:
# Sound.get_num_channels(): return count
# count how many times this Sound is playing
#
# Return the number of active channels this sound is playing on.
self.fail()
def todo_test_get_volume(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.Sound.get_volume:
# Sound.get_volume(): return value
# get the playback volume
#
# Return a value from 0.0 to 1.0 representing the volume for this Sound.
self.fail()
def todo_test_play(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.Sound.play:
# Sound.play(loops=0, maxtime=0, fade_ms=0): return Channel
# begin sound playback
#
# Begin playback of the Sound (i.e., on the computer's speakers) on an
# available Channel. This will forcibly select a Channel, so playback
# may cut off a currently playing sound if necessary.
#
# The loops argument controls how many times the sample will be
# repeated after being played the first time. A value of 5 means that
# the sound will be played once, then repeated five times, and so is
# played a total of six times. The default value (zero) means the
# Sound is not repeated, and so is only played once. If loops is set
# to -1 the Sound will loop indefinitely (though you can still call
# stop() to stop it).
#
# The maxtime argument can be used to stop playback after a given
# number of milliseconds.
#
# The fade_ms argument will make the sound start playing at 0 volume
# and fade up to full volume over the time given. The sample may end
# before the fade-in is complete.
#
# This returns the Channel object for the channel that was selected.
self.fail()
def todo_test_set_volume(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.Sound.set_volume:
# Sound.set_volume(value): return None
# set the playback volume for this Sound
#
# This will set the playback volume (loudness) for this Sound. This
# will immediately affect the Sound if it is playing. It will also
# affect any future playback of this Sound. The argument is a value
# from 0.0 to 1.0.
#
self.fail()
def todo_test_stop(self):
# __doc__ (as of 2008-08-02) for pygame.mixer.Sound.stop:
# Sound.stop(): return None
# stop sound playback
#
# This will stop the playback of this Sound on any active Channels.
self.fail()
##################################### MAIN #####################################
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/mixer_music_test.py 0000644 0001750 0001750 00000015763 11207055754 021201 0 ustar vincent vincent if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils \
import test_not_implemented, unittest, example_path
else:
from test.test_utils \
import test_not_implemented, unittest, example_path
import pygame
import os
class MixerMusicModuleTest(unittest.TestCase):
def test_load(self):
# __doc__ (as of 2008-07-13) for pygame.mixer_music.load:
# pygame.mixer.music.load(filename): return None
# Load a music file for playback
data_fname = example_path('data')
pygame.mixer.init()
# The mp3 test file can crash smpeg on some systems.
## formats = ['mp3', 'ogg', 'wav']
formats = ['ogg', 'wav']
for f in formats:
musfn = os.path.join(data_fname, 'house_lo.%s' % f)
pygame.mixer.music.load(musfn)
#NOTE: TODO: loading from filelikes are disabled...
# because as of writing it only works in SDL_mixer svn.
#pygame.mixer.music.load(open(musfn))
#musf = open(musfn)
#pygame.mixer.music.load(musf)
pygame.mixer.quit()
def todo_test_queue(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.queue:
# This will load a music file and queue it. A queued music file will
# begin as soon as the current music naturally ends. If the current
# music is ever stopped or changed, the queued song will be lost.
#
# The following example will play music by Bach six times, then play
# music by Mozart once:
#
# pygame.mixer.music.load('bach.ogg')
# pygame.mixer.music.play(5) # Plays six times, not five!
# pygame.mixer.music.queue('mozart.ogg')
self.fail()
def todo_test_stop(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.stop:
# Stops the music playback if it is currently playing.
self.fail()
def todo_test_rewind(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.rewind:
# Resets playback of the current music to the beginning.
self.fail()
def todo_test_get_pos(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.get_pos:
# This gets the number of milliseconds that the music has been playing
# for. The returned time only represents how long the music has been
# playing; it does not take into account any starting position
# offsets.
#
self.fail()
def todo_test_fadeout(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.fadeout:
# This will stop the music playback after it has been faded out over
# the specified time (measured in milliseconds).
#
# Note, that this function blocks until the music has faded out.
self.fail()
def todo_test_play(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.play:
# This will play the loaded music stream. If the music is already
# playing it will be restarted.
#
# The loops argument controls the number of repeats a music will play.
# play(5) will cause the music to played once, then repeated five
# times, for a total of six. If the loops is -1 then the music will
# repeat indefinitely.
#
# The starting position argument controls where in the music the song
# starts playing. The starting position is dependent on the format of
# music playing. MP3 and OGG use the position as time (in seconds).
# MOD music it is the pattern order number. Passing a startpos will
# raise a NotImplementedError if it cannot set the start position
#
self.fail()
def todo_test_load(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.load:
# This will load a music file and prepare it for playback. If a music
# stream is already playing it will be stopped. This does not start
# the music playing.
#
# Music can only be loaded from filenames, not python file objects
# like the other pygame loading functions.
#
self.fail()
def todo_test_get_volume(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.get_volume:
# Returns the current volume for the mixer. The value will be between
# 0.0 and 1.0.
#
self.fail()
def todo_test_set_endevent(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.set_endevent:
# This causes Pygame to signal (by means of the event queue) when the
# music is done playing. The argument determines the type of event
# that will be queued.
#
# The event will be queued every time the music finishes, not just the
# first time. To stop the event from being queued, call this method
# with no argument.
#
self.fail()
def todo_test_pause(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.pause:
# Temporarily stop playback of the music stream. It can be resumed
# with the pygame.mixer.music.unpause() function.
#
self.fail()
def todo_test_get_busy(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.get_busy:
# Returns True when the music stream is actively playing. When the
# music is idle this returns False.
#
self.fail()
def todo_test_get_endevent(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.get_endevent:
# Returns the event type to be sent every time the music finishes
# playback. If there is no endevent the function returns
# pygame.NOEVENT.
#
self.fail()
def todo_test_unpause(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.unpause:
# This will resume the playback of a music stream after it has been paused.
self.fail()
def todo_test_set_volume(self):
# __doc__ (as of 2008-08-02) for pygame.mixer_music.set_volume:
# Set the volume of the music playback. The value argument is between
# 0.0 and 1.0. When new music is loaded the volume is reset.
#
self.fail()
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/midi_test.py 0000644 0001750 0001750 00000041237 11226530200 017553 0 ustar vincent vincent if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests import test_utils
from pygame.tests.test_utils import test_not_implemented, unittest
else:
from test import test_utils
from test.test_utils import test_not_implemented, unittest
import pygame
import pygame.midi
import pygame.compat
from pygame.locals import *
import os
import sys
import time
class MidiTest( unittest.TestCase ):
def todo_test_poll(self):
# __doc__ (as of 2009-05-19) for pygame.midi.Input.poll:
# returns true if there's data, or false if not.
# Input.poll(): return Bool
#
# raises a MidiException on error.
self.fail()
def todo_test_read(self):
# __doc__ (as of 2009-05-19) for pygame.midi.Input.read:
# reads num_events midi events from the buffer.
# Input.read(num_events): return midi_event_list
#
# Reads from the Input buffer and gives back midi events.
# [[[status,data1,data2,data3],timestamp],
# [[status,data1,data2,data3],timestamp],...]
self.fail()
def test_MidiException(self):
# __doc__ (as of 2009-05-19) for pygame.midi.MidiException.message:
def raiseit():
raise pygame.midi.MidiException(0)
self.assertRaises(pygame.midi.MidiException, raiseit)
try:
raise pygame.midi.MidiException(0)
except pygame.midi.MidiException:
e = pygame.compat.geterror()
self.assertEqual(e.parameter, 0)
def test_note_off(self):
"""|tags: interactive|
"""
# __doc__ (as of 2009-05-19) for pygame.midi.Output.note_off:
# turns a midi note off. Note must be on.
# Output.note_off(note, velocity=None, channel = 0)
#
# Turn a note off in the output stream. The note must already
# be on for this to work correctly.
i = pygame.midi.get_default_output_id()
if i != -1:
o = pygame.midi.Output(i)
o.note_on(5, 30, 0)
o.note_off(5, 30, 0)
def test_note_on(self):
"""|tags: interactive|
"""
# __doc__ (as of 2009-05-19) for pygame.midi.Output.note_on:
# turns a midi note on. Note must be off.
# Output.note_on(note, velocity=None, channel = 0)
#
# Turn a note on in the output stream. The note must already
# be off for this to work correctly.
i = pygame.midi.get_default_output_id()
if i != -1:
o = pygame.midi.Output(i)
o.note_on(5, 30, 0)
def todo_test_set_instrument(self):
# __doc__ (as of 2009-05-19) for pygame.midi.Output.set_instrument:
# Select an instrument, with a value between 0 and 127.
# Output.set_instrument(instrument_id, channel = 0)
self.fail()
def todo_test_write(self):
# __doc__ (as of 2009-05-19) for pygame.midi.Output.write:
# writes a list of midi data to the Output.
# Output.write(data)
#
# writes series of MIDI information in the form of a list:
# write([[[status <,data1><,data2><,data3>],timestamp],
# [[status <,data1><,data2><,data3>],timestamp],...])
# fields are optional
# example: choose program change 1 at time 20000 and
# send note 65 with velocity 100 500 ms later.
# write([[[0xc0,0,0],20000],[[0x90,60,100],20500]])
# notes:
# 1. timestamps will be ignored if latency = 0.
# 2. To get a note to play immediately, send MIDI info with
# timestamp read from function Time.
# 3. understanding optional data fields:
# write([[[0xc0,0,0],20000]]) is equivalent to
# write([[[0xc0],20000]])
#
# Can send up to 1024 elements in your data list, otherwise an
# IndexError exception is raised.
self.fail()
def test_write_short(self):
"""|tags: interactive|
"""
# __doc__ (as of 2009-05-19) for pygame.midi.Output.write_short:
# write_short(status <, data1><, data2>)
# Output.write_short(status)
# Output.write_short(status, data1 = 0, data2 = 0)
#
# output MIDI information of 3 bytes or less.
# data fields are optional
# status byte could be:
# 0xc0 = program change
# 0x90 = note on
# etc.
# data bytes are optional and assumed 0 if omitted
# example: note 65 on with velocity 100
# write_short(0x90,65,100)
i = pygame.midi.get_default_output_id()
if i != -1:
o = pygame.midi.Output(i)
# put a note on, then off.
o.write_short(0x90,65,100)
o.write_short(0x80,65,100)
def test_Input(self):
"""|tags: interactive|
"""
i = pygame.midi.get_default_input_id()
if i != -1:
o = pygame.midi.Input(i)
del o
# try feeding it an input id.
i = pygame.midi.get_default_output_id()
# can handle some invalid input too.
self.assertRaises(pygame.midi.MidiException, pygame.midi.Input, i)
self.assertRaises(pygame.midi.MidiException, pygame.midi.Input, 9009)
self.assertRaises(pygame.midi.MidiException, pygame.midi.Input, -1)
self.assertRaises(TypeError, pygame.midi.Input,"1234")
self.assertRaises(OverflowError, pygame.midi.Input, pow(2,99))
def test_Output(self):
"""|tags: interactive|
"""
i = pygame.midi.get_default_output_id()
if i != -1:
o = pygame.midi.Output(i)
del o
# try feeding it an input id.
i = pygame.midi.get_default_input_id()
# can handle some invalid input too.
self.assertRaises(pygame.midi.MidiException, pygame.midi.Output, i)
self.assertRaises(pygame.midi.MidiException, pygame.midi.Output, 9009)
self.assertRaises(pygame.midi.MidiException, pygame.midi.Output, -1)
self.assertRaises(TypeError, pygame.midi.Output,"1234")
self.assertRaises(OverflowError, pygame.midi.Output, pow(2,99))
def todo_test_write_sys_ex(self):
# __doc__ (as of 2009-05-19) for pygame.midi.Output.write_sys_ex:
# writes a timestamped system-exclusive midi message.
# Output.write_sys_ex(when, msg)
#
# write_sys_ex(,)
#
# msg - can be a *list* or a *string*
# example:
# (assuming o is an onput MIDI stream)
# o.write_sys_ex(0,'\xF0\x7D\x10\x11\x12\x13\xF7')
# is equivalent to
# o.write_sys_ex(pygame.midi.Time,
# [0xF0,0x7D,0x10,0x11,0x12,0x13,0xF7])
self.fail()
def tearDown(self):
pygame.midi.quit()
def setUp(self):
pygame.midi.init()
def test_get_count(self):
# __doc__ (as of 2009-05-19) for pygame.midi.get_count:
# gets the number of devices.
# pygame.midi.get_count(): return num_devices
#
#
# Device ids range from 0 to get_count() -1
c = pygame.midi.get_count()
self.assertEqual(type(c), type(1))
self.failUnless(c >= 0)
def test_get_default_input_id(self):
# __doc__ (as of 2009-05-19) for pygame.midi.get_default_input_device_id:
# gets the device number of the default input device.
# pygame.midi.get_default_input_device_id(): return default_id
#
#
# Return the default device ID or -1 if there are no devices.
# The result can be passed to the Input()/Ouput() class.
#
# On the PC, the user can specify a default device by
# setting an environment variable. For example, to use device #1.
#
# set PM_RECOMMENDED_INPUT_DEVICE=1
#
# The user should first determine the available device ID by using
# the supplied application "testin" or "testout".
#
# In general, the registry is a better place for this kind of info,
# and with USB devices that can come and go, using integers is not
# very reliable for device identification. Under Windows, if
# PM_RECOMMENDED_OUTPUT_DEVICE (or PM_RECOMMENDED_INPUT_DEVICE) is
# *NOT* found in the environment, then the default device is obtained
# by looking for a string in the registry under:
# HKEY_LOCAL_MACHINE/SOFTWARE/PortMidi/Recommended_Input_Device
# and HKEY_LOCAL_MACHINE/SOFTWARE/PortMidi/Recommended_Output_Device
# for a string. The number of the first device with a substring that
# matches the string exactly is returned. For example, if the string
# in the registry is "USB", and device 1 is named
# "In USB MidiSport 1x1", then that will be the default
# input because it contains the string "USB".
#
# In addition to the name, get_device_info() returns "interf", which
# is the interface name. (The "interface" is the underlying software
# system or API used by PortMidi to access devices. Examples are
# MMSystem, DirectX (not implemented), ALSA, OSS (not implemented), etc.)
# At present, the only Win32 interface is "MMSystem", the only Linux
# interface is "ALSA", and the only Max OS X interface is "CoreMIDI".
# To specify both the interface and the device name in the registry,
# separate the two with a comma and a space, e.g.:
# MMSystem, In USB MidiSport 1x1
# In this case, the string before the comma must be a substring of
# the "interf" string, and the string after the space must be a
# substring of the "name" name string in order to match the device.
#
# Note: in the current release, the default is simply the first device
# (the input or output device with the lowest PmDeviceID).
c = pygame.midi.get_default_input_id()
# if there is a not None return make sure it is an int.
self.assertEqual(type(c), type(1))
self.failUnless(c >= 0 or c == -1)
def test_get_default_output_id(self):
# __doc__ (as of 2009-05-19) for pygame.midi.get_default_output_device_id:
# get the device number of the default output device.
# pygame.midi.get_default_output_device_id(): return default_id
#
#
# Return the default device ID or -1 if there are no devices.
# The result can be passed to the Input()/Ouput() class.
#
# On the PC, the user can specify a default device by
# setting an environment variable. For example, to use device #1.
#
# set PM_RECOMMENDED_OUTPUT_DEVICE=1
#
# The user should first determine the available device ID by using
# the supplied application "testin" or "testout".
#
# In general, the registry is a better place for this kind of info,
# and with USB devices that can come and go, using integers is not
# very reliable for device identification. Under Windows, if
# PM_RECOMMENDED_OUTPUT_DEVICE (or PM_RECOMMENDED_INPUT_DEVICE) is
# *NOT* found in the environment, then the default device is obtained
# by looking for a string in the registry under:
# HKEY_LOCAL_MACHINE/SOFTWARE/PortMidi/Recommended_Input_Device
# and HKEY_LOCAL_MACHINE/SOFTWARE/PortMidi/Recommended_Output_Device
# for a string. The number of the first device with a substring that
# matches the string exactly is returned. For example, if the string
# in the registry is "USB", and device 1 is named
# "In USB MidiSport 1x1", then that will be the default
# input because it contains the string "USB".
#
# In addition to the name, get_device_info() returns "interf", which
# is the interface name. (The "interface" is the underlying software
# system or API used by PortMidi to access devices. Examples are
# MMSystem, DirectX (not implemented), ALSA, OSS (not implemented), etc.)
# At present, the only Win32 interface is "MMSystem", the only Linux
# interface is "ALSA", and the only Max OS X interface is "CoreMIDI".
# To specify both the interface and the device name in the registry,
# separate the two with a comma and a space, e.g.:
# MMSystem, In USB MidiSport 1x1
# In this case, the string before the comma must be a substring of
# the "interf" string, and the string after the space must be a
# substring of the "name" name string in order to match the device.
#
# Note: in the current release, the default is simply the first device
# (the input or output device with the lowest PmDeviceID).
c = pygame.midi.get_default_output_id()
self.assertEqual(type(c), type(1))
self.failUnless(c >= 0 or c == -1)
def test_get_device_info(self):
# __doc__ (as of 2009-05-19) for pygame.midi.get_device_info:
# returns (interf, name, input, output, opened)
# pygame.midi.get_device_info(an_id): return (interf, name, input,
# output, opened)
#
#
# If the id is out of range, the function returns None.
an_id = pygame.midi.get_default_output_id()
if an_id != -1:
interf, name, input, output, opened = pygame.midi.get_device_info(an_id)
#print interf
#print name
#print input, output, opened
self.assertEqual(output, 1)
self.assertEqual(input, 0)
self.assertEqual(opened, 0)
an_in_id = pygame.midi.get_default_input_id()
if an_in_id != -1:
r = pygame.midi.get_device_info(an_in_id)
# if r is None, it means that the id is out of range.
try:
interf, name, input, output, opened = r
except TypeError:
raise Exception(repr(r))
self.assertEqual(output, 0)
self.assertEqual(input, 1)
self.assertEqual(opened, 0)
def test_init(self):
# __doc__ (as of 2009-05-19) for pygame.midi.init:
# initialize the midi module
# pygame.midi.init(): return None
#
# Call the initialisation function before using the midi module.
#
# It is safe to call this more than once.
pygame.midi.quit()
self.assertRaises(RuntimeError, pygame.midi.get_count)
# initialising many times should be fine.
pygame.midi.init()
pygame.midi.init()
pygame.midi.init()
pygame.midi.init()
def todo_test_midis2events(self):
# __doc__ (as of 2009-05-19) for pygame.midi.midis2events:
# converts midi events to pygame events
# pygame.midi.midis2events(midis, device_id): return [Event, ...]
#
# Takes a sequence of midi events and returns list of pygame events.
self.fail()
def test_quit(self):
# __doc__ (as of 2009-05-19) for pygame.midi.quit:
# uninitialize the midi module
# pygame.midi.quit(): return None
#
#
# Called automatically atexit if you don't call it.
#
# It is safe to call this function more than once.
# It is safe to call this more than once.
pygame.midi.quit()
pygame.midi.init()
pygame.midi.quit()
pygame.midi.quit()
pygame.midi.init()
pygame.midi.init()
pygame.midi.quit()
def test_time(self):
# __doc__ (as of 2009-05-19) for pygame.midi.time:
# returns the current time in ms of the PortMidi timer
# pygame.midi.time(): return time
t = pygame.midi.time()
self.assertEqual(type(t), type(1))
# should be close to 2-3... since the timer is just init'd.
self.failUnless(t >= 0 and t < 100)
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/mask_test.py 0000644 0001750 0001750 00000034050 11207055754 017576 0 ustar vincent vincent if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils import test_not_implemented, unittest
else:
from test.test_utils import test_not_implemented, unittest
import pygame
import pygame.mask
from pygame.locals import *
import random
def random_mask(size = (100,100)):
"""random_mask(size=(100,100)): return Mask
Create a mask of the given size, with roughly half the bits set at random."""
m = pygame.Mask(size)
for i in range(size[0] * size[1] // 2):
x, y = random.randint(0,size[0] - 1), random.randint(0, size[1] - 1)
m.set_at((x,y))
return m
def maskFromSurface(surface, threshold = 127):
mask = pygame.Mask(surface.get_size())
key = surface.get_colorkey()
if key:
for y in range(surface.get_height()):
for x in range(surface.get_width()):
if surface.get_at((x+0.1,y+0.1)) != key:
mask.set_at((x,y),1)
else:
for y in range(surface.get_height()):
for x in range (surface.get_width()):
if surface.get_at((x,y))[3] > threshold:
mask.set_at((x,y),1)
return mask
#pygame.init()
#pygame.display.set_mode((10,10))
class MaskTypeTest( unittest.TestCase ):
def assertMaskEquals(self, m1, m2):
self.assertEquals(m1.get_size(), m2.get_size())
for i in range(m1.get_size()[0]):
for j in range(m1.get_size()[1]):
self.assertEquals(m1.get_at((i,j)), m2.get_at((i,j)))
def todo_test_get_at(self):
# __doc__ (as of 2008-08-02) for pygame.mask.Mask.get_at:
# Mask.get_at((x,y)) -> int
# Returns nonzero if the bit at (x,y) is set.
#
# Coordinates start at (0,0) is top left - just like Surfaces.
self.fail()
def todo_test_get_size(self):
# __doc__ (as of 2008-08-02) for pygame.mask.Mask.get_size:
# Mask.get_size() -> width,height
# Returns the size of the mask.
self.fail()
def todo_test_overlap(self):
# __doc__ (as of 2008-08-02) for pygame.mask.Mask.overlap:
# Mask.overlap(othermask, offset) -> x,y
# Returns the point of intersection if the masks overlap with the
# given offset - or None if it does not overlap.
# The overlap tests uses the following offsets (which may be negative):
# +----+----------..
# |A | yoffset
# | +-+----------..
# +--|B
# |xoffset
# | |
# : :
self.fail()
def todo_test_overlap_area(self):
# __doc__ (as of 2008-08-02) for pygame.mask.Mask.overlap_area:
# Mask.overlap_area(othermask, offset) -> numpixels
# Returns the number of overlapping 'pixels'.
#
# You can see how many pixels overlap with the other mask given. This
# can be used to see in which direction things collide, or to see how
# much the two masks collide.
self.fail()
def todo_test_set_at(self):
# __doc__ (as of 2008-08-02) for pygame.mask.Mask.set_at:
# Mask.set_at((x,y),value)
# Sets the position in the mask given by x and y.
self.fail()
def test_mask_access( self ):
""" do the set_at, and get_at parts work correctly?
"""
m = pygame.Mask((10,10))
m.set_at((0,0), 1)
self.assertEqual(m.get_at((0,0)), 1)
m.set_at((9,0), 1)
self.assertEqual(m.get_at((9,0)), 1)
#s = pygame.Surface((10,10))
#s.set_at((1,0), (0, 0, 1, 255))
#self.assertEqual(s.get_at((1,0)), (0, 0, 1, 255))
#s.set_at((-1,0), (0, 0, 1, 255))
# out of bounds, should get IndexError
self.assertRaises(IndexError, lambda : m.get_at((-1,0)) )
self.assertRaises(IndexError, lambda : m.set_at((-1,0), 1) )
self.assertRaises(IndexError, lambda : m.set_at((10,0), 1) )
self.assertRaises(IndexError, lambda : m.set_at((0,10), 1) )
def test_drawing(self):
""" Test fill, clear, invert, draw, erase
"""
m = pygame.Mask((100,100))
self.assertEqual(m.count(), 0)
m.fill()
self.assertEqual(m.count(), 10000)
m2 = pygame.Mask((10,10))
m2.fill()
m.erase(m2, (50,50))
self.assertEqual(m.count(), 9900)
m.invert()
self.assertEqual(m.count(), 100)
m.draw(m2, (0,0))
self.assertEqual(m.count(), 200)
m.clear()
self.assertEqual(m.count(), 0)
def test_outline(self):
"""
"""
m = pygame.Mask((20,20))
self.assertEqual(m.outline(), [])
m.set_at((10,10), 1)
self.assertEqual(m.outline(), [(10,10)])
m.set_at((10,12), 1)
self.assertEqual(m.outline(10), [(10,10)])
m.set_at((11,11), 1)
self.assertEqual(m.outline(), [(10,10), (11,11), (10,12), (11,11), (10,10)])
self.assertEqual(m.outline(2), [(10,10), (10,12), (10,10)])
#TODO: Test more corner case outlines.
def test_convolve__size(self):
sizes = [(1,1), (31,31), (32,32), (100,100)]
for s1 in sizes:
m1 = pygame.Mask(s1)
for s2 in sizes:
m2 = pygame.Mask(s2)
o = m1.convolve(m2)
for i in (0,1):
self.assertEquals(o.get_size()[i], m1.get_size()[i] + m2.get_size()[i] - 1)
def test_convolve__point_identities(self):
"""Convolving with a single point is the identity, while convolving a point with something flips it."""
m = random_mask((100,100))
k = pygame.Mask((1,1))
k.set_at((0,0))
self.assertMaskEquals(m,m.convolve(k))
self.assertMaskEquals(m,k.convolve(k.convolve(m)))
def test_convolve__with_output(self):
"""checks that convolution modifies only the correct portion of the output"""
m = random_mask((10,10))
k = pygame.Mask((2,2))
k.set_at((0,0))
o = pygame.Mask((50,50))
test = pygame.Mask((50,50))
m.convolve(k,o)
test.draw(m,(1,1))
self.assertMaskEquals(o, test)
o.clear()
test.clear()
m.convolve(k,o, (10,10))
test.draw(m,(11,11))
self.assertMaskEquals(o, test)
def test_convolve__out_of_range(self):
full = pygame.Mask((2,2))
full.fill()
self.assertEquals(full.convolve(full, None, ( 0, 3)).count(), 0)
self.assertEquals(full.convolve(full, None, ( 0, 2)).count(), 3)
self.assertEquals(full.convolve(full, None, (-2, -2)).count(), 1)
self.assertEquals(full.convolve(full, None, (-3, -3)).count(), 0)
def test_convolve(self):
"""Tests the definition of convolution"""
m1 = random_mask((100,100))
m2 = random_mask((100,100))
conv = m1.convolve(m2)
for i in range(conv.get_size()[0]):
for j in range(conv.get_size()[1]):
self.assertEquals(conv.get_at((i,j)) == 0, m1.overlap(m2, (i - 99, j - 99)) is None)
def test_connected_components(self):
"""
"""
m = pygame.Mask((10,10))
self.assertEquals(repr(m.connected_components()), "[]")
comp = m.connected_component()
self.assertEquals(m.count(), comp.count())
m.set_at((0,0), 1)
m.set_at((1,1), 1)
comp = m.connected_component()
comps = m.connected_components()
comps1 = m.connected_components(1)
comps2 = m.connected_components(2)
comps3 = m.connected_components(3)
self.assertEquals(comp.count(), comps[0].count())
self.assertEquals(comps1[0].count(), 2)
self.assertEquals(comps2[0].count(), 2)
self.assertEquals(repr(comps3), "[]")
m.set_at((9, 9), 1)
comp = m.connected_component()
comp1 = m.connected_component((1, 1))
comp2 = m.connected_component((2, 2))
comps = m.connected_components()
comps1 = m.connected_components(1)
comps2 = m.connected_components(2)
comps3 = m.connected_components(3)
self.assertEquals(comp.count(), 2)
self.assertEquals(comp1.count(), 2)
self.assertEquals(comp2.count(), 0)
self.assertEquals(len(comps), 2)
self.assertEquals(len(comps1), 2)
self.assertEquals(len(comps2), 1)
self.assertEquals(len(comps3), 0)
def test_get_bounding_rects(self):
"""
"""
m = pygame.Mask((10,10))
m.set_at((0,0), 1)
m.set_at((1,0), 1)
m.set_at((0,1), 1)
m.set_at((0,3), 1)
m.set_at((3,3), 1)
r = m.get_bounding_rects()
self.assertEquals(repr(r), "[, , ]")
#1100
#1111
m = pygame.Mask((4,2))
m.set_at((0,0), 1)
m.set_at((1,0), 1)
m.set_at((2,0), 0)
m.set_at((3,0), 0)
m.set_at((0,1), 1)
m.set_at((1,1), 1)
m.set_at((2,1), 1)
m.set_at((3,1), 1)
r = m.get_bounding_rects()
self.assertEquals(repr(r), "[]")
#00100
#01110
#00100
m = pygame.Mask((5,3))
m.set_at((0,0), 0)
m.set_at((1,0), 0)
m.set_at((2,0), 1)
m.set_at((3,0), 0)
m.set_at((4,0), 0)
m.set_at((0,1), 0)
m.set_at((1,1), 1)
m.set_at((2,1), 1)
m.set_at((3,1), 1)
m.set_at((4,1), 0)
m.set_at((0,2), 0)
m.set_at((1,2), 0)
m.set_at((2,2), 1)
m.set_at((3,2), 0)
m.set_at((4,2), 0)
r = m.get_bounding_rects()
self.assertEquals(repr(r), "[]")
#00010
#00100
#01000
m = pygame.Mask((5,3))
m.set_at((0,0), 0)
m.set_at((1,0), 0)
m.set_at((2,0), 0)
m.set_at((3,0), 1)
m.set_at((4,0), 0)
m.set_at((0,1), 0)
m.set_at((1,1), 0)
m.set_at((2,1), 1)
m.set_at((3,1), 0)
m.set_at((4,1), 0)
m.set_at((0,2), 0)
m.set_at((1,2), 1)
m.set_at((2,2), 0)
m.set_at((3,2), 0)
m.set_at((4,2), 0)
r = m.get_bounding_rects()
self.assertEquals(repr(r), "[]")
#00011
#11111
m = pygame.Mask((5,2))
m.set_at((0,0), 0)
m.set_at((1,0), 0)
m.set_at((2,0), 0)
m.set_at((3,0), 1)
m.set_at((4,0), 1)
m.set_at((0,1), 1)
m.set_at((1,1), 1)
m.set_at((2,1), 1)
m.set_at((3,1), 1)
m.set_at((3,1), 1)
r = m.get_bounding_rects()
#TODO: this should really make one bounding rect.
#self.assertEquals(repr(r), "[]")
class MaskModuleTest(unittest.TestCase):
def test_from_surface(self):
""" Does the mask.from_surface() work correctly?
"""
mask_from_surface = pygame.mask.from_surface
surf = pygame.Surface((70,70), SRCALPHA, 32)
surf.fill((255,255,255,255))
amask = pygame.mask.from_surface(surf)
#amask = mask_from_surface(surf)
self.assertEqual(amask.get_at((0,0)), 1)
self.assertEqual(amask.get_at((66,1)), 1)
self.assertEqual(amask.get_at((69,1)), 1)
surf.set_at((0,0), (255,255,255,127))
surf.set_at((1,0), (255,255,255,128))
surf.set_at((2,0), (255,255,255,0))
surf.set_at((3,0), (255,255,255,255))
amask = mask_from_surface(surf)
self.assertEqual(amask.get_at((0,0)), 0)
self.assertEqual(amask.get_at((1,0)), 1)
self.assertEqual(amask.get_at((2,0)), 0)
self.assertEqual(amask.get_at((3,0)), 1)
surf.fill((255,255,255,0))
amask = mask_from_surface(surf)
self.assertEqual(amask.get_at((0,0)), 0)
#TODO: test a color key surface.
def test_from_threshold(self):
""" Does mask.from_threshold() work correctly?
"""
a = [16, 24, 32]
for i in a:
surf = pygame.surface.Surface((70,70), 0, i)
surf.fill((100,50,200),(20,20,20,20))
mask = pygame.mask.from_threshold(surf,(100,50,200,255),(10,10,10,255))
self.assertEqual(mask.count(), 400)
self.assertEqual(mask.get_bounding_rects(), [pygame.Rect((20,20,20,20))])
for i in a:
surf = pygame.surface.Surface((70,70), 0, i)
surf2 = pygame.surface.Surface((70,70), 0, i)
surf.fill((100,100,100))
surf2.fill((150,150,150))
surf2.fill((100,100,100), (40,40,10,10))
mask = pygame.mask.from_threshold(surf, (0,0,0,0), (10,10,10,255), surf2)
self.assertEqual(mask.count(), 100)
self.assertEqual(mask.get_bounding_rects(), [pygame.Rect((40,40,10,10))])
if __name__ == '__main__':
if 1:
unittest.main()
else:
mask_from_surface = maskFromSurface
surf = pygame.Surface((70,70), SRCALPHA, 32)
#surf = surf.convert_alpha()
surf.set_at((0,0), (255,255,255,0))
print (surf.get_at((0,0)))
print ("asdf")
print (surf)
pygame-1.9.1release/test/key_test.py 0000644 0001750 0001750 00000011605 11207055754 017434 0 ustar vincent vincent if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils import test_not_implemented, unittest
else:
from test.test_utils import test_not_implemented, unittest
import pygame
import os
class KeyModuleTest(unittest.TestCase):
def test_import(self):
'does it import'
import pygame.key
def todo_test_get_focused(self):
# __doc__ (as of 2008-08-02) for pygame.key.get_focused:
# pygame.key.get_focused(): return bool
# true if the display is receiving keyboard input from the system
#
# This is true when the display window has keyboard focus from the
# system. If the display needs to ensure it does not lose keyboard
# focus, it can use pygame.event.set_grab() to grab all input.
#
self.fail()
def todo_test_get_mods(self):
# __doc__ (as of 2008-08-02) for pygame.key.get_mods:
# pygame.key.get_mods(): return int
# determine which modifier keys are being held
#
# Returns a single integer representing a bitmask of all the modifier
# keys being held. Using bitwise operators you can test if specific
# shift keys are pressed, the state of the capslock button, and more.
#
self.fail()
def todo_test_get_pressed(self):
# __doc__ (as of 2008-08-02) for pygame.key.get_pressed:
# pygame.key.get_pressed(): return bools
# get the state of all keyboard buttons
#
# Returns a sequence of boolean values representing the state of every
# key on the keyboard. Use the key constant values to index the array.
# A True value means the that button is pressed.
#
# Getting the list of pushed buttons with this function is not the
# proper way to handle text entry from the user. You have no way to
# know the order of keys pressed, and rapidly pushed keys can be
# completely unnoticed between two calls to pygame.key.get_pressed().
# There is also no way to translate these pushed keys into a fully
# translated character value. See the pygame.KEYDOWN events on the
# event queue for this functionality.
#
self.fail()
def todo_test_get_repeat(self):
# __doc__ (as of 2008-08-02) for pygame.key.get_repeat:
# pygame.key.get_repeat(): return (delay, interval)
# see how held keys are repeated
#
# When the keyboard repeat is enabled, keys that are held down will
# generate multiple pygame.KEYDOWN events. The delay is the number of
# milliseconds before the first repeated pygame.KEYDOWN will be sent.
# After that another pygame.KEYDOWN will be sent every interval
# milliseconds.
#
# When pygame is initialized the key repeat is disabled.
# New in pygame 1.8.
self.fail()
def todo_test_name(self):
# __doc__ (as of 2008-08-02) for pygame.key.name:
# pygame.key.name(key): return string
# get the name of a key identifier
#
# Get the descriptive name of the button from a keyboard button id constant.
self.fail()
def todo_test_set_mods(self):
# __doc__ (as of 2008-08-02) for pygame.key.set_mods:
# pygame.key.set_mods(int): return None
# temporarily set which modifier keys are pressed
#
# Create a bitmask of the modifier constants you want to impose on your program.
self.fail()
def todo_test_set_repeat(self):
# __doc__ (as of 2008-08-02) for pygame.key.set_repeat:
# pygame.key.set_repeat(): return None
# pygame.key.set_repeat(delay, interval): return None
# control how held keys are repeated
#
# When the keyboard repeat is enabled, keys that are held down will
# generate multiple pygame.KEYDOWN events. The delay is the number of
# milliseconds before the first repeated pygame.KEYDOWN will be sent.
# After that another pygame.KEYDOWN will be sent every interval
# milliseconds. If no arguments are passed the key repeat is disabled.
#
# When pygame is initialized the key repeat is disabled.
self.fail()
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/joystick_test.py 0000644 0001750 0001750 00000010005 11207055754 020474 0 ustar vincent vincent #################################### IMPORTS ###################################
if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils import test_not_implemented, unittest
else:
from test.test_utils import test_not_implemented, unittest
################################################################################
class JoystickTypeTest(unittest.TestCase):
def todo_test_Joystick(self):
# __doc__ (as of 2008-08-02) for pygame.joystick.Joystick:
# pygame.joystick.Joystick(id): return Joystick
# create a new Joystick object
#
# Create a new joystick to access a physical device. The id argument
# must be a value from 0 to pygame.joystick.get_count()-1.
#
# To access most of the Joystick methods, you'll need to init() the
# Joystick. This is separate from making sure the joystick module is
# initialized. When multiple Joysticks objects are created for the
# same physical joystick device (i.e., they have the same ID number),
# the state and values for those Joystick objects will be shared.
#
# The Joystick object allows you to get information about the types of
# controls on a joystick device. Once the device is initialized the
# Pygame event queue will start receiving events about its input.
#
# You can call the Joystick.get_name() and Joystick.get_id() functions
# without initializing the Joystick object.
#
self.fail()
class JoytickModuleTest(unittest.TestCase):
def todo_test_get_count(self):
# __doc__ (as of 2008-08-02) for pygame.joystick.get_count:
# pygame.joystick.get_count(): return count
# number of joysticks on the system
#
# Return the number of joystick devices on the system. The count will
# be 0 if there are no joysticks on the system.
#
# When you create Joystick objects using Joystick(id), you pass an
# integer that must be lower than this count.
#
self.fail()
def todo_test_get_init(self):
# __doc__ (as of 2008-08-02) for pygame.joystick.get_init:
# pygame.joystick.get_init(): return bool
# true if the joystick module is initialized
#
# Test if the pygame.joystick.init() function has been called.
self.fail()
def todo_test_init(self):
# __doc__ (as of 2008-08-02) for pygame.joystick.init:
# pygame.joystick.init(): return None
# initialize the joystick module
#
# This function is called automatically by pygame.init().
# It initializes the joystick module. This will scan the system for
# all joystick devices. The module must be initialized before any
# other functions will work.
#
# It is safe to call this function more than once.
self.fail()
def todo_test_quit(self):
# __doc__ (as of 2008-08-02) for pygame.joystick.quit:
# pygame.joystick.quit(): return None
# uninitialize the joystick module
#
# Uninitialize the joystick module. After you call this any existing
# joystick objects will no longer work.
#
# It is safe to call this function more than once.
self.fail()
################################################################################
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/image_test.py 0000644 0001750 0001750 00000027056 11207055754 017735 0 ustar vincent vincent if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils \
import test_not_implemented, example_path, unittest
else:
from test.test_utils \
import test_not_implemented, example_path, unittest
import pygame, pygame.image, pygame.pkgdata
from pygame.compat import xrange_, ord_
import os
import array
def test_magic(f, magic_hex):
""" tests a given file to see if the magic hex matches.
"""
data = f.read(len(magic_hex))
if len(data) != len(magic_hex):
return 0
for i in range(len(magic_hex)):
if magic_hex[i] != ord_(data[i]):
return 0
return 1
class ImageModuleTest( unittest.TestCase ):
def testLoadIcon(self):
""" see if we can load the pygame icon.
"""
f = pygame.pkgdata.getResource("pygame_icon.bmp")
self.assertEqual(f.mode, "rb")
surf = pygame.image.load_basic(f)
self.assertEqual(surf.get_at((0,0)),(5, 4, 5, 255))
self.assertEqual(surf.get_height(),32)
self.assertEqual(surf.get_width(),32)
def testLoadPNG(self):
""" see if we can load a png.
"""
f = example_path('data/alien1.png') # normalized
# f = os.path.join("examples", "data", "alien1.png")
surf = pygame.image.load(f)
f = open(f, 'rb')
# f = open(os.path.join("examples", "data", "alien1.png"), "rb")
surf = pygame.image.load(f)
def testLoadJPG(self):
""" see if we can load a jpg.
"""
f = example_path('data/alien1.jpg') # normalized
# f = os.path.join("examples", "data", "alien1.jpg")
surf = pygame.image.load(f)
f = open(f, "rb")
# f = open(os.path.join("examples", "data", "alien1.jpg"), "rb")
surf = pygame.image.load(f)
# surf = pygame.image.load(open(os.path.join("examples", "data", "alien1.jpg"), "rb"))
def test_save(self):
s = pygame.Surface((10,10))
s.fill((23,23,23))
magic_hex = {}
magic_hex['jpg'] = [0xff, 0xd8, 0xff, 0xe0]
magic_hex['png'] = [0x89 ,0x50 ,0x4e ,0x47]
magic_hex['tga'] = [0x0, 0x0, 0xa]
magic_hex['bmp'] = [0x42, 0x4d]
formats = ["jpg", "png", "tga", "bmp"]
# uppercase too... JPG
formats = formats + [x.upper() for x in formats]
for fmt in formats:
try:
temp_filename = "%s.%s" % ("tmpimg", fmt)
pygame.image.save(s, temp_filename)
# test the magic numbers at the start of the file to ensure they are saved
# as the correct file type.
self.assertEqual((1, fmt), (test_magic(open(temp_filename, "rb"), magic_hex[fmt.lower()]), fmt))
# load the file to make sure it was saved correctly.
# Note load can load a jpg saved with a .png file name.
s2 = pygame.image.load(temp_filename)
#compare contents, might only work reliably for png...
# but because it's all one color it seems to work with jpg.
self.assertEquals(s2.get_at((0,0)), s.get_at((0,0)))
finally:
#clean up the temp file, comment out to leave tmp file after run.
os.remove(temp_filename)
pass
def assertPremultipliedAreEqual(self, string1, string2, source_string):
self.assertEqual(len(string1), len(string2))
block_size = 20
if string1 != string2:
for block_start in xrange_(0, len(string1), block_size):
block_end = min(block_start + block_size, len(string1))
block1 = string1[block_start:block_end]
block2 = string2[block_start:block_end]
if block1 != block2:
source_block = source_string[block_start:block_end]
msg = "string difference in %d to %d of %d:\n%s\n%s\nsource:\n%s" % (block_start, block_end, len(string1), block1.encode("hex"), block2.encode("hex"), source_block.encode("hex"))
self.fail(msg)
def test_to_string__premultiplied(self):
""" test to make sure we can export a surface to a premultiplied alpha string
"""
def convertRGBAtoPremultiplied(surface_to_modify):
for x in xrange_(surface_to_modify.get_width()):
for y in xrange_(surface_to_modify.get_height()):
color = surface_to_modify.get_at((x, y))
premult_color = (color[0]*color[3]/255,
color[1]*color[3]/255,
color[2]*color[3]/255,
color[3])
surface_to_modify.set_at((x, y), premult_color)
test_surface = pygame.Surface((256, 256), pygame.SRCALPHA, 32)
for x in xrange_(test_surface.get_width()):
for y in xrange_(test_surface.get_height()):
i = x + y*test_surface.get_width()
test_surface.set_at((x,y), ((i*7) % 256, (i*13) % 256, (i*27) % 256, y))
premultiplied_copy = test_surface.copy()
convertRGBAtoPremultiplied(premultiplied_copy)
self.assertPremultipliedAreEqual(pygame.image.tostring(test_surface, "RGBA_PREMULT"),
pygame.image.tostring(premultiplied_copy, "RGBA"),
pygame.image.tostring(test_surface, "RGBA"))
self.assertPremultipliedAreEqual(pygame.image.tostring(test_surface, "ARGB_PREMULT"),
pygame.image.tostring(premultiplied_copy, "ARGB"),
pygame.image.tostring(test_surface, "ARGB"))
no_alpha_surface = pygame.Surface((256, 256), 0, 24)
self.assertRaises(ValueError, pygame.image.tostring, no_alpha_surface, "RGBA_PREMULT")
def test_fromstring__and_tostring(self):
""" see if fromstring, and tostring methods are symmetric.
"""
def AreSurfacesIdentical(surf_a, surf_b):
if surf_a.get_width() != surf_b.get_width() or surf_a.get_height() != surf_b.get_height():
return False
for y in xrange_(surf_a.get_height()):
for x in xrange_(surf_b.get_width()):
if surf_a.get_at((x,y)) != surf_b.get_at((x,y)):
return False
return True
####################################################################
def RotateRGBAtoARGB(str_buf):
byte_buf = array.array("B", str_buf)
num_quads = len(byte_buf)//4
for i in xrange_(num_quads):
alpha = byte_buf[i*4 + 3]
byte_buf[i*4 + 3] = byte_buf[i*4 + 2]
byte_buf[i*4 + 2] = byte_buf[i*4 + 1]
byte_buf[i*4 + 1] = byte_buf[i*4 + 0]
byte_buf[i*4 + 0] = alpha
return byte_buf.tostring()
####################################################################
def RotateARGBtoRGBA(str_buf):
byte_buf = array.array("B", str_buf)
num_quads = len(byte_buf)//4
for i in xrange_(num_quads):
alpha = byte_buf[i*4 + 0]
byte_buf[i*4 + 0] = byte_buf[i*4 + 1]
byte_buf[i*4 + 1] = byte_buf[i*4 + 2]
byte_buf[i*4 + 2] = byte_buf[i*4 + 3]
byte_buf[i*4 + 3] = alpha
return byte_buf.tostring()
####################################################################
test_surface = pygame.Surface((64, 256), flags=pygame.SRCALPHA, depth=32)
for i in xrange_(256):
for j in xrange_(16):
intensity = j*16 + 15
test_surface.set_at((j + 0, i), (intensity, i, i, i))
test_surface.set_at((j + 16, i), (i, intensity, i, i))
test_surface.set_at((j + 32, i), (i, i, intensity, i))
test_surface.set_at((j + 32, i), (i, i, i, intensity))
self.assert_(AreSurfacesIdentical(test_surface, test_surface))
rgba_buf = pygame.image.tostring(test_surface, "RGBA")
rgba_buf = RotateARGBtoRGBA(RotateRGBAtoARGB(rgba_buf))
test_rotate_functions = pygame.image.fromstring(rgba_buf, test_surface.get_size(), "RGBA")
self.assert_(AreSurfacesIdentical(test_surface, test_rotate_functions))
rgba_buf = pygame.image.tostring(test_surface, "RGBA")
argb_buf = RotateRGBAtoARGB(rgba_buf)
test_from_argb_string = pygame.image.fromstring(argb_buf, test_surface.get_size(), "ARGB")
self.assert_(AreSurfacesIdentical(test_surface, test_from_argb_string))
#"ERROR: image.fromstring with ARGB failed"
argb_buf = pygame.image.tostring(test_surface, "ARGB")
rgba_buf = RotateARGBtoRGBA(argb_buf)
test_to_argb_string = pygame.image.fromstring(rgba_buf, test_surface.get_size(), "RGBA")
self.assert_(AreSurfacesIdentical(test_surface, test_to_argb_string))
#"ERROR: image.tostring with ARGB failed"
argb_buf = pygame.image.tostring(test_surface, "ARGB")
test_to_from_argb_string = pygame.image.fromstring(argb_buf, test_surface.get_size(), "ARGB")
self.assert_(AreSurfacesIdentical(test_surface, test_to_from_argb_string))
#"ERROR: image.fromstring and image.tostring with ARGB are not symmetric"
def todo_test_frombuffer(self):
# __doc__ (as of 2008-08-02) for pygame.image.frombuffer:
# pygame.image.frombuffer(string, size, format): return Surface
# create a new Surface that shares data inside a string buffer
#
# Create a new Surface that shares pixel data directly from the string
# buffer. This method takes the same arguments as
# pygame.image.fromstring(), but is unable to vertically flip the
# source data.
#
# This will run much faster than pygame.image.fromstring, since no
# pixel data must be allocated and copied.
self.fail()
def todo_test_get_extended(self):
# __doc__ (as of 2008-08-02) for pygame.image.get_extended:
# pygame.image.get_extended(): return bool
# test if extended image formats can be loaded
#
# If pygame is built with extended image formats this function will
# return True. It is still not possible to determine which formats
# will be available, but generally you will be able to load them all.
self.fail()
def todo_test_load_basic(self):
# __doc__ (as of 2008-08-02) for pygame.image.load_basic:
# pygame.image.load(filename): return Surface
# pygame.image.load(fileobj, namehint=): return Surface
# load new image from a file
self.fail()
def todo_test_load_extended(self):
# __doc__ (as of 2008-08-02) for pygame.image.load_extended:
# pygame module for image transfer
self.fail()
def todo_test_save_extended(self):
# __doc__ (as of 2008-08-02) for pygame.image.save_extended:
# pygame module for image transfer
self.fail()
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/image__save_gl_surface_test.py 0000644 0001750 0001750 00000003274 11207055754 023300 0 ustar vincent vincent if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests import test_utils
from pygame.tests.test_utils import unittest
else:
from test import test_utils
from test.test_utils import unittest
import pygame, os
from pygame.locals import *
class GL_ImageSave(unittest.TestCase):
def test_image_save_works_with_opengl_surfaces(self):
"|tags:display,slow|"
pygame.display.init()
screen = pygame.display.set_mode((640,480), OPENGL|DOUBLEBUF)
pygame.display.flip()
tmp_dir = test_utils.get_tmp_dir()
# Try the imageext module.
tmp_file = os.path.join(tmp_dir, "opengl_save_surface_test.png")
pygame.image.save(screen, tmp_file)
self.assert_(os.path.exists(tmp_file))
os.remove(tmp_file)
# Only test the image module.
tmp_file = os.path.join(tmp_dir, "opengl_save_surface_test.bmp")
pygame.image.save(screen, tmp_file)
self.assert_(os.path.exists(tmp_file))
os.remove(tmp_file)
# stops tonnes of tmp dirs building up in trunk dir
os.rmdir(tmp_dir)
pygame.display.quit()
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/gfxdraw_test.py 0000644 0001750 0001750 00000072576 11210364127 020313 0 ustar vincent vincent if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils import unittest
else:
from test.test_utils import unittest
import pygame
import pygame.gfxdraw
from pygame.locals import *
def intensity(c, i):
"""Return color c changed by intensity i
For 0 <= i <= 127 the color is a shade, with 0 being black, 127 being the
unaltered color.
For 128 <= i <= 255 the color is a tint, with 255 being white, 128 the
unaltered color.
"""
r, g, b = c[0:3]
if 0 <= i <= 127:
# Darken
return ((r * i) // 127, (g * i) // 127, (b * i) // 127)
# Lighten
return (r + ((255 - r) * (255 - i)) // 127,
g + ((255 - g) * (255 - i)) // 127,
b + ((255 - b) * (255 - i)) // 127)
class GfxdrawDefaultTest( unittest.TestCase ):
is_started = False
foreground_color = (128, 64, 8)
background_color = (255, 255, 255)
def make_palette(base_color):
"""Return color palette that is various intensities of base_color"""
# Need this function for Python 3.x so the base_color
# is within the scope of the list comprehension.
return [intensity(base_color, i) for i in range(0, 256)]
default_palette = make_palette(foreground_color)
default_size = (100, 100)
def check_at(self, surf, posn, color):
sc = surf.get_at(posn)
fail_msg = ("%s != %s at %s, bitsize: %i, flags: %i, masks: %s" %
(sc, color, posn, surf.get_bitsize(), surf.get_flags(),
surf.get_masks()))
self.failUnlessEqual(sc, color, fail_msg)
def check_not_at(self, surf, posn, color):
sc = surf.get_at(posn)
fail_msg = ("%s != %s at %s, bitsize: %i, flags: %i, masks: %s" %
(sc, color, posn, surf.get_bitsize(), surf.get_flags(),
surf.get_masks()))
self.failIfEqual(sc, color, fail_msg)
def setUp(self):
Surface = pygame.Surface
size = self.default_size
palette = self.default_palette
if not self.is_started:
# Necessary for Surface.set_palette.
pygame.init()
pygame.display.set_mode((1, 1))
# Create test surfaces
self.surfaces = [Surface(size, 0, 8),
Surface(size, 0, 16),
Surface(size, 0, 24),
Surface(size, 0, 32),
Surface(size, SRCALPHA, 16),
Surface(size, SRCALPHA, 32)]
self.surfaces[0].set_palette(palette)
# Special pixel formats
for i in range(1, 6):
s = self.surfaces[i]
flags = s.get_flags()
bitsize = s.get_bitsize()
masks = s.get_masks()
if flags:
masks = (masks[1], masks[2], masks[3], masks[0])
else:
masks = (masks[1], masks[2], masks[0], masks[3])
self.surfaces.append(Surface(size, flags, bitsize, masks))
for surf in self.surfaces:
surf.fill(self.background_color)
def test_pixel(self):
"""pixel(surface, x, y, color): return None"""
fg = self.foreground_color
bg = self.background_color
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.pixel(surf, 2, 2, fg)
for x in range(1, 4):
for y in range(1, 4):
if x == 2 and y == 2:
self.check_at(surf, (x, y), fg_adjusted)
else:
self.check_at(surf, (x, y), bg_adjusted)
def test_hline(self):
"""hline(surface, x1, x2, y, color): return None"""
fg = self.foreground_color
bg = self.background_color
startx = 10
stopx = 80
y = 50
fg_test_points = [(startx, y), (stopx, y), ((stopx - startx) // 2, y)]
bg_test_points = [(startx - 1, y), (stopx + 1, y),
(startx, y - 1), (startx, y + 1),
(stopx, y - 1), (stopx, y + 1)]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.hline(surf, startx, stopx, y, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_vline(self):
"""vline(surface, x, y1, y2, color): return None"""
fg = self.foreground_color
bg = self.background_color
x = 50
starty = 10
stopy = 80
fg_test_points = [(x, starty), (x, stopy), (x, (stopy - starty) // 2)]
bg_test_points = [(x, starty - 1), (x, stopy + 1),
(x - 1, starty), (x + 1, starty),
(x - 1, stopy), (x + 1, stopy)]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.vline(surf, x, starty, stopy, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_rectangle(self):
"""rectangle(surface, rect, color): return None"""
fg = self.foreground_color
bg = self.background_color
rect = pygame.Rect(10, 15, 55, 62)
rect_tuple = tuple(rect)
fg_test_points = [rect.topleft,
(rect.right - 1, rect.top),
(rect.left, rect.bottom - 1),
(rect.right - 1, rect.bottom - 1)]
bg_test_points = [(rect.left - 1, rect.top - 1),
(rect.left + 1, rect.top + 1),
(rect.right, rect.top - 1),
(rect.right - 2, rect.top + 1),
(rect.left - 1, rect.bottom),
(rect.left + 1, rect.bottom - 2),
(rect.right, rect.bottom),
(rect.right - 2, rect.bottom - 2)]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.rectangle(surf, rect, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
surf.fill(bg)
pygame.gfxdraw.rectangle(surf, rect_tuple, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_box(self):
"""box(surface, rect, color): return None"""
fg = self.foreground_color
bg = self.background_color
rect = pygame.Rect(10, 15, 55, 62)
rect_tuple = tuple(rect)
fg_test_points = [rect.topleft,
(rect.left + 1, rect.top + 1),
(rect.right - 1, rect.top),
(rect.right - 2, rect.top + 1),
(rect.left, rect.bottom - 1),
(rect.left + 1, rect.bottom - 2),
(rect.right - 1, rect.bottom - 1),
(rect.right - 2, rect.bottom - 2)]
bg_test_points = [(rect.left - 1, rect.top - 1),
(rect.right, rect.top - 1),
(rect.left - 1, rect.bottom),
(rect.right, rect.bottom)]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.box(surf, rect, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
surf.fill(bg)
pygame.gfxdraw.box(surf, rect_tuple, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_line(self):
"""line(surface, x1, y1, x2, y2, color): return None"""
fg = self.foreground_color
bg = self.background_color
x1 = 10
y1 = 15
x2 = 92
y2 = 77
fg_test_points = [(x1, y1), (x2, y2)]
bg_test_points = [(x1 - 1, y1), (x1, y1 - 1), (x1 - 1, y1 - 1),
(x2 + 1, y2), (x2, y2 + 1), (x2 + 1, y2 + 1)]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.line(surf, x1, y1, x2, y2, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_circle(self):
"""circle(surface, x, y, r, color): return None"""
fg = self.foreground_color
bg = self.background_color
x = 45
y = 40
r = 30
fg_test_points = [(x, y - r),
(x, y + r),
(x - r, y),
(x + r, y)]
bg_test_points = [(x, y),
(x, y - r + 1),
(x, y - r - 1),
(x, y + r + 1),
(x, y + r - 1),
(x - r - 1, y),
(x - r + 1, y),
(x + r + 1, y),
(x + r - 1, y)]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.circle(surf, x, y, r, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_arc(self):
"""arc(surface, x, y, r, start, end, color): return None"""
fg = self.foreground_color
bg = self.background_color
x = 45
y = 40
r = 30
start = 0 # +x direction, but not (x + r, y) (?)
end = 90 # -y direction, including (x, y + r)
fg_test_points = [(x, y + r), (x + r, y + 1)]
bg_test_points = [(x, y),
(x, y - r),
(x - r, y),
(x, y + r + 1),
(x, y + r - 1),
(x - 1, y + r),
(x + r + 1, y),
(x + r - 1, y),
(x + r, y)]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.arc(surf, x, y, r, start, end, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_aacircle(self):
"""aacircle(surface, x, y, r, color): return None"""
fg = self.foreground_color
bg = self.background_color
x = 45
y = 40
r = 30
fg_test_points = [(x, y - r),
(x, y + r),
(x - r, y),
(x + r, y)]
bg_test_points = [(x, y),
(x, y - r + 1),
(x, y - r - 1),
(x, y + r + 1),
(x, y + r - 1),
(x - r - 1, y),
(x - r + 1, y),
(x + r + 1, y),
(x + r - 1, y)]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.aacircle(surf, x, y, r, fg)
for posn in fg_test_points:
self.check_not_at(surf, posn, bg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_filled_circle(self):
"""filled_circle(surface, x, y, r, color): return None"""
fg = self.foreground_color
bg = self.background_color
x = 45
y = 40
r = 30
fg_test_points = [(x, y - r),
(x, y - r + 1),
(x, y + r),
(x, y + r - 1),
(x - r, y),
(x - r + 1, y),
(x + r, y),
(x + r - 1, y),
(x, y)]
bg_test_points = [(x, y - r - 1),
(x, y + r + 1),
(x - r - 1, y),
(x + r + 1, y)]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.filled_circle(surf, x, y, r, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_ellipse(self):
"""ellipse(surface, x, y, rx, ry, color): return None"""
fg = self.foreground_color
bg = self.background_color
x = 45
y = 40
rx = 30
ry = 35
fg_test_points = [(x, y - ry),
(x, y + ry),
(x - rx, y),
(x + rx, y)]
bg_test_points = [(x, y),
(x, y - ry + 1),
(x, y - ry - 1),
(x, y + ry + 1),
(x, y + ry - 1),
(x - rx - 1, y),
(x - rx + 1, y),
(x + rx + 1, y),
(x + rx - 1, y)]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.ellipse(surf, x, y, rx, ry, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_aaellipse(self):
"""aaellipse(surface, x, y, rx, ry, color): return None"""
fg = self.foreground_color
bg = self.background_color
x = 45
y = 40
rx = 30
ry = 35
fg_test_points = [(x, y - ry),
(x, y + ry),
(x - rx, y),
(x + rx, y)]
bg_test_points = [(x, y),
(x, y - ry + 1),
(x, y - ry - 1),
(x, y + ry + 1),
(x, y + ry - 1),
(x - rx - 1, y),
(x - rx + 1, y),
(x + rx + 1, y),
(x + rx - 1, y)]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.aaellipse(surf, x, y, rx, ry, fg)
for posn in fg_test_points:
self.check_not_at(surf, posn, bg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_filled_ellipse(self):
"""filled_ellipse(surface, x, y, rx, ry, color): return None"""
fg = self.foreground_color
bg = self.background_color
x = 45
y = 40
rx = 30
ry = 35
fg_test_points = [(x, y - ry),
(x, y - ry + 1),
(x, y + ry),
(x, y + ry - 1),
(x - rx, y),
(x - rx + 1, y),
(x + rx, y),
(x + rx - 1, y),
(x, y)]
bg_test_points = [(x, y - ry - 1),
(x, y + ry + 1),
(x - rx - 1, y),
(x + rx + 1, y)]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.filled_ellipse(surf, x, y, rx, ry, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_pie(self):
"""pie(surface, x, y, r, start, end, color): return None"""
fg = self.foreground_color
bg = self.background_color
x = 45
y = 40
r = 30
start = 0 # +x direction, including (x + r, y)
end = 90 # -y direction, but not (x, y + r) (?)
fg_test_points = [(x, y),
(x + 1, y),
(x, y + 1),
(x + r, y)]
bg_test_points = [(x - 1, y),
(x, y - 1),
(x - 1, y - 1),
(x + 1, y + 1),
(x + r + 1, y),
(x + r, y - 1),
(x, y + r)]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.pie(surf, x, y, r, start, end, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_trigon(self):
"""trigon(surface, x1, y1, x2, y2, x3, y3, color): return None"""
fg = self.foreground_color
bg = self.background_color
x1 = 10
y1 = 15
x2 = 92
y2 = 77
x3 = 20
y3 = 60
fg_test_points = [(x1, y1), (x2, y2), (x3, y3)]
bg_test_points = [(x1 - 1, y1 - 1),
(x2 + 1, y2 + 1),
(x3 - 1, y3 + 1),
(x1 + 10, y1 + 30)]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.trigon(surf, x1, y1, x2, y2, x3, y3, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_aatrigon(self):
"""aatrigon(surface, x1, y1, x2, y2, x3, y3, color): return None"""
fg = self.foreground_color
bg = self.background_color
x1 = 10
y1 = 15
x2 = 92
y2 = 77
x3 = 20
y3 = 60
fg_test_points = [(x1, y1), (x2, y2), (x3, y3)]
bg_test_points = [(x1 - 1, y1 - 1),
(x2 + 1, y2 + 1),
(x3 - 1, y3 + 1),
(x1 + 10, y1 + 30)]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.aatrigon(surf, x1, y1, x2, y2, x3, y3, fg)
for posn in fg_test_points:
self.check_not_at(surf, posn, bg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_filled_trigon(self):
"""filled_trigon(surface, x1, y1, x2, y2, x3, y3, color): return None"""
fg = self.foreground_color
bg = self.background_color
x1 = 10
y1 = 15
x2 = 92
y2 = 77
x3 = 20
y3 = 60
fg_test_points = [(x1, y1), (x2, y2), (x3, y3),
(x1 + 10, y1 + 30)]
bg_test_points = [(x1 - 1, y1 - 1),
(x2 + 1, y2 + 1),
(x3 - 1, y3 + 1)]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.filled_trigon(surf, x1, y1, x2, y2, x3, y3, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_polygon(self):
"""polygon(surface, points, color): return None"""
fg = self.foreground_color
bg = self.background_color
points = [(10, 80), (10, 15), (92, 25), (92, 80)]
fg_test_points = (points +
[(points[0][0], points[0][1] - 1),
(points[0][0] + 1, points[0][1]),
(points[3][0] - 1, points[3][1]),
(points[3][0], points[3][1] - 1),
(points[2][0], points[2][1] + 1)])
bg_test_points = [(points[0][0] - 1, points[0][1]),
(points[0][0], points[0][1] + 1),
(points[0][0] - 1, points[0][1] + 1),
(points[0][0] + 1, points[0][1] - 1),
(points[3][0] + 1, points[3][1]),
(points[3][0], points[3][1] + 1),
(points[3][0] + 1, points[3][1] + 1),
(points[3][0] - 1, points[3][1] - 1),
(points[2][0] + 1, points[2][1]),
(points[2][0] - 1, points[2][1] + 1),
(points[1][0] - 1, points[1][1]),
(points[1][0], points[1][1] - 1),
(points[1][0] - 1, points[1][1] - 1)]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.polygon(surf, points, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_aapolygon(self):
"""aapolygon(surface, points, color): return None"""
fg = self.foreground_color
bg = self.background_color
points = [(10, 80), (10, 15), (92, 25), (92, 80)]
fg_test_points = (points +
[(points[0][0], points[0][1] - 1),
(points[0][0] + 1, points[0][1]),
(points[3][0] - 1, points[3][1]),
(points[3][0], points[3][1] - 1),
(points[2][0], points[2][1] + 1)])
bg_test_points = [(points[0][0] - 1, points[0][1]),
(points[0][0], points[0][1] + 1),
(points[0][0] - 1, points[0][1] + 1),
(points[0][0] + 1, points[0][1] - 1),
(points[3][0] + 1, points[3][1]),
(points[3][0], points[3][1] + 1),
(points[3][0] + 1, points[3][1] + 1),
(points[3][0] - 1, points[3][1] - 1),
(points[2][0] + 1, points[2][1]),
(points[2][0] - 1, points[2][1] + 1),
(points[1][0] - 1, points[1][1]),
(points[1][0], points[1][1] - 1),
(points[1][0] - 1, points[1][1] - 1)]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.aapolygon(surf, points, fg)
for posn in fg_test_points:
self.check_not_at(surf, posn, bg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_filled_polygon(self):
"""filled_polygon(surface, points, color): return None"""
fg = self.foreground_color
bg = self.background_color
points = [(10, 80), (10, 15), (92, 25), (92, 80)]
fg_test_points = (points +
[(points[0][0], points[0][1] - 1),
(points[0][0] + 1, points[0][1]),
(points[0][0] + 1, points[0][1] - 1),
(points[3][0] - 1, points[3][1]),
(points[3][0], points[3][1] - 1),
(points[3][0] - 1, points[3][1] - 1),
(points[2][0], points[2][1] + 1),
(points[2][0] - 1, points[2][1] + 1)])
bg_test_points = [(points[0][0] - 1, points[0][1]),
(points[0][0], points[0][1] + 1),
(points[0][0] - 1, points[0][1] + 1),
(points[3][0] + 1, points[3][1]),
(points[3][0], points[3][1] + 1),
(points[3][0] + 1, points[3][1] + 1),
(points[2][0] + 1, points[2][1]),
(points[1][0] - 1, points[1][1]),
(points[1][0], points[1][1] - 1),
(points[1][0] - 1, points[1][1] - 1)]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.filled_polygon(surf, points, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
def test_textured_polygon(self):
"""textured_polygon(surface, points, texture, tx, ty): return None"""
w, h = self.default_size
fg = self.foreground_color
bg = self.background_color
tx = 0
ty = 0
texture = pygame.Surface((w + tx, h + ty), 0, 24)
texture.fill(fg, (0, 0, w, h))
points = [(10, 80), (10, 15), (92, 25), (92, 80)]
# Don't know how to really check this as boarder points may
# or may not be included in the textured polygon.
fg_test_points = [(points[1][0] + 30, points[1][1] + 40)]
bg_test_points = [(points[0][0] - 1, points[0][1]),
(points[0][0], points[0][1] + 1),
(points[0][0] - 1, points[0][1] + 1),
(points[3][0] + 1, points[3][1]),
(points[3][0], points[3][1] + 1),
(points[3][0] + 1, points[3][1] + 1),
(points[2][0] + 1, points[2][1]),
(points[1][0] - 1, points[1][1]),
(points[1][0], points[1][1] - 1),
(points[1][0] - 1, points[1][1] - 1)]
for surf in self.surfaces[1:]:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.textured_polygon(surf, points, texture, -tx, -ty)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
# Alpha blit to 8 bits-per-pixel surface forbidden.
texture = pygame.Surface(self.default_size, SRCALPHA, 32)
self.failUnlessRaises(ValueError,
pygame.gfxdraw.textured_polygon,
self.surfaces[0],
points,
texture, 0, 0)
def test_bezier(self):
"""bezier(surface, points, steps, color): return None"""
fg = self.foreground_color
bg = self.background_color
points = [(10, 50), (25, 15), (60, 80), (92, 30)]
fg_test_points = [points[0], points[3]]
bg_test_points = [(points[0][0] - 1, points[0][1]),
(points[3][0] + 1, points[3][1]),
(points[1][0], points[1][1] + 3),
(points[2][0], points[2][1] - 3)]
for surf in self.surfaces:
fg_adjusted = surf.unmap_rgb(surf.map_rgb(fg))
bg_adjusted = surf.unmap_rgb(surf.map_rgb(bg))
pygame.gfxdraw.bezier(surf, points, 30, fg)
for posn in fg_test_points:
self.check_at(surf, posn, fg_adjusted)
for posn in bg_test_points:
self.check_at(surf, posn, bg_adjusted)
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/font_test.py 0000644 0001750 0001750 00000033345 11210734730 017607 0 ustar vincent vincent import sys
import os
if __name__ == '__main__':
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils import test_not_implemented, unittest, \
geterror
else:
from test.test_utils import test_not_implemented, unittest, geterror
import pygame
class FontModuleTest( unittest.TestCase ):
def setUp(self):
pygame.font.init()
def tearDown(self):
pygame.font.quit()
def test_SysFont(self):
# Can only check that a font object is returned.
fonts = pygame.font.get_fonts()
o = pygame.font.SysFont(fonts[0], 20)
self.failUnless(isinstance(o, pygame.font.FontType))
o = pygame.font.SysFont(fonts[0], 20, italic=True)
self.failUnless(isinstance(o, pygame.font.FontType))
o = pygame.font.SysFont(fonts[0], 20, bold=True)
self.failUnless(isinstance(o, pygame.font.FontType))
o = pygame.font.SysFont('thisisnotafont', 20)
self.failUnless(isinstance(o, pygame.font.FontType))
def test_get_default_font(self):
self.failUnlessEqual(pygame.font.get_default_font(), 'freesansbold.ttf')
def test_get_fonts_returns_something(self):
fnts = pygame.font.get_fonts()
self.failUnless(fnts)
def test_get_fonts(self):
fnts = pygame.font.get_fonts()
if not fnts:
raise Exception(repr(fnts))
self.failUnless(fnts)
# strange python 2.x bug... if you assign to unicode,
# all sorts of weirdness happens.
if sys.version_info <= (3, 0, 0):
unicod = unicode
else:
unicod = str
for name in fnts:
# note, on ubuntu 2.6 they are all unicode strings.
self.failUnless(isinstance(name, (str, unicod)))
self.failUnless(name.islower(), name)
self.failUnless(name.isalnum(), name)
def test_get_init(self):
self.failUnless(pygame.font.get_init())
pygame.font.quit()
self.failIf(pygame.font.get_init())
def test_init(self):
pygame.font.init()
def test_match_font_all_exist(self):
fonts = pygame.font.get_fonts()
# Ensure all listed fonts are in fact available, and the returned file
# name is a full path.
for font in fonts:
path = pygame.font.match_font(font)
self.failIf(path is None)
self.failUnless(os.path.isabs(path))
def test_match_font_bold(self):
fonts = pygame.font.get_fonts()
# Look for a bold font.
for font in fonts:
if pygame.font.match_font(font, bold=True) is not None:
break
else:
self.fail()
def test_match_font_italic(self):
fonts = pygame.font.get_fonts()
# Look for an italic font.
for font in fonts:
if pygame.font.match_font(font, italic=True) is not None:
break
else:
self.fail()
def test_match_font_comma_separated(self):
fonts = pygame.font.get_fonts()
# Check for not found.
self.failUnless(pygame.font.match_font('thisisnotafont') is None)
# Check comma separated list.
names = ','.join(['thisisnotafont', fonts[-1], 'anothernonfont'])
self.failIf(pygame.font.match_font(names) is None)
names = ','.join(['thisisnotafont1', 'thisisnotafont2', 'thisisnotafont3'])
self.failUnless(pygame.font.match_font(names) is None)
def test_quit(self):
pygame.font.quit()
class FontTypeTest( unittest.TestCase ):
def setUp(self):
pygame.font.init()
def tearDown(self):
pygame.font.quit()
def test_get_ascent(self):
# Ckecking ascent would need a custom test font to do properly.
f = pygame.font.Font(None, 20)
ascent = f.get_ascent()
self.failUnless(isinstance(ascent, int))
self.failUnless(ascent > 0)
s = f.render("X", False, (255, 255, 255))
self.failUnless(s.get_size()[1] > ascent)
def test_get_descent(self):
# Ckecking descent would need a custom test font to do properly.
f = pygame.font.Font(None, 20)
descent = f.get_descent()
self.failUnless(isinstance(descent, int))
self.failUnless(descent < 0)
def test_get_height(self):
# Ckecking height would need a custom test font to do properly.
f = pygame.font.Font(None, 20)
height = f.get_height()
self.failUnless(isinstance(height, int))
self.failUnless(height > 0)
s = f.render("X", False, (255, 255, 255))
self.failUnless(s.get_size()[1] == height)
def test_get_linesize(self):
# Ckecking linesize would need a custom test font to do properly.
# Questions: How do linesize, height and descent relate?
f = pygame.font.Font(None, 20)
linesize = f.get_linesize()
self.failUnless(isinstance(linesize, int))
self.failUnless(linesize > 0)
def todo_test_metrics(self):
# The documentation is useless here. How large a list?
# How do list positions relate to character codes?
# What about unicode characters?
# __doc__ (as of 2008-08-02) for pygame.font.Font.metrics:
# Font.metrics(text): return list
# Gets the metrics for each character in the pased string.
#
# The list contains tuples for each character, which contain the
# minimum X offset, the maximum X offset, the minimum Y offset, the
# maximum Y offset and the advance offset (bearing plus width) of the
# character. [(minx, maxx, miny, maxy, advance), (minx, maxx, miny,
# maxy, advance), ...]
self.fail()
def test_render(self):
"""
"""
f = pygame.font.Font(None, 20)
s = f.render("foo", True, [0, 0, 0], [255, 255, 255])
s = f.render("xxx", True, [0, 0, 0], [255, 255, 255])
s = f.render("", True, [0, 0, 0], [255, 255, 255])
s = f.render("foo", False, [0, 0, 0], [255, 255, 255])
s = f.render("xxx", False, [0, 0, 0], [255, 255, 255])
s = f.render("xxx", False, [0, 0, 0])
s = f.render(" ", False, [0, 0, 0])
s = f.render(" ", False, [0, 0, 0], [255, 255, 255])
# null text should be 1 pixel wide.
s = f.render("", False, [0, 0, 0], [255, 255, 255])
self.assertEqual(s.get_size()[0], 1)
# is background transparent for antialiasing?
s = f.render(".", True, [255, 255, 255])
self.failUnlessEqual(s.get_at((0, 0))[3], 0)
# __doc__ (as of 2008-08-02) for pygame.font.Font.render:
# Font.render(text, antialias, color, background=None): return Surface
# draw text on a new Surface
#
# This creates a new Surface with the specified text rendered on it.
# Pygame provides no way to directly draw text on an existing Surface:
# instead you must use Font.render() to create an image (Surface) of
# the text, then blit this image onto another Surface.
#
# The text can only be a single line: newline characters are not
# rendered. The antialias argument is a boolean: if true the
# characters will have smooth edges. The color argument is the color
# of the text [e.g.: (0,0,255) for blue]. The optional background
# argument is a color to use for the text background. If no background
# is passed the area outside the text will be transparent.
#
# The Surface returned will be of the dimensions required to hold the
# text. (the same as those returned by Font.size()). If an empty
# string is passed for the text, a blank surface will be returned that
# is one pixel wide and the height of the font.
#
# Depending on the type of background and antialiasing used, this
# returns different types of Surfaces. For performance reasons, it is
# good to know what type of image will be used. If antialiasing is not
# used, the return image will always be an 8bit image with a two color
# palette. If the background is transparent a colorkey will be set.
# Antialiased images are rendered to 24-bit RGB images. If the
# background is transparent a pixel alpha will be included.
#
# Optimization: if you know that the final destination for the text
# (on the screen) will always have a solid background, and the text is
# antialiased, you can improve performance by specifying the
# background color. This will cause the resulting image to maintain
# transparency information by colorkey rather than (much less
# efficient) alpha values.
#
# If you render '\n' a unknown char will be rendered. Usually a
# rectangle. Instead you need to handle new lines yourself.
#
# Font rendering is not thread safe: only a single thread can render
# text any time.
def test_set_bold(self):
f = pygame.font.Font(None, 20)
self.failIf(f.get_bold())
f.set_bold(True)
self.failUnless(f.get_bold())
f.set_bold(False)
self.failIf(f.get_bold())
def test_set_italic(self):
f = pygame.font.Font(None, 20)
self.failIf(f.get_italic())
f.set_italic(True)
self.failUnless(f.get_italic())
f.set_italic(False)
self.failIf(f.get_bold())
def test_set_underline(self):
f = pygame.font.Font(None, 20)
self.failIf(f.get_underline())
f.set_underline(True)
self.failUnless(f.get_underline())
f.set_underline(False)
self.failIf(f.get_underline())
def test_size(self):
f = pygame.font.Font(None, 20)
text = "Xg"
size = f.size(text)
w, h = size
self.failUnless(isinstance(w, int) and isinstance(h, int))
s = f.render(text, False, (255, 255, 255))
self.failUnlessEqual(size, s.get_size())
def test_font_file_not_found(self):
# A per BUG reported by Bo Jangeborg on pygame-user mailing list,
# http://www.mail-archive.com/pygame-users@seul.org/msg11675.html
pygame.font.init()
def fetch():
font = pygame.font.Font('some-fictional-font.ttf', 20)
self.failUnlessRaises(IOError, fetch)
class VisualTests( unittest.TestCase ):
__tags__ = ['interactive']
screen = None
aborted = False
def setUp(self):
if self.screen is None:
pygame.init()
self.screen = pygame.display.set_mode((600, 200))
self.screen.fill((255, 255, 255))
pygame.display.flip()
self.f = pygame.font.Font(None, 32)
def abort(self):
if self.screen is not None:
pygame.quit()
self.aborted = True
def query(self,
bold=False, italic=False, underline=False, antialiase=False):
if self.aborted:
return False
spacing = 10
offset = 20
y = spacing
f = self.f
screen = self.screen
screen.fill((255, 255, 255))
pygame.display.flip()
if not (bold or italic or underline or antialiase):
text = "normal"
else:
modes = []
if bold:
modes.append("bold")
if italic:
modes.append("italic")
if underline:
modes.append("underlined")
if antialiase:
modes.append("antialiased")
text = "%s (y/n):" % ('-'.join(modes),)
f.set_bold(bold)
f.set_italic(italic)
f.set_underline(underline)
s = f.render(text, antialiase, (0, 0, 0))
screen.blit(s, (offset, y))
y += s.get_size()[1] + spacing
f.set_bold(False)
f.set_italic(False)
f.set_underline(False)
s = f.render("(some comparison text)", False, (0, 0, 0))
screen.blit(s, (offset, y))
pygame.display.flip()
while 1:
for evt in pygame.event.get():
if evt.type == pygame.KEYDOWN:
if evt.key == pygame.K_ESCAPE:
self.abort()
return False
if evt.key == pygame.K_y:
return True
if evt.key == pygame.K_n:
return False
if evt.type == pygame.QUIT:
self.abort()
return False
def test_bold(self):
self.failUnless(self.query(bold=True))
def test_italic(self):
self.failUnless(self.query(italic=True))
def test_underline(self):
self.failUnless(self.query(underline=True))
def test_antialiase(self):
self.failUnless(self.query(antialiase=True))
def test_bold_antialiase(self):
self.failUnless(self.query(bold=True, antialiase=True))
def test_italic_underline(self):
self.failUnless(self.query(italic=True, underline=True))
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/fastevent_test.py 0000644 0001750 0001750 00000013140 11207055754 020637 0 ustar vincent vincent #################################### IMPORTS ###################################
if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils import test_not_implemented, unittest
from pygame.tests.event_test import race_condition_notification
else:
from test.test_utils import test_not_implemented, unittest
from test.event_test import race_condition_notification
import pygame
from pygame import event, fastevent
from pygame.compat import geterror
################################################################################
class FasteventModuleTest(unittest.TestCase):
def setUp(self):
pygame.display.init()
fastevent.init()
event.clear()
self.assert_(not event.get())
def tearDown(self):
pygame.display.quit()
def test_get(self):
# __doc__ (as of 2008-08-02) for pygame.fastevent.get:
# pygame.fastevent.get() -> list of Events
# get all events from the queue
for _ in range(1, 11):
event.post(event.Event(pygame.USEREVENT))
self.assertEquals (
[e.type for e in fastevent.get()], [pygame.USEREVENT] * 10,
race_condition_notification
)
def todo_test_init(self):
# __doc__ (as of 2008-08-02) for pygame.fastevent.init:
# pygame.fastevent.init() -> None
# initialize pygame.fastevent.
self.fail()
def test_poll(self):
# __doc__ (as of 2008-08-02) for pygame.fastevent.poll:
# pygame.fastevent.poll() -> Event
# get an available event
#
# Returns next event on queue. If there is no event waiting on the
# queue, this will return an event with type NOEVENT.
self.assertEquals (
fastevent.poll().type, pygame.NOEVENT, race_condition_notification
)
def test_post(self):
# __doc__ (as of 2008-08-02) for pygame.fastevent.post:
# pygame.fastevent.post(Event) -> None
# place an event on the queue
#
# This will post your own event objects onto the event queue.
# You can past any event type you want, but some care must be
# taken. For example, if you post a MOUSEBUTTONDOWN event to the
# queue, it is likely any code receiving the event will expect
# the standard MOUSEBUTTONDOWN attributes to be available, like
# 'pos' and 'button'.
#
# Because pygame.fastevent.post() may have to wait for the queue
# to empty, you can get into a dead lock if you try to append an
# event on to a full queue from the thread that processes events.
# For that reason I do not recommend using this function in the
# main thread of an SDL program.
for _ in range(1, 11):
fastevent.post(event.Event(pygame.USEREVENT))
self.assertEquals (
[e.type for e in event.get()], [pygame.USEREVENT] * 10,
race_condition_notification
)
try:
# Special case for post: METH_O.
fastevent.post(1)
except TypeError:
e = geterror()
msg = ("argument 1 must be %s, not %s" %
(fastevent.Event.__name__, type(1).__name__))
self.failUnlessEqual(str(e), msg)
else:
self.fail()
def todo_test_pump(self):
# __doc__ (as of 2008-08-02) for pygame.fastevent.pump:
# pygame.fastevent.pump() -> None
# update the internal messages
#
# For each frame of your game, you will need to make some sort
# of call to the event queue. This ensures your program can internally
# interact with the rest of the operating system. If you are not using
# other event functions in your game, you should call pump() to allow
# pygame to handle internal actions.
#
# There are important things that must be dealt with internally in the
# event queue. The main window may need to be repainted. Certain joysticks
# must be polled for their values. If you fail to make a call to the event
# queue for too long, the system may decide your program has locked up.
self.fail()
def test_wait(self):
# __doc__ (as of 2008-08-02) for pygame.fastevent.wait:
# pygame.fastevent.wait() -> Event
# wait for an event
#
# Returns the current event on the queue. If there are no messages
# waiting on the queue, this will not return until one is
# available. Sometimes it is important to use this wait to get
# events from the queue, it will allow your application to idle
# when the user isn't doing anything with it.
event.post(pygame.event.Event(1))
self.assertEquals(fastevent.wait().type, 1, race_condition_notification)
################################################################################
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/event_test.py 0000644 0001750 0001750 00000021235 11207055754 017765 0 ustar vincent vincent #################################### IMPORTS ###################################
if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils import test_not_implemented, unittest
else:
from test.test_utils import test_not_implemented, unittest
import pygame
################################################################################
class EventTypeTest(unittest.TestCase):
def test_Event(self):
# __doc__ (as of 2008-08-02) for pygame.event.Event:
# pygame.event.Event(type, dict): return Event
# pygame.event.Event(type, **attributes): return Event
# create a new event object
#
# Creates a new event with the given type. The event is created with
# the given attributes and values. The attributes can come from a
# dictionary argument, or as string keys from a dictionary.
#
# The given attributes will be readonly attributes on the new event
# object itself. These are the only attributes on the Event object,
# there are no methods attached to Event objects.
e = pygame.event.Event(pygame.USEREVENT, some_attr=1, other_attr='1')
self.assertEquals(e.some_attr, 1)
self.assertEquals(e.other_attr, "1")
race_condition_notification = """
This test is dependent on timing. The event queue is cleared in preparation for
tests. There is a small window where outside events from the OS may have effected
results. Try running the test again.
"""
class EventModuleTest(unittest.TestCase):
def setUp(self):
# flush events
pygame.display.init()
pygame.event.clear()
self.assert_(not pygame.event.get())
def tearDown(self):
pygame.display.quit()
def test_set_blocked(self):
# __doc__ (as of 2008-06-25) for pygame.event.set_blocked:
# pygame.event.set_blocked(type): return None
# pygame.event.set_blocked(typelist): return None
# pygame.event.set_blocked(None): return None
# control which events are allowed on the queue
pygame.event.set_blocked(2)
self.assert_(pygame.event.get_blocked(2))
pygame.event.post(pygame.event.Event(2))
events = pygame.event.get()
should_be_blocked = [e for e in events if e.type == 2]
self.assertEquals(should_be_blocked, [])
def test_post__and_poll(self):
# __doc__ (as of 2008-06-25) for pygame.event.post:
# pygame.event.post(Event): return None
# place a new event on the queue
e1 = pygame.event.Event(pygame.USEREVENT, attr1='attr1')
pygame.event.post(e1)
posted_event = pygame.event.poll()
self.assertEquals (
e1.attr1, posted_event.attr1, race_condition_notification
)
# fuzzing event types
for i in range(1, 11):
pygame.event.post(pygame.event.Event(i))
self.assertEquals (
pygame.event.poll().type, i, race_condition_notification
)
def test_get(self):
# __doc__ (as of 2008-06-25) for pygame.event.get:
# pygame.event.get(): return Eventlist
# pygame.event.get(type): return Eventlist
# pygame.event.get(typelist): return Eventlist
# get events from the queue
# Put 10 events on the queue
for _ in range(1, 11):
pygame.event.post(pygame.event.Event(pygame.USEREVENT))
self.assert_ ( len(pygame.event.get()) >= 10 )
def test_clear(self):
# __doc__ (as of 2008-06-25) for pygame.event.clear:
# pygame.event.clear(): return None
# pygame.event.clear(type): return None
# pygame.event.clear(typelist): return None
# remove all events from the queue
for _ in range(1, 11):
pygame.event.post(pygame.event.Event(_))
self.assert_(pygame.event.poll()) # there are some events on queue
pygame.event.clear()
self.assert_(not pygame.event.poll(), race_condition_notification)
def test_event_name(self):
# __doc__ (as of 2008-06-25) for pygame.event.event_name:
# pygame.event.event_name(type): return string
# get the string name from and event id
self.assertEquals(pygame.event.event_name(2), "KeyDown")
self.assertEquals(pygame.event.event_name(24), "UserEvent")
def test_wait(self):
# __doc__ (as of 2008-06-25) for pygame.event.wait:
# pygame.event.wait(): return Event
# wait for a single event from the queue
pygame.event.post ( pygame.event.Event(2) )
self.assert_(pygame.event.wait())
def test_peek(self):
# __doc__ (as of 2008-06-25) for pygame.event.peek:
# pygame.event.peek(type): return bool
# pygame.event.peek(typelist): return bool
# test if event types are waiting on the queue
event_types = [2, 3, 4]
for event_type in event_types:
pygame.event.post (
pygame.event.Event(event_type)
)
self.assert_(pygame.event.peek(event_type))
self.assert_(pygame.event.peek(event_types))
def test_set_allowed(self):
# __doc__ (as of 2008-06-25) for pygame.event.set_allowed:
# pygame.event.set_allowed(type): return None
# pygame.event.set_allowed(typelist): return None
# pygame.event.set_allowed(None): return None
# control which events are allowed on the queue
pygame.event.set_blocked(2)
self.assert_(pygame.event.get_blocked(2))
pygame.event.set_allowed(2)
self.assert_(not pygame.event.get_blocked(2))
def test_pump(self):
# __doc__ (as of 2008-06-25) for pygame.event.pump:
# pygame.event.pump(): return None
# internally process pygame event handlers
# see it doesn't cause an error
pygame.event.pump()
def test_set_grab__and_get_symmetric(self):
# __doc__ (as of 2008-06-25) for pygame.event.set_grab:
# pygame.event.set_grab(bool): return None
# control the sharing of input devices with other applications
pygame.event.set_grab(True)
self.assert_(pygame.event.get_grab())
pygame.event.set_grab(False)
self.assert_(not pygame.event.get_grab())
def test_event_equality(self):
a = pygame.event.Event(1, a=1)
b = pygame.event.Event(1, a=1)
c = pygame.event.Event(2, a=1)
d = pygame.event.Event(1, a=2)
self.failUnless(a == a)
self.failIf(a != a)
self.failUnless(a == b)
self.failIf(a != b)
self.failUnless(a != c)
self.failIf(a == c)
self.failUnless(a != d)
self.failIf(a == d)
def todo_test_get_blocked(self):
# __doc__ (as of 2008-08-02) for pygame.event.get_blocked:
# pygame.event.get_blocked(type): return bool
# test if a type of event is blocked from the queue
#
# Returns true if the given event type is blocked from the queue.
self.fail()
def todo_test_get_grab(self):
# __doc__ (as of 2008-08-02) for pygame.event.get_grab:
# pygame.event.get_grab(): return bool
# test if the program is sharing input devices
#
# Returns true when the input events are grabbed for this application.
# Use pygame.event.set_grab() to control this state.
#
self.fail()
def todo_test_poll(self):
# __doc__ (as of 2008-08-02) for pygame.event.poll:
# pygame.event.poll(): return Event
# get a single event from the queue
#
# Returns a single event from the queue. If the event queue is empty
# an event of type pygame.NOEVENT will be returned immediately. The
# returned event is removed from the queue.
#
self.fail()
################################################################################
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/draw_test.py 0000644 0001750 0001750 00000017527 11207055754 017612 0 ustar vincent vincent #################################### IMPORTS ###################################
if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests import test_utils
from pygame.tests.test_utils \
import test_not_implemented, unordered_equality, unittest
else:
from test import test_utils
from test.test_utils \
import test_not_implemented, unordered_equality, unittest
import pygame
from pygame import draw
################################################################################
class DrawModuleTest(unittest.TestCase):
def setUp(self):
(self.surf_w, self.surf_h) = self.surf_size = (320, 200)
self.surf = pygame.Surface(self.surf_size, pygame.SRCALPHA)
self.color = (1, 13, 24, 205)
def test_rect__fill(self):
# __doc__ (as of 2008-06-25) for pygame.draw.rect:
# pygame.draw.rect(Surface, color, Rect, width=0): return Rect
# draw a rectangle shape
rect = pygame.Rect(10, 10, 25, 20)
drawn = draw.rect(self.surf, self.color, rect, 0)
self.assert_(drawn == rect)
#Should be colored where it's supposed to be
for pt in test_utils.rect_area_pts(rect):
color_at_pt = self.surf.get_at(pt)
self.assert_(color_at_pt == self.color)
#And not where it shouldn't
for pt in test_utils.rect_outer_bounds(rect):
color_at_pt = self.surf.get_at(pt)
self.assert_(color_at_pt != self.color)
def test_rect__one_pixel_lines(self):
# __doc__ (as of 2008-06-25) for pygame.draw.rect:
# pygame.draw.rect(Surface, color, Rect, width=0): return Rect
# draw a rectangle shape
rect = pygame.Rect(10, 10, 56, 20)
drawn = draw.rect(self.surf, self.color, rect, 1)
self.assert_(drawn == rect)
#Should be colored where it's supposed to be
for pt in test_utils.rect_perimeter_pts(drawn):
color_at_pt = self.surf.get_at(pt)
self.assert_(color_at_pt == self.color)
#And not where it shouldn't
for pt in test_utils.rect_outer_bounds(drawn):
color_at_pt = self.surf.get_at(pt)
self.assert_(color_at_pt != self.color)
def test_line(self):
# __doc__ (as of 2008-06-25) for pygame.draw.line:
# pygame.draw.line(Surface, color, start_pos, end_pos, width=1): return Rect
# draw a straight line segment
drawn = draw.line(self.surf, self.color, (1, 0), (200, 0)) #(l, t), (l, t)
self.assert_(drawn.right == 201,
"end point arg should be (or at least was) inclusive"
)
#Should be colored where it's supposed to be
for pt in test_utils.rect_area_pts(drawn):
self.assert_(self.surf.get_at(pt) == self.color)
#And not where it shouldn't
for pt in test_utils.rect_outer_bounds(drawn):
self.assert_(self.surf.get_at(pt) != self.color)
def todo_test_aaline(self):
# __doc__ (as of 2008-08-02) for pygame.draw.aaline:
# pygame.draw.aaline(Surface, color, startpos, endpos, blend=1): return Rect
# draw fine antialiased lines
#
# Draws an anti-aliased line on a surface. This will respect the
# clipping rectangle. A bounding box of the affected area is returned
# returned as a rectangle. If blend is true, the shades will be be
# blended with existing pixel shades instead of overwriting them. This
# function accepts floating point values for the end points.
#
self.fail()
def todo_test_aalines(self):
# __doc__ (as of 2008-08-02) for pygame.draw.aalines:
# pygame.draw.aalines(Surface, color, closed, pointlist, blend=1): return Rect
#
# Draws a sequence on a surface. You must pass at least two points in
# the sequence of points. The closed argument is a simple boolean and
# if true, a line will be draw between the first and last points. The
# boolean blend argument set to true will blend the shades with
# existing shades instead of overwriting them. This function accepts
# floating point values for the end points.
#
self.fail()
def todo_test_arc(self):
# __doc__ (as of 2008-08-02) for pygame.draw.arc:
# pygame.draw.arc(Surface, color, Rect, start_angle, stop_angle,
# width=1): return Rect
#
# draw a partial section of an ellipse
#
# Draws an elliptical arc on the Surface. The rect argument is the
# area that the ellipse will fill. The two angle arguments are the
# initial and final angle in radians, with the zero on the right. The
# width argument is the thickness to draw the outer edge.
#
self.fail()
def todo_test_circle(self):
# __doc__ (as of 2008-08-02) for pygame.draw.circle:
# pygame.draw.circle(Surface, color, pos, radius, width=0): return Rect
# draw a circle around a point
#
# Draws a circular shape on the Surface. The pos argument is the
# center of the circle, and radius is the size. The width argument is
# the thickness to draw the outer edge. If width is zero then the
# circle will be filled.
#
self.fail()
def todo_test_ellipse(self):
# __doc__ (as of 2008-08-02) for pygame.draw.ellipse:
# pygame.draw.ellipse(Surface, color, Rect, width=0): return Rect
# draw a round shape inside a rectangle
#
# Draws an elliptical shape on the Surface. The given rectangle is the
# area that the circle will fill. The width argument is the thickness
# to draw the outer edge. If width is zero then the ellipse will be
# filled.
#
self.fail()
def todo_test_lines(self):
# __doc__ (as of 2008-08-02) for pygame.draw.lines:
# pygame.draw.lines(Surface, color, closed, pointlist, width=1): return Rect
# draw multiple contiguous line segments
#
# Draw a sequence of lines on a Surface. The pointlist argument is a
# series of points that are connected by a line. If the closed
# argument is true an additional line segment is drawn between the
# first and last points.
#
# This does not draw any endcaps or miter joints. Lines with sharp
# corners and wide line widths can have improper looking corners.
#
self.fail()
def todo_test_polygon(self):
# __doc__ (as of 2008-08-02) for pygame.draw.polygon:
# pygame.draw.polygon(Surface, color, pointlist, width=0): return Rect
# draw a shape with any number of sides
#
# Draws a polygonal shape on the Surface. The pointlist argument is
# the vertices of the polygon. The width argument is the thickness to
# draw the outer edge. If width is zero then the polygon will be
# filled.
#
# For aapolygon, use aalines with the 'closed' parameter.
self.fail()
################################################################################
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/display_test.py 0000644 0001750 0001750 00000052422 11207055754 020313 0 ustar vincent vincent if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils import test_not_implemented, unittest
else:
from test.test_utils import test_not_implemented, unittest
import pygame, pygame.transform
class DisplayModuleTest( unittest.TestCase ):
def test_update( self ):
""" see if pygame.display.update takes rects with negative values.
"|Tags:display|"
"""
if 1:
pygame.init()
screen = pygame.display.set_mode((100,100))
screen.fill((55,55,55))
r1 = pygame.Rect(0,0,100,100)
pygame.display.update(r1)
r2 = pygame.Rect(-10,0,100,100)
pygame.display.update(r2)
r3 = pygame.Rect(-10,0,-100,-100)
pygame.display.update(r3)
# NOTE: if I don't call pygame.quit there is a segfault. hrmm.
pygame.quit()
# I think it's because unittest runs stuff in threads
# here's a stack trace...
# NOTE to author of above:
# unittest doesn't run tests in threads
# segfault was probably caused by another tests need
# for a "clean slate"
"""
#0 0x08103b7c in PyFrame_New ()
#1 0x080bd666 in PyEval_EvalCodeEx ()
#2 0x08105202 in PyFunction_SetClosure ()
#3 0x080595ae in PyObject_Call ()
#4 0x080b649f in PyEval_CallObjectWithKeywords ()
#5 0x08059585 in PyObject_CallObject ()
#6 0xb7f7aa2d in initbase () from /usr/lib/python2.4/site-packages/pygame/base.so
#7 0x080e09bd in Py_Finalize ()
#8 0x08055597 in Py_Main ()
#9 0xb7e04eb0 in __libc_start_main () from /lib/tls/libc.so.6
#10 0x08054e31 in _start ()
"""
def todo_test_Info(self):
# __doc__ (as of 2008-08-02) for pygame.display.Info:
# pygame.display.Info(): return VideoInfo
# Create a video display information object
#
# Creates a simple object containing several attributes to describe
# the current graphics environment. If this is called before
# pygame.display.set_mode() some platforms can provide information
# about the default display mode. This can also be called after
# setting the display mode to verify specific display options were
# satisfied. The VidInfo object has several attributes:
#
# hw: True if the display is hardware accelerated
# wm: True if windowed display modes can be used
# video_mem: The megabytes of video memory on the display. This is 0 if unknown
# bitsize: Number of bits used to store each pixel
# bytesize: Number of bytes used to store each pixel
# masks: Four values used to pack RGBA values into pixels
# shifts: Four values used to pack RGBA values into pixels
# losses: Four values used to pack RGBA values into pixels
# blit_hw: True if hardware Surface blitting is accelerated
# blit_hw_CC: True if hardware Surface colorkey blitting is accelerated
# blit_hw_A: True if hardware Surface pixel alpha blitting is accelerated
# blit_sw: True if software Surface blitting is accelerated
# blit_sw_CC: True if software Surface colorkey blitting is accelerated
# blit_sw_A: True if software Surface pixel alpha blitting is acclerated
# current_h, current_h: Width and height of the current video mode, or of the
# desktop mode if called before the display.set_mode is called.
# (current_h, current_w are available since SDL 1.2.10, and pygame 1.8.0)
# They are -1 on error, or if an old SDL is being used.
self.fail()
if 0:
pygame.init()
inf = pygame.display.Info()
print ("before a display mode has been set")
print (inf)
self.assertNotEqual(inf.current_h, -1)
self.assertNotEqual(inf.current_w, -1)
#probably have an older SDL than 1.2.10 if -1.
screen = pygame.display.set_mode((100,100))
inf = pygame.display.Info()
print (inf)
self.assertNotEqual(inf.current_h, -1)
self.assertEqual(inf.current_h, 100)
self.assertEqual(inf.current_w, 100)
#pygame.quit()
def todo_test_flip(self):
# __doc__ (as of 2008-08-02) for pygame.display.flip:
# pygame.display.flip(): return None
# update the full display Surface to the screen
#
# This will update the contents of the entire display. If your display
# mode is using the flags pygame.HWSURFACE and pygame.DOUBLEBUF, this
# will wait for a vertical retrace and swap the surfaces. If you are
# using a different type of display mode, it will simply update the
# entire contents of the surface.
#
# When using an pygame.OPENGL display mode this will perform a gl buffer swap.
self.fail()
def todo_test_get_active(self):
# __doc__ (as of 2008-08-02) for pygame.display.get_active:
# pygame.display.get_active(): return bool
# true when the display is active on the display
#
# After pygame.display.set_mode() is called the display Surface will
# be visible on the screen. Most windowed displays can be hidden by
# the user. If the display Surface is hidden or iconified this will
# return False.
#
self.fail()
def todo_test_get_caption(self):
# __doc__ (as of 2008-08-02) for pygame.display.get_caption:
# pygame.display.get_caption(): return (title, icontitle)
# get the current window caption
#
# Returns the title and icontitle for the display Surface. These will
# often be the same value.
#
self.fail()
def todo_test_get_driver(self):
# __doc__ (as of 2008-08-02) for pygame.display.get_driver:
# pygame.display.get_driver(): return name
# get the name of the pygame display backend
#
# Pygame chooses one of many available display backends when it is
# initialized. This returns the internal name used for the display
# backend. This can be used to provide limited information about what
# display capabilities might be accelerated. See the SDL_VIDEODRIVER
# flags in pygame.display.set_mode() to see some of the common
# options.
#
self.fail()
def todo_test_get_init(self):
# __doc__ (as of 2008-08-02) for pygame.display.get_init:
# pygame.display.get_init(): return bool
# true if the display module is initialized
#
# Returns True if the pygame.display module is currently initialized.
self.fail()
def todo_test_get_surface(self):
# __doc__ (as of 2008-08-02) for pygame.display.get_surface:
# pygame.display.get_surface(): return Surface
# get a reference to the currently set display surface
#
# Return a reference to the currently set display Surface. If no
# display mode has been set this will return None.
#
self.fail()
def todo_test_get_wm_info(self):
# __doc__ (as of 2008-08-02) for pygame.display.get_wm_info:
# pygame.display.get_wm_info(): return dict
# Get information about the current windowing system
#
# Creates a dictionary filled with string keys. The strings and values
# are arbitrarily created by the system. Some systems may have no
# information and an empty dictionary will be returned. Most platforms
# will return a "window" key with the value set to the system id for
# the current display.
#
# New with pygame 1.7.1
self.fail()
def todo_test_gl_get_attribute(self):
# __doc__ (as of 2008-08-02) for pygame.display.gl_get_attribute:
# pygame.display.gl_get_attribute(flag): return value
# get the value for an opengl flag for the current display
#
# After calling pygame.display.set_mode() with the pygame.OPENGL flag,
# it is a good idea to check the value of any requested OpenGL
# attributes. See pygame.display.gl_set_attribute() for a list of
# valid flags.
#
self.fail()
def todo_test_gl_set_attribute(self):
# __doc__ (as of 2008-08-02) for pygame.display.gl_set_attribute:
# pygame.display.gl_set_attribute(flag, value): return None
# request an opengl display attribute for the display mode
#
# When calling pygame.display.set_mode() with the pygame.OPENGL flag,
# Pygame automatically handles setting the OpenGL attributes like
# color and doublebuffering. OpenGL offers several other attributes
# you may want control over. Pass one of these attributes as the flag,
# and its appropriate value. This must be called before
# pygame.display.set_mode()
#
# The OPENGL flags are;
# GL_ALPHA_SIZE, GL_DEPTH_SIZE, GL_STENCIL_SIZE, GL_ACCUM_RED_SIZE,
# GL_ACCUM_GREEN_SIZE, GL_ACCUM_BLUE_SIZE, GL_ACCUM_ALPHA_SIZE,
# GL_MULTISAMPLEBUFFERS, GL_MULTISAMPLESAMPLES, GL_STEREO
self.fail()
def todo_test_iconify(self):
# __doc__ (as of 2008-08-02) for pygame.display.iconify:
# pygame.display.iconify(): return bool
# iconify the display surface
#
# Request the window for the display surface be iconified or hidden.
# Not all systems and displays support an iconified display. The
# function will return True if successfull.
#
# When the display is iconified pygame.display.get_active() will
# return False. The event queue should receive a ACTIVEEVENT event
# when the window has been iconified.
#
self.fail()
def todo_test_init(self):
# __doc__ (as of 2008-08-02) for pygame.display.init:
# pygame.display.init(): return None
# initialize the display module
#
# Initializes the pygame display module. The display module cannot do
# anything until it is initialized. This is usually handled for you
# automatically when you call the higher level pygame.init().
#
# Pygame will select from one of several internal display backends
# when it is initialized. The display mode will be chosen depending on
# the platform and permissions of current user. Before the display
# module is initialized the environment variable SDL_VIDEODRIVER can
# be set to control which backend is used. The systems with multiple
# choices are listed here.
#
# Windows : windib, directx
# Unix : x11, dga, fbcon, directfb, ggi, vgl, svgalib, aalib
# On some platforms it is possible to embed the pygame display into an
# already existing window. To do this, the environment variable
# SDL_WINDOWID must be set to a string containing the window id or
# handle. The environment variable is checked when the pygame display
# is initialized. Be aware that there can be many strange side effects
# when running in an embedded display.
#
# It is harmless to call this more than once, repeated calls have no effect.
self.fail()
def todo_test_list_modes(self):
# __doc__ (as of 2008-08-02) for pygame.display.list_modes:
# pygame.display.list_modes(depth=0, flags=pygame.FULLSCREEN): return list
# get list of available fullscreen modes
#
# This function returns a list of possible dimensions for a specified
# color depth. The return value will be an empty list if no display
# modes are available with the given arguments. A return value of -1
# means that any requested resolution should work (this is likely the
# case for windowed modes). Mode sizes are sorted from biggest to
# smallest.
#
# If depth is 0, SDL will choose the current/best color depth for the
# display. The flags defaults to pygame.FULLSCREEN, but you may need
# to add additional flags for specific fullscreen modes.
#
self.fail()
def todo_test_mode_ok(self):
# __doc__ (as of 2008-08-02) for pygame.display.mode_ok:
# pygame.display.mode_ok(size, flags=0, depth=0): return depth
# pick the best color depth for a display mode
#
# This function uses the same arguments as pygame.display.set_mode().
# It is used to depermine if a requested display mode is available. It
# will return 0 if the display mode cannot be set. Otherwise it will
# return a pixel depth that best matches the display asked for.
#
# Usually the depth argument is not passed, but some platforms can
# support multiple display depths. If passed it will hint to which
# depth is a better match.
#
# The most useful flags to pass will be pygame.HWSURFACE,
# pygame.DOUBLEBUF, and maybe pygame.FULLSCREEN. The function will
# return 0 if these display flags cannot be set.
#
self.fail()
def todo_test_quit(self):
# __doc__ (as of 2008-08-02) for pygame.display.quit:
# pygame.display.quit(): return None
# uninitialize the display module
#
# This will shut down the entire display module. This means any active
# displays will be closed. This will also be handled automatically
# when the program exits.
#
# It is harmless to call this more than once, repeated calls have no effect.
self.fail()
def todo_test_set_caption(self):
# __doc__ (as of 2008-08-02) for pygame.display.set_caption:
# pygame.display.set_caption(title, icontitle=None): return None
# set the current window caption
#
# If the display has a window title, this function will change the
# name on the window. Some systems support an alternate shorter title
# to be used for minimized displays.
#
self.fail()
def todo_test_set_gamma(self):
# __doc__ (as of 2008-08-02) for pygame.display.set_gamma:
# pygame.display.set_gamma(red, green=None, blue=None): return bool
# change the hardware gamma ramps
#
# Set the red, green, and blue gamma values on the display hardware.
# If the green and blue arguments are not passed, they will both be
# the same as red. Not all systems and hardware support gamma ramps,
# if the function succeeds it will return True.
#
# A gamma value of 1.0 creates a linear color table. Lower values will
# darken the display and higher values will brighten.
#
self.fail()
def todo_test_set_gamma_ramp(self):
# __doc__ (as of 2008-08-02) for pygame.display.set_gamma_ramp:
# change the hardware gamma ramps with a custom lookup
# pygame.display.set_gamma_ramp(red, green, blue): return bool
# set_gamma_ramp(red, green, blue): return bool
#
# Set the red, green, and blue gamma ramps with an explicit lookup
# table. Each argument should be sequence of 256 integers. The
# integers should range between 0 and 0xffff. Not all systems and
# hardware support gamma ramps, if the function succeeds it will
# return True.
#
self.fail()
def todo_test_set_icon(self):
# __doc__ (as of 2008-08-02) for pygame.display.set_icon:
# pygame.display.set_icon(Surface): return None
# change the system image for the display window
#
# Sets the runtime icon the system will use to represent the display
# window. All windows default to a simple pygame logo for the window
# icon.
#
# You can pass any surface, but most systems want a smaller image
# around 32x32. The image can have colorkey transparency which will be
# passed to the system.
#
# Some systems do not allow the window icon to change after it has
# been shown. This function can be called before
# pygame.display.set_mode() to create the icon before the display mode
# is set.
#
self.fail()
def todo_test_set_mode(self):
# __doc__ (as of 2008-08-02) for pygame.display.set_mode:
# pygame.display.set_mode(resolution=(0,0), flags=0, depth=0): return Surface
# initialize a window or screen for display
#
# This function will create a display Surface. The arguments passed in
# are requests for a display type. The actual created display will be
# the best possible match supported by the system.
#
# The resolution argument is a pair of numbers representing the width
# and height. The flags argument is a collection of additional
# options. The depth argument represents the number of bits to use
# for color.
#
# The Surface that gets returned can be drawn to like a regular
# Surface but changes will eventually be seen on the monitor.
#
# If no resolution is passed or is set to (0, 0) and pygame uses SDL
# version 1.2.10 or above, the created Surface will have the same size
# as the current screen resolution. If only the width or height are
# set to 0, the Surface will have the same width or height as the
# screen resolution. Using a SDL version prior to 1.2.10 will raise an
# exception.
#
# It is usually best to not pass the depth argument. It will default
# to the best and fastest color depth for the system. If your game
# requires a specific color format you can control the depth with this
# argument. Pygame will emulate an unavailable color depth which can
# be slow.
#
# When requesting fullscreen display modes, sometimes an exact match
# for the requested resolution cannot be made. In these situations
# pygame will select the closest compatable match. The returned
# surface will still always match the requested resolution.
#
# The flags argument controls which type of display you want. There
# are several to choose from, and you can even combine multiple types
# using the bitwise or operator, (the pipe "|" character). If you pass
# 0 or no flags argument it will default to a software driven window.
# Here are the display flags you will want to choose from:
#
# pygame.FULLSCREEN create a fullscreen display
# pygame.DOUBLEBUF recommended for HWSURFACE or OPENGL
# pygame.HWSURFACE hardware accelerated, only in FULLSCREEN
# pygame.OPENGL create an opengl renderable display
# pygame.RESIZABLE display window should be sizeable
# pygame.NOFRAME display window will have no border or controls
self.fail()
def todo_test_set_palette(self):
# __doc__ (as of 2008-08-02) for pygame.display.set_palette:
# pygame.display.set_palette(palette=None): return None
# set the display color palette for indexed displays
#
# This will change the video display color palette for 8bit displays.
# This does not change the palette for the actual display Surface,
# only the palette that is used to display the Surface. If no palette
# argument is passed, the system default palette will be restored. The
# palette is a sequence of RGB triplets.
#
self.fail()
def todo_test_toggle_fullscreen(self):
# __doc__ (as of 2008-08-02) for pygame.display.toggle_fullscreen:
# pygame.display.toggle_fullscreen(): return bool
# switch between fullscreen and windowed displays
#
# Switches the display window between windowed and fullscreen modes.
# This function only works under the unix x11 video driver. For most
# situations it is better to call pygame.display.set_mode() with new
# display flags.
#
self.fail()
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/cursors_test.py 0000644 0001750 0001750 00000006036 11207055754 020346 0 ustar vincent vincent #################################### IMPORTS ###################################
if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils \
import test_not_implemented, fixture_path, unittest
else:
from test.test_utils \
import test_not_implemented, fixture_path, unittest
import pygame
################################################################################
class CursorsModuleTest(unittest.TestCase):
def todo_test_compile(self):
# __doc__ (as of 2008-06-25) for pygame.cursors.compile:
# pygame.cursors.compile(strings, black, white,xor) -> data, mask
# compile cursor strings into cursor data
#
# This takes a set of strings with equal length and computes
# the binary data for that cursor. The string widths must be
# divisible by 8.
#
# The black and white arguments are single letter strings that
# tells which characters will represent black pixels, and which
# characters represent white pixels. All other characters are
# considered clear.
#
# This returns a tuple containing the cursor data and cursor mask
# data. Both these arguments are used when setting a cursor with
# pygame.mouse.set_cursor().
self.fail()
def test_load_xbm(self):
# __doc__ (as of 2008-06-25) for pygame.cursors.load_xbm:
# pygame.cursors.load_xbm(cursorfile, maskfile) -> cursor_args
# reads a pair of XBM files into set_cursor arguments
#
# Arguments can either be filenames or filelike objects
# with the readlines method. Not largely tested, but
# should work with typical XBM files.
# Test that load_xbm will take filenames as arguments
cursorfile = fixture_path(r"xbm_cursors/white_sizing.xbm")
maskfile = fixture_path(r"xbm_cursors/white_sizing_mask.xbm")
cursor = pygame.cursors.load_xbm(cursorfile, maskfile)
# Test that load_xbm will take file objects as arguments
cursorfile, maskfile = [open(pth) for pth in (cursorfile, maskfile)]
cursor = pygame.cursors.load_xbm(cursorfile, maskfile)
# Is it in a format that mouse.set_cursor won't blow up on?
pygame.display.init()
pygame.mouse.set_cursor(*cursor)
pygame.display.quit()
################################################################################
if __name__ == '__main__':
unittest.main()
################################################################################
pygame-1.9.1release/test/color_test.py 0000644 0001750 0001750 00000070407 11225022142 017750 0 ustar vincent vincent #################################### IMPORTS ###################################
from __future__ import generators
if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils import test_not_implemented, unittest
else:
from test.test_utils import test_not_implemented, unittest
import pygame
from pygame.compat import long_
import math
################################### CONSTANTS ##################################
rgba_vals = [0, 1, 62, 63, 126, 127, 255]
rgba_combinations = [ (r,g,b,a) for r in rgba_vals
for g in rgba_vals
for b in rgba_vals
for a in rgba_vals ]
################################################################################
def rgba_combos_Color_generator ():
for rgba in rgba_combinations:
yield pygame.Color(*rgba)
# Python gamma correct
def gamma_correct (rgba_0_255, gamma):
corrected = round(255.0 * math.pow(rgba_0_255/255.0, gamma))
return max(min( int(corrected), 255), 0)
################################################################################
# TODO: add tests for
# correct_gamma() -- test against statically defined verified correct values
# coerce () -- ??
def _assignr (x, y):
x.r = y
def _assigng (x, y):
x.g = y
def _assignb (x, y):
x.b = y
def _assigna (x, y):
x.a = y
def _assign_item (x, p, y):
x[p] = y
class ColorTypeTest (unittest.TestCase):
def test_invalid_html_hex_codes(self):
# This was a problem with the way 2 digit hex numbers were
# calculated. The test_hex_digits test is related to the fix.
Color = pygame.color.Color
self.failUnlessRaises(ValueError, lambda: Color('# f000000'))
self.failUnlessRaises(ValueError, lambda: Color('#f 000000'))
self.failUnlessRaises(ValueError, lambda: Color('#-f000000'))
def test_hex_digits(self):
# This is an implementation specific test.
# Two digit hex numbers are calculated using table lookups
# for the upper and lower digits.
Color = pygame.color.Color
self.assertEqual(Color('#00000000').r, 0x00)
self.assertEqual(Color('#10000000').r, 0x10)
self.assertEqual(Color('#20000000').r, 0x20)
self.assertEqual(Color('#30000000').r, 0x30)
self.assertEqual(Color('#40000000').r, 0x40)
self.assertEqual(Color('#50000000').r, 0x50)
self.assertEqual(Color('#60000000').r, 0x60)
self.assertEqual(Color('#70000000').r, 0x70)
self.assertEqual(Color('#80000000').r, 0x80)
self.assertEqual(Color('#90000000').r, 0x90)
self.assertEqual(Color('#A0000000').r, 0xA0)
self.assertEqual(Color('#B0000000').r, 0xB0)
self.assertEqual(Color('#C0000000').r, 0xC0)
self.assertEqual(Color('#D0000000').r, 0xD0)
self.assertEqual(Color('#E0000000').r, 0xE0)
self.assertEqual(Color('#F0000000').r, 0xF0)
self.assertEqual(Color('#01000000').r, 0x01)
self.assertEqual(Color('#02000000').r, 0x02)
self.assertEqual(Color('#03000000').r, 0x03)
self.assertEqual(Color('#04000000').r, 0x04)
self.assertEqual(Color('#05000000').r, 0x05)
self.assertEqual(Color('#06000000').r, 0x06)
self.assertEqual(Color('#07000000').r, 0x07)
self.assertEqual(Color('#08000000').r, 0x08)
self.assertEqual(Color('#09000000').r, 0x09)
self.assertEqual(Color('#0A000000').r, 0x0A)
self.assertEqual(Color('#0B000000').r, 0x0B)
self.assertEqual(Color('#0C000000').r, 0x0C)
self.assertEqual(Color('#0D000000').r, 0x0D)
self.assertEqual(Color('#0E000000').r, 0x0E)
self.assertEqual(Color('#0F000000').r, 0x0F)
def test_comparison(self):
Color = pygame.color.Color
# Check valid comparisons
self.failUnless(Color(255, 0, 0, 0) == Color(255, 0, 0, 0))
self.failUnless(Color(0, 255, 0, 0) == Color(0, 255, 0, 0))
self.failUnless(Color(0, 0, 255, 0) == Color(0, 0, 255, 0))
self.failUnless(Color(0, 0, 0, 255) == Color(0, 0, 0, 255))
self.failIf(Color(0, 0, 0, 0) == Color(255, 0, 0, 0))
self.failIf(Color(0, 0, 0, 0) == Color(0, 255, 0, 0))
self.failIf(Color(0, 0, 0, 0) == Color(0, 0, 255, 0))
self.failIf(Color(0, 0, 0, 0) == Color(0, 0, 0, 255))
self.failUnless(Color(0, 0, 0, 0) != Color(255, 0, 0, 0))
self.failUnless(Color(0, 0, 0, 0) != Color(0, 255, 0, 0))
self.failUnless(Color(0, 0, 0, 0) != Color(0, 0, 255, 0))
self.failUnless(Color(0, 0, 0, 0) != Color(0, 0, 0, 255))
self.failIf(Color(255, 0, 0, 0) != Color(255, 0, 0, 0))
self.failIf(Color(0, 255, 0, 0) != Color(0, 255, 0, 0))
self.failIf(Color(0, 0, 255, 0) != Color(0, 0, 255, 0))
self.failIf(Color(0, 0, 0, 255) != Color(0, 0, 0, 255))
self.failUnless(Color(255, 0, 0, 0) == (255, 0, 0, 0))
self.failUnless(Color(0, 255, 0, 0) == (0, 255, 0, 0))
self.failUnless(Color(0, 0, 255, 0) == (0, 0, 255, 0))
self.failUnless(Color(0, 0, 0, 255) == (0, 0, 0, 255))
self.failIf(Color(0, 0, 0, 0) == (255, 0, 0, 0))
self.failIf(Color(0, 0, 0, 0) == (0, 255, 0, 0))
self.failIf(Color(0, 0, 0, 0) == (0, 0, 255, 0))
self.failIf(Color(0, 0, 0, 0) == (0, 0, 0, 255))
self.failUnless(Color(0, 0, 0, 0) != (255, 0, 0, 0))
self.failUnless(Color(0, 0, 0, 0) != (0, 255, 0, 0))
self.failUnless(Color(0, 0, 0, 0) != (0, 0, 255, 0))
self.failUnless(Color(0, 0, 0, 0) != (0, 0, 0, 255))
self.failIf(Color(255, 0, 0, 0) != (255, 0, 0, 0))
self.failIf(Color(0, 255, 0, 0) != (0, 255, 0, 0))
self.failIf(Color(0, 0, 255, 0) != (0, 0, 255, 0))
self.failIf(Color(0, 0, 0, 255) != (0, 0, 0, 255))
self.failUnless((255, 0, 0, 0) == Color(255, 0, 0, 0))
self.failUnless((0, 255, 0, 0) == Color(0, 255, 0, 0))
self.failUnless((0, 0, 255, 0) == Color(0, 0, 255, 0))
self.failUnless((0, 0, 0, 255) == Color(0, 0, 0, 255))
self.failIf((0, 0, 0, 0) == Color(255, 0, 0, 0))
self.failIf((0, 0, 0, 0) == Color(0, 255, 0, 0))
self.failIf((0, 0, 0, 0) == Color(0, 0, 255, 0))
self.failIf((0, 0, 0, 0) == Color(0, 0, 0, 255))
self.failUnless((0, 0, 0, 0) != Color(255, 0, 0, 0))
self.failUnless((0, 0, 0, 0) != Color(0, 255, 0, 0))
self.failUnless((0, 0, 0, 0) != Color(0, 0, 255, 0))
self.failUnless((0, 0, 0, 0) != Color(0, 0, 0, 255))
self.failIf((255, 0, 0, 0) != Color(255, 0, 0, 0))
self.failIf((0, 255, 0, 0) != Color(0, 255, 0, 0))
self.failIf((0, 0, 255, 0) != Color(0, 0, 255, 0))
self.failIf((0, 0, 0, 255) != Color(0, 0, 0, 255))
class TupleSubclass(tuple):
pass
self.failUnless(Color(255, 0, 0, 0) == TupleSubclass((255, 0, 0, 0)))
self.failUnless(TupleSubclass((255, 0, 0, 0)) == Color(255, 0, 0, 0))
self.failIf(Color(255, 0, 0, 0) != TupleSubclass((255, 0, 0, 0)))
self.failIf(TupleSubclass((255, 0, 0, 0)) != Color(255, 0, 0, 0))
# These are not supported so will be unequal.
self.failIf(Color(255, 0, 0, 0) == "#ff000000")
self.failUnless(Color(255, 0, 0, 0) != "#ff000000")
self.failIf("#ff000000" == Color(255, 0, 0, 0))
self.failUnless("#ff000000" != Color(255, 0, 0, 0))
self.failIf(Color(255, 0, 0, 0) == 0xff000000)
self.failUnless(Color(255, 0, 0, 0) != 0xff000000)
self.failIf(0xff000000 == Color(255, 0, 0, 0))
self.failUnless(0xff000000 != Color(255, 0, 0, 0))
self.failIf(Color(255, 0, 0, 0) == [255, 0, 0, 0])
self.failUnless(Color(255, 0, 0, 0) != [255, 0, 0, 0])
self.failIf([255, 0, 0, 0] == Color(255, 0, 0 ,0))
self.failUnless([255, 0, 0, 0] != Color(255, 0, 0, 0))
# Comparison is not implemented for invalid color values.
class Test(object):
def __eq__(self, other):
return -1
def __ne__(self, other):
return -2
class TestTuple(tuple):
def __eq__(self, other):
return -1
def __ne__(self, other):
return -2
t = Test()
t_tuple = TestTuple(('a', 0, 0, 0))
black = Color('black')
self.assertEqual(black == t, -1)
self.assertEqual(t == black, -1)
self.assertEqual(black != t, -2)
self.assertEqual(t != black, -2)
self.assertEqual(black == t_tuple, -1)
self.assertEqual(black != t_tuple, -2)
self.assertEqual(t_tuple == black, -1)
self.assertEqual(t_tuple != black, -2)
def test_ignore_whitespace(self):
self.assertEquals(pygame.color.Color('red'), pygame.color.Color(' r e d '))
def test_slice(self):
#"""|tags: python3_ignore|"""
# slicing a color gives you back a tuple.
# do all sorts of slice combinations.
c = pygame.Color(1,2,3,4)
self.assertEquals((1,2,3,4), c[:])
self.assertEquals((1,2,3), c[:-1])
self.assertEquals((), c[:-5])
self.assertEquals((1,2,3,4), c[:4])
self.assertEquals((1,2,3,4), c[:5])
self.assertEquals((1,2), c[:2])
self.assertEquals((1,), c[:1])
self.assertEquals((), c[:0])
self.assertEquals((2,), c[1:-2])
self.assertEquals((3, 4), c[-2:])
self.assertEquals((4,), c[-1:])
# NOTE: assigning to a slice is currently unsupported.
def test_unpack(self):
# should be able to unpack to r,g,b,a and r,g,b
c = pygame.Color(1,2,3,4)
r,g,b,a = c
self.assertEquals((1,2,3,4), (r,g,b,a))
self.assertEquals(c, (r,g,b,a))
c.set_length(3)
r,g,b = c
self.assertEquals((1,2,3), (r,g,b))
def test_length(self):
# should be able to unpack to r,g,b,a and r,g,b
c = pygame.Color(1,2,3,4)
self.assertEquals(len(c), 4)
c.set_length(3)
self.assertEquals(len(c), 3)
# it keeps the old alpha anyway...
self.assertEquals(c.a, 4)
# however you can't get the alpha in this way:
self.assertRaises (IndexError, lambda x:c[x], 4)
c.set_length(4)
self.assertEquals(len(c), 4)
self.assertEquals(len(c), 4)
self.assertRaises (ValueError, c.set_length, 5)
self.assertRaises (ValueError, c.set_length, -1)
self.assertRaises (ValueError, c.set_length, 0)
self.assertRaises (ValueError, c.set_length, pow(2,long_(33)))
def test_case_insensitivity_of_string_args(self):
self.assertEquals(pygame.color.Color('red'), pygame.color.Color('Red'))
def test_color (self):
c = pygame.Color (10, 20, 30, 40)
self.assertEquals (c.r, 10)
self.assertEquals (c.g, 20)
self.assertEquals (c.b, 30)
self.assertEquals (c.a, 40)
c = pygame.Color ("indianred3")
self.assertEquals (c.r, 205)
self.assertEquals (c.g, 85)
self.assertEquals (c.b, 85)
self.assertEquals (c.a, 255)
c = pygame.Color (0xAABBCCDD)
self.assertEquals (c.r, 0xAA)
self.assertEquals (c.g, 0xBB)
self.assertEquals (c.b, 0xCC)
self.assertEquals (c.a, 0xDD)
self.assertRaises (ValueError, pygame.Color, 257, 10, 105, 44)
self.assertRaises (ValueError, pygame.Color, 10, 257, 105, 44)
self.assertRaises (ValueError, pygame.Color, 10, 105, 257, 44)
self.assertRaises (ValueError, pygame.Color, 10, 105, 44, 257)
def test_rgba (self):
c = pygame.Color (0)
self.assertEquals (c.r, 0)
self.assertEquals (c.g, 0)
self.assertEquals (c.b, 0)
self.assertEquals (c.a, 0)
# Test simple assignments
c.r = 123
self.assertEquals (c.r, 123)
self.assertRaises (ValueError, _assignr, c, 537)
self.assertEquals (c.r, 123)
self.assertRaises (ValueError, _assignr, c, -3)
self.assertEquals (c.r, 123)
c.g = 55
self.assertEquals (c.g, 55)
self.assertRaises (ValueError, _assigng, c, 348)
self.assertEquals (c.g, 55)
self.assertRaises (ValueError, _assigng, c, -44)
self.assertEquals (c.g, 55)
c.b = 77
self.assertEquals (c.b, 77)
self.assertRaises (ValueError, _assignb, c, 256)
self.assertEquals (c.b, 77)
self.assertRaises (ValueError, _assignb, c, -12)
self.assertEquals (c.b, 77)
c.a = 255
self.assertEquals (c.a, 255)
self.assertRaises (ValueError, _assigna, c, 312)
self.assertEquals (c.a, 255)
self.assertRaises (ValueError, _assigna, c, -10)
self.assertEquals (c.a, 255)
def test_repr (self):
c = pygame.Color (68, 38, 26, 69)
t = "(68, 38, 26, 69)"
self.assertEquals (repr (c), t)
def test_add (self):
c1 = pygame.Color (0)
self.assertEquals (c1.r, 0)
self.assertEquals (c1.g, 0)
self.assertEquals (c1.b, 0)
self.assertEquals (c1.a, 0)
c2 = pygame.Color (20, 33, 82, 193)
self.assertEquals (c2.r, 20)
self.assertEquals (c2.g, 33)
self.assertEquals (c2.b, 82)
self.assertEquals (c2.a, 193)
c3 = c1 + c2
self.assertEquals (c3.r, 20)
self.assertEquals (c3.g, 33)
self.assertEquals (c3.b, 82)
self.assertEquals (c3.a, 193)
c3 = c3 + c2
self.assertEquals (c3.r, 40)
self.assertEquals (c3.g, 66)
self.assertEquals (c3.b, 164)
self.assertEquals (c3.a, 255)
def test_sub (self):
c1 = pygame.Color (0xFFFFFFFF)
self.assertEquals (c1.r, 255)
self.assertEquals (c1.g, 255)
self.assertEquals (c1.b, 255)
self.assertEquals (c1.a, 255)
c2 = pygame.Color (20, 33, 82, 193)
self.assertEquals (c2.r, 20)
self.assertEquals (c2.g, 33)
self.assertEquals (c2.b, 82)
self.assertEquals (c2.a, 193)
c3 = c1 - c2
self.assertEquals (c3.r, 235)
self.assertEquals (c3.g, 222)
self.assertEquals (c3.b, 173)
self.assertEquals (c3.a, 62)
c3 = c3 - c2
self.assertEquals (c3.r, 215)
self.assertEquals (c3.g, 189)
self.assertEquals (c3.b, 91)
self.assertEquals (c3.a, 0)
def test_mul (self):
c1 = pygame.Color (0x01010101)
self.assertEquals (c1.r, 1)
self.assertEquals (c1.g, 1)
self.assertEquals (c1.b, 1)
self.assertEquals (c1.a, 1)
c2 = pygame.Color (2, 5, 3, 22)
self.assertEquals (c2.r, 2)
self.assertEquals (c2.g, 5)
self.assertEquals (c2.b, 3)
self.assertEquals (c2.a, 22)
c3 = c1 * c2
self.assertEquals (c3.r, 2)
self.assertEquals (c3.g, 5)
self.assertEquals (c3.b, 3)
self.assertEquals (c3.a, 22)
c3 = c3 * c2
self.assertEquals (c3.r, 4)
self.assertEquals (c3.g, 25)
self.assertEquals (c3.b, 9)
self.assertEquals (c3.a, 255)
def test_div (self):
c1 = pygame.Color (0x80808080)
self.assertEquals (c1.r, 128)
self.assertEquals (c1.g, 128)
self.assertEquals (c1.b, 128)
self.assertEquals (c1.a, 128)
c2 = pygame.Color (2, 4, 8, 16)
self.assertEquals (c2.r, 2)
self.assertEquals (c2.g, 4)
self.assertEquals (c2.b, 8)
self.assertEquals (c2.a, 16)
c3 = c1 // c2
self.assertEquals (c3.r, 64)
self.assertEquals (c3.g, 32)
self.assertEquals (c3.b, 16)
self.assertEquals (c3.a, 8)
c3 = c3 // c2
self.assertEquals (c3.r, 32)
self.assertEquals (c3.g, 8)
self.assertEquals (c3.b, 2)
self.assertEquals (c3.a, 0)
def test_mod (self):
c1 = pygame.Color (0xFFFFFFFF)
self.assertEquals (c1.r, 255)
self.assertEquals (c1.g, 255)
self.assertEquals (c1.b, 255)
self.assertEquals (c1.a, 255)
c2 = pygame.Color (2, 4, 8, 16)
self.assertEquals (c2.r, 2)
self.assertEquals (c2.g, 4)
self.assertEquals (c2.b, 8)
self.assertEquals (c2.a, 16)
c3 = c1 % c2
self.assertEquals (c3.r, 1)
self.assertEquals (c3.g, 3)
self.assertEquals (c3.b, 7)
self.assertEquals (c3.a, 15)
def test_float (self):
c = pygame.Color (0xCC00CC00)
self.assertEquals (c.r, 204)
self.assertEquals (c.g, 0)
self.assertEquals (c.b, 204)
self.assertEquals (c.a, 0)
self.assertEquals (float (c), float (0xCC00CC00))
c = pygame.Color (0x33727592)
self.assertEquals (c.r, 51)
self.assertEquals (c.g, 114)
self.assertEquals (c.b, 117)
self.assertEquals (c.a, 146)
self.assertEquals (float (c), float (0x33727592))
def test_oct (self):
c = pygame.Color (0xCC00CC00)
self.assertEquals (c.r, 204)
self.assertEquals (c.g, 0)
self.assertEquals (c.b, 204)
self.assertEquals (c.a, 0)
self.assertEquals (oct (c), oct (0xCC00CC00))
c = pygame.Color (0x33727592)
self.assertEquals (c.r, 51)
self.assertEquals (c.g, 114)
self.assertEquals (c.b, 117)
self.assertEquals (c.a, 146)
self.assertEquals (oct (c), oct (0x33727592))
def test_hex (self):
c = pygame.Color (0xCC00CC00)
self.assertEquals (c.r, 204)
self.assertEquals (c.g, 0)
self.assertEquals (c.b, 204)
self.assertEquals (c.a, 0)
self.assertEquals (hex (c), hex (0xCC00CC00))
c = pygame.Color (0x33727592)
self.assertEquals (c.r, 51)
self.assertEquals (c.g, 114)
self.assertEquals (c.b, 117)
self.assertEquals (c.a, 146)
self.assertEquals (hex (c), hex (0x33727592))
def test_webstyle(self):
c = pygame.Color ("#CC00CC11")
self.assertEquals (c.r, 204)
self.assertEquals (c.g, 0)
self.assertEquals (c.b, 204)
self.assertEquals (c.a, 17)
self.assertEquals (hex (c), hex (0xCC00CC11))
c = pygame.Color ("#CC00CC")
self.assertEquals (c.r, 204)
self.assertEquals (c.g, 0)
self.assertEquals (c.b, 204)
self.assertEquals (c.a, 255)
self.assertEquals (hex (c), hex (0xCC00CCFF))
c = pygame.Color ("0xCC00CC11")
self.assertEquals (c.r, 204)
self.assertEquals (c.g, 0)
self.assertEquals (c.b, 204)
self.assertEquals (c.a, 17)
self.assertEquals (hex (c), hex (0xCC00CC11))
c = pygame.Color ("0xCC00CC")
self.assertEquals (c.r, 204)
self.assertEquals (c.g, 0)
self.assertEquals (c.b, 204)
self.assertEquals (c.a, 255)
self.assertEquals (hex (c), hex (0xCC00CCFF))
self.assertRaises (ValueError, pygame.Color, "#cc00qq")
self.assertRaises (ValueError, pygame.Color, "0xcc00qq")
self.assertRaises (ValueError, pygame.Color, "09abcdef")
self.assertRaises (ValueError, pygame.Color, "09abcde")
self.assertRaises (ValueError, pygame.Color, "quarky")
def test_int (self):
# This will be a long
c = pygame.Color (0xCC00CC00)
self.assertEquals (c.r, 204)
self.assertEquals (c.g, 0)
self.assertEquals (c.b, 204)
self.assertEquals (c.a, 0)
self.assertEquals (int (c), int (0xCC00CC00))
# This will be an int
c = pygame.Color (0x33727592)
self.assertEquals (c.r, 51)
self.assertEquals (c.g, 114)
self.assertEquals (c.b, 117)
self.assertEquals (c.a, 146)
self.assertEquals (int (c), int (0x33727592))
def test_long (self):
# This will be a long
c = pygame.Color (0xCC00CC00)
self.assertEquals (c.r, 204)
self.assertEquals (c.g, 0)
self.assertEquals (c.b, 204)
self.assertEquals (c.a, 0)
self.assertEquals (long_ (c), long_ (0xCC00CC00))
# This will be an int
c = pygame.Color (0x33727592)
self.assertEquals (c.r, 51)
self.assertEquals (c.g, 114)
self.assertEquals (c.b, 117)
self.assertEquals (c.a, 146)
self.assertEquals (long_ (c), long_ (0x33727592))
def test_normalize (self):
c = pygame.Color (204, 38, 194, 55)
self.assertEquals (c.r, 204)
self.assertEquals (c.g, 38)
self.assertEquals (c.b, 194)
self.assertEquals (c.a, 55)
t = c.normalize ()
self.assertAlmostEquals (t[0], 0.800000, 5)
self.assertAlmostEquals (t[1], 0.149016, 5)
self.assertAlmostEquals (t[2], 0.760784, 5)
self.assertAlmostEquals (t[3], 0.215686, 5)
def test_len (self):
c = pygame.Color (204, 38, 194, 55)
self.assertEquals (len (c), 4)
def test_get_item (self):
c = pygame.Color (204, 38, 194, 55)
self.assertEquals (c[0], 204)
self.assertEquals (c[1], 38)
self.assertEquals (c[2], 194)
self.assertEquals (c[3], 55)
def test_set_item (self):
c = pygame.Color (204, 38, 194, 55)
self.assertEquals (c[0], 204)
self.assertEquals (c[1], 38)
self.assertEquals (c[2], 194)
self.assertEquals (c[3], 55)
c[0] = 33
self.assertEquals (c[0], 33)
c[1] = 48
self.assertEquals (c[1], 48)
c[2] = 173
self.assertEquals (c[2], 173)
c[3] = 213
self.assertEquals (c[3], 213)
# Now try some 'invalid' ones
self.assertRaises (ValueError, _assign_item, c, 0, 95.485)
self.assertEquals (c[0], 33)
self.assertRaises (ValueError, _assign_item, c, 1, -83)
self.assertEquals (c[1], 48)
self.assertRaises (ValueError, _assign_item, c, 2, "Hello")
self.assertEquals (c[2], 173)
def test_Color_type_works_for_Surface_get_and_set_colorkey(self):
s = pygame.Surface((32, 32))
c = pygame.Color(33, 22, 11, 255)
s.set_colorkey(c)
get_r, get_g, get_b, get_a = s.get_colorkey()
self.assert_(get_r == c.r)
self.assert_(get_g == c.g)
self.assert_(get_b == c.b)
self.assert_(get_a == c.a)
########## HSLA, HSVA, CMY, I1I2I3 ALL ELEMENTS WITHIN SPECIFIED RANGE #########
def test_hsla__all_elements_within_limits (self):
for c in rgba_combos_Color_generator():
h, s, l, a = c.hsla
self.assert_(0 <= h <= 360)
self.assert_(0 <= s <= 100)
self.assert_(0 <= l <= 100)
self.assert_(0 <= a <= 100)
def test_hsva__all_elements_within_limits (self):
for c in rgba_combos_Color_generator():
h, s, v, a = c.hsva
self.assert_(0 <= h <= 360)
self.assert_(0 <= s <= 100)
self.assert_(0 <= v <= 100)
self.assert_(0 <= a <= 100)
def test_cmy__all_elements_within_limits (self):
for c in rgba_combos_Color_generator():
c, m, y = c.cmy
self.assert_(0 <= c <= 1)
self.assert_(0 <= m <= 1)
self.assert_(0 <= y <= 1)
def test_i1i2i3__all_elements_within_limits (self):
for c in rgba_combos_Color_generator():
i1, i2, i3 = c.i1i2i3
self.assert_( 0 <= i1 <= 1)
self.assert_( -0.5 <= i2 <= 0.5)
self.assert_( -0.5 <= i3 <= 0.5)
####################### COLORSPACE PROPERTY SANITY TESTS #######################
def colorspaces_converted_should_not_raise (self, prop):
fails = 0
x = 0
for c in rgba_combos_Color_generator():
x += 1
other = pygame.Color(0)
try:
setattr(other, prop, getattr(c, prop))
#eg other.hsla = c.hsla
except ValueError:
fails += 1
self.assert_(x > 0, "x is combination counter, 0 means no tests!")
self.assert_((fails, x) == (0, x))
def test_hsla__sanity_testing_converted_should_not_raise (self):
self.colorspaces_converted_should_not_raise('hsla')
def test_hsva__sanity_testing_converted_should_not_raise (self):
self.colorspaces_converted_should_not_raise('hsva')
def test_cmy__sanity_testing_converted_should_not_raise (self):
self.colorspaces_converted_should_not_raise('cmy')
def test_i1i2i3__sanity_testing_converted_should_not_raise (self):
self.colorspaces_converted_should_not_raise('i1i2i3')
################################################################################
def colorspaces_converted_should_equate_bar_rounding (self, prop):
for c in rgba_combos_Color_generator():
other = pygame.Color(0)
try:
setattr(other, prop, getattr(c, prop))
#eg other.hsla = c.hsla
self.assert_(abs(other.r - c.r) <= 1)
self.assert_(abs(other.b - c.b) <= 1)
self.assert_(abs(other.g - c.g) <= 1)
# CMY and I1I2I3 do not care about the alpha
if not prop in ("cmy", "i1i2i3"):
self.assert_(abs(other.a - c.a) <= 1)
except ValueError:
pass # other tests will notify, this tests equation
def test_hsla__sanity_testing_converted_should_equate_bar_rounding(self):
self.colorspaces_converted_should_equate_bar_rounding('hsla')
def test_hsva__sanity_testing_converted_should_equate_bar_rounding(self):
self.colorspaces_converted_should_equate_bar_rounding('hsva')
def test_cmy__sanity_testing_converted_should_equate_bar_rounding(self):
self.colorspaces_converted_should_equate_bar_rounding('cmy')
def test_i1i2i3__sanity_testing_converted_should_equate_bar_rounding(self):
self.colorspaces_converted_should_equate_bar_rounding('i1i2i3')
################################################################################
def test_correct_gamma__verified_against_python_implementation(self):
"|tags:slow|"
# gamma_correct defined at top of page
gammas = [i / 10.0 for i in range(1, 31)] # [0.1 ... 3.0]
gammas_len = len(gammas)
for i, c in enumerate(rgba_combos_Color_generator()):
gamma = gammas[i % gammas_len]
corrected = pygame.Color(*[gamma_correct(x, gamma)
for x in tuple(c)])
lib_corrected = c.correct_gamma(gamma)
self.assert_(corrected.r == lib_corrected.r)
self.assert_(corrected.g == lib_corrected.g)
self.assert_(corrected.b == lib_corrected.b)
self.assert_(corrected.a == lib_corrected.a)
# TODO: test against statically defined verified _correct_ values
# assert corrected.r == 125 etc.
def test_pickle(self):
import pickle
c1 = pygame.Color(1,2,3,4)
#c2 = pygame.Color(255,254,253,252)
pickle_string = pickle.dumps(c1)
c1_frompickle = pickle.loads(pickle_string)
self.assertEqual(c1,c1_frompickle)
################################################################################
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/cdrom_test.py 0000644 0001750 0001750 00000030021 11207055754 017741 0 ustar vincent vincent #################################### IMPORTS ###################################
if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils \
import test_not_implemented, question, prompt, unittest
else:
from test.test_utils \
import test_not_implemented, question, prompt, unittest
import pygame
################################################################################
class CdromModuleTest(unittest.TestCase):
def todo_test_CD(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD:
# pygame.cdrom.CD(id): return CD
# class to manage a cdrom drive
#
# You can create a CD object for each cdrom on the system. Use
# pygame.cdrom.get_count() to determine how many drives actually
# exist. The id argument is an integer of the drive, starting at zero.
#
# The CD object is not initialized, you can only call CD.get_id() and
# CD.get_name() on an uninitialized drive.
#
# It is safe to create multiple CD objects for the same drive, they
# will all cooperate normally.
#
self.fail()
def todo_test_get_count(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.get_count:
# pygame.cdrom.get_count(): return count
# number of cd drives on the system
#
# Return the number of cd drives on the system. When you create CD
# objects you need to pass an integer id that must be lower than this
# count. The count will be 0 if there are no drives on the system.
#
self.fail()
def todo_test_get_init(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.get_init:
# pygame.cdrom.get_init(): return bool
# true if the cdrom module is initialized
#
# Test if the cdrom module is initialized or not. This is different
# than the CD.init() since each drive must also be initialized
# individually.
#
self.fail()
def todo_test_init(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.init:
# pygame.cdrom.init(): return None
# initialize the cdrom module
#
# Initialize the cdrom module. This will scan the system for all CD
# devices. The module must be initialized before any other functions
# will work. This automatically happens when you call pygame.init().
#
# It is safe to call this function more than once.
self.fail()
def todo_test_quit(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.quit:
# pygame.cdrom.quit(): return None
# uninitialize the cdrom module
#
# Uninitialize the cdrom module. After you call this any existing CD
# objects will no longer work.
#
# It is safe to call this function more than once.
self.fail()
class CDTypeTest(unittest.TestCase):
def setUp(self):
pygame.cdrom.init()
#TODO:
try:
self.cd = pygame.cdrom.CD(0)
except pygame.error:
self.cd = None
def tearDown(self):
pygame.cdrom.quit()
def test_1_eject(self):
# __doc__ (as of 2008-07-02) for pygame.cdrom.CD.eject:
# CD.eject(): return None
# eject or open the cdrom drive
# should raise if cd object not initialized
if self.cd:
self.cd.init()
self.cd.eject()
self.assert_(question('Did the cd eject?'))
prompt("Please close the cd drive")
def test_2_get_name(self):
# __doc__ (as of 2008-07-02) for pygame.cdrom.CD.get_name:
# CD.get_name(): return name
# the system name of the cdrom drive
if self.cd:
cd_name = self.cd.get_name()
self.assert_ (
question('Is %s the correct name for the cd drive?' % cd_name)
)
def todo_test_get_all(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.get_all:
# CD.get_all(): return [(audio, start, end, lenth), ...]
# get all track information
#
# Return a list with information for every track on the cdrom. The
# information consists of a tuple with four values. The audio value is
# True if the track contains audio data. The start, end, and length
# values are floating point numbers in seconds. Start and end
# represent absolute times on the entire disc.
#
self.fail()
def todo_test_get_busy(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.get_busy:
# CD.get_busy(): return bool
# true if the drive is playing audio
#
# Returns True if the drive busy playing back audio.
self.fail()
def todo_test_get_current(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.get_current:
# CD.get_current(): return track, seconds
# the current audio playback position
#
# Returns both the current track and time of that track. This method
# works when the drive is either playing or paused.
#
# Note, track 0 is the first track on the CD. Track numbers start at zero.
self.fail()
def todo_test_get_empty(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.get_empty:
# CD.get_empty(): return bool
# False if a cdrom is in the drive
#
# Return False if there is a cdrom currently in the drive. If the
# drive is empty this will return True.
#
self.fail()
def todo_test_get_id(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.get_id:
# CD.get_init(): return bool
# true if this cd device initialized
#
# Returns the integer id that was used to create the CD instance. This
# method can work on an uninitialized CD.
#
self.fail()
def todo_test_get_init(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.get_init:
# CD.get_init(): return bool
# true if this cd device initialized
#
# Test if this CDROM device is initialized. This is different than the
# pygame.cdrom.init() since each drive must also be initialized
# individually.
#
self.fail()
def todo_test_get_numtracks(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.get_numtracks:
# CD.get_numtracks(): return count
# the number of tracks on the cdrom
#
# Return the number of tracks on the cdrom in the drive. This will
# return zero of the drive is empty or has no tracks.
#
self.fail()
def todo_test_get_paused(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.get_paused:
# CD.get_paused(): return bool
# true if the drive is paused
#
# Returns True if the drive is currently paused.
self.fail()
def todo_test_get_track_audio(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.get_track_audio:
# CD.get_track_audio(track): return bool
# true if the cdrom track has audio data
#
# Determine if a track on a cdrom contains audio data. You can also
# call CD.num_tracks() and CD.get_all() to determine more information
# about the cdrom.
#
# Note, track 0 is the first track on the CD. Track numbers start at zero.
self.fail()
def todo_test_get_track_length(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.get_track_length:
# CD.get_track_length(track): return seconds
# length of a cdrom track
#
# Return a floating point value in seconds of the length of the cdrom track.
# Note, track 0 is the first track on the CD. Track numbers start at zero.
self.fail()
def todo_test_get_track_start(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.get_track_start:
# CD.get_track_start(track): return seconds
# start time of a cdrom track
#
# Return the absolute time in seconds where at start of the cdrom track.
# Note, track 0 is the first track on the CD. Track numbers start at zero.
self.fail()
def todo_test_init(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.init:
# CD.init(): return None
# initialize a cdrom drive for use
#
# Initialize the cdrom drive for use. The drive must be initialized
# for most CD methods to work. Even if the rest of pygame has been
# initialized.
#
# There may be a brief pause while the drive is initialized. Avoid
# CD.init() if the program should not stop for a second or two.
#
self.fail()
def todo_test_pause(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.pause:
# CD.pause(): return None
# temporarily stop audio playback
#
# Temporarily stop audio playback on the CD. The playback can be
# resumed at the same point with the CD.resume() method. If the CD is
# not playing this method does nothing.
#
# Note, track 0 is the first track on the CD. Track numbers start at zero.
self.fail()
def todo_test_play(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.play:
# CD.init(): return None
# initialize a cdrom drive for use
#
# Playback audio from an audio cdrom in the drive. Besides the track
# number argument, you can also pass a starting and ending time for
# playback. The start and end time are in seconds, and can limit the
# section of an audio track played.
#
# If you pass a start time but no end, the audio will play to the end
# of the track. If you pass a start time and 'None' for the end time,
# the audio will play to the end of the entire disc.
#
# See the CD.get_numtracks() and CD.get_track_audio() to find tracks to playback.
# Note, track 0 is the first track on the CD. Track numbers start at zero.
self.fail()
def todo_test_quit(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.quit:
# CD.quit(): return None
# uninitialize a cdrom drive for use
#
# Uninitialize a drive for use. Call this when your program will not
# be accessing the drive for awhile.
#
self.fail()
def todo_test_resume(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.resume:
# CD.resume(): return None
# unpause audio playback
#
# Unpause a paused CD. If the CD is not paused or already playing,
# this method does nothing.
#
self.fail()
def todo_test_stop(self):
# __doc__ (as of 2008-08-02) for pygame.cdrom.CD.stop:
# CD.stop(): return None
# stop audio playback
#
# Stops playback of audio from the cdrom. This will also lose the
# current playback position. This method does nothing if the drive
# isn't already playing audio.
#
self.fail()
################################################################################
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/cdrom_tags.py 0000644 0001750 0001750 00000000033 11207055754 017720 0 ustar vincent vincent __tags__ = ['interactive']
pygame-1.9.1release/test/bufferproxy_test.py 0000644 0001750 0001750 00000003745 11207055754 021225 0 ustar vincent vincent #################################### IMPORTS ###################################
if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils import test_not_implemented, unittest
else:
from test.test_utils import test_not_implemented, unittest
import pygame
################################################################################
class BufferProxyTypeTest(unittest.TestCase):
def test_creation(self):
self.assert_(pygame.bufferproxy.BufferProxy())
def todo_test_length(self):
# __doc__ (as of 2008-08-02) for pygame.bufferproxy.BufferProxy.length:
# The size of the buffer data in bytes.
self.fail()
def todo_test_raw(self):
# __doc__ (as of 2008-08-02) for pygame.bufferproxy.BufferProxy.raw:
# The raw buffer data as string. The string may contain NUL bytes.
self.fail()
def todo_test_write(self):
# __doc__ (as of 2008-08-02) for pygame.bufferproxy.BufferProxy.write:
# B.write (bufferproxy, buffer, offset) -> None
#
# Writes raw data to the bufferproxy.
#
# Writes the raw data from buffer to the BufferProxy object, starting
# at the specified offset within the BufferProxy.
# If the length of the passed buffer exceeds the length of the
# BufferProxy (reduced by the offset), an IndexError will be raised.
self.fail()
################################################################################
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/blit_test.py 0000644 0001750 0001750 00000005227 11207055754 017601 0 ustar vincent vincent if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils import unittest
else:
from test.test_utils import unittest
import pygame
from pygame.locals import *
class BlitTest( unittest.TestCase ):
def test_SRCALPHA( self ):
""" SRCALPHA tests.
"""
#blend(s, 0, d) = d
s = pygame.Surface((1,1), SRCALPHA, 32)
s.fill((255, 255,255, 0))
d = pygame.Surface((1,1), SRCALPHA, 32)
d.fill((0, 0,255, 255))
s.blit(d, (0,0))
self.assertEqual(s.get_at((0,0)), d.get_at((0,0)) )
#blend(s, 255, d) = s
s = pygame.Surface((1,1), SRCALPHA, 32)
s.fill((123, 0, 0, 255))
s1 = pygame.Surface((1,1), SRCALPHA, 32)
s1.fill((123, 0, 0, 255))
d = pygame.Surface((1,1), SRCALPHA, 32)
d.fill((10, 0,0, 0))
s.blit(d, (0,0))
self.assertEqual(s.get_at((0,0)), s1.get_at((0,0)) )
#TODO: these should be true too.
#blend(0, sA, 0) = 0
#blend(255, sA, 255) = 255
#blend(s, sA, d) <= 255
def test_BLEND( self ):
""" BLEND_ tests.
"""
#test that it doesn't overflow, and that it is saturated.
s = pygame.Surface((1,1), SRCALPHA, 32)
s.fill((255, 255,255, 0))
d = pygame.Surface((1,1), SRCALPHA, 32)
d.fill((0, 0,255, 255))
s.blit(d, (0,0), None, BLEND_ADD)
#print "d %s" % (d.get_at((0,0)),)
#print s.get_at((0,0))
#self.assertEqual(s.get_at((0,0))[2], 255 )
#self.assertEqual(s.get_at((0,0))[3], 0 )
s.blit(d, (0,0), None, BLEND_RGBA_ADD)
#print s.get_at((0,0))
self.assertEqual(s.get_at((0,0))[3], 255 )
# test adding works.
s.fill((20, 255,255, 0))
d.fill((10, 0,255, 255))
s.blit(d, (0,0), None, BLEND_ADD)
self.assertEqual(s.get_at((0,0))[2], 255 )
# test subbing works.
s.fill((20, 255,255, 0))
d.fill((10, 0,255, 255))
s.blit(d, (0,0), None, BLEND_SUB)
self.assertEqual(s.get_at((0,0))[0], 10 )
# no overflow in sub blend.
s.fill((20, 255,255, 0))
d.fill((30, 0,255, 255))
s.blit(d, (0,0), None, BLEND_SUB)
self.assertEqual(s.get_at((0,0))[0], 0 )
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/base_test.py 0000644 0001750 0001750 00000013162 11207055754 017556 0 ustar vincent vincent if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils import test_not_implemented, unittest
else:
from test.test_utils import test_not_implemented, unittest
import pygame
init_called = quit_called = 0
def __PYGAMEinit__(): #called automatically by pygame.init()
global init_called
init_called = init_called + 1
pygame.register_quit(pygame_quit)
def pygame_quit():
global quit_called
quit_called = quit_called + 1
quit_hook_ran = 0
def quit_hook():
global quit_hook_ran
quit_hook_ran = 1
class BaseModuleTest(unittest.TestCase):
def testAutoInit(self):
pygame.init()
pygame.quit()
self.assertEqual(init_called, 1)
self.assertEqual(quit_called, 1)
def test_get_sdl_byteorder(self):
# __doc__ (as of 2008-06-25) for pygame.base.get_sdl_byteorder:
# pygame.get_sdl_byteorder(): return int
# get the byte order of SDL
self.assert_(pygame.get_sdl_byteorder() + 1)
def test_get_sdl_version(self):
# __doc__ (as of 2008-06-25) for pygame.base.get_sdl_version:
# pygame.get_sdl_version(): return major, minor, patch
# get the version number of SDL
self.assert_( len(pygame.get_sdl_version()) == 3)
def not_init_assertions(self):
self.assert_(not pygame.display.get_init(),
"display shouldn't be initialized" )
self.assert_(not pygame.mixer.get_init(),
"mixer shouldn't be initialized" )
self.assert_(not pygame.font.get_init(),
"init shouldn't be initialized" )
## !!! TODO : Remove when scrap works for OS X
import platform
if platform.system().startswith('Darwin'):
return
try:
self.assertRaises(pygame.error, pygame.scrap.get)
except NotImplementedError:
# Scrap is optional.
pass
# pygame.cdrom
# pygame.joystick
def init_assertions(self):
self.assert_(pygame.display.get_init())
self.assert_(pygame.mixer.get_init())
self.assert_(pygame.font.get_init())
def test_quit__and_init(self):
# __doc__ (as of 2008-06-25) for pygame.base.quit:
# pygame.quit(): return None
# uninitialize all pygame modules
# Make sure everything is not init
self.not_init_assertions()
# Initiate it
pygame.init()
# Check
self.init_assertions()
# Quit
pygame.quit()
# All modules have quit
self.not_init_assertions()
def test_register_quit(self):
# __doc__ (as of 2008-06-25) for pygame.base.register_quit:
# register_quit(callable): return None
# register a function to be called when pygame quits
self.assert_(not quit_hook_ran)
pygame.init()
pygame.register_quit(quit_hook)
pygame.quit()
self.assert_(quit_hook_ran)
def test_get_error(self):
# __doc__ (as of 2008-08-02) for pygame.base.get_error:
# pygame.get_error(): return errorstr
# get the current error message
#
# SDL maintains an internal error message. This message will usually
# be given to you when pygame.error is raised. You will rarely need to
# call this function.
#
self.assertEqual(pygame.get_error(), "")
pygame.set_error("hi")
self.assertEqual(pygame.get_error(), "hi")
pygame.set_error("")
self.assertEqual(pygame.get_error(), "")
def test_set_error(self):
self.assertEqual(pygame.get_error(), "")
pygame.set_error("hi")
self.assertEqual(pygame.get_error(), "hi")
pygame.set_error("")
self.assertEqual(pygame.get_error(), "")
def test_init(self):
# __doc__ (as of 2008-08-02) for pygame.base.init:
# pygame.init(): return (numpass, numfail)
# initialize all imported pygame modules
#
# Initialize all imported Pygame modules. No exceptions will be raised
# if a module fails, but the total number if successful and failed
# inits will be returned as a tuple. You can always initialize
# individual modules manually, but pygame.init is a convenient way to
# get everything started. The init() functions for individual modules
# will raise exceptions when they fail.
#
# You may want to initalise the different modules seperately to speed
# up your program or to not use things your game does not.
#
# It is safe to call this init() more than once: repeated calls will
# have no effect. This is true even if you have pygame.quit() all the
# modules.
#
# Make sure everything is not init
self.not_init_assertions()
# Initiate it
pygame.init()
# Check
self.init_assertions()
# Quit
pygame.quit()
# All modules have quit
self.not_init_assertions()
def todo_test_segfault(self):
# __doc__ (as of 2008-08-02) for pygame.base.segfault:
# crash
self.fail()
if __name__ == '__main__':
unittest.main()
pygame-1.9.1release/test/__main__.py 0000644 0001750 0001750 00000007460 11210364057 017322 0 ustar vincent vincent """Load and run the Pygame test suite
python -c "import pygame.tests.go" []
or
python test/go.py []
Command line option --help displays a command line usage message.
run_tests.py in the main distribution directory is an alternative to test.go
"""
import sys
if __name__ == '__main__':
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils.run_tests import run
from pygame.tests.test_utils.test_runner import opt_parser
else:
from test.test_utils.run_tests import run
from test.test_utils.test_runner import opt_parser
if is_pygame_pkg:
test_pkg_name = "pygame.tests"
else:
test_pkg_name = "test"
program_name = sys.argv[0]
if program_name == '-c':
program_name = 'python -c "import %s.go"' % test_pkg_name
###########################################################################
# Set additional command line options
#
# Defined in test_runner.py as it shares options, added to here
opt_parser.set_usage("""
Runs all or some of the %(pkg)s.xxxx_test tests.
$ %(exec)s sprite threads -sd
Runs the sprite and threads module tests isolated in subprocesses, dumping
all failing tests info in the form of a dict.
""" % {'pkg': test_pkg_name, 'exec': program_name})
opt_parser.add_option (
"-d", "--dump", action = 'store_true',
help = "dump failures/errors as dict ready to eval" )
opt_parser.add_option (
"-F", "--file",
help = "dump failures/errors to a file" )
opt_parser.add_option (
"-a", "--all", action = 'store_true',
help = "dump all results not just errors eg. -da" )
opt_parser.add_option (
"-m", "--multi_thread", metavar = 'THREADS', type = 'int',
help = "run subprocessed tests in x THREADS" )
opt_parser.add_option (
"-t", "--time_out", metavar = 'SECONDS', type = 'int',
help = "kill stalled subprocessed tests after SECONDS" )
opt_parser.add_option (
"-f", "--fake", metavar = "DIR",
help = "run fake tests in run_tests__tests/$DIR" )
opt_parser.add_option (
"-p", "--python", metavar = "PYTHON",
help = "path to python excutable to run subproccesed tests\n"
"default (sys.executable): %s" % sys.executable)
opt_parser.add_option (
"-I", "--interactive", action = 'store_true',
help = "include tests requiring user input")
###########################################################################
# Set run() keyword arguements according to command line arguemnts.
# args will be the test module list, passed as positional argumemts.
options, args = opt_parser.parse_args()
kwds = {}
if options.incomplete:
kwds['incomplete'] = True
if options.nosubprocess:
kwds['nosubprocess'] = True
if options.dump:
kwds['dump'] = True
if options.file:
kwds['file'] = options.file
kwds['timings'] = options.timings
if options.exclude:
kwds['exclude'] = options.exclude
if options.show_output:
kwds['show_output'] = True
if options.all:
kwds['all'] = True
if options.randomize:
kwds['randomize'] = True
if options.seed is not None:
kwds['seed'] = options.seed
if options.multi_thread is not None:
kwds['multi_thread'] = options.multi_thread
if options.time_out is not None:
kwds['time_out'] = options.time_out
if options.fake:
kwds['fake'] = options.fake
if options.python:
kwds['python'] = options.python
if options.interactive:
kwds['interactive'] = True
###########################################################################
# Run the test suite.
run(*args, **kwds)
pygame-1.9.1release/test/__init__.py 0000644 0001750 0001750 00000002371 11211102014 017315 0 ustar vincent vincent """Pygame unit test suite package
Exports function run()
A quick way to run the test suite package from the command line
is by importing the go submodule:
python -m "import pygame.tests" []
Command line option --help displays a usage message. Available options
correspond to the pygame.tests.run arguments.
The xxxx_test submodules of the tests package are unit test suites for
individual parts of Pygame. Each can also be run as a main program. This is
useful if the test, such as cdrom_test, is interactive.
For Pygame development the test suite can be run from a Pygame distribution
root directory using run_tests.py. Alternately, test/__main__.py can be run
directly.
"""
if __name__ == 'pygame.tests':
from pygame.tests.test_utils.run_tests import run
elif __name__ == '__main__':
import os
import sys
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
if is_pygame_pkg:
import pygame.tests.__main__
else:
import test.__main__
else:
from test.test_utils.run_tests import run
pygame-1.9.1release/src/transform.doc 0000644 0001750 0001750 00000017304 11206423535 017542 0 ustar vincent vincent pygame.transform
pygame module to transform surfaces
A Surface transform is an operation that moves or resizes the pixels. All
these functions take a Surface to operate on and return a new Surface with
the results.
Some of the transforms are considered destructive. These means every time
they are performed they lose pixel data. Common examples of this are resizing
and rotating. For this reason, it is better to retransform the original surface than to
keep transforming an image multiple times. (For example, suppose you are animating
a bouncing spring which expands and contracts. If you applied the size changes
incrementally to the previous images, you would lose detail. Instead, always
begin with the original image and scale to the desired size.)
flip
flip vertically and horizontally
pygame.transform.flip(Surface, xbool, ybool): return Surface
This can flip a Surface either vertically, horizontally, or both. Flipping
a Surface is nondestructive and returns a new Surface with the same dimensions.
scale
resize to new resolution
pygame.transform.scale(Surface, (width, height), DestSurface = None): return Surface
Resizes the Surface to a new resolution. This is a fast scale operation
that does not sample the results.
An optional destination surface can be used, rather than have it create
a new one. This is quicker if you want to repeatedly scale something.
However the destination must be the same size as the (width, height) passed
in. Also the destination surface must be the same format.
rotate
rotate an image
pygame.transform.rotate(Surface, angle): return Surface
Unfiltered counterclockwise rotation. The angle argument represents degrees
and can be any floating point value. Negative angle amounts will rotate
clockwise.
Unless rotating by 90 degree increments, the image will be padded larger
to hold the new size. If the image has pixel alphas, the padded area will
be transparent. Otherwise pygame will pick a color that matches the Surface
colorkey or the topleft pixel value.
rotozoom
filtered scale and rotation
pygame.transform.rotozoom(Surface, angle, scale): return Surface
This is a combined scale and rotation transform. The resulting Surface will
be a filtered 32-bit Surface. The scale argument is a floating point value
that will be multiplied by the current resolution. The angle argument is
a floating point value that represents the counterclockwise degrees to
rotate. A negative rotation angle will rotate clockwise.
scale2x
specialized image doubler
pygame.transform.scale2x(Surface, DestSurface = None): Surface
This will return a new image that is double the size of the original. It uses
the AdvanceMAME Scale2X algorithm which does a 'jaggie-less' scale of bitmap
graphics.
This really only has an effect on simple images with solid colors. On
photographic and antialiased images it will look like a regular unfiltered
scale.
An optional destination surface can be used, rather than have it create
a new one. This is quicker if you want to repeatedly scale something.
However the destination must be twice the size of the source surface passed
in. Also the destination surface must be the same format.
smoothscale
scale a surface to an arbitrary size smoothly
pygame.transform.smoothscale(Surface, (width, height), DestSurface = None): return Surface
Uses one of two different algorithms for scaling each
dimension of the input surface as required. For shrinkage,
the output pixels are area averages of the colors they
cover. For expansion, a bilinear filter is used. For the
amd64 and i686 architectures, optimized MMX routines are
included and will run much faster than other machine types.
The size is a 2 number sequence for (width, height). This
function only works for 24-bit or 32-bit surfaces. An
exception will be thrown if the input surface bit depth is
less than 24.
New in pygame 1.8
get_smoothscale_backend
return smoothscale filter version in use: 'GENERIC', 'MMX', or 'SSE'
pygame.transform.get_smoothscale_backend(): return String
Shows whether or not smoothscale is using MMX or SSE acceleration.
If no acceleration is available then "GENERIC" is returned. For a
x86 processor the level of acceleration to use is determined at
runtime.
This function is provided for Pygame testing and debugging.
set_smoothscale_backend
set smoothscale filter version to one of: 'GENERIC', 'MMX', or 'SSE'
pygame.transform.get_smoothscale_backend(type): return None
Sets smoothscale acceleration. Takes a string argument. A value
of 'GENERIC' turns off acceleration. 'MMX' uses MMX instructions
only. 'SSE' allows SSE extensions as well. A value error is raised
if type is not recognized or not supported by the current processor.
This function is provided for Pygame testing and debugging. If
smoothscale causes an invalid instruction error then it is a
Pygame/SDL bug that should be reported. Use this function as a
temporary fix only.
chop
gets a copy of an image with an interior area removed
pygame.transform.chop(Surface, rect): return Surface
Extracts a portion of an image. All vertical and
horizontal pixels surrounding the given rectangle area are removed.
The corner areas (diagonal to the rect) are then brought together.
(The original image is not altered by this operation.)
NOTE: If you want a "crop" that returns the part of an image within
a rect, you can blit with a rect to a new surface or copy a subsurface.
laplacian
find edges in a surface
pygame.transform.laplacian(Surface, DestSurface = None): return Surface
Finds the edges in a surface using the laplacian algorithm.
New in pygame 1.8
average_surfaces
find the average surface from many surfaces.
pygame.transform.average_surfaces(Surfaces, DestSurface = None, palette_colors = 1): return Surface
Takes a sequence of surfaces and returns a surface with average colors from each
of the surfaces.
palette_colors - if true we average the colors in palette, otherwise we
average the pixel values. This is useful if the surface is actually greyscale
colors, and not palette colors.
Note, this function currently does not handle palette using surfaces correctly.
New in pygame 1.8
palette_colors argument new in pygame 1.9
average_color
finds the average color of a surface
pygame.transform.average_color(Surface, Rect = None): return Color
Finds the average color of a Surface or a region of a surface specified by a
Rect, and returns it as a Color.
threshold
finds which, and how many pixels in a surface are within a threshold of a color.
pygame.transform.threshold(DestSurface, Surface, color, threshold = (0,0,0,0), diff_color = (0,0,0,0), change_return = 1, Surface = None, inverse = False): return num_threshold_pixels
Finds which, and how many pixels in a surface are within a threshold of a color.
It can set the destination surface where all of the pixels not within the
threshold are changed to diff_color. If inverse is optionally set to True, the
pixels that are within the threshold are instead changed to diff_color.
If the optional second surface is given, it is used to threshold against
rather than the specified color. That is, it will find each pixel in the first
Surface that is within the threshold of the pixel at the same coordinates of
the second Surface.
If change_return is set to 0, it can be used to just count the number of
pixels within the threshold if you set
If change_return is set to 1, the pixels set in DestSurface will be
those from the color.
If change_return is set to 2, the pixels set in DestSurface will be
those from the first Surface.
You can use a threshold of (r,g,b,a) where the r,g,b can have different thresholds. So
you could use an r threshold of 40 and a blue threshold of 2 if you like.
New in pygame 1.8
pygame-1.9.1release/src/transform.c 0000644 0001750 0001750 00000255700 11207055754 017230 0 ustar vincent vincent /*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
Copyright (C) 2007 Rene Dudfield, Richard Goedeken
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
/*
* surface transformations for pygame
*/
#include "pygame.h"
#include "pgcompat.h"
#include "pygamedocs.h"
#include
#include
#include "scale.h"
typedef void (* SMOOTHSCALE_FILTER_P)(Uint8 *, Uint8 *, int, int, int, int, int);
struct _module_state {
const char *filter_type;
SMOOTHSCALE_FILTER_P filter_shrink_X;
SMOOTHSCALE_FILTER_P filter_shrink_Y;
SMOOTHSCALE_FILTER_P filter_expand_X;
SMOOTHSCALE_FILTER_P filter_expand_Y;
};
#if defined(SCALE_MMX_SUPPORT)
#include
#if PY3
#define GETSTATE(m) PY3_GETSTATE (_module_state, m)
#else
static struct _module_state _state = {0, 0, 0, 0, 0};
#define GETSTATE(m) PY2_GETSTATE (_state)
#endif
#else /* if defined(SCALE_MMX_SUPPORT) */
static void filter_shrink_X_ONLYC(Uint8 *, Uint8 *, int, int, int, int, int);
static void filter_shrink_Y_ONLYC(Uint8 *, Uint8 *, int, int, int, int, int);
static void filter_expand_X_ONLYC(Uint8 *, Uint8 *, int, int, int, int, int);
static void filter_expand_Y_ONLYC(Uint8 *, Uint8 *, int, int, int, int, int);
static struct _module_state _state = {
"GENERIC",
filter_shrink_X_ONLYC,
filter_shrink_Y_ONLYC,
filter_expand_X_ONLYC,
filter_expand_Y_ONLYC};
#define GETSTATE(m) PY2_GETSTATE (_state)
#define smoothscale_init(st)
#endif /* if defined(SCALE_MMX_SUPPORT) */
void scale2x (SDL_Surface *src, SDL_Surface *dst);
extern SDL_Surface* rotozoomSurface (SDL_Surface *src, double angle,
double zoom, int smooth);
static SDL_Surface*
newsurf_fromsurf (SDL_Surface* surf, int width, int height)
{
SDL_Surface* newsurf;
int result;
if (surf->format->BytesPerPixel <= 0 || surf->format->BytesPerPixel > 4)
return (SDL_Surface*)
(RAISE (PyExc_ValueError,
"unsupport Surface bit depth for transform"));
newsurf = SDL_CreateRGBSurface (surf->flags, width, height,
surf->format->BitsPerPixel,
surf->format->Rmask, surf->format->Gmask,
surf->format->Bmask, surf->format->Amask);
if (!newsurf)
return (SDL_Surface*) (RAISE (PyExc_SDLError, SDL_GetError ()));
/* Copy palette, colorkey, etc info */
if (surf->format->BytesPerPixel==1 && surf->format->palette)
SDL_SetColors (newsurf, surf->format->palette->colors, 0,
surf->format->palette->ncolors);
if (surf->flags & SDL_SRCCOLORKEY)
SDL_SetColorKey (newsurf, (surf->flags&SDL_RLEACCEL) | SDL_SRCCOLORKEY,
surf->format->colorkey);
if (surf->flags&SDL_SRCALPHA)
{
result = SDL_SetAlpha (newsurf, surf->flags, surf->format->alpha);
if (result == -1)
return (SDL_Surface*) (RAISE (PyExc_SDLError, SDL_GetError ()));
}
return newsurf;
}
static SDL_Surface*
rotate90 (SDL_Surface *src, int angle)
{
int numturns = (angle / 90) % 4;
int dstwidth, dstheight;
SDL_Surface* dst;
char *srcpix, *dstpix, *srcrow, *dstrow;
int srcstepx, srcstepy, dststepx, dststepy;
int loopx, loopy;
if (numturns < 0)
numturns = 4 + numturns;
if (!(numturns % 2))
{
dstwidth = src->w;
dstheight = src->h;
}
else
{
dstwidth = src->h;
dstheight = src->w;
}
dst = newsurf_fromsurf (src, dstwidth, dstheight);
if (!dst)
return NULL;
SDL_LockSurface (dst);
srcrow = (char*) src->pixels;
dstrow = (char*) dst->pixels;
srcstepx = dststepx = src->format->BytesPerPixel;
srcstepy = src->pitch;
dststepy = dst->pitch;
switch (numturns)
{
/*case 0: we don't need to change anything*/
case 1:
srcrow += ((src->w - 1) * srcstepx);
srcstepy = -srcstepx;
srcstepx = src->pitch;
break;
case 2:
srcrow += ((src->h - 1) * srcstepy) + ((src->w - 1) * srcstepx);
srcstepx = -srcstepx;
srcstepy = -srcstepy;
break;
case 3:
srcrow += ((src->h - 1) * srcstepy);
srcstepx = -srcstepy;
srcstepy = src->format->BytesPerPixel;
break;
}
switch (src->format->BytesPerPixel)
{
case 1:
for (loopy = 0; loopy < dstheight; ++loopy)
{
dstpix = dstrow;
srcpix = srcrow;
for (loopx = 0; loopx < dstwidth; ++loopx)
{
*dstpix = *srcpix;
srcpix += srcstepx;
dstpix += dststepx;
}
dstrow += dststepy;
srcrow += srcstepy;
}
break;
case 2:
for (loopy = 0; loopy < dstheight; ++loopy)
{
dstpix = dstrow;
srcpix = srcrow;
for (loopx = 0; loopx < dstwidth; ++loopx)
{
*(Uint16*)dstpix = *(Uint16*)srcpix;
srcpix += srcstepx;
dstpix += dststepx;
}
dstrow += dststepy;
srcrow += srcstepy;
}
break;
case 3:
for (loopy = 0; loopy < dstheight; ++loopy)
{
dstpix = dstrow;
srcpix = srcrow;
for (loopx = 0; loopx < dstwidth; ++loopx)
{
dstpix[0] = srcpix[0];
dstpix[1] = srcpix[1];
dstpix[2] = srcpix[2];
srcpix += srcstepx;
dstpix += dststepx;
}
dstrow += dststepy;
srcrow += srcstepy;
}
break;
case 4:
for (loopy = 0; loopy < dstheight; ++loopy)
{
dstpix = dstrow;
srcpix = srcrow;
for (loopx = 0; loopx < dstwidth; ++loopx)
{
*(Uint32*)dstpix = *(Uint32*)srcpix;
srcpix += srcstepx;
dstpix += dststepx;
}
dstrow += dststepy;
srcrow += srcstepy;
}
break;
}
SDL_UnlockSurface (dst);
return dst;
}
static void
rotate (SDL_Surface *src, SDL_Surface *dst, Uint32 bgcolor, double sangle,
double cangle)
{
int x, y, dx, dy;
Uint8 *srcpix = (Uint8*) src->pixels;
Uint8 *dstrow = (Uint8*) dst->pixels;
int srcpitch = src->pitch;
int dstpitch = dst->pitch;
int cy = dst->h / 2;
int xd = ((src->w - dst->w) << 15);
int yd = ((src->h - dst->h) << 15);
int isin = (int)(sangle * 65536);
int icos = (int)(cangle * 65536);
int ax = ((dst->w) << 15) - (int)(cangle * ((dst->w - 1) << 15));
int ay = ((dst->h) << 15) - (int)(sangle * ((dst->w - 1) << 15));
int xmaxval = ((src->w) << 16) - 1;
int ymaxval = ((src->h) << 16) - 1;
switch (src->format->BytesPerPixel)
{
case 1:
for (y = 0; y < dst->h; y++)
{
Uint8 *dstpos = (Uint8*)dstrow;
dx = (ax + (isin * (cy - y))) + xd;
dy = (ay - (icos * (cy - y))) + yd;
for (x = 0; x < dst->w; x++)
{
if(dx < 0 || dy < 0 || dx > xmaxval || dy > ymaxval)
*dstpos++ = bgcolor;
else
*dstpos++ = *(Uint8*)
(srcpix + ((dy >> 16) * srcpitch) + (dx >> 16));
dx += icos;
dy += isin;
}
dstrow += dstpitch;
}
break;
case 2:
for (y = 0; y < dst->h; y++)
{
Uint16 *dstpos = (Uint16*)dstrow;
dx = (ax + (isin * (cy - y))) + xd;
dy = (ay - (icos * (cy - y))) + yd;
for (x = 0; x < dst->w; x++)
{
if (dx < 0 || dy < 0 || dx > xmaxval || dy > ymaxval)
*dstpos++ = bgcolor;
else
*dstpos++ = *(Uint16*)
(srcpix + ((dy >> 16) * srcpitch) + (dx >> 16 << 1));
dx += icos;
dy += isin;
}
dstrow += dstpitch;
}
break;
case 4:
for (y = 0; y < dst->h; y++)
{
Uint32 *dstpos = (Uint32*)dstrow;
dx = (ax + (isin * (cy - y))) + xd;
dy = (ay - (icos * (cy - y))) + yd;
for (x = 0; x < dst->w; x++)
{
if (dx < 0 || dy < 0 || dx > xmaxval || dy > ymaxval)
*dstpos++ = bgcolor;
else
*dstpos++ = *(Uint32*)
(srcpix + ((dy >> 16) * srcpitch) + (dx >> 16 << 2));
dx += icos;
dy += isin;
}
dstrow += dstpitch;
}
break;
default: /*case 3:*/
for (y = 0; y < dst->h; y++)
{
Uint8 *dstpos = (Uint8*)dstrow;
dx = (ax + (isin * (cy - y))) + xd;
dy = (ay - (icos * (cy - y))) + yd;
for (x = 0; x < dst->w; x++)
{
if (dx < 0 || dy < 0 || dx > xmaxval || dy > ymaxval)
{
dstpos[0] = ((Uint8*) &bgcolor)[0];
dstpos[1] = ((Uint8*) &bgcolor)[1];
dstpos[2] = ((Uint8*) &bgcolor)[2];
dstpos += 3;
}
else
{
Uint8* srcpos = (Uint8*)
(srcpix + ((dy >> 16) * srcpitch) + ((dx >> 16) * 3));
dstpos[0] = srcpos[0];
dstpos[1] = srcpos[1];
dstpos[2] = srcpos[2];
dstpos += 3;
}
dx += icos; dy += isin;
}
dstrow += dstpitch;
}
break;
}
}
static void
stretch (SDL_Surface *src, SDL_Surface *dst)
{
int looph, loopw;
Uint8* srcrow = (Uint8*) src->pixels;
Uint8* dstrow = (Uint8*) dst->pixels;
int srcpitch = src->pitch;
int dstpitch = dst->pitch;
int dstwidth = dst->w;
int dstheight = dst->h;
int dstwidth2 = dst->w << 1;
int dstheight2 = dst->h << 1;
int srcwidth2 = src->w << 1;
int srcheight2 = src->h << 1;
int w_err, h_err = srcheight2 - dstheight2;
switch (src->format->BytesPerPixel)
{
case 1:
for (looph = 0; looph < dstheight; ++looph)
{
Uint8 *srcpix = (Uint8*)srcrow, *dstpix = (Uint8*)dstrow;
w_err = srcwidth2 - dstwidth2;
for (loopw = 0; loopw < dstwidth; ++ loopw)
{
*dstpix++ = *srcpix;
while (w_err >= 0)
{
++srcpix;
w_err -= dstwidth2;
}
w_err += srcwidth2;
}
while (h_err >= 0)
{
srcrow += srcpitch;
h_err -= dstheight2;
}
dstrow += dstpitch;
h_err += srcheight2;
}
break;
case 2:
for (looph = 0; looph < dstheight; ++looph)
{
Uint16 *srcpix = (Uint16*)srcrow, *dstpix = (Uint16*)dstrow;
w_err = srcwidth2 - dstwidth2;
for (loopw = 0; loopw < dstwidth; ++ loopw)
{
*dstpix++ = *srcpix;
while (w_err >= 0)
{
++srcpix;
w_err -= dstwidth2;
}
w_err += srcwidth2;
}
while (h_err >= 0)
{
srcrow += srcpitch;
h_err -= dstheight2;
}
dstrow += dstpitch;
h_err += srcheight2;
}
break;
case 3:
for (looph = 0; looph < dstheight; ++looph)
{
Uint8 *srcpix = (Uint8*)srcrow, *dstpix = (Uint8*)dstrow;
w_err = srcwidth2 - dstwidth2;
for (loopw = 0; loopw < dstwidth; ++ loopw)
{
dstpix[0] = srcpix[0];
dstpix[1] = srcpix[1];
dstpix[2] = srcpix[2];
dstpix += 3;
while (w_err >= 0)
{
srcpix+=3;
w_err -= dstwidth2;
}
w_err += srcwidth2;
}
while (h_err >= 0)
{
srcrow += srcpitch;
h_err -= dstheight2;
}
dstrow += dstpitch;
h_err += srcheight2;
}
break;
default: /*case 4:*/
for (looph = 0; looph < dstheight; ++looph)
{
Uint32 *srcpix = (Uint32*)srcrow, *dstpix = (Uint32*)dstrow;
w_err = srcwidth2 - dstwidth2;
for (loopw = 0; loopw < dstwidth; ++ loopw)
{
*dstpix++ = *srcpix;
while (w_err >= 0)
{
++srcpix;
w_err -= dstwidth2;
}
w_err += srcwidth2;
}
while (h_err >= 0)
{
srcrow += srcpitch;
h_err -= dstheight2;
}
dstrow += dstpitch;
h_err += srcheight2;
}
break;
}
}
static PyObject*
surf_scale (PyObject* self, PyObject* arg)
{
PyObject *surfobj, *surfobj2;
SDL_Surface* surf, *newsurf;
int width, height;
surfobj2 = NULL;
/*get all the arguments*/
if (!PyArg_ParseTuple (arg, "O!(ii)|O!", &PySurface_Type, &surfobj,
&width, &height, &PySurface_Type, &surfobj2))
return NULL;
if (width < 0 || height < 0)
return RAISE (PyExc_ValueError, "Cannot scale to negative size");
surf = PySurface_AsSurface (surfobj);
if (!surfobj2)
{
newsurf = newsurf_fromsurf (surf, width, height);
if (!newsurf)
return NULL;
}
else
newsurf = PySurface_AsSurface (surfobj2);
/* check to see if the size is twice as big. */
if (newsurf->w != width || newsurf->h != height)
return RAISE (PyExc_ValueError,
"Destination surface not the given width or height.");
/* check to see if the format of the surface is the same. */
if (surf->format->BytesPerPixel != newsurf->format->BytesPerPixel)
return RAISE (PyExc_ValueError,
"Source and destination surfaces need the same format.");
if (width && height)
{
SDL_LockSurface (newsurf);
PySurface_Lock (surfobj);
Py_BEGIN_ALLOW_THREADS;
stretch (surf, newsurf);
Py_END_ALLOW_THREADS;
PySurface_Unlock (surfobj);
SDL_UnlockSurface (newsurf);
}
if (surfobj2)
{
Py_INCREF (surfobj2);
return surfobj2;
}
else
return PySurface_New (newsurf);
}
static PyObject*
surf_scale2x (PyObject* self, PyObject* arg)
{
PyObject *surfobj, *surfobj2;
SDL_Surface *surf;
SDL_Surface *newsurf;
int width, height;
surfobj2 = NULL;
/*get all the arguments*/
if (!PyArg_ParseTuple (arg, "O!|O!", &PySurface_Type, &surfobj,
&PySurface_Type, &surfobj2))
return NULL;
surf = PySurface_AsSurface (surfobj);
/* if the second surface is not there, then make a new one. */
if (!surfobj2)
{
width = surf->w * 2;
height = surf->h * 2;
newsurf = newsurf_fromsurf (surf, width, height);
if (!newsurf)
return NULL;
}
else
newsurf = PySurface_AsSurface (surfobj2);
/* check to see if the size is twice as big. */
if (newsurf->w != (surf->w * 2) || newsurf->h != (surf->h * 2))
return RAISE (PyExc_ValueError, "Destination surface not 2x bigger.");
/* check to see if the format of the surface is the same. */
if (surf->format->BytesPerPixel != newsurf->format->BytesPerPixel)
return RAISE (PyExc_ValueError,
"Source and destination surfaces need the same format.");
SDL_LockSurface (newsurf);
SDL_LockSurface (surf);
Py_BEGIN_ALLOW_THREADS;
scale2x (surf, newsurf);
Py_END_ALLOW_THREADS;
SDL_UnlockSurface (surf);
SDL_UnlockSurface (newsurf);
if (surfobj2)
{
Py_INCREF (surfobj2);
return surfobj2;
}
else
return PySurface_New (newsurf);
}
static PyObject*
surf_rotate (PyObject* self, PyObject* arg)
{
PyObject *surfobj;
SDL_Surface* surf, *newsurf;
float angle;
double radangle, sangle, cangle;
double x, y, cx, cy, sx, sy;
int nxmax,nymax;
Uint32 bgcolor;
/*get all the arguments*/
if (!PyArg_ParseTuple (arg, "O!f", &PySurface_Type, &surfobj, &angle))
return NULL;
surf = PySurface_AsSurface (surfobj);
if (surf->format->BytesPerPixel <= 0 || surf->format->BytesPerPixel > 4)
return RAISE (PyExc_ValueError,
"unsupport Surface bit depth for transform");
if ( !( fmod((double)angle, (double)90.0f) ) ) {
PySurface_Lock (surfobj);
Py_BEGIN_ALLOW_THREADS;
newsurf = rotate90 (surf, (int) angle);
Py_END_ALLOW_THREADS;
PySurface_Unlock (surfobj);
if (!newsurf)
return NULL;
return PySurface_New (newsurf);
}
radangle = angle*.01745329251994329;
sangle = sin (radangle);
cangle = cos (radangle);
x = surf->w;
y = surf->h;
cx = cangle*x;
cy = cangle*y;
sx = sangle*x;
sy = sangle*y;
nxmax = (int) (MAX (MAX (MAX (fabs (cx + sy), fabs (cx - sy)),
fabs (-cx + sy)), fabs (-cx - sy)));
nymax = (int) (MAX (MAX (MAX (fabs (sx + cy), fabs (sx - cy)),
fabs (-sx + cy)), fabs (-sx - cy)));
newsurf = newsurf_fromsurf (surf, nxmax, nymax);
if (!newsurf)
return NULL;
/* get the background color */
if (surf->flags & SDL_SRCCOLORKEY)
bgcolor = surf->format->colorkey;
else
{
SDL_LockSurface (surf);
switch (surf->format->BytesPerPixel)
{
case 1:
bgcolor = *(Uint8*) surf->pixels;
break;
case 2:
bgcolor = *(Uint16*) surf->pixels;
break;
case 4:
bgcolor = *(Uint32*) surf->pixels;
break;
default: /*case 3:*/
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
bgcolor = (((Uint8*) surf->pixels)[0]) +
(((Uint8*) surf->pixels)[1] << 8) +
(((Uint8*) surf->pixels)[2] << 16);
#else
bgcolor = (((Uint8*) surf->pixels)[2]) +
(((Uint8*) surf->pixels)[1] << 8) +
(((Uint8*) surf->pixels)[0] << 16);
#endif
}
SDL_UnlockSurface (surf);
bgcolor &= ~surf->format->Amask;
}
SDL_LockSurface (newsurf);
PySurface_Lock (surfobj);
Py_BEGIN_ALLOW_THREADS;
rotate (surf, newsurf, bgcolor, sangle, cangle);
Py_END_ALLOW_THREADS;
PySurface_Unlock (surfobj);
SDL_UnlockSurface (newsurf);
return PySurface_New (newsurf);
}
static PyObject*
surf_flip (PyObject* self, PyObject* arg)
{
PyObject *surfobj;
SDL_Surface* surf, *newsurf;
int xaxis, yaxis;
int loopx, loopy;
int pixsize, srcpitch, dstpitch;
Uint8 *srcpix, *dstpix;
/*get all the arguments*/
if (!PyArg_ParseTuple (arg, "O!ii", &PySurface_Type, &surfobj,
&xaxis, &yaxis))
return NULL;
surf = PySurface_AsSurface (surfobj);
newsurf = newsurf_fromsurf (surf, surf->w, surf->h);
if (!newsurf)
return NULL;
pixsize = surf->format->BytesPerPixel;
srcpitch = surf->pitch;
dstpitch = newsurf->pitch;
SDL_LockSurface (newsurf);
PySurface_Lock (surfobj);
srcpix = (Uint8*) surf->pixels;
dstpix = (Uint8*) newsurf->pixels;
Py_BEGIN_ALLOW_THREADS;
if (!xaxis)
{
if (!yaxis)
{
for (loopy = 0; loopy < surf->h; ++loopy)
memcpy (dstpix + loopy * dstpitch, srcpix + loopy * srcpitch,
surf->w * surf->format->BytesPerPixel);
}
else
{
for (loopy = 0; loopy < surf->h; ++loopy)
memcpy (dstpix + loopy * dstpitch,
srcpix + (surf->h - 1 - loopy) * srcpitch,
surf->w * surf->format->BytesPerPixel);
}
}
else /*if (xaxis)*/
{
if (yaxis)
{
switch (surf->format->BytesPerPixel)
{
case 1:
for (loopy = 0; loopy < surf->h; ++loopy)
{
Uint8* dst = (Uint8*) (dstpix + loopy * dstpitch);
Uint8* src = ((Uint8*) (srcpix + (surf->h - 1 - loopy)
* srcpitch)) + surf->w - 1;
for (loopx = 0; loopx < surf->w; ++loopx)
*dst++ = *src--;
}
break;
case 2:
for (loopy = 0; loopy < surf->h; ++loopy)
{
Uint16* dst = (Uint16*) (dstpix + loopy * dstpitch);
Uint16* src = ((Uint16*)
(srcpix + (surf->h - 1 - loopy)
* srcpitch)) + surf->w - 1;
for (loopx = 0; loopx < surf->w; ++loopx)
*dst++ = *src--;
}
break;
case 4:
for (loopy = 0; loopy < surf->h; ++loopy)
{
Uint32* dst = (Uint32*) (dstpix + loopy * dstpitch);
Uint32* src = ((Uint32*)
(srcpix + (surf->h - 1 - loopy)
* srcpitch)) + surf->w - 1;
for (loopx = 0; loopx < surf->w; ++loopx)
*dst++ = *src--;
}
break;
case 3:
for (loopy = 0; loopy < surf->h; ++loopy)
{
Uint8* dst = (Uint8*) (dstpix + loopy * dstpitch);
Uint8* src = ((Uint8*) (srcpix + (surf->h - 1 - loopy)
* srcpitch)) + surf->w * 3 - 3;
for (loopx = 0; loopx < surf->w; ++loopx)
{
dst[0] = src[0];
dst[1] = src[1];
dst[2] = src[2];
dst += 3;
src -= 3;
}
}
break;
}
}
else
{
switch (surf->format->BytesPerPixel)
{
case 1:
for (loopy = 0; loopy < surf->h; ++loopy)
{
Uint8* dst = (Uint8*) (dstpix + loopy * dstpitch);
Uint8* src = ((Uint8*) (srcpix + loopy * srcpitch)) +
surf->w - 1;
for (loopx = 0; loopx < surf->w; ++loopx)
*dst++ = *src--;
}
break;
case 2:
for (loopy = 0; loopy < surf->h; ++loopy)
{
Uint16* dst = (Uint16*) (dstpix + loopy * dstpitch);
Uint16* src = ((Uint16*) (srcpix + loopy * srcpitch))
+ surf->w - 1;
for (loopx = 0; loopx < surf->w; ++loopx)
*dst++ = *src--;
}
break;
case 4:
for (loopy = 0; loopy < surf->h; ++loopy)
{
Uint32* dst = (Uint32*) (dstpix + loopy * dstpitch);
Uint32* src = ((Uint32*) (srcpix + loopy * srcpitch))
+ surf->w - 1;
for (loopx = 0; loopx < surf->w; ++loopx)
*dst++ = *src--;
}
break;
case 3:
for (loopy = 0; loopy < surf->h; ++loopy)
{
Uint8* dst = (Uint8*) (dstpix + loopy * dstpitch);
Uint8* src = ((Uint8*) (srcpix + loopy * srcpitch))
+ surf->w * 3 - 3;
for (loopx = 0; loopx < surf->w; ++loopx)
{
dst[0] = src[0];
dst[1] = src[1];
dst[2] = src[2];
dst += 3;
src -= 3;
}
}
break;
}
}
}
Py_END_ALLOW_THREADS;
PySurface_Unlock (surfobj);
SDL_UnlockSurface (newsurf);
return PySurface_New (newsurf);
}
static PyObject*
surf_rotozoom (PyObject* self, PyObject* arg)
{
PyObject *surfobj;
SDL_Surface *surf, *newsurf, *surf32;
float scale, angle;
/*get all the arguments*/
if (!PyArg_ParseTuple (arg, "O!ff", &PySurface_Type, &surfobj, &angle,
&scale))
return NULL;
surf = PySurface_AsSurface (surfobj);
if (scale == 0.0)
{
newsurf = newsurf_fromsurf (surf, surf->w, surf->h);
return PySurface_New (newsurf);
}
if (surf->format->BitsPerPixel == 32)
{
surf32 = surf;
PySurface_Lock (surfobj);
}
else
{
Py_BEGIN_ALLOW_THREADS;
surf32 = SDL_CreateRGBSurface (SDL_SWSURFACE, surf->w, surf->h, 32,
0x000000ff, 0x0000ff00, 0x00ff0000,
0xff000000);
SDL_BlitSurface (surf, NULL, surf32, NULL);
Py_END_ALLOW_THREADS;
}
Py_BEGIN_ALLOW_THREADS;
newsurf = rotozoomSurface (surf32, angle, scale, 1);
Py_END_ALLOW_THREADS;
if (surf32 == surf)
PySurface_Unlock (surfobj);
else
SDL_FreeSurface (surf32);
return PySurface_New (newsurf);
}
static SDL_Surface*
chop (SDL_Surface *src, int x, int y, int width, int height)
{
SDL_Surface* dst;
int dstwidth,dstheight;
char *srcpix, *dstpix, *srcrow, *dstrow;
int srcstepx, srcstepy, dststepx, dststepy;
int loopx,loopy;
if ((x + width) > src->w)
width = src->w - x;
if ((y + height) > src->h)
height=src->h - y;
if (x < 0)
{
width -= (-x);
x = 0;
}
if (y < 0)
{
height -= (-y);
y = 0;
}
dstwidth = src->w-width;
dstheight = src->h-height;
dst = newsurf_fromsurf (src,dstwidth,dstheight);
if (!dst)
return NULL;
SDL_LockSurface (dst);
srcrow = (char*) src->pixels;
dstrow = (char*) dst->pixels;
srcstepx = dststepx = src->format->BytesPerPixel;
srcstepy = src->pitch;
dststepy = dst->pitch;
for (loopy = 0; loopy < src->h; loopy++)
{
if ((loopy < y) || (loopy >= (y + height)))
{
dstpix = dstrow;
srcpix = srcrow;
for (loopx = 0; loopx < src->w; loopx++)
{
if ((loopx < x) || (loopx >= (x + width)))
{
switch (src->format->BytesPerPixel)
{
case 1:
*dstpix = *srcpix;
break;
case 2:
*(Uint16*) dstpix = *(Uint16*) srcpix;
break;
case 3:
dstpix[0] = srcpix[0];
dstpix[1] = srcpix[1];
dstpix[2] = srcpix[2];
break;
case 4:
*(Uint32*) dstpix = *(Uint32*) srcpix;
break;
}
dstpix += dststepx;
}
srcpix += srcstepx;
}
dstrow += dststepy;
}
srcrow += srcstepy;
}
SDL_UnlockSurface (dst);
return dst;
}
static PyObject*
surf_chop (PyObject* self, PyObject* arg)
{
PyObject *surfobj, *rectobj;
SDL_Surface* surf, *newsurf;
GAME_Rect* rect, temp;
if (!PyArg_ParseTuple (arg, "O!O", &PySurface_Type, &surfobj, &rectobj))
return NULL;
if (!(rect = GameRect_FromObject (rectobj, &temp)))
return RAISE (PyExc_TypeError, "Rect argument is invalid");
surf=PySurface_AsSurface (surfobj);
Py_BEGIN_ALLOW_THREADS;
newsurf = chop (surf, rect->x, rect->y, rect->w, rect->h);
Py_END_ALLOW_THREADS;
return PySurface_New (newsurf);
}
/*
* smooth scale functions.
*/
/* this function implements an area-averaging shrinking filter in the X-dimension */
static void filter_shrink_X_ONLYC(Uint8 *srcpix, Uint8 *dstpix, int height, int srcpitch, int dstpitch, int srcwidth, int dstwidth)
{
int srcdiff = srcpitch - (srcwidth * 4);
int dstdiff = dstpitch - (dstwidth * 4);
int x, y;
int xspace = 0x10000 * srcwidth / dstwidth; /* must be > 1 */
int xrecip = (int) (0x100000000LL / xspace);
for (y = 0; y < height; y++)
{
Uint16 accumulate[4] = {0,0,0,0};
int xcounter = xspace;
for (x = 0; x < srcwidth; x++)
{
if (xcounter > 0x10000)
{
accumulate[0] += (Uint16) *srcpix++;
accumulate[1] += (Uint16) *srcpix++;
accumulate[2] += (Uint16) *srcpix++;
accumulate[3] += (Uint16) *srcpix++;
xcounter -= 0x10000;
}
else
{
int xfrac = 0x10000 - xcounter;
/* write out a destination pixel */
*dstpix++ = (Uint8) (((accumulate[0] + ((srcpix[0] * xcounter) >> 16)) * xrecip) >> 16);
*dstpix++ = (Uint8) (((accumulate[1] + ((srcpix[1] * xcounter) >> 16)) * xrecip) >> 16);
*dstpix++ = (Uint8) (((accumulate[2] + ((srcpix[2] * xcounter) >> 16)) * xrecip) >> 16);
*dstpix++ = (Uint8) (((accumulate[3] + ((srcpix[3] * xcounter) >> 16)) * xrecip) >> 16);
/* reload the accumulator with the remainder of this pixel */
accumulate[0] = (Uint16) ((*srcpix++ * xfrac) >> 16);
accumulate[1] = (Uint16) ((*srcpix++ * xfrac) >> 16);
accumulate[2] = (Uint16) ((*srcpix++ * xfrac) >> 16);
accumulate[3] = (Uint16) ((*srcpix++ * xfrac) >> 16);
xcounter = xspace - xfrac;
}
}
srcpix += srcdiff;
dstpix += dstdiff;
}
}
/* this function implements an area-averaging shrinking filter in the Y-dimension */
static void filter_shrink_Y_ONLYC(Uint8 *srcpix, Uint8 *dstpix, int width, int srcpitch, int dstpitch, int srcheight, int dstheight)
{
Uint16 *templine;
int srcdiff = srcpitch - (width * 4);
int dstdiff = dstpitch - (width * 4);
int x, y;
int yspace = 0x10000 * srcheight / dstheight; /* must be > 1 */
int yrecip = (int) (0x100000000LL / yspace);
int ycounter = yspace;
/* allocate and clear a memory area for storing the accumulator line */
templine = (Uint16 *) malloc(dstpitch * 2);
if (templine == NULL) return;
memset(templine, 0, dstpitch * 2);
for (y = 0; y < srcheight; y++)
{
Uint16 *accumulate = templine;
if (ycounter > 0x10000)
{
for (x = 0; x < width; x++)
{
*accumulate++ += (Uint16) *srcpix++;
*accumulate++ += (Uint16) *srcpix++;
*accumulate++ += (Uint16) *srcpix++;
*accumulate++ += (Uint16) *srcpix++;
}
ycounter -= 0x10000;
}
else
{
int yfrac = 0x10000 - ycounter;
/* write out a destination line */
for (x = 0; x < width; x++)
{
*dstpix++ = (Uint8) (((*accumulate++ + ((*srcpix++ * ycounter) >> 16)) * yrecip) >> 16);
*dstpix++ = (Uint8) (((*accumulate++ + ((*srcpix++ * ycounter) >> 16)) * yrecip) >> 16);
*dstpix++ = (Uint8) (((*accumulate++ + ((*srcpix++ * ycounter) >> 16)) * yrecip) >> 16);
*dstpix++ = (Uint8) (((*accumulate++ + ((*srcpix++ * ycounter) >> 16)) * yrecip) >> 16);
}
dstpix += dstdiff;
/* reload the accumulator with the remainder of this line */
accumulate = templine;
srcpix -= 4 * width;
for (x = 0; x < width; x++)
{
*accumulate++ = (Uint16) ((*srcpix++ * yfrac) >> 16);
*accumulate++ = (Uint16) ((*srcpix++ * yfrac) >> 16);
*accumulate++ = (Uint16) ((*srcpix++ * yfrac) >> 16);
*accumulate++ = (Uint16) ((*srcpix++ * yfrac) >> 16);
}
ycounter = yspace - yfrac;
}
srcpix += srcdiff;
} /* for (int y = 0; y < srcheight; y++) */
/* free the temporary memory */
free(templine);
}
/* this function implements a bilinear filter in the X-dimension */
static void filter_expand_X_ONLYC(Uint8 *srcpix, Uint8 *dstpix, int height, int srcpitch, int dstpitch, int srcwidth, int dstwidth)
{
int dstdiff = dstpitch - (dstwidth * 4);
int *xidx0, *xmult0, *xmult1;
int x, y;
int factorwidth = 4;
/* Allocate memory for factors */
xidx0 = malloc(dstwidth * 4);
if (xidx0 == NULL) return;
xmult0 = (int *) malloc(dstwidth * factorwidth);
xmult1 = (int *) malloc(dstwidth * factorwidth);
if (xmult0 == NULL || xmult1 == NULL)
{
free(xidx0);
if (xmult0) free(xmult0);
if (xmult1) free(xmult1);
}
/* Create multiplier factors and starting indices and put them in arrays */
for (x = 0; x < dstwidth; x++)
{
xidx0[x] = x * (srcwidth - 1) / dstwidth;
xmult1[x] = 0x10000 * ((x * (srcwidth - 1)) % dstwidth) / dstwidth;
xmult0[x] = 0x10000 - xmult1[x];
}
/* Do the scaling in raster order so we don't trash the cache */
for (y = 0; y < height; y++)
{
Uint8 *srcrow0 = srcpix + y * srcpitch;
for (x = 0; x < dstwidth; x++)
{
Uint8 *src = srcrow0 + xidx0[x] * 4;
int xm0 = xmult0[x];
int xm1 = xmult1[x];
*dstpix++ = (Uint8) (((src[0] * xm0) + (src[4] * xm1)) >> 16);
*dstpix++ = (Uint8) (((src[1] * xm0) + (src[5] * xm1)) >> 16);
*dstpix++ = (Uint8) (((src[2] * xm0) + (src[6] * xm1)) >> 16);
*dstpix++ = (Uint8) (((src[3] * xm0) + (src[7] * xm1)) >> 16);
}
dstpix += dstdiff;
}
/* free memory */
free(xidx0);
free(xmult0);
free(xmult1);
}
/* this function implements a bilinear filter in the Y-dimension */
static void filter_expand_Y_ONLYC(Uint8 *srcpix, Uint8 *dstpix, int width, int srcpitch, int dstpitch, int srcheight, int dstheight)
{
int x, y;
for (y = 0; y < dstheight; y++)
{
int yidx0 = y * (srcheight - 1) / dstheight;
Uint8 *srcrow0 = srcpix + yidx0 * srcpitch;
Uint8 *srcrow1 = srcrow0 + srcpitch;
int ymult1 = 0x10000 * ((y * (srcheight - 1)) % dstheight) / dstheight;
int ymult0 = 0x10000 - ymult1;
for (x = 0; x < width; x++)
{
*dstpix++ = (Uint8) (((*srcrow0++ * ymult0) + (*srcrow1++ * ymult1)) >> 16);
*dstpix++ = (Uint8) (((*srcrow0++ * ymult0) + (*srcrow1++ * ymult1)) >> 16);
*dstpix++ = (Uint8) (((*srcrow0++ * ymult0) + (*srcrow1++ * ymult1)) >> 16);
*dstpix++ = (Uint8) (((*srcrow0++ * ymult0) + (*srcrow1++ * ymult1)) >> 16);
}
}
}
#if defined(SCALE_MMX_SUPPORT)
static void
smoothscale_init (struct _module_state *st)
{
if (st->filter_shrink_X == 0)
{
if (SDL_HasSSE ())
{
st->filter_type = "SSE";
st->filter_shrink_X = filter_shrink_X_SSE;
st->filter_shrink_Y = filter_shrink_Y_SSE;
st->filter_expand_X = filter_expand_X_SSE;
st->filter_expand_Y = filter_expand_Y_SSE;
}
else if (SDL_HasMMX ())
{
st->filter_type = "MMX";
st->filter_shrink_X = filter_shrink_X_MMX;
st->filter_shrink_Y = filter_shrink_Y_MMX;
st->filter_expand_X = filter_expand_X_MMX;
st->filter_expand_Y = filter_expand_Y_MMX;
}
else
{
st->filter_type = "GENERIC";
st->filter_shrink_X = filter_shrink_X_ONLYC;
st->filter_shrink_Y = filter_shrink_Y_ONLYC;
st->filter_expand_X = filter_expand_X_ONLYC;
st->filter_expand_Y = filter_expand_Y_ONLYC;
}
}
}
#endif
static void convert_24_32(Uint8 *srcpix, int srcpitch, Uint8 *dstpix, int dstpitch, int width, int height)
{
int srcdiff = srcpitch - (width * 3);
int dstdiff = dstpitch - (width * 4);
int x, y;
for (y = 0; y < height; y++)
{
for (x = 0; x < width; x++)
{
*dstpix++ = *srcpix++;
*dstpix++ = *srcpix++;
*dstpix++ = *srcpix++;
*dstpix++ = 0xff;
}
srcpix += srcdiff;
dstpix += dstdiff;
}
}
static void convert_32_24(Uint8 *srcpix, int srcpitch, Uint8 *dstpix, int dstpitch, int width, int height)
{
int srcdiff = srcpitch - (width * 4);
int dstdiff = dstpitch - (width * 3);
int x, y;
for (y = 0; y < height; y++)
{
for (x = 0; x < width; x++)
{
*dstpix++ = *srcpix++;
*dstpix++ = *srcpix++;
*dstpix++ = *srcpix++;
srcpix++;
}
srcpix += srcdiff;
dstpix += dstdiff;
}
}
static void
scalesmooth(SDL_Surface *src, SDL_Surface *dst,
struct _module_state *st)
{
Uint8* srcpix = (Uint8*)src->pixels;
Uint8* dstpix = (Uint8*)dst->pixels;
Uint8* dst32 = NULL;
int srcpitch = src->pitch;
int dstpitch = dst->pitch;
int srcwidth = src->w;
int srcheight = src->h;
int dstwidth = dst->w;
int dstheight = dst->h;
int bpp = src->format->BytesPerPixel;
Uint8 *temppix = NULL;
int tempwidth=0, temppitch=0, tempheight=0;
/* convert to 32-bit if necessary */
if (bpp == 3)
{
int newpitch = srcwidth * 4;
Uint8 *newsrc = (Uint8 *) malloc(newpitch * srcheight);
if (!newsrc)
return;
convert_24_32(srcpix, srcpitch, newsrc, newpitch, srcwidth, srcheight);
srcpix = newsrc;
srcpitch = newpitch;
/* create a destination buffer for the 32-bit result */
dstpitch = dstwidth << 2;
dst32 = (Uint8 *) malloc(dstpitch * dstheight);
if (dst32 == NULL)
{
free(srcpix);
return;
}
dstpix = dst32;
}
/* Create a temporary processing buffer if we will be scaling both X and Y */
if (srcwidth != dstwidth && srcheight != dstheight)
{
tempwidth = dstwidth;
temppitch = tempwidth << 2;
tempheight = srcheight;
temppix = (Uint8 *) malloc(temppitch * tempheight);
if (temppix == NULL)
{
if (bpp == 3)
{
free(srcpix);
free(dstpix);
}
return;
}
}
/* Start the filter by doing X-scaling */
if (dstwidth < srcwidth) /* shrink */
{
if (srcheight != dstheight)
st->filter_shrink_X(srcpix, temppix, srcheight, srcpitch, temppitch, srcwidth, dstwidth);
else
st->filter_shrink_X(srcpix, dstpix, srcheight, srcpitch, dstpitch, srcwidth, dstwidth);
}
else if (dstwidth > srcwidth) /* expand */
{
if (srcheight != dstheight)
st->filter_expand_X(srcpix, temppix, srcheight, srcpitch, temppitch, srcwidth, dstwidth);
else
st->filter_expand_X(srcpix, dstpix, srcheight, srcpitch, dstpitch, srcwidth, dstwidth);
}
/* Now do the Y scale */
if (dstheight < srcheight) /* shrink */
{
if (srcwidth != dstwidth)
st->filter_shrink_Y(temppix, dstpix, tempwidth, temppitch, dstpitch, srcheight, dstheight);
else
st->filter_shrink_Y(srcpix, dstpix, srcwidth, srcpitch, dstpitch, srcheight, dstheight);
}
else if (dstheight > srcheight) /* expand */
{
if (srcwidth != dstwidth)
st->filter_expand_Y(temppix, dstpix, tempwidth, temppitch, dstpitch, srcheight, dstheight);
else
st->filter_expand_Y(srcpix, dstpix, srcwidth, srcpitch, dstpitch, srcheight, dstheight);
}
/* Convert back to 24-bit if necessary */
if (bpp == 3)
{
convert_32_24(dst32, dstpitch, (Uint8*)dst->pixels, dst->pitch, dstwidth, dstheight);
free(dst32);
dst32 = NULL;
free(srcpix);
srcpix = NULL;
}
/* free temporary buffer if necessary */
if (temppix != NULL)
free(temppix);
}
static PyObject* surf_scalesmooth(PyObject* self, PyObject* arg)
{
PyObject *surfobj, *surfobj2;
SDL_Surface* surf, *newsurf;
int width, height, bpp;
surfobj2 = NULL;
/*get all the arguments*/
if (!PyArg_ParseTuple (arg, "O!(ii)|O!", &PySurface_Type, &surfobj,
&width, &height, &PySurface_Type, &surfobj2))
return NULL;
if (width < 0 || height < 0)
return RAISE (PyExc_ValueError, "Cannot scale to negative size");
surf = PySurface_AsSurface (surfobj);
bpp = surf->format->BytesPerPixel;
if(bpp < 3 || bpp > 4)
return RAISE(PyExc_ValueError, "Only 24-bit or 32-bit surfaces can be smoothly scaled");
if (!surfobj2)
{
newsurf = newsurf_fromsurf (surf, width, height);
if (!newsurf)
return NULL;
}
else
newsurf = PySurface_AsSurface (surfobj2);
/* check to see if the size is twice as big. */
if (newsurf->w != width || newsurf->h != height)
return RAISE (PyExc_ValueError,
"Destination surface not the given width or height.");
if(((width * bpp + 3) >> 2) > newsurf->pitch)
return RAISE(PyExc_ValueError, "SDL Error: destination surface pitch not 4-byte aligned.");
if(width && height)
{
SDL_LockSurface(newsurf);
PySurface_Lock(surfobj);
Py_BEGIN_ALLOW_THREADS;
/* handle trivial case */
if (surf->w == width && surf->h == height) {
int y;
for (y = 0; y < height; y++) {
memcpy((Uint8*)newsurf->pixels + y * newsurf->pitch,
(Uint8*)surf->pixels + y * surf->pitch, width * bpp);
}
}
else {
scalesmooth(surf, newsurf, GETSTATE (self));
}
Py_END_ALLOW_THREADS;
PySurface_Unlock(surfobj);
SDL_UnlockSurface(newsurf);
}
if (surfobj2)
{
Py_INCREF (surfobj2);
return surfobj2;
}
else
return PySurface_New (newsurf);
}
static PyObject *
surf_get_smoothscale_backend (PyObject *self)
{
return Text_FromUTF8 (GETSTATE (self)->filter_type);
}
static PyObject *
surf_set_smoothscale_backend (PyObject *self, PyObject *args, PyObject *kwds)
{
struct _module_state *st = GETSTATE (self);
char *keywords[] = {"type", NULL};
const char *type;
if (!PyArg_ParseTupleAndKeywords (args, kwds, "s:set_smoothscale_backend",
keywords, &type))
{
return NULL;
}
#if defined(SCALE_MMX_SUPPORT)
if (strcmp (type, "GENERIC") == 0)
{
st->filter_type = "GENERIC";
st->filter_shrink_X = filter_shrink_X_ONLYC;
st->filter_shrink_Y = filter_shrink_Y_ONLYC;
st->filter_expand_X = filter_expand_X_ONLYC;
st->filter_expand_Y = filter_expand_Y_ONLYC;
}
else if (strcmp (type, "MMX") == 0)
{
if (!SDL_HasMMX ())
{
return RAISE (PyExc_ValueError,
"MMX not supported on this machine");
}
st->filter_type = "MMX";
st->filter_shrink_X = filter_shrink_X_MMX;
st->filter_shrink_Y = filter_shrink_Y_MMX;
st->filter_expand_X = filter_expand_X_MMX;
st->filter_expand_Y = filter_expand_Y_MMX;
}
else if (strcmp (type, "SSE") == 0)
{
if (!SDL_HasSSE ())
{
return RAISE (PyExc_ValueError,
"SSE not supported on this machine");
}
st->filter_type = "SSE";
st->filter_shrink_X = filter_shrink_X_SSE;
st->filter_shrink_Y = filter_shrink_Y_SSE;
st->filter_expand_X = filter_expand_X_SSE;
st->filter_expand_Y = filter_expand_Y_SSE;
}
else
{
return PyErr_Format (PyExc_ValueError,
"Unknown backend type %s", type);
}
Py_RETURN_NONE;
#else /* Not an x86 processor */
if (strcmp (type, "GENERIC") != 0)
{
if (strcmp (st->filter_type, "MMX") == 0 ||
strcmp (st->filter_type, "SSE") == 0 )
{
return PyErr_Format (PyExc_ValueError,
"%s not supported on this machine", type);
}
return PyErr_Format (PyExc_ValueError,
"Unknown backend type %s", type);
}
Py_RETURN_NONE;
#endif /* defined(SCALE_MMX_SUPPORT) */
}
static int get_threshold (SDL_Surface *destsurf, SDL_Surface *surf,
SDL_Surface *surf2, Uint32 color, Uint32 threshold,
Uint32 diff_color, int change_return, int inverse)
{
int x, y, result, similar, rshift, gshift, bshift, rshift2, gshift2, bshift2;
int rloss, gloss, bloss, rloss2, gloss2, bloss2;
Uint8 *pixels, *destpixels, *pixels2;
SDL_Rect sdlrect;
SDL_PixelFormat *format, *destformat, *format2;
Uint32 the_color, the_color2, rmask, gmask, bmask, rmask2, gmask2, bmask2;
Uint8 *pix, *byte_buf;
Uint8 r, g, b, a;
Uint8 dr, dg, db, da;
Uint8 tr, tg, tb, ta;
similar = 0;
pixels = (Uint8 *) surf->pixels;
format = surf->format;
rmask = format->Rmask;
gmask = format->Gmask;
bmask = format->Bmask;
rshift = format->Rshift;
gshift = format->Gshift;
bshift = format->Bshift;
rloss = format->Rloss;
gloss = format->Gloss;
bloss = format->Bloss;
if(change_return) {
sdlrect.x = sdlrect.y = 0;
sdlrect.w = destsurf->w;
sdlrect.h = destsurf->h;
destpixels = (Uint8 *) destsurf->pixels;
destformat = destsurf->format;
result = SDL_FillRect (destsurf, &sdlrect, diff_color);
} else { /* make gcc stop complaining */
destpixels = NULL;
destformat = NULL;
}
if(surf2) {
format2 = surf2->format;
rmask2 = format2->Rmask;
gmask2 = format2->Gmask;
bmask2 = format2->Bmask;
rshift2 = format2->Rshift;
gshift2 = format2->Gshift;
bshift2 = format2->Bshift;
rloss2 = format2->Rloss;
gloss2 = format2->Gloss;
bloss2 = format2->Bloss;
pixels2 = (Uint8 *) surf2->pixels;
} else { /* make gcc stop complaining */
rmask2 = gmask2 = bmask2 = 0;
rshift2 = gshift2 = bshift2 = 0;
rloss2 = gloss2 = bloss2 = 0;
format2 = NULL;
pixels2 = NULL;
}
SDL_GetRGBA (color, format, &r, &g, &b, &a);
SDL_GetRGBA (threshold, format, &tr, &tg, &tb, &ta);
SDL_GetRGBA (diff_color, format, &dr, &dg, &db, &da);
for(y=0; y < surf->h; y++) {
pixels = (Uint8 *) surf->pixels + y*surf->pitch;
if (surf2) {
pixels2 = (Uint8 *) surf2->pixels + y*surf2->pitch;
}
for(x=0; x < surf->w; x++) {
/* the_color = surf->get_at(x,y) */
switch (format->BytesPerPixel)
{
case 1:
the_color = (Uint32)*((Uint8 *) pixels);
pixels++;
break;
case 2:
the_color = (Uint32)*((Uint16 *) pixels);
pixels += 2;
break;
case 3:
pix = ((Uint8 *) pixels);
pixels += 3;
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
the_color = (pix[0]) + (pix[1] << 8) + (pix[2] << 16);
#else
the_color = (pix[2]) + (pix[1] << 8) + (pix[0] << 16);
#endif
break;
default: /* case 4: */
the_color = *((Uint32 *) pixels);
pixels += 4;
break;
}
if (surf2) {
switch (format2->BytesPerPixel) {
case 1:
the_color2 = (Uint32)*((Uint8 *) pixels2);
pixels2++;
break;
case 2:
the_color2 = (Uint32)*((Uint16 *) pixels2);
pixels2 += 2;
break;
case 3:
pix = ((Uint8 *) pixels2);
pixels2 += 3;
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
the_color2 = (pix[0]) + (pix[1] << 8) + (pix[2] << 16);
#else
the_color2 = (pix[2]) + (pix[1] << 8) + (pix[0] << 16);
#endif
break;
default: /* case 4: */
the_color2 = *((Uint32 *) pixels2);
pixels2 += 4;
break;
}
if (((abs((((the_color2 & rmask2) >> rshift2) << rloss2) - (((the_color & rmask) >> rshift) << rloss)) <= tr) &
(abs((((the_color2 & gmask2) >> gshift2) << gloss2) - (((the_color & gmask) >> gshift) << gloss)) <= tg) &
(abs((((the_color2 & bmask2) >> bshift2) << bloss2) - (((the_color & bmask) >> bshift) << bloss)) <= tb))
^ inverse) {
/* this pixel is within the threshold of the pixel in the
other surface. */
if (change_return == 2) {
/* change the pixel to the color from the first surface. */
/* destsurf->set_at((x,y), the_color) */
switch (destformat->BytesPerPixel) {
case 1:
*((Uint8 *) destpixels + y * destsurf->pitch + x) = (Uint8) the_color;
break;
case 2:
*((Uint16 *) (destpixels + y * destsurf->pitch) + x) = (Uint16) the_color;
break;
case 3:
byte_buf = (Uint8 *) (destpixels + y * destsurf->pitch) + x * 3;
#if (SDL_BYTEORDER == SDL_LIL_ENDIAN)
*(byte_buf + (destformat->Rshift >> 3)) = (Uint8) (the_color >> 16);
*(byte_buf + (destformat->Gshift >> 3)) = (Uint8) (the_color >> 8);
*(byte_buf + (destformat->Bshift >> 3)) = (Uint8) the_color;
#else
*(byte_buf + 2 - (destformat->Rshift >> 3)) = (Uint8) (the_color >> 16);
*(byte_buf + 2 - (destformat->Gshift >> 3)) = (Uint8) (the_color >> 8);
*(byte_buf + 2 - (destformat->Bshift >> 3)) = (Uint8) the_color;
#endif
break;
default: /* case 4: */
*((Uint32 *) (destpixels + y * destsurf->pitch) + x) = the_color;
break;
}
}
else if (change_return == 1) {
/* change the pixel to color. */
/* destsurf->set_at((x,y), color) */
switch (destformat->BytesPerPixel) {
case 1:
*((Uint8 *) destpixels + y * destsurf->pitch + x) = (Uint8) color;
break;
case 2:
*((Uint16 *) (destpixels + y * destsurf->pitch) + x) = (Uint16) color;
break;
case 3:
byte_buf = (Uint8 *) (destpixels + y * destsurf->pitch) + x * 3;
#if (SDL_BYTEORDER == SDL_LIL_ENDIAN)
*(byte_buf + (destformat->Rshift >> 3)) = (Uint8) (color >> 16);
*(byte_buf + (destformat->Gshift >> 3)) = (Uint8) (color >> 8);
*(byte_buf + (destformat->Bshift >> 3)) = (Uint8) color;
#else
*(byte_buf + 2 - (destformat->Rshift >> 3)) = (Uint8) (color >> 16);
*(byte_buf + 2 - (destformat->Gshift >> 3)) = (Uint8) (color >> 8);
*(byte_buf + 2 - (destformat->Bshift >> 3)) = (Uint8) color;
#endif
break;
default: /* case 4: */
*((Uint32 *) (destpixels + y * destsurf->pitch) + x) = color;
break;
}
}
similar++;
}
} else if (((abs((((the_color & rmask) >> rshift) << rloss) - r) <= tr) &
(abs((((the_color & gmask) >> gshift) << gloss) - g) <= tg) &
(abs((((the_color & bmask) >> bshift) << bloss) - b) <= tb))
^ inverse) {
/* Comparing the threshold against the color. */
/* this pixel is within the threshold. */
if (change_return == 2) {
/* destsurf->set_at((x,y), the_color) */
switch (destformat->BytesPerPixel)
{
case 1:
*((Uint8 *) destpixels + y * destsurf->pitch + x) = (Uint8) the_color;
break;
case 2:
*((Uint16 *) (destpixels + y * destsurf->pitch) + x) = (Uint16) the_color;
break;
case 3:
byte_buf = (Uint8 *) (destpixels + y * destsurf->pitch) + x * 3;
#if (SDL_BYTEORDER == SDL_LIL_ENDIAN)
*(byte_buf + (destformat->Rshift >> 3)) = (Uint8) (the_color >> 16);
*(byte_buf + (destformat->Gshift >> 3)) = (Uint8) (the_color >> 8);
*(byte_buf + (destformat->Bshift >> 3)) = (Uint8) the_color;
#else
*(byte_buf + 2 - (destformat->Rshift >> 3)) = (Uint8) (the_color >> 16);
*(byte_buf + 2 - (destformat->Gshift >> 3)) = (Uint8) (the_color >> 8);
*(byte_buf + 2 - (destformat->Bshift >> 3)) = (Uint8) the_color;
#endif
break;
default: /* case 4: */
*((Uint32 *) (destpixels + y * destsurf->pitch) + x) = the_color;
break;
}
}
else if (change_return == 1) {
/* change the pixel to color. */
/* destsurf->set_at((x,y), color) */
switch (destformat->BytesPerPixel)
{
case 1:
*((Uint8 *) destpixels + y * destsurf->pitch + x) = (Uint8) color;
break;
case 2:
*((Uint16 *) (destpixels + y * destsurf->pitch) + x) = (Uint16) color;
break;
case 3:
byte_buf = (Uint8 *) (destpixels + y * destsurf->pitch) + x * 3;
#if (SDL_BYTEORDER == SDL_LIL_ENDIAN)
*(byte_buf + (destformat->Rshift >> 3)) = (Uint8) (color >> 16);
*(byte_buf + (destformat->Gshift >> 3)) = (Uint8) (color >> 8);
*(byte_buf + (destformat->Bshift >> 3)) = (Uint8) color;
#else
*(byte_buf + 2 - (destformat->Rshift >> 3)) = (Uint8) (color >> 16);
*(byte_buf + 2 - (destformat->Gshift >> 3)) = (Uint8) (color >> 8);
*(byte_buf + 2 - (destformat->Bshift >> 3)) = (Uint8) color;
#endif
break;
default: /* case 4: */
*((Uint32 *) (destpixels + y * destsurf->pitch) + x) = color;
break;
}
}
similar++;
}
}
}
return similar;
}
static PyObject* surf_threshold(PyObject* self, PyObject* arg)
{
PyObject *surfobj, *surfobj2 = NULL, *surfobj3 = NULL;
SDL_Surface* surf = NULL, *destsurf = NULL, *surf2 = NULL;
int bpp, change_return = 1, inverse = 0;
int num_threshold_pixels = 0;
PyObject *rgba_obj_color;
PyObject *rgba_obj_threshold = NULL;
PyObject *rgba_obj_diff_color = NULL;
Uint8 rgba_color[4];
Uint8 rgba_threshold[4] = {0, 0, 0, 255};
Uint8 rgba_diff_color[4] = {0, 0, 0, 255};
Uint32 color;
Uint32 color_threshold;
Uint32 color_diff_color;
/*get all the arguments*/
if (!PyArg_ParseTuple (arg, "O!O!O|OOiO!i", &PySurface_Type, &surfobj,
&PySurface_Type, &surfobj2,
&rgba_obj_color, &rgba_obj_threshold, &rgba_obj_diff_color,
&change_return,
&PySurface_Type, &surfobj3, &inverse))
return NULL;
destsurf = PySurface_AsSurface (surfobj);
surf = PySurface_AsSurface (surfobj2);
if(surfobj3) {
surf2 = PySurface_AsSurface (surfobj3);
}
if (PyInt_Check (rgba_obj_color)) {
color = (Uint32) PyInt_AsLong (rgba_obj_color);
} else if (PyLong_Check (rgba_obj_color)) {
color = (Uint32) PyLong_AsUnsignedLong (rgba_obj_color);
}
else if (RGBAFromColorObj (rgba_obj_color, rgba_color)) {
color = SDL_MapRGBA (surf->format, rgba_color[0], rgba_color[1],
rgba_color[2], rgba_color[3]);
} else {
return RAISE (PyExc_TypeError, "invalid color argument");
}
if(rgba_obj_threshold) {
if (PyInt_Check (rgba_obj_threshold))
color_threshold = (Uint32) PyInt_AsLong (rgba_obj_threshold);
else if (PyLong_Check (rgba_obj_threshold))
color_threshold = (Uint32) PyLong_AsUnsignedLong
(rgba_obj_threshold);
else if (RGBAFromColorObj (rgba_obj_threshold, rgba_threshold))
color_threshold = SDL_MapRGBA (surf->format,
rgba_threshold[0],
rgba_threshold[1],
rgba_threshold[2],
rgba_threshold[3]);
else
return RAISE (PyExc_TypeError, "invalid threshold argument");
} else {
color_threshold = SDL_MapRGBA (surf->format,
rgba_threshold[0],
rgba_threshold[1],
rgba_threshold[2],
rgba_threshold[3]);
}
if(rgba_obj_diff_color) {
if (PyInt_Check (rgba_obj_diff_color))
color_diff_color = (Uint32) PyInt_AsLong (rgba_obj_diff_color);
else if (PyLong_Check (rgba_obj_diff_color))
color_diff_color = (Uint32) PyLong_AsUnsignedLong
(rgba_obj_diff_color);
else if (RGBAFromColorObj (rgba_obj_diff_color, rgba_diff_color))
color_diff_color = SDL_MapRGBA (surf->format,
rgba_diff_color[0],
rgba_diff_color[1],
rgba_diff_color[2],
rgba_diff_color[3]);
else
return RAISE (PyExc_TypeError, "invalid diff_color argument");
} else {
color_diff_color = SDL_MapRGBA (surf->format,
rgba_diff_color[0],
rgba_diff_color[1],
rgba_diff_color[2],
rgba_diff_color[3]);
}
bpp = surf->format->BytesPerPixel;
PySurface_Lock(surfobj);
PySurface_Lock(surfobj2);
if(surfobj3) {
PySurface_Lock(surfobj3);
}
Py_BEGIN_ALLOW_THREADS;
num_threshold_pixels = get_threshold (destsurf,
surf,
surf2,
color,
color_threshold,
color_diff_color,
change_return,
inverse);
Py_END_ALLOW_THREADS;
PySurface_Unlock(surfobj);
PySurface_Unlock(surfobj2);
if(surfobj3) {
PySurface_Unlock(surfobj3);
}
return PyInt_FromLong (num_threshold_pixels);
}
/*
TODO:
add_4
sub_4
mul_4
clamp_4
*/
#define SURF_GET_AT(p_color, p_surf, p_x, p_y, p_pixels, p_format, p_pix) \
switch (p_format->BytesPerPixel) \
{ \
case 1: \
p_color = (Uint32)*((Uint8 *) (p_pixels) + (p_y) * p_surf->pitch + (p_x)); \
break; \
case 2: \
p_color = (Uint32)*((Uint16 *) ((p_pixels) + (p_y) * p_surf->pitch) + (p_x)); \
break; \
case 3: \
p_pix = ((Uint8 *) (p_pixels + (p_y) * p_surf->pitch) + (p_x) * 3); \
p_color = (SDL_BYTEORDER == SDL_LIL_ENDIAN) ? \
(p_pix[0]) + (p_pix[1] << 8) + (p_pix[2] << 16) : \
(p_pix[2]) + (p_pix[1] << 8) + (p_pix[0] << 16); \
break; \
default: /* case 4: */ \
p_color = *((Uint32 *) (p_pixels + (p_y) * p_surf->pitch) + (p_x)); \
break; \
} \
#if (SDL_BYTEORDER == SDL_LIL_ENDIAN)
#define SURF_SET_AT(p_color, p_surf, p_x, p_y, p_pixels, p_format, p_byte_buf) \
switch (p_format->BytesPerPixel) \
{ \
case 1: \
*((Uint8 *) p_pixels + (p_y) * p_surf->pitch + (p_x)) = (Uint8) p_color; \
break; \
case 2: \
*((Uint16 *) (p_pixels + (p_y) * p_surf->pitch) + (p_x)) = (Uint16) p_color; \
break; \
case 3: \
p_byte_buf = (Uint8 *) (p_pixels + (p_y) * p_surf->pitch) + (p_x) * 3; \
*(p_byte_buf + (p_format->Rshift >> 3)) = (Uint8) (p_color >> 16); \
*(p_byte_buf + (p_format->Gshift >> 3)) = (Uint8) (p_color >> 8); \
*(p_byte_buf + (p_format->Bshift >> 3)) = (Uint8) p_color; \
break; \
default: \
*((Uint32 *) (p_pixels + (p_y) * p_surf->pitch) + (p_x)) = p_color; \
break; \
} \
#else
#define SURF_SET_AT(p_color, p_surf, p_x, p_y, p_pixels, p_format, p_byte_buf) \
switch (p_format->BytesPerPixel) \
{ \
case 1: \
*((Uint8 *) p_pixels + (p_y) * p_surf->pitch + (p_x)) = (Uint8) p_color; \
break; \
case 2: \
*((Uint16 *) (p_pixels + (p_y) * p_surf->pitch) + (p_x)) = (Uint16) p_color; \
break; \
case 3: \
p_byte_buf = (Uint8 *) (p_pixels + (p_y) * p_surf->pitch) + (p_x) * 3; \
*(p_byte_buf + 2 - (p_format->Rshift >> 3)) = (Uint8) (p_color >> 16); \
*(p_byte_buf + 2 - (p_format->Gshift >> 3)) = (Uint8) (p_color >> 8); \
*(p_byte_buf + 2 - (p_format->Bshift >> 3)) = (Uint8) p_color; \
break; \
default: \
*((Uint32 *) (p_pixels + (p_y) * p_surf->pitch) + (p_x)) = p_color; \
break; \
} \
#endif
/*
number to use for missing samples
*/
#define LAPLACIAN_NUM 0xFFFFFFFF
void laplacian(SDL_Surface *surf, SDL_Surface *destsurf) {
int ii;
int x,y,height,width;
Uint32 sample[9];
//Uint32 total[4];
int total[4];
Uint8 c1r, c1g, c1b, c1a;
//Uint32 c1r, c1g, c1b, c1a;
Uint8 acolor[4];
Uint32 the_color;
int atmp0;
int atmp1;
int atmp2;
int atmp3;
SDL_PixelFormat *format, *destformat;
Uint8 *pixels, *destpixels;
Uint8 *pix;
Uint8 *byte_buf;
height = surf->h;
width = surf->w;
pixels = (Uint8 *) surf->pixels;
format = surf->format;
destpixels = (Uint8 *) destsurf->pixels;
destformat = destsurf->format;
/*
-1 -1 -1
-1 8 -1
-1 -1 -1
col = (sample[4] * 8) - (sample[0] + sample[1] + sample[2] +
sample[3] + sample[5] +
sample[6] + sample[7] + sample[8])
[(-1,-1), (0,-1), (1,-1), (-1,0), (0,0), (1,0), (-1,1), (0,1), (1,1)]
*/
for(y=0;y 0) {
if(x>0) {
SURF_GET_AT(sample[0], surf, x+ -1, y+ -1, pixels, format, pix);
}
SURF_GET_AT(sample[1], surf, x+ 0, y+ -1, pixels, format, pix);
if(x+10) {
SURF_GET_AT(sample[3], surf, x+ -1, y+ 0, pixels, format, pix);
} else {
sample[3] = LAPLACIAN_NUM;
}
//SURF_GET_AT(sample[4], surf, x+0 , y+0);
sample[4] = 0;
if(x+10) {
SURF_GET_AT(sample[6], surf, x+ -1, y+ 1, pixels, format, pix);
}
SURF_GET_AT(sample[7], surf, x+ 0, y+ 1, pixels, format, pix);
if(x+1format, acolor[0], acolor[1], acolor[2], acolor[3]);
// set_at(destsurf, color, x,y);
switch (destformat->BytesPerPixel)
{
case 1:
*((Uint8 *) destpixels + y * destsurf->pitch + x) = (Uint8) the_color;
break;
case 2:
*((Uint16 *) (destpixels + y * destsurf->pitch) + x) = (Uint16) the_color;
break;
case 3:
byte_buf = (Uint8 *) (destpixels + y * destsurf->pitch) + x * 3;
#if (SDL_BYTEORDER == SDL_LIL_ENDIAN)
*(byte_buf + (destformat->Rshift >> 3)) = (Uint8) (the_color >> 16);
*(byte_buf + (destformat->Gshift >> 3)) = (Uint8) (the_color >> 8);
*(byte_buf + (destformat->Bshift >> 3)) = (Uint8) the_color;
#else
*(byte_buf + 2 - (destformat->Rshift >> 3)) = (Uint8) (the_color >> 16);
*(byte_buf + 2 - (destformat->Gshift >> 3)) = (Uint8) (the_color >> 8);
*(byte_buf + 2 - (destformat->Bshift >> 3)) = (Uint8) the_color;
#endif
break;
default:
*((Uint32 *) (destpixels + y * destsurf->pitch) + x) = the_color;
break;
}
}
}
}
static PyObject*
surf_laplacian (PyObject* self, PyObject* arg)
{
PyObject *surfobj, *surfobj2;
SDL_Surface *surf;
SDL_Surface *newsurf;
int width, height;
surfobj2 = NULL;
/*get all the arguments*/
if (!PyArg_ParseTuple (arg, "O!|O!", &PySurface_Type, &surfobj,
&PySurface_Type, &surfobj2))
return NULL;
surf = PySurface_AsSurface (surfobj);
/* if the second surface is not there, then make a new one. */
if (!surfobj2)
{
width = surf->w;
height = surf->h;
newsurf = newsurf_fromsurf (surf, width, height);
if (!newsurf)
return NULL;
}
else
newsurf = PySurface_AsSurface (surfobj2);
/* check to see if the size is the correct size. */
if (newsurf->w != (surf->w) || newsurf->h != (surf->h))
return RAISE (PyExc_ValueError, "Destination surface not the same size.");
/* check to see if the format of the surface is the same. */
if (surf->format->BytesPerPixel != newsurf->format->BytesPerPixel)
return RAISE (PyExc_ValueError,
"Source and destination surfaces need the same format.");
SDL_LockSurface (newsurf);
SDL_LockSurface (surf);
Py_BEGIN_ALLOW_THREADS;
laplacian (surf, newsurf);
Py_END_ALLOW_THREADS;
SDL_UnlockSurface (surf);
SDL_UnlockSurface (newsurf);
if (surfobj2)
{
Py_INCREF (surfobj2);
return surfobj2;
}
else
return PySurface_New (newsurf);
}
int average_surfaces(SDL_Surface **surfaces,
int num_surfaces,
SDL_Surface *destsurf,
int palette_colors) {
/*
returns the average surface from the ones given.
All surfaces need to be the same size.
palette_colors - if true we average the colors in palette, otherwise we
average the pixel values. This is useful if the surface is
actually greyscale colors, and not palette colors.
*/
Uint32 *accumulate;
Uint32 *the_idx;
Uint32 the_color;
SDL_Surface *surf;
int height, width, x, y, surf_idx;
float div_inv;
SDL_PixelFormat *format, *destformat;
Uint8 *pixels, *destpixels;
Uint8 *pix;
Uint8 *byte_buf;
Uint32 rmask, gmask, bmask;
int rshift, gshift, bshift, rloss, gloss, bloss;
int num_elements;
if(!num_surfaces) { return 0; }
height = surfaces[0]->h;
width = surfaces[0]->w;
destpixels = (Uint8 *) destsurf->pixels;
destformat = destsurf->format;
/* allocate an array to accumulate them all.
If we're using 1 byte per pixel, then only need to average on that much.
*/
if((destformat->BytesPerPixel == 1) &&
(destformat->palette) &&
(!palette_colors)) {
num_elements = 1;
} else {
num_elements = 3;
}
accumulate = (Uint32 *) calloc(1, sizeof(Uint32) * height * width * num_elements );
if(!accumulate) { return -1; }
/* add up the r,g,b from all the surfaces. */
for(surf_idx=0;surf_idx < num_surfaces;surf_idx++) {
surf = surfaces[surf_idx];
pixels = (Uint8 *) surf->pixels;
format = surf->format;
rmask = format->Rmask;
gmask = format->Gmask;
bmask = format->Bmask;
rshift = format->Rshift;
gshift = format->Gshift;
bshift = format->Bshift;
rloss = format->Rloss;
gloss = format->Gloss;
bloss = format->Bloss;
the_idx = accumulate;
/* If palette surface, we use a different code path... */
if((format->BytesPerPixel == 1 && destformat->BytesPerPixel == 1)
&& (format->palette) && (destformat->palette) && (!palette_colors)
) {
/*
This is useful if the surface is actually greyscale colors,
and not palette colors.
*/
for(y=0;y> rshift) << rloss;
*(the_idx + 1) += ((the_color & gmask) >> gshift) << gloss;
*(the_idx + 2) += ((the_color & bmask) >> bshift) << bloss;
the_idx += 3;
}
}
}
}
/* blit the accumulated array back to the destination surface. */
div_inv = (float) (1.0L / (num_surfaces));
the_idx = accumulate;
if(num_elements == 1 && (!palette_colors)) {
/* this is where we are using the palette surface without using its
colors from the palette.
*/
for(y=0;y> rshift) << rloss;
*(the_idx + 1) += ((the_color & gmask) >> gshift) << gloss;
*(the_idx + 2) += ((the_color & bmask) >> bshift) << bloss;
*/
SURF_SET_AT(the_color, destsurf, x, y, destpixels, destformat, byte_buf);
the_idx += 3;
}
}
} else {
free(accumulate);
return -4;
}
free(accumulate);
return 1;
}
/*
returns the average surface from the ones given.
All surfaces need to be the same size.
palette_colors - if true we average the colors in palette, otherwise we
average the pixel values. This is useful if the surface is
actually greyscale colors, and not palette colors.
*/
static PyObject*
surf_average_surfaces (PyObject* self, PyObject* arg)
{
PyObject *surfobj2;
SDL_Surface *surf;
SDL_Surface *newsurf;
SDL_Surface **surfaces;
int width, height;
int an_error;
size_t size, loop, loop_up_to;
int palette_colors = 1;
PyObject* list, *obj;
PyObject* ret = NULL;
an_error = 0;
surfobj2 = NULL;
newsurf = NULL;
if (!PyArg_ParseTuple (arg, "O|O!i", &list, &PySurface_Type, &surfobj2, &palette_colors ))
return NULL;
if (!PySequence_Check (list))
return RAISE (PyExc_TypeError, "Argument must be a sequence of surface objects.");
size = PySequence_Length (list); /*warning, size could be -1 on error?*/
if(size < 1)
return RAISE (PyExc_TypeError, "Needs to be given at least one surface.");
/* Allocate an array of surface pointers. */
surfaces = (SDL_Surface **) calloc(1, sizeof(SDL_Surface *) * size);
if(!surfaces) {
return RAISE (PyExc_MemoryError, "Not enough memory to store surfaces.\n");
}
/* Iterate over 'surfaces' passed in. */
/* need to get the first surface to see how big it is */
loop = 0;
for (loop = 0; loop < size; ++loop)
{
obj = PySequence_GetItem (list, loop);
if(!obj) {
Py_XDECREF (obj);
ret = RAISE (PyExc_TypeError, "Needs to be a surface object.");
an_error = 1;
break;
}
if (!PySurface_Check (obj)) {
Py_XDECREF (obj);
ret = RAISE (PyExc_TypeError, "Needs to be a surface object.");
an_error = 1;
break;
}
surf = PySurface_AsSurface (obj);
if(!surf) {
Py_XDECREF (obj);
ret = RAISE (PyExc_TypeError, "Needs to be a surface object.");
an_error = 1;
break;
}
if(loop == 0) {
/* if the second surface is not there, then make a new one. */
if (!surfobj2) {
width = surf->w;
height = surf->h;
newsurf = newsurf_fromsurf (surf, width, height);
if (!newsurf) {
Py_XDECREF (obj);
ret = RAISE (PyExc_ValueError, "Could not create new surface.");
an_error = 1;
break;
}
}
else
newsurf = PySurface_AsSurface (surfobj2);
/* check to see if the size is the correct size. */
if (newsurf->w != (surf->w) || newsurf->h != (surf->h)) {
Py_XDECREF (obj);
ret = RAISE (PyExc_ValueError, "Destination surface not the same size.");
an_error = 1;
break;
}
/* check to see if the format of the surface is the same. */
if (surf->format->BytesPerPixel != newsurf->format->BytesPerPixel) {
Py_XDECREF (obj);
ret = RAISE (PyExc_ValueError, "Source and destination surfaces need the same format.");
an_error = 1;
break;
}
}
/* Copy surface pointer, and also lock surface. */
SDL_LockSurface (surf);
surfaces[loop] = surf;
Py_DECREF (obj);
}
loop_up_to = loop;
if(!an_error) {
/* Process images, get average surface. */
SDL_LockSurface (newsurf);
Py_BEGIN_ALLOW_THREADS;
average_surfaces (surfaces, size, newsurf, palette_colors);
Py_END_ALLOW_THREADS;
SDL_UnlockSurface (newsurf);
if (surfobj2)
{
Py_INCREF (surfobj2);
ret = surfobj2;
}
else {
ret = PySurface_New (newsurf);
}
} else {
}
/* cleanup */
/* unlock the surfaces we got up to. */
for (loop = 0; loop < loop_up_to; loop++) {
if(surfaces[loop]) {
SDL_UnlockSurface (surfaces[loop]);
}
}
free(surfaces);
return ret;
}
void average_color(SDL_Surface* surf, int x, int y, int width, int height, Uint8* r, Uint8* g, Uint8* b, Uint8* a) {
Uint32 color, rmask, gmask, bmask, amask;
Uint8 *pixels, *pix;
unsigned int rtot, gtot, btot, atot, size, rshift, gshift, bshift, ashift;
unsigned int rloss, gloss, bloss, aloss;
int row, col;
SDL_PixelFormat *format;
format = surf->format;
rmask = format->Rmask;
gmask = format->Gmask;
bmask = format->Bmask;
amask = format->Amask;
rshift = format->Rshift;
gshift = format->Gshift;
bshift = format->Bshift;
ashift = format->Ashift;
rloss = format->Rloss;
gloss = format->Gloss;
bloss = format->Bloss;
aloss = format->Aloss;
rtot = gtot = btot = atot = 0;
/* make sure the area specified is within the Surface */
if ((x + width) > surf->w)
width = surf->w - x;
if ((y + height) > surf->h)
height = surf->h - y;
if (x < 0)
{
width -= (-x);
x = 0;
}
if (y < 0)
{
height -= (-y);
y = 0;
}
size = width*height;
switch (format->BytesPerPixel) {
case 1:
for (row = y; row < y+height; row++) {
pixels = (Uint8 *) surf->pixels + row*surf->pitch + x;
for (col = x; col < x+width; col++) {
color = (Uint32)*((Uint8 *) pixels);
rtot += ((color & rmask) >> rshift) << rloss;
gtot += ((color & gmask) >> gshift) << gloss;
btot += ((color & bmask) >> bshift) << bloss;
atot += ((color & amask) >> ashift) << aloss;
pixels++;
}
}
break;
case 2:
for (row = y; row < y+height; row++) {
pixels = (Uint8 *) surf->pixels + row*surf->pitch + x*2;
for (col = x; col < x+width; col++) {
color = (Uint32)*((Uint16 *) pixels);
rtot += ((color & rmask) >> rshift) << rloss;
gtot += ((color & gmask) >> gshift) << gloss;
btot += ((color & bmask) >> bshift) << bloss;
atot += ((color & amask) >> ashift) << aloss;
pixels += 2;
}
}
break;
case 3:
for (row = y; row < y+height; row++) {
pixels = (Uint8 *) surf->pixels + row*surf->pitch + x*3;
for (col = x; col < x+width; col++) {
pix = pixels;
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
color = (pix[0]) + (pix[1] << 8) + (pix[2] << 16);
#else
color = (pix[2]) + (pix[1] << 8) + (pix[0] << 16);
#endif
rtot += ((color & rmask) >> rshift) << rloss;
gtot += ((color & gmask) >> gshift) << gloss;
btot += ((color & bmask) >> bshift) << bloss;
atot += ((color & amask) >> ashift) << aloss;
pixels += 3;
}
}
break;
default: /* case 4: */
for (row = y; row < y+height; row++) {
pixels = (Uint8 *) surf->pixels + row*surf->pitch + x*4;
for (col = x; col < x+width; col++) {
color = *(Uint32 *)pixels;
rtot += ((color & rmask) >> rshift) << rloss;
gtot += ((color & gmask) >> gshift) << gloss;
btot += ((color & bmask) >> bshift) << bloss;
atot += ((color & amask) >> ashift) << aloss;
pixels += 4;
}
}
break;
}
*r = rtot/size;
*g = gtot/size;
*b = btot/size;
*a = atot/size;
}
static PyObject* surf_average_color(PyObject* self, PyObject* arg)
{
PyObject *surfobj, *rectobj = NULL;
SDL_Surface* surf;
GAME_Rect* rect, temp;
Uint8 r, g, b, a;
int x, y, w, h;
if (!PyArg_ParseTuple (arg, "O!|O", &PySurface_Type, &surfobj, &rectobj))
return NULL;
surf = PySurface_AsSurface (surfobj);
PySurface_Lock (surfobj);
if (!rectobj) {
x = 0;
y = 0;
w = surf->w;
h = surf->h;
} else {
if (!(rect = GameRect_FromObject (rectobj, &temp)))
return RAISE (PyExc_TypeError, "Rect argument is invalid");
x = rect->x;
y = rect->y;
w = rect->w;
h = rect->h;
}
Py_BEGIN_ALLOW_THREADS;
average_color(surf, x, y, w, h, &r, &g, &b, &a);
Py_END_ALLOW_THREADS;
PySurface_Unlock (surfobj);
return Py_BuildValue ("(bbbb)", r, g, b, a);
}
static PyMethodDef _transform_methods[] =
{
{ "scale", surf_scale, METH_VARARGS, DOC_PYGAMETRANSFORMSCALE },
{ "rotate", surf_rotate, METH_VARARGS, DOC_PYGAMETRANSFORMROTATE },
{ "flip", surf_flip, METH_VARARGS, DOC_PYGAMETRANSFORMFLIP },
{ "rotozoom", surf_rotozoom, METH_VARARGS, DOC_PYGAMETRANSFORMROTOZOOM},
{ "chop", surf_chop, METH_VARARGS, DOC_PYGAMETRANSFORMCHOP },
{ "scale2x", surf_scale2x, METH_VARARGS, DOC_PYGAMETRANSFORMSCALE2X },
{ "smoothscale", surf_scalesmooth, METH_VARARGS, DOC_PYGAMETRANSFORMSMOOTHSCALE },
{ "get_smoothscale_backend", (PyCFunction) surf_get_smoothscale_backend, METH_NOARGS,
DOC_PYGAMETRANSFORMGETSMOOTHSCALEBACKEND },
{ "set_smoothscale_backend", (PyCFunction) surf_set_smoothscale_backend,
METH_VARARGS | METH_KEYWORDS,
DOC_PYGAMETRANSFORMSETSMOOTHSCALEBACKEND },
{ "threshold", surf_threshold, METH_VARARGS, DOC_PYGAMETRANSFORMTHRESHOLD },
{ "laplacian", surf_laplacian, METH_VARARGS, DOC_PYGAMETRANSFORMTHRESHOLD },
{ "average_surfaces", surf_average_surfaces, METH_VARARGS, DOC_PYGAMETRANSFORMAVERAGESURFACES },
{ "average_color", surf_average_color, METH_VARARGS, DOC_PYGAMETRANSFORMAVERAGECOLOR },
{ NULL, NULL, 0, NULL }
};
MODINIT_DEFINE (transform)
{
PyObject *module;
struct _module_state *st;
#if PY3
static struct PyModuleDef _module = {
PyModuleDef_HEAD_INIT,
"transform",
DOC_PYGAMETRANSFORM,
sizeof (struct _module_state),
_transform_methods,
NULL, NULL, NULL, NULL
};
#endif
/* imported needed apis; Do this first so if there is an error
the module is not loaded.
*/
import_pygame_base ();
if (PyErr_Occurred ()) {
MODINIT_ERROR;
}
import_pygame_color ();
if (PyErr_Occurred ()) {
MODINIT_ERROR;
}
import_pygame_rect ();
if (PyErr_Occurred ()) {
MODINIT_ERROR;
}
import_pygame_surface ();
if (PyErr_Occurred ()) {
MODINIT_ERROR;
}
/* create the module */
#if PY3
module = PyModule_Create (&_module);
#else
module = Py_InitModule3 (MODPREFIX "transform",
_transform_methods,
DOC_PYGAMETRANSFORM);
#endif
if (module == 0) {
MODINIT_ERROR;
}
st = GETSTATE (module);
if (st->filter_type == 0) {
smoothscale_init (st);
}
MODINIT_RETURN (module);
}
pygame-1.9.1release/src/time.doc 0000644 0001750 0001750 00000007722 11205141271 016461 0 ustar vincent vincent pygame.time
pygame module for monitoring time
Times in pygame are represented in milliseconds (1/1000 seconds).
Most platforms have a limited time resolution of around 10 milliseconds.
This resolution, in milliseconds, is given in the TIMER_RESOLUTION constant.
get_ticks
get the time in milliseconds
pygame.time.get_ticks(): return milliseconds
Return the number of millisconds since pygame.init() was called. Before
pygame is initialized this will always be 0.
wait
pause the program for an amount of time
pygame.time.wait(milliseconds): return time
Will pause for a given number of milliseconds. This function sleeps the
process to share the processor with other programs. A program that waits
for even a few milliseconds will consume very little processor time.
It is slightly less accurate than the pygame.time.delay() function.
This returns the actual number of milliseconds used.
delay
pause the program for an amount of time
pygame.time.delay(milliseconds): return time
Will pause for a given number of milliseconds. This function will use the
processor (rather than sleeping) in order to make the delay more accurate than pygame.time.wait().
This returns the actual number of milliseconds used.
set_timer
repeatedly create an event on the event queue
pygame.time.set_timer(eventid, milliseconds): return None
Set an event type to appear on the event queue every given number of
milliseconds. The first event will not appear until the amount of time has
passed.
Every event type can have a separate timer attached to it. It is best to
use the value between pygame.USEREVENT and pygame.NUMEVENTS.
To disable the timer for an event, set the milliseconds argument to 0.
Clock
create an object to help track time
pygame.time.Clock(): return Clock
Creates a new Clock object that can be used to track an amount of time.
The clock also provides several functions to help control a game's framerate.
tick
update the clock
Clock.tick(framerate=0): return milliseconds
control timer events
This method should be called once per frame. It will compute how many
milliseconds have passed since the previous call.
If you pass the optional framerate argument the function will delay to keep
the game running slower than the given ticks per second. This can be used
to help limit the runtime speed of a game. By calling Clock.tick(40) once
per frame, the program will never run at more than 40 frames per second.
Note that this function uses SDL_Delay function which is not accurate
on every platform, but does not use much cpu. Use tick_busy_loop
if you want an accurate timer, and don't mind chewing cpu.
tick_busy_loop
update the clock
Clock.tick_busy_loop(framerate=0): return milliseconds
control timer events
This method should be called once per frame. It will compute how many
milliseconds have passed since the previous call.
If you pass the optional framerate argument the function will delay to keep
the game running slower than the given ticks per second. This can be used
to help limit the runtime speed of a game. By calling Clock.tick(40) once
per frame, the program will never run at more than 40 frames per second.
Note that this function uses pygame.time.delay, which uses lots of cpu
in a busy loop to make sure that timing is more acurate.
New in pygame 1.8.0.
get_time
time used in the previous tick
Clock.get_time(): return milliseconds
Returns the parameter passed to the last call to Clock.tick().
It is the number of milliseconds passed between the previous two calls to
Pygame.tick().
get_rawtime
actual time used in the previous tick
Clock.get_rawtime(): return milliseconds
Similar to Clock.get_time(), but this does not include any time used while
Clock.tick() was delaying to limit the framerate.
get_fps
compute the clock framerate
Clock.get_fps(): return float
Compute your game's framerate (in frames per second). It is computed by
averaging the last few calls to Clock.tick().
pygame-1.9.1release/src/time.c 0000644 0001750 0001750 00000027464 11207055754 016157 0 ustar vincent vincent /*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
#include "pygame.h"
#include "pgcompat.h"
#include "pygamedocs.h"
#define WORST_CLOCK_ACCURACY 12
static SDL_TimerID event_timers[SDL_NUMEVENTS] = {NULL};
static Uint32
timer_callback (Uint32 interval, void* param)
{
if (SDL_WasInit (SDL_INIT_VIDEO))
{
SDL_Event event;
memset (&event, 0, sizeof (event));
event.type = (intptr_t) param;
SDL_PushEvent (&event);
}
return interval;
}
static int
accurate_delay (int ticks)
{
int funcstart, delay;
if (ticks <= 0)
return 0;
if (!SDL_WasInit (SDL_INIT_TIMER))
{
if (SDL_InitSubSystem (SDL_INIT_TIMER))
{
RAISE (PyExc_SDLError, SDL_GetError ());
return -1;
}
}
funcstart = SDL_GetTicks ();
if (ticks >= WORST_CLOCK_ACCURACY)
{
delay = (ticks - 2) - (ticks % WORST_CLOCK_ACCURACY);
if (delay >= WORST_CLOCK_ACCURACY)
{
Py_BEGIN_ALLOW_THREADS;
SDL_Delay (delay);
Py_END_ALLOW_THREADS;
}
}
do
{
delay = ticks - (SDL_GetTicks () - funcstart);
}
while (delay > 0);
return SDL_GetTicks () - funcstart;
}
static PyObject*
time_get_ticks (PyObject* self)
{
if (!SDL_WasInit (SDL_INIT_TIMER))
return PyInt_FromLong (0);
return PyInt_FromLong (SDL_GetTicks ());
}
static PyObject*
time_delay (PyObject* self, PyObject* arg)
{
int ticks;
PyObject* arg0;
/*for some reason PyArg_ParseTuple is puking on -1's! BLARG!*/
if (PyTuple_Size (arg) != 1)
return RAISE (PyExc_ValueError,
"delay requires one integer argument");
arg0 = PyTuple_GET_ITEM (arg, 0);
if (!PyInt_Check (arg0))
return RAISE (PyExc_TypeError, "delay requires one integer argument");
ticks = PyInt_AsLong (arg0);
if (ticks < 0)
ticks = 0;
ticks = accurate_delay (ticks);
if (ticks == -1)
return NULL;
return PyInt_FromLong (ticks);
}
static PyObject*
time_wait (PyObject* self, PyObject* arg)
{
int ticks, start;
PyObject* arg0;
/*for some reason PyArg_ParseTuple is puking on -1's! BLARG!*/
if (PyTuple_Size (arg) != 1)
return RAISE (PyExc_ValueError, "delay requires one integer argument");
arg0 = PyTuple_GET_ITEM (arg, 0);
if (!PyInt_Check (arg0))
return RAISE (PyExc_TypeError, "delay requires one integer argument");
if (!SDL_WasInit (SDL_INIT_TIMER))
{
if (SDL_InitSubSystem (SDL_INIT_TIMER))
{
RAISE (PyExc_SDLError, SDL_GetError ());
return NULL;
}
}
ticks = PyInt_AsLong (arg0);
if (ticks < 0)
ticks = 0;
start = SDL_GetTicks ();
Py_BEGIN_ALLOW_THREADS;
SDL_Delay (ticks);
Py_END_ALLOW_THREADS;
return PyInt_FromLong (SDL_GetTicks () - start);
}
static PyObject*
time_set_timer (PyObject* self, PyObject* arg)
{
SDL_TimerID newtimer;
int ticks = 0;
intptr_t event = SDL_NOEVENT;
if (!PyArg_ParseTuple (arg, "ii", &event, &ticks))
return NULL;
if (event <= SDL_NOEVENT || event >= SDL_NUMEVENTS)
return RAISE (PyExc_ValueError,
"Event id must be between NOEVENT(0) and NUMEVENTS(32)");
/*stop original timer*/
if (event_timers[event])
{
SDL_RemoveTimer (event_timers[event]);
event_timers[event] = NULL;
}
if (ticks <= 0)
Py_RETURN_NONE;
/*just doublecheck that timer is initialized*/
if (!SDL_WasInit (SDL_INIT_TIMER))
{
if (SDL_InitSubSystem (SDL_INIT_TIMER))
return RAISE (PyExc_SDLError, SDL_GetError ());
}
newtimer = SDL_AddTimer (ticks, timer_callback, (void*) event);
if (!newtimer)
return RAISE (PyExc_SDLError, SDL_GetError ());
event_timers[event] = newtimer;
Py_RETURN_NONE;
}
/*clock object interface*/
typedef struct
{
PyObject_HEAD
int last_tick;
int fps_count, fps_tick;
float fps;
int timepassed, rawpassed;
PyObject* rendered;
} PyClockObject;
// to be called by the other tick functions.
static PyObject*
clock_tick_base(PyObject* self, PyObject* arg, int use_accurate_delay)
{
PyClockObject* _clock = (PyClockObject*) self;
float framerate = 0.0f;
int nowtime;
if (!PyArg_ParseTuple (arg, "|f", &framerate))
return NULL;
if (framerate)
{
int delay, endtime = (int) ((1.0f / framerate) * 1000.0f);
_clock->rawpassed = SDL_GetTicks () - _clock->last_tick;
delay = endtime - _clock->rawpassed;
/*just doublecheck that timer is initialized*/
if (!SDL_WasInit (SDL_INIT_TIMER))
{
if (SDL_InitSubSystem (SDL_INIT_TIMER))
{
RAISE (PyExc_SDLError, SDL_GetError ());
return NULL;
}
}
if (use_accurate_delay)
delay = accurate_delay (delay);
else
{
// this uses sdls delay, which can be inaccurate.
if (delay < 0)
delay = 0;
Py_BEGIN_ALLOW_THREADS;
SDL_Delay ((Uint32) delay);
Py_END_ALLOW_THREADS;
}
if (delay == -1)
return NULL;
}
nowtime = SDL_GetTicks ();
_clock->timepassed = nowtime - _clock->last_tick;
_clock->fps_count += 1;
_clock->last_tick = nowtime;
if (!framerate)
_clock->rawpassed = _clock->timepassed;
if (!_clock->fps_tick)
{
_clock->fps_count = 0;
_clock->fps_tick = nowtime;
}
else if (_clock->fps_count >= 10)
{
_clock->fps = _clock->fps_count /
((nowtime - _clock->fps_tick) / 1000.0f);
_clock->fps_count = 0;
_clock->fps_tick = nowtime;
Py_XDECREF (_clock->rendered);
}
return PyInt_FromLong (_clock->timepassed);
}
static PyObject*
clock_tick (PyObject* self, PyObject* arg)
{
return clock_tick_base (self, arg, 0);
}
static PyObject*
clock_tick_busy_loop (PyObject* self, PyObject* arg)
{
return clock_tick_base (self, arg, 1);
}
static PyObject*
clock_get_fps (PyObject* self, PyObject* args)
{
PyClockObject* _clock = (PyClockObject*) self;
return PyFloat_FromDouble (_clock->fps);
}
static PyObject*
clock_get_time (PyObject* self)
{
PyClockObject* _clock = (PyClockObject*) self;
return PyInt_FromLong (_clock->timepassed);
}
static PyObject*
clock_get_rawtime (PyObject* self)
{
PyClockObject* _clock = (PyClockObject*) self;
return PyInt_FromLong (_clock->rawpassed);
}
/* clock object internals */
static struct PyMethodDef clock_methods[] =
{
{ "tick", clock_tick, METH_VARARGS, DOC_CLOCKTICK },
{ "get_fps", (PyCFunction) clock_get_fps, METH_NOARGS, DOC_CLOCKGETFPS },
{ "get_time", (PyCFunction) clock_get_time, METH_NOARGS,
DOC_CLOCKGETTIME },
{ "get_rawtime", (PyCFunction) clock_get_rawtime, METH_NOARGS,
DOC_CLOCKGETRAWTIME },
{ "tick_busy_loop", clock_tick_busy_loop, METH_VARARGS,
DOC_CLOCKTICKBUSYLOOP },
{ NULL, NULL, 0, NULL}
};
static void
clock_dealloc (PyObject* self)
{
PyClockObject* _clock = (PyClockObject*) self;
Py_XDECREF (_clock->rendered);
PyObject_DEL (self);
}
PyObject*
clock_str (PyObject* self)
{
char str[1024];
PyClockObject* _clock = (PyClockObject*) self;
sprintf (str, "", (float) _clock->fps);
return Text_FromUTF8 (str);
}
static PyTypeObject PyClock_Type =
{
TYPE_HEAD (NULL, 0)
"Clock", /* name */
sizeof(PyClockObject), /* basic size */
0, /* itemsize */
clock_dealloc, /* dealloc */
0, /* print */
0, /* getattr */
0, /* setattr */
0, /* compare */
clock_str, /* repr */
0, /* as_number */
0, /* as_sequence */
0, /* as_mapping */
(hashfunc)0, /* hash */
(ternaryfunc)0, /* call */
clock_str, /* str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
0, /* flags */
DOC_PYGAMETIMECLOCK, /* Documentation string */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
clock_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
};
PyObject*
ClockInit (PyObject* self)
{
PyClockObject* _clock = PyObject_NEW (PyClockObject, &PyClock_Type);
if (!_clock) {
return NULL;
}
/*just doublecheck that timer is initialized*/
if (!SDL_WasInit (SDL_INIT_TIMER))
{
if (SDL_InitSubSystem (SDL_INIT_TIMER))
return RAISE (PyExc_SDLError, SDL_GetError ());
}
_clock->fps_tick = 0;
_clock->last_tick = SDL_GetTicks ();
_clock->fps = 0.0f;
_clock->fps_count = 0;
_clock->rendered = NULL;
return (PyObject*) _clock;
}
static PyMethodDef _time_methods[] =
{
{ "get_ticks", (PyCFunction) time_get_ticks, METH_NOARGS,
DOC_PYGAMETIMEGETTICKS },
{ "delay", time_delay, METH_VARARGS, DOC_PYGAMETIMEDELAY },
{ "wait", time_wait, METH_VARARGS, DOC_PYGAMETIMEWAIT },
{ "set_timer", time_set_timer, METH_VARARGS, DOC_PYGAMETIMESETTIMER },
{ "Clock", (PyCFunction) ClockInit, METH_NOARGS, DOC_PYGAMETIMECLOCK },
{ NULL, NULL, 0, NULL }
};
#ifdef __SYMBIAN32__
PYGAME_EXPORT
void initpygame_time (void)
#else
MODINIT_DEFINE (time)
#endif
{
PyObject *module;
#if PY3
static struct PyModuleDef _module = {
PyModuleDef_HEAD_INIT,
"time",
DOC_PYGAMETIME,
-1,
_time_methods,
NULL, NULL, NULL, NULL
};
#endif
/* need to import base module, just so SDL is happy. Do this first so if
the module is there is an error the module is not loaded.
*/
import_pygame_base ();
if (PyErr_Occurred ()) {
MODINIT_ERROR;
}
/* type preparation */
if (PyType_Ready (&PyClock_Type) < 0) {
MODINIT_ERROR;
}
/* create the module */
#if PY3
module = PyModule_Create (&_module);
#else
module = Py_InitModule3 (MODPREFIX "time", _time_methods, DOC_PYGAMETIME);
#endif
MODINIT_RETURN (module);
}
pygame-1.9.1release/src/surflock.c 0000644 0001750 0001750 00000021303 11207055754 017033 0 ustar vincent vincent /*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
Copyright (C) 2008 Marcus von Appen
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
/*
* internal surface locking support for python objects
*/
#define PYGAMEAPI_SURFLOCK_INTERNAL
#include "pygame.h"
#include "pgcompat.h"
static int PySurface_Lock (PyObject* surfobj);
static int PySurface_Unlock (PyObject* surfobj);
static int PySurface_LockBy (PyObject* surfobj, PyObject* lockobj);
static int PySurface_UnlockBy (PyObject* surfobj, PyObject* lockobj);
static void _lifelock_dealloc (PyObject* self);
static void
PySurface_Prep (PyObject* surfobj)
{
struct SubSurface_Data* data = ((PySurfaceObject*) surfobj)->subsurface;
if (data)
{
SDL_Surface* surf = PySurface_AsSurface (surfobj);
SDL_Surface* owner = PySurface_AsSurface (data->owner);
PySurface_LockBy (data->owner, surfobj);
surf->pixels = ((char*) owner->pixels) + data->pixeloffset;
}
}
static void
PySurface_Unprep (PyObject* surfobj)
{
struct SubSurface_Data* data = ((PySurfaceObject*) surfobj)->subsurface;
if (data)
PySurface_UnlockBy (data->owner, surfobj);
}
static int
PySurface_Lock (PyObject* surfobj)
{
return PySurface_LockBy (surfobj, surfobj);
}
static int
PySurface_Unlock (PyObject* surfobj)
{
return PySurface_UnlockBy (surfobj, surfobj);
}
static int
PySurface_LockBy (PyObject* surfobj, PyObject* lockobj)
{
PyObject *ref;
PySurfaceObject* surf = (PySurfaceObject*) surfobj;
if (!surf->locklist)
{
surf->locklist = PyList_New (0);
if (!surf->locklist)
return 0;
}
ref = PyWeakref_NewRef (lockobj, NULL);
if (!ref)
return 0;
if (ref == Py_None)
{
Py_DECREF (ref);
return 0;
}
PyList_Append (surf->locklist, ref);
Py_DECREF (ref);
if (surf->subsurface)
PySurface_Prep (surfobj);
if (SDL_LockSurface (surf->surf) == -1)
{
PyErr_SetString (PyExc_RuntimeError, "error locking surface");
return 0;
}
return 1;
}
static int
PySurface_UnlockBy (PyObject* surfobj, PyObject* lockobj)
{
PySurfaceObject* surf = (PySurfaceObject*) surfobj;
int found = 0;
int noerror = 1;
if (surf->locklist)
{
PyObject *item, *ref;
Py_ssize_t len = PyList_Size (surf->locklist);
while (--len >= 0 && !found)
{
item = PyList_GetItem (surf->locklist, len);
ref = PyWeakref_GetObject (item);
if (ref == lockobj)
{
if (PySequence_DelItem (surf->locklist, len) == -1)
return 0;
else
found = 1;
}
}
/* Clear dead references */
len = PyList_Size (surf->locklist);
while (--len >= 0)
{
item = PyList_GetItem (surf->locklist, len);
ref = PyWeakref_GetObject (item);
if (ref == Py_None)
{
if (PySequence_DelItem (surf->locklist, len) == -1)
noerror = 0;
else
found++;
}
}
}
if (!found)
return noerror;
/* Release all found locks. */
while (found > 0)
{
if (surf->surf != NULL)
SDL_UnlockSurface (surf->surf);
if (surf->subsurface)
PySurface_Unprep (surfobj);
found--;
}
return noerror;
}
static PyTypeObject PyLifetimeLock_Type =
{
TYPE_HEAD (NULL, 0)
"SurfLifeLock", /*name*/
sizeof(PyLifetimeLock), /*basic size*/
0, /* tp_itemsize */
_lifelock_dealloc, /* tp_dealloc*/
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS,
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
offsetof (PyLifetimeLock, weakrefs), /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
0, /* tp_free */
0, /* tp_is_gc */
0, /* tp_bases */
0, /* tp_mro */
0, /* tp_cache */
0, /* tp_subclasses */
0, /* tp_weaklist */
0 /* tp_del */
};
/* lifetimelock object internals */
static void
_lifelock_dealloc (PyObject* self)
{
PyLifetimeLock* lifelock = (PyLifetimeLock*) self;
if (lifelock->weakrefs)
PyObject_ClearWeakRefs (self);
PySurface_UnlockBy (lifelock->surface, lifelock->lockobj);
Py_DECREF (lifelock->surface);
PyObject_DEL (self);
}
static PyObject*
PySurface_LockLifetime (PyObject* surfobj, PyObject *lockobj)
{
PyLifetimeLock* life;
if (!surfobj)
return RAISE (PyExc_SDLError, SDL_GetError ());
life = PyObject_NEW (PyLifetimeLock, &PyLifetimeLock_Type);
if (life)
{
life->surface = surfobj;
life->lockobj = lockobj;
life->weakrefs = NULL;
Py_INCREF (surfobj);
if (!PySurface_LockBy (surfobj, lockobj))
return NULL;
}
return (PyObject*) life;
}
static PyMethodDef _surflock_methods[] =
{
{ NULL, NULL, 0, NULL }
};
/*DOC*/ static char _surflock_doc[] =
/*DOC*/ "Surface locking support";
MODINIT_DEFINE (surflock)
{
PyObject *module, *dict, *apiobj;
int ecode;
static void* c_api[PYGAMEAPI_SURFLOCK_NUMSLOTS];
#if PY3
static struct PyModuleDef _module = {
PyModuleDef_HEAD_INIT,
"surflock",
_surflock_doc,
-1,
_surflock_methods,
NULL, NULL, NULL, NULL
};
#endif
if (PyType_Ready (&PyLifetimeLock_Type) < 0) {
MODINIT_ERROR;
}
/* Create the module and add the functions */
#if PY3
module = PyModule_Create (&_module);
#else
module = Py_InitModule3 (MODPREFIX "surflock",
_surflock_methods,
_surflock_doc);
#endif
if (module == NULL) {
MODINIT_ERROR;
}
dict = PyModule_GetDict (module);
/* export the c api */
c_api[0] = &PyLifetimeLock_Type;
c_api[1] = PySurface_Prep;
c_api[2] = PySurface_Unprep;
c_api[3] = PySurface_Lock;
c_api[4] = PySurface_Unlock;
c_api[5] = PySurface_LockBy;
c_api[6] = PySurface_UnlockBy;
c_api[7] = PySurface_LockLifetime;
apiobj = PyCObject_FromVoidPtr (c_api, NULL);
if (apiobj == NULL) {
DECREF_MOD (module);
MODINIT_ERROR;
}
ecode = PyDict_SetItemString (dict, PYGAMEAPI_LOCAL_ENTRY, apiobj);
Py_DECREF (apiobj);
if (ecode) {
DECREF_MOD (module);
MODINIT_ERROR;
}
MODINIT_RETURN (module);
}
pygame-1.9.1release/src/surface_fill.c 0000644 0001750 0001750 00000056026 11207055754 017653 0 ustar vincent vincent /*
pygame - Python Game Library
Copyright (C) 2007 Marcus von Appen
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "surface.h"
static int
surface_fill_blend_add (SDL_Surface *surface, SDL_Rect *rect, Uint32 color)
{
Uint8 *pixels;
int width = rect->w;
int height = rect->h;
int skip;
int bpp = surface->format->BytesPerPixel;
int n;
SDL_PixelFormat *fmt = surface->format;
Uint8 sR, sG, sB, sA, cR, cG, cB, cA;
Uint32 pixel;
Uint32 tmp;
int result = -1;
int ppa = (surface->flags & SDL_SRCALPHA && fmt->Amask);
pixels = (Uint8 *) surface->pixels + surface->offset +
(Uint16) rect->y * surface->pitch + (Uint16) rect->x * bpp;
skip = surface->pitch - width * bpp;
switch (bpp)
{
case 1:
{
SDL_GetRGBA (color, fmt, &cR, &cG, &cB, &cA);
while (height--)
{
LOOP_UNROLLED4(
{
GET_PIXELVALS_1 (sR, sG, sB, sA, pixels, fmt);
BLEND_ADD (tmp, cR, cG, cB, cA, sR, sG, sB, sA);
*pixels = SDL_MapRGBA (fmt, sR, sG, sB, sA);
pixels += bpp;
}, n, width);
pixels += skip;
}
result = 0;
break;
}
case 3:
{
size_t offsetR, offsetG, offsetB;
SET_OFFSETS_24 (offsetR, offsetG, offsetB, fmt);
GET_PIXELVALS (cR, cG, cB, cA, color, fmt, ppa);
while (height--)
{
LOOP_UNROLLED4(
{
GET_PIXEL (pixel, bpp, pixels);
GET_PIXELVALS (sR, sG, sB, sA, pixel, fmt, ppa);
BLEND_ADD (tmp, cR, cG, cB, cA, sR, sG, sB, sA);
pixels[offsetR] = sR;
pixels[offsetG] = sG;
pixels[offsetB] = sB;
pixels += bpp;
}, n, width);
pixels += skip;
}
result = 0;
break;
}
default:
{
GET_PIXELVALS (cR, cG, cB, cA, color, fmt, ppa);
/*
printf ("Color: %d, %d, %d, %d, BPP is: %d\n", cR, cG, cB, cA, bpp);
*/
while (height--)
{
LOOP_UNROLLED4(
{
GET_PIXEL (pixel, bpp, pixels);
GET_PIXELVALS (sR, sG, sB, sA, pixel, fmt, ppa);
BLEND_ADD (tmp, cR, cG, cB, cA, sR, sG, sB, sA);
CREATE_PIXEL(pixels, sR, sG, sB, sA, bpp, fmt);
pixels += bpp;
}, n, width);
pixels += skip;
}
result = 0;
break;
}
}
return result;
}
static int
surface_fill_blend_sub (SDL_Surface *surface, SDL_Rect *rect, Uint32 color)
{
Uint8 *pixels;
int width = rect->w;
int height = rect->h;
int skip;
int bpp = surface->format->BytesPerPixel;
int n;
SDL_PixelFormat *fmt = surface->format;
Uint8 sR, sG, sB, sA, cR, cG, cB, cA;
Uint32 pixel;
Sint32 tmp2;
int result = -1;
int ppa = (surface->flags & SDL_SRCALPHA && fmt->Amask);
pixels = (Uint8 *) surface->pixels + surface->offset +
(Uint16) rect->y * surface->pitch + (Uint16) rect->x * bpp;
skip = surface->pitch - width * bpp;
switch (bpp)
{
case 1:
{
SDL_GetRGBA (color, fmt, &cR, &cG, &cB, &cA);
while (height--)
{
LOOP_UNROLLED4(
{
GET_PIXELVALS_1 (sR, sG, sB, sA, pixels, fmt);
BLEND_SUB (tmp2, cR, cG, cB, cA, sR, sG, sB, sA);
*pixels = SDL_MapRGBA (fmt, sR, sG, sB, sA);
pixels += bpp;
}, n, width);
pixels += skip;
}
result = 0;
break;
}
case 3:
{
size_t offsetR, offsetG, offsetB;
SET_OFFSETS_24 (offsetR, offsetG, offsetB, fmt);
GET_PIXELVALS (cR, cG, cB, cA, color, fmt, ppa);
while (height--)
{
LOOP_UNROLLED4(
{
GET_PIXEL (pixel, bpp, pixels);
GET_PIXELVALS (sR, sG, sB, sA, pixel, fmt, ppa);
BLEND_SUB (tmp2, cR, cG, cB, cA, sR, sG, sB, sA);
pixels[offsetR] = sR;
pixels[offsetG] = sG;
pixels[offsetB] = sB;
pixels += bpp;
}, n, width);
pixels += skip;
}
result = 0;
break;
}
default:
{
GET_PIXELVALS (cR, cG, cB, cA, color, fmt, ppa);
/*
printf ("Color: %d, %d, %d, %d, BPP is: %d\n", cR, cG, cB, cA, bpp);
*/
while (height--)
{
LOOP_UNROLLED4(
{
GET_PIXEL (pixel, bpp, pixels);
GET_PIXELVALS (sR, sG, sB, sA, pixel, fmt, ppa);
BLEND_SUB (tmp2, cR, cG, cB, cA, sR, sG, sB, sA);
CREATE_PIXEL(pixels, sR, sG, sB, sA, bpp, fmt);
pixels += bpp;
}, n, width);
pixels += skip;
}
result = 0;
break;
}
}
return result;
}
static int
surface_fill_blend_mult (SDL_Surface *surface, SDL_Rect *rect, Uint32 color)
{
Uint8 *pixels;
int width = rect->w;
int height = rect->h;
int skip;
int bpp = surface->format->BytesPerPixel;
int n;
SDL_PixelFormat *fmt = surface->format;
Uint8 sR, sG, sB, sA, cR, cG, cB, cA;
Uint32 pixel;
int result = -1;
int ppa = (surface->flags & SDL_SRCALPHA && fmt->Amask);
pixels = (Uint8 *) surface->pixels + surface->offset +
(Uint16) rect->y * surface->pitch + (Uint16) rect->x * bpp;
skip = surface->pitch - width * bpp;
switch (bpp)
{
case 1:
{
SDL_GetRGBA (color, fmt, &cR, &cG, &cB, &cA);
while (height--)
{
LOOP_UNROLLED4(
{
GET_PIXELVALS_1 (sR, sG, sB, sA, pixels, fmt);
BLEND_MULT (cR, cG, cB, cA, sR, sG, sB, sA);
*pixels = SDL_MapRGBA (fmt, sR, sG, sB, sA);
pixels += bpp;
}, n, width);
pixels += skip;
}
result = 0;
break;
}
case 3:
{
size_t offsetR, offsetG, offsetB;
SET_OFFSETS_24 (offsetR, offsetG, offsetB, fmt);
GET_PIXELVALS (cR, cG, cB, cA, color, fmt, ppa);
while (height--)
{
LOOP_UNROLLED4(
{
GET_PIXEL (pixel, bpp, pixels);
GET_PIXELVALS (sR, sG, sB, sA, pixel, fmt, ppa);
BLEND_MULT (cR, cG, cB, cA, sR, sG, sB, sA);
pixels[offsetR] = sR;
pixels[offsetG] = sG;
pixels[offsetB] = sB;
pixels += bpp;
}, n, width);
pixels += skip;
}
result = 0;
break;
}
default:
{
GET_PIXELVALS (cR, cG, cB, cA, color, fmt, ppa);
/*
printf ("Color: %d, %d, %d, %d, BPP is: %d\n", cR, cG, cB, cA, bpp);
*/
while (height--)
{
LOOP_UNROLLED4(
{
GET_PIXEL (pixel, bpp, pixels);
GET_PIXELVALS (sR, sG, sB, sA, pixel, fmt, ppa);
BLEND_MULT (cR, cG, cB, cA, sR, sG, sB, sA);
CREATE_PIXEL(pixels, sR, sG, sB, sA, bpp, fmt);
pixels += bpp;
}, n, width);
pixels += skip;
}
result = 0;
break;
}
}
return result;
}
static int
surface_fill_blend_min (SDL_Surface *surface, SDL_Rect *rect, Uint32 color)
{
Uint8 *pixels;
int width = rect->w;
int height = rect->h;
int skip;
int bpp = surface->format->BytesPerPixel;
int n;
SDL_PixelFormat *fmt = surface->format;
Uint8 sR, sG, sB, sA, cR, cG, cB, cA;
Uint32 pixel;
int result = -1;
int ppa = (surface->flags & SDL_SRCALPHA && fmt->Amask);
pixels = (Uint8 *) surface->pixels + surface->offset +
(Uint16) rect->y * surface->pitch + (Uint16) rect->x * bpp;
skip = surface->pitch - width * bpp;
switch (bpp)
{
case 1:
{
SDL_GetRGBA (color, fmt, &cR, &cG, &cB, &cA);
while (height--)
{
LOOP_UNROLLED4(
{
GET_PIXELVALS_1 (sR, sG, sB, sA, pixels, fmt);
BLEND_MIN (cR, cG, cB, cA, sR, sG, sB, sA);
*pixels = SDL_MapRGBA (fmt, sR, sG, sB, sA);
pixels += bpp;
}, n, width);
pixels += skip;
}
result = 0;
break;
}
case 3:
{
size_t offsetR, offsetG, offsetB;
SET_OFFSETS_24 (offsetR, offsetG, offsetB, fmt);
GET_PIXELVALS (cR, cG, cB, cA, color, fmt, ppa);
while (height--)
{
LOOP_UNROLLED4(
{
GET_PIXEL (pixel, bpp, pixels);
GET_PIXELVALS (sR, sG, sB, sA, pixel, fmt, ppa);
BLEND_MIN (cR, cG, cB, cA, sR, sG, sB, sA);
pixels[offsetR] = sR;
pixels[offsetG] = sG;
pixels[offsetB] = sB;
pixels += bpp;
}, n, width);
pixels += skip;
}
result = 0;
break;
}
default:
{
GET_PIXELVALS (cR, cG, cB, cA, color, fmt, ppa);
/*
printf ("Color: %d, %d, %d, %d, BPP is: %d\n", cR, cG, cB, cA, bpp);
*/
while (height--)
{
LOOP_UNROLLED4(
{
GET_PIXEL (pixel, bpp, pixels);
GET_PIXELVALS (sR, sG, sB, sA, pixel, fmt, ppa);
BLEND_MIN (cR, cG, cB, cA, sR, sG, sB, sA);
CREATE_PIXEL(pixels, sR, sG, sB, sA, bpp, fmt);
pixels += bpp;
}, n, width);
pixels += skip;
}
result = 0;
break;
}
}
return result;
}
static int
surface_fill_blend_max (SDL_Surface *surface, SDL_Rect *rect, Uint32 color)
{
Uint8 *pixels;
int width = rect->w;
int height = rect->h;
int skip;
int bpp = surface->format->BytesPerPixel;
int n;
SDL_PixelFormat *fmt = surface->format;
Uint8 sR, sG, sB, sA, cR, cG, cB, cA;
Uint32 pixel;
int result = -1;
int ppa = (surface->flags & SDL_SRCALPHA && fmt->Amask);
pixels = (Uint8 *) surface->pixels + surface->offset +
(Uint16) rect->y * surface->pitch + (Uint16) rect->x * bpp;
skip = surface->pitch - width * bpp;
switch (bpp)
{
case 1:
{
SDL_GetRGBA (color, fmt, &cR, &cG, &cB, &cA);
while (height--)
{
LOOP_UNROLLED4(
{
GET_PIXELVALS_1 (sR, sG, sB, sA, pixels, fmt);
BLEND_MAX (cR, cG, cB, cA, sR, sG, sB, sA);
*pixels = SDL_MapRGBA (fmt, sR, sG, sB, sA);
pixels += bpp;
}, n, width);
pixels += skip;
}
result = 0;
break;
}
case 3:
{
size_t offsetR, offsetG, offsetB;
SET_OFFSETS_24 (offsetR, offsetG, offsetB, fmt);
GET_PIXELVALS (cR, cG, cB, cA, color, fmt, ppa);
while (height--)
{
LOOP_UNROLLED4(
{
GET_PIXEL (pixel, bpp, pixels);
GET_PIXELVALS (sR, sG, sB, sA, pixel, fmt, ppa);
BLEND_MAX (cR, cG, cB, cA, sR, sG, sB, sA);
pixels[offsetR] = sR;
pixels[offsetG] = sG;
pixels[offsetB] = sB;
pixels += bpp;
}, n, width);
pixels += skip;
}
result = 0;
break;
}
default:
{
GET_PIXELVALS (cR, cG, cB, cA, color, fmt, ppa);
/*
printf ("Color: %d, %d, %d, %d, BPP is: %d\n", cR, cG, cB, cA, bpp);
*/
while (height--)
{
LOOP_UNROLLED4(
{
GET_PIXEL (pixel, bpp, pixels);
GET_PIXELVALS (sR, sG, sB, sA, pixel, fmt, ppa);
BLEND_MAX (cR, cG, cB, cA, sR, sG, sB, sA);
CREATE_PIXEL(pixels, sR, sG, sB, sA, bpp, fmt);
pixels += bpp;
}, n, width);
pixels += skip;
}
result = 0;
break;
}
}
return result;
}
/* ------------------------- */
static int
surface_fill_blend_rgba_add (SDL_Surface *surface, SDL_Rect *rect, Uint32 color)
{
Uint8 *pixels;
int width = rect->w;
int height = rect->h;
int skip;
int bpp = surface->format->BytesPerPixel;
int n;
SDL_PixelFormat *fmt = surface->format;
Uint8 sR, sG, sB, sA, cR, cG, cB, cA;
Uint32 pixel;
Uint32 tmp;
int result = -1;
int ppa = (surface->flags & SDL_SRCALPHA && fmt->Amask);
if (!ppa)
{
return surface_fill_blend_add (surface, rect, color);
}
pixels = (Uint8 *) surface->pixels + surface->offset +
(Uint16) rect->y * surface->pitch + (Uint16) rect->x * bpp;
skip = surface->pitch - width * bpp;
switch (bpp)
{
case 1:
{
SDL_GetRGBA (color, fmt, &cR, &cG, &cB, &cA);
while (height--)
{
LOOP_UNROLLED4(
{
GET_PIXELVALS_1 (sR, sG, sB, sA, pixels, fmt);
BLEND_RGBA_ADD (tmp, cR, cG, cB, cA, sR, sG, sB, sA);
*pixels = SDL_MapRGBA (fmt, sR, sG, sB, sA);
pixels += bpp;
}, n, width);
pixels += skip;
}
result = 0;
break;
}
default:
{
GET_PIXELVALS (cR, cG, cB, cA, color, fmt, ppa);
/*
printf ("Color: %d, %d, %d, %d, BPP is: %d\n", cR, cG, cB, cA, bpp);
*/
while (height--)
{
LOOP_UNROLLED4(
{
GET_PIXEL (pixel, bpp, pixels);
GET_PIXELVALS (sR, sG, sB, sA, pixel, fmt, ppa);
BLEND_RGBA_ADD (tmp, cR, cG, cB, cA, sR, sG, sB, sA);
CREATE_PIXEL(pixels, sR, sG, sB, sA, bpp, fmt);
pixels += bpp;
}, n, width);
pixels += skip;
}
result = 0;
break;
}
}
return result;
}
static int
surface_fill_blend_rgba_sub (SDL_Surface *surface, SDL_Rect *rect, Uint32 color)
{
Uint8 *pixels;
int width = rect->w;
int height = rect->h;
int skip;
int bpp = surface->format->BytesPerPixel;
int n;
SDL_PixelFormat *fmt = surface->format;
Uint8 sR, sG, sB, sA, cR, cG, cB, cA;
Uint32 pixel;
Sint32 tmp2;
int result = -1;
int ppa = (surface->flags & SDL_SRCALPHA && fmt->Amask);
if (!ppa)
{
return surface_fill_blend_sub (surface, rect, color);
}
pixels = (Uint8 *) surface->pixels + surface->offset +
(Uint16) rect->y * surface->pitch + (Uint16) rect->x * bpp;
skip = surface->pitch - width * bpp;
switch (bpp)
{
case 1:
{
SDL_GetRGBA (color, fmt, &cR, &cG, &cB, &cA);
while (height--)
{
LOOP_UNROLLED4(
{
GET_PIXELVALS_1 (sR, sG, sB, sA, pixels, fmt);
BLEND_RGBA_SUB (tmp2, cR, cG, cB, cA, sR, sG, sB, sA);
*pixels = SDL_MapRGBA (fmt, sR, sG, sB, sA);
pixels += bpp;
}, n, width);
pixels += skip;
}
result = 0;
break;
}
default:
{
GET_PIXELVALS (cR, cG, cB, cA, color, fmt, ppa);
/*
printf ("Color: %d, %d, %d, %d, BPP is: %d\n", cR, cG, cB, cA, bpp);
*/
while (height--)
{
LOOP_UNROLLED4(
{
GET_PIXEL (pixel, bpp, pixels);
GET_PIXELVALS (sR, sG, sB, sA, pixel, fmt, ppa);
BLEND_RGBA_SUB (tmp2, cR, cG, cB, cA, sR, sG, sB, sA);
CREATE_PIXEL(pixels, sR, sG, sB, sA, bpp, fmt);
pixels += bpp;
}, n, width);
pixels += skip;
}
result = 0;
break;
}
}
return result;
}
static int
surface_fill_blend_rgba_mult (SDL_Surface *surface, SDL_Rect *rect, Uint32 color)
{
Uint8 *pixels;
int width = rect->w;
int height = rect->h;
int skip;
int bpp = surface->format->BytesPerPixel;
int n;
SDL_PixelFormat *fmt = surface->format;
Uint8 sR, sG, sB, sA, cR, cG, cB, cA;
Uint32 pixel;
int result = -1;
int ppa = (surface->flags & SDL_SRCALPHA && fmt->Amask);
if (!ppa)
{
return surface_fill_blend_mult (surface, rect, color);
}
pixels = (Uint8 *) surface->pixels + surface->offset +
(Uint16) rect->y * surface->pitch + (Uint16) rect->x * bpp;
skip = surface->pitch - width * bpp;
switch (bpp)
{
case 1:
{
SDL_GetRGBA (color, fmt, &cR, &cG, &cB, &cA);
while (height--)
{
LOOP_UNROLLED4(
{
GET_PIXELVALS_1 (sR, sG, sB, sA, pixels, fmt);
BLEND_RGBA_MULT (cR, cG, cB, cA, sR, sG, sB, sA);
*pixels = SDL_MapRGBA (fmt, sR, sG, sB, sA);
pixels += bpp;
}, n, width);
pixels += skip;
}
result = 0;
break;
}
default:
{
GET_PIXELVALS (cR, cG, cB, cA, color, fmt, ppa);
/*
printf ("Color: %d, %d, %d, %d, BPP is: %d\n", cR, cG, cB, cA, bpp);
*/
while (height--)
{
LOOP_UNROLLED4(
{
GET_PIXEL (pixel, bpp, pixels);
GET_PIXELVALS (sR, sG, sB, sA, pixel, fmt, ppa);
BLEND_RGBA_MULT (cR, cG, cB, cA, sR, sG, sB, sA);
CREATE_PIXEL(pixels, sR, sG, sB, sA, bpp, fmt);
pixels += bpp;
}, n, width);
pixels += skip;
}
result = 0;
break;
}
}
return result;
}
static int
surface_fill_blend_rgba_min (SDL_Surface *surface, SDL_Rect *rect, Uint32 color)
{
Uint8 *pixels;
int width = rect->w;
int height = rect->h;
int skip;
int bpp = surface->format->BytesPerPixel;
int n;
SDL_PixelFormat *fmt = surface->format;
Uint8 sR, sG, sB, sA, cR, cG, cB, cA;
Uint32 pixel;
int result = -1;
int ppa = (surface->flags & SDL_SRCALPHA && fmt->Amask);
if (!ppa)
{
return surface_fill_blend_min (surface, rect, color);
}
pixels = (Uint8 *) surface->pixels + surface->offset +
(Uint16) rect->y * surface->pitch + (Uint16) rect->x * bpp;
skip = surface->pitch - width * bpp;
switch (bpp)
{
case 1:
{
SDL_GetRGBA (color, fmt, &cR, &cG, &cB, &cA);
while (height--)
{
LOOP_UNROLLED4(
{
GET_PIXELVALS_1 (sR, sG, sB, sA, pixels, fmt);
BLEND_RGBA_MIN (cR, cG, cB, cA, sR, sG, sB, sA);
*pixels = SDL_MapRGBA (fmt, sR, sG, sB, sA);
pixels += bpp;
}, n, width);
pixels += skip;
}
result = 0;
break;
}
default:
{
GET_PIXELVALS (cR, cG, cB, cA, color, fmt, ppa);
/*
printf ("Color: %d, %d, %d, %d, BPP is: %d\n", cR, cG, cB, cA, bpp);
*/
while (height--)
{
LOOP_UNROLLED4(
{
GET_PIXEL (pixel, bpp, pixels);
GET_PIXELVALS (sR, sG, sB, sA, pixel, fmt, ppa);
BLEND_RGBA_MIN (cR, cG, cB, cA, sR, sG, sB, sA);
CREATE_PIXEL(pixels, sR, sG, sB, sA, bpp, fmt);
pixels += bpp;
}, n, width);
pixels += skip;
}
result = 0;
break;
}
}
return result;
}
static int
surface_fill_blend_rgba_max (SDL_Surface *surface, SDL_Rect *rect, Uint32 color)
{
Uint8 *pixels;
int width = rect->w;
int height = rect->h;
int skip;
int bpp = surface->format->BytesPerPixel;
int n;
SDL_PixelFormat *fmt = surface->format;
Uint8 sR, sG, sB, sA, cR, cG, cB, cA;
Uint32 pixel;
int result = -1;
int ppa = (surface->flags & SDL_SRCALPHA && fmt->Amask);
if (!ppa)
{
return surface_fill_blend_max (surface, rect, color);
}
pixels = (Uint8 *) surface->pixels + surface->offset +
(Uint16) rect->y * surface->pitch + (Uint16) rect->x * bpp;
skip = surface->pitch - width * bpp;
switch (bpp)
{
case 1:
{
SDL_GetRGBA (color, fmt, &cR, &cG, &cB, &cA);
while (height--)
{
LOOP_UNROLLED4(
{
GET_PIXELVALS_1 (sR, sG, sB, sA, pixels, fmt);
BLEND_RGBA_MAX (cR, cG, cB, cA, sR, sG, sB, sA);
*pixels = SDL_MapRGBA (fmt, sR, sG, sB, sA);
pixels += bpp;
}, n, width);
pixels += skip;
}
result = 0;
break;
}
default:
{
GET_PIXELVALS (cR, cG, cB, cA, color, fmt, ppa);
/*
printf ("Color: %d, %d, %d, %d, BPP is: %d\n", cR, cG, cB, cA, bpp);
*/
while (height--)
{
LOOP_UNROLLED4(
{
GET_PIXEL (pixel, bpp, pixels);
GET_PIXELVALS (sR, sG, sB, sA, pixel, fmt, ppa);
BLEND_RGBA_MAX (cR, cG, cB, cA, sR, sG, sB, sA);
CREATE_PIXEL(pixels, sR, sG, sB, sA, bpp, fmt);
pixels += bpp;
}, n, width);
pixels += skip;
}
result = 0;
break;
}
}
return result;
}
int
surface_fill_blend (SDL_Surface *surface, SDL_Rect *rect, Uint32 color,
int blendargs)
{
int result = -1;
int locked = 0;
/* Lock the surface, if needed */
if (SDL_MUSTLOCK (surface))
{
if (SDL_LockSurface (surface) < 0)
return -1;
locked = 1;
}
switch (blendargs)
{
case PYGAME_BLEND_ADD:
{
result = surface_fill_blend_add (surface, rect, color);
break;
}
case PYGAME_BLEND_SUB:
{
result = surface_fill_blend_sub (surface, rect, color);
break;
}
case PYGAME_BLEND_MULT:
{
result = surface_fill_blend_mult (surface, rect, color);
break;
}
case PYGAME_BLEND_MIN:
{
result = surface_fill_blend_min (surface, rect, color);
break;
}
case PYGAME_BLEND_MAX:
{
result = surface_fill_blend_max (surface, rect, color);
break;
}
case PYGAME_BLEND_RGBA_ADD:
{
result = surface_fill_blend_rgba_add (surface, rect, color);
break;
}
case PYGAME_BLEND_RGBA_SUB:
{
result = surface_fill_blend_rgba_sub (surface, rect, color);
break;
}
case PYGAME_BLEND_RGBA_MULT:
{
result = surface_fill_blend_rgba_mult (surface, rect, color);
break;
}
case PYGAME_BLEND_RGBA_MIN:
{
result = surface_fill_blend_rgba_min (surface, rect, color);
break;
}
case PYGAME_BLEND_RGBA_MAX:
{
result = surface_fill_blend_rgba_max (surface, rect, color);
break;
}
default:
{
result = -1;
break;
}
}
if (locked)
{
SDL_UnlockSurface (surface);
}
return result;
}
pygame-1.9.1release/src/surface.h 0000644 0001750 0001750 00000031025 11147144371 016637 0 ustar vincent vincent /*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
Copyright (C) 2007 Marcus von Appen
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
#ifndef SURFACE_H
#define SURFACE_H
#include
#include "pygame.h"
#define PYGAME_BLEND_ADD 0x1
#define PYGAME_BLEND_SUB 0x2
#define PYGAME_BLEND_MULT 0x3
#define PYGAME_BLEND_MIN 0x4
#define PYGAME_BLEND_MAX 0x5
#define PYGAME_BLEND_RGB_ADD 0x1
#define PYGAME_BLEND_RGB_SUB 0x2
#define PYGAME_BLEND_RGB_MULT 0x3
#define PYGAME_BLEND_RGB_MIN 0x4
#define PYGAME_BLEND_RGB_MAX 0x5
#define PYGAME_BLEND_RGBA_ADD 0x6
#define PYGAME_BLEND_RGBA_SUB 0x7
#define PYGAME_BLEND_RGBA_MULT 0x8
#define PYGAME_BLEND_RGBA_MIN 0x9
#define PYGAME_BLEND_RGBA_MAX 0x10
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
#define GET_PIXEL_24(b) (b[0] + (b[1] << 8) + (b[2] << 16))
#else
#define GET_PIXEL_24(b) (b[2] + (b[1] << 8) + (b[0] << 16))
#endif
#define GET_PIXEL(pxl, bpp, source) \
switch (bpp) \
{ \
case 2: \
pxl = *((Uint16 *) (source)); \
break; \
case 4: \
pxl = *((Uint32 *) (source)); \
break; \
default: \
{ \
Uint8 *b = (Uint8 *) source; \
pxl = GET_PIXEL_24(b); \
} \
break; \
}
#define GET_PIXELVALS(_sR, _sG, _sB, _sA, px, fmt, ppa) \
_sR = ((px & fmt->Rmask) >> fmt->Rshift); \
_sR = (_sR << fmt->Rloss) + (_sR >> (8 - (fmt->Rloss << 1))); \
_sG = ((px & fmt->Gmask) >> fmt->Gshift); \
_sG = (_sG << fmt->Gloss) + (_sG >> (8 - (fmt->Gloss << 1))); \
_sB = ((px & fmt->Bmask) >> fmt->Bshift); \
_sB = (_sB << fmt->Bloss) + (_sB >> (8 - (fmt->Bloss << 1))); \
if (ppa) \
{ \
_sA = ((px & fmt->Amask) >> fmt->Ashift); \
_sA = (_sA << fmt->Aloss) + (_sA >> (8 - (fmt->Aloss << 1))); \
} \
else \
{ \
_sA = 255; \
}
#define GET_PIXELVALS_1(sr, sg, sb, sa, _src, _fmt) \
sr = _fmt->palette->colors[*((Uint8 *) (_src))].r; \
sg = _fmt->palette->colors[*((Uint8 *) (_src))].g; \
sb = _fmt->palette->colors[*((Uint8 *) (_src))].b; \
sa = 255;
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
#define SET_OFFSETS_24(or, og, ob, fmt) \
{ \
or = (fmt->Rshift == 0 ? 0 : \
fmt->Rshift == 8 ? 1 : \
2 ); \
og = (fmt->Gshift == 0 ? 0 : \
fmt->Gshift == 8 ? 1 : \
2 ); \
ob = (fmt->Bshift == 0 ? 0 : \
fmt->Bshift == 8 ? 1 : \
2 ); \
}
#define SET_OFFSETS_32(or, og, ob, fmt) \
{ \
or = (fmt->Rshift == 0 ? 0 : \
fmt->Rshift == 8 ? 1 : \
fmt->Rshift == 16 ? 2 : \
3 ); \
og = (fmt->Gshift == 0 ? 0 : \
fmt->Gshift == 8 ? 1 : \
fmt->Gshift == 16 ? 2 : \
3 ); \
ob = (fmt->Bshift == 0 ? 0 : \
fmt->Bshift == 8 ? 1 : \
fmt->Bshift == 16 ? 2 : \
3 ); \
}
#else
#define SET_OFFSETS_24(or, og, ob, fmt) \
{ \
or = (fmt->Rshift == 0 ? 2 : \
fmt->Rshift == 8 ? 1 : \
0 ); \
og = (fmt->Gshift == 0 ? 2 : \
fmt->Gshift == 8 ? 1 : \
0 ); \
ob = (fmt->Bshift == 0 ? 2 : \
fmt->Bshift == 8 ? 1 : \
0 ); \
}
#define SET_OFFSETS_32(or, og, ob, fmt) \
{ \
or = (fmt->Rshift == 0 ? 3 : \
fmt->Rshift == 8 ? 2 : \
fmt->Rshift == 16 ? 1 : \
0 ); \
og = (fmt->Gshift == 0 ? 3 : \
fmt->Gshift == 8 ? 2 : \
fmt->Gshift == 16 ? 1 : \
0 ); \
ob = (fmt->Bshift == 0 ? 3 : \
fmt->Bshift == 8 ? 2 : \
fmt->Bshift == 16 ? 1 : \
0 ); \
}
#endif
#define CREATE_PIXEL(buf, r, g, b, a, bp, ft) \
switch (bp) \
{ \
case 2: \
*((Uint16 *) (buf)) = \
((r >> ft->Rloss) << ft->Rshift) | \
((g >> ft->Gloss) << ft->Gshift) | \
((b >> ft->Bloss) << ft->Bshift) | \
((a >> ft->Aloss) << ft->Ashift); \
break; \
case 4: \
*((Uint32 *) (buf)) = \
((r >> ft->Rloss) << ft->Rshift) | \
((g >> ft->Gloss) << ft->Gshift) | \
((b >> ft->Bloss) << ft->Bshift) | \
((a >> ft->Aloss) << ft->Ashift); \
break; \
}
/* Pretty good idea from Tom Duff :-). */
#define LOOP_UNROLLED4(code, n, width) \
n = (width + 3) / 4; \
switch (width & 3) \
{ \
case 0: do { code; \
case 3: code; \
case 2: code; \
case 1: code; \
} while (--n > 0); \
}
/* Used in the srcbpp == dstbpp == 1 blend functions */
#define REPEAT_3(code) \
code; \
code; \
code;
#define REPEAT_4(code) \
code; \
code; \
code; \
code;
#define BLEND_ADD(tmp, sR, sG, sB, sA, dR, dG, dB, dA) \
tmp = dR + sR; dR = (tmp <= 255 ? tmp : 255); \
tmp = dG + sG; dG = (tmp <= 255 ? tmp : 255); \
tmp = dB + sB; dB = (tmp <= 255 ? tmp : 255);
#define BLEND_SUB(tmp, sR, sG, sB, sA, dR, dG, dB, dA) \
tmp = dR - sR; dR = (tmp >= 0 ? tmp : 0); \
tmp = dG - sG; dG = (tmp >= 0 ? tmp : 0); \
tmp = dB - sB; dB = (tmp >= 0 ? tmp : 0);
#define BLEND_MULT(sR, sG, sB, sA, dR, dG, dB, dA) \
dR = (dR && sR) ? (dR * sR) >> 8 : 0; \
dG = (dG && sG) ? (dG * sG) >> 8 : 0; \
dB = (dB && sB) ? (dB * sB) >> 8 : 0;
#define BLEND_MIN(sR, sG, sB, sA, dR, dG, dB, dA) \
if(sR < dR) { dR = sR; } \
if(sG < dG) { dG = sG; } \
if(sB < dB) { dB = sB; }
#define BLEND_MAX(sR, sG, sB, sA, dR, dG, dB, dA) \
if(sR > dR) { dR = sR; } \
if(sG > dG) { dG = sG; } \
if(sB > dB) { dB = sB; }
#define BLEND_RGBA_ADD(tmp, sR, sG, sB, sA, dR, dG, dB, dA) \
tmp = dR + sR; dR = (tmp <= 255 ? tmp : 255); \
tmp = dG + sG; dG = (tmp <= 255 ? tmp : 255); \
tmp = dB + sB; dB = (tmp <= 255 ? tmp : 255); \
tmp = dA + sA; dA = (tmp <= 255 ? tmp : 255);
#define BLEND_RGBA_SUB(tmp, sR, sG, sB, sA, dR, dG, dB, dA) \
tmp = dR - sR; dR = (tmp >= 0 ? tmp : 0); \
tmp = dG - sG; dG = (tmp >= 0 ? tmp : 0); \
tmp = dB - sB; dB = (tmp >= 0 ? tmp : 0); \
tmp = dA - sA; dA = (tmp >= 0 ? tmp : 0);
#define BLEND_RGBA_MULT(sR, sG, sB, sA, dR, dG, dB, dA) \
dR = (dR && sR) ? (dR * sR) >> 8 : 0; \
dG = (dG && sG) ? (dG * sG) >> 8 : 0; \
dB = (dB && sB) ? (dB * sB) >> 8 : 0; \
dA = (dA && sA) ? (dA * sA) >> 8 : 0;
#define BLEND_RGBA_MIN(sR, sG, sB, sA, dR, dG, dB, dA) \
if(sR < dR) { dR = sR; } \
if(sG < dG) { dG = sG; } \
if(sB < dB) { dB = sB; } \
if(sA < dA) { dA = sA; }
#define BLEND_RGBA_MAX(sR, sG, sB, sA, dR, dG, dB, dA) \
if(sR > dR) { dR = sR; } \
if(sG > dG) { dG = sG; } \
if(sB > dB) { dB = sB; } \
if(sA > dA) { dA = sA; }
#if 1
/* Choose an alpha blend equation. If the sign is preserved on a right shift
* then use a specialized, faster, equation. Otherwise a more general form,
* where all additions are done before the shift, is needed.
*/
#if (-1 >> 1) < 0
#define ALPHA_BLEND_COMP(sC, dC, sA) ((((sC - dC) * sA + sC) >> 8) + dC)
#else
#define ALPHA_BLEND_COMP(sC, dC, sA) (((dC << 8) + (sC - dC) * sA + sC) >> 8)
#endif
#define ALPHA_BLEND(sR, sG, sB, sA, dR, dG, dB, dA) \
do { \
if (dA) \
{ \
dR = ALPHA_BLEND_COMP(sR, dR, sA); \
dG = ALPHA_BLEND_COMP(sG, dG, sA); \
dB = ALPHA_BLEND_COMP(sB, dB, sA); \
dA = sA + dA - ((sA * dA) / 255); \
} \
else \
{ \
dR = sR; \
dG = sG; \
dB = sB; \
dA = sA; \
} \
} while(0)
#elif 0
#define ALPHA_BLEND(sR, sG, sB, sA, dR, dG, dB, dA) \
do { \
if(sA){ \
if(dA && sA < 255){ \
int dContrib = dA*(255 - sA)/255; \
dA = sA+dA - ((sA*dA)/255); \
dR = (dR*dContrib + sR*sA)/dA; \
dG = (dG*dContrib + sG*sA)/dA; \
dB = (dB*dContrib + sB*sA)/dA; \
}else{ \
dR = sR; \
dG = sG; \
dB = sB; \
dA = sA; \
} \
} \
} while(0)
#endif
int
surface_fill_blend (SDL_Surface *surface, SDL_Rect *rect, Uint32 color,
int blendargs);
int
pygame_AlphaBlit (SDL_Surface * src, SDL_Rect * srcrect,
SDL_Surface * dst, SDL_Rect * dstrect, int the_args);
int
pygame_Blit (SDL_Surface * src, SDL_Rect * srcrect,
SDL_Surface * dst, SDL_Rect * dstrect, int the_args);
#endif /* SURFACE_H */
pygame-1.9.1release/src/surface.doc 0000644 0001750 0001750 00000057417 11227457534 017201 0 ustar vincent vincent pygame.Surface
pygame object for representing images
pygame.Surface((width, height), flags=0, depth=0, masks=None): return Surface
pygame.Surface((width, height), flags=0, Surface): return Surface
A pygame Surface is used to represent any image. The Surface has a fixed
resolution and pixel format. Surfaces with 8bit pixels use a color palette
to map to 24bit color.
Call pygame.Surface() to create a new image object. The Surface will be
cleared to all black. The only required arguments are the sizes. With no
additional arguments, the Surface will be created in a format that best
matches the display Surface.
The pixel format can be controlled by passing the bit depth or an existing
Surface. The flags argument is a bitmask of additional features for the
surface. You can pass any combination of these flags:
HWSURFACE, creates the image in video memory
SRCALPHA, the pixel format will include a per-pixel alpha
Both flags are only a request, and may not be possible for all displays and
formats.
Advance users can combine a set of bitmasks with a depth value. The masks
are a set of 4 integers representing which bits in a pixel will represent
each color. Normal Surfaces should not require the masks argument.
Surfaces can have many extra attributes like alpha planes, colorkeys, source
rectangle clipping. These functions mainly effect how the Surface is blitted
to other Surfaces. The blit routines will attempt to use hardware acceleration
when possible, otherwise they will use highly optimized software blitting
methods.
There are three types of transparency supported in Pygame: colorkeys,
surface alphas, and pixel alphas. Surface alphas can be mixed with colorkeys,
but an image with per pixel alphas cannot use the other modes. Colorkey
transparency makes a single color value transparent. Any pixels matching
the colorkey will not be drawn. The surface alpha value is a single value
that changes the transparency for the entire image. A surface alpha of 255
is opaque, and a value of 0 is completely transparent.
Per pixel alphas are different because they store a transparency value for
every pixel. This allows for the most precise transparency effects, but it
also the slowest. Per pixel alphas cannot be mixed with surface alpha and
colorkeys.
There is support for pixel access for the Surfaces. Pixel access on hardware
surfaces is slow and not recommended. Pixels can be accessed using the get_at()
and set_at() functions. These methods are fine for simple access, but will be
considerably slow when doing of pixel work with them. If you plan on doing a
lot of pixel level work, it is recommended to use the pygame.surfarray module,
which can treat the surfaces like large multidimensional arrays
(and it's quite quick).
Any functions that directly access a surface's pixel data will need that
surface to be lock()'ed. These functions can lock() and unlock() the surfaces
themselves without assistance. But, if a function will be called many times,
there will be a lot of overhead for multiple locking and unlocking of the
surface. It is best to lock the surface manually before making the function
call many times, and then unlocking when you are finished. All functions that
need a locked surface will say so in their docs. Remember to leave the Surface
locked only while necessary.
Surface pixels are stored internally as a single number that has all the
colors encoded into it. Use the Surface.map_rgb() and Surface.unmap_rgb()
to convert between individual red, green, and blue values into a packed
integer for that Surface.
Surfaces can also reference sections of other Surfaces. These are created
with the Surface.subsurface() method. Any change to either Surface will
effect the other.
Each Surface contains a clipping area. By default the clip area covers the
entire Surface. If it is changed, all drawing operations will only effect
the smaller area.
blit
draw one image onto another
Surface.blit(source, dest, area=None, special_flags = 0): return Rect
Draws a source Surface onto this Surface. The draw can be positioned with
the dest argument. Dest can either be pair of coordinates representing the
upper left corner of the source. A Rect can also be passed as the destination
and the topleft corner of the rectangle will be used as the position for the
blit. The size of the destination rectangle does not effect the blit.
An optional area rectangle can be passed as well. This represents a smaller
portion of the source Surface to draw.
An optional special flags is for passing in
new in 1.8.0:
BLEND_ADD, BLEND_SUB, BLEND_MULT, BLEND_MIN, BLEND_MAX
new in 1.8.1:
BLEND_RGBA_ADD, BLEND_RGBA_SUB, BLEND_RGBA_MULT, BLEND_RGBA_MIN, BLEND_RGBA_MAX
BLEND_RGB_ADD, BLEND_RGB_SUB, BLEND_RGB_MULT, BLEND_RGB_MIN, BLEND_RGB_MAX
With other special blitting flags perhaps added in the future.
The return rectangle is the area of the affected pixels, excluding any pixels
outside the destination Surface, or outside the clipping area.
Pixel alphas will be ignored when blitting to an 8 bit Surface.
special_flags new in pygame 1.8.
For a surface with colorkey or blanket alpha, a blit to self may give slightly
different colors than a non self-blit.
convert
change the pixel format of an image
Surface.convert(Surface): return Surface
Surface.convert(depth, flags=0): return Surface
Surface.convert(masks, flags=0): return Surface
Surface.convert(): return Surface
Creates a new copy of the Surface with the pixel format changed. The new pixel
format can be determined from another existing Surface. Otherwise depth,
flags, and masks arguments can be used, similar to the pygame.Surface() call.
If no arguments are passed the new Surface will have the same pixel format
as the display Surface. This is always the fastest format for blitting. It
is a good idea to convert all Surfaces before they are blitted many times.
The converted Surface will have no pixel alphas. They will be stripped if
the original had them. See Surface.convert_alpha() for preserving or creating
per-pixel alphas.
convert_alpha
change the pixel format of an image including per pixel alphas
Surface.convert_alpha(Surface): return Surface
Surface.convert_alpha(): return Surface
Creates a new copy of the surface with the desired pixel format. The new
surface will be in a format suited for quick blitting to the given format
with per pixel alpha. If no surface is given, the new surface will be
optimized for blitting to the current display.
Unlike the Surface.convert() method, the pixel format for the new image will not
be exactly the same as the requested source, but it will be optimized for
fast alpha blitting to the destination.
copy
create a new copy of a Surface
Surface.copy(): return Surface
Makes a duplicate copy of a Surface. The new Surface will have the same
pixel formats, color palettes, and transparency settings as the original.
fill
fill Surface with a solid color
Surface.fill(color, rect=None, special_flags=0): return Rect
Fill the Surface with a solid color. If no rect argument is given the
entire Surface will be filled. The rect argument will limit the fill to
a specific area. The fill will also be contained by the Surface clip area.
The color argument can be either a RGB sequence, a RGBA sequence or
a mapped color index. If using RGBA, the Alpha (A part of RGBA) is ignored
unless the surface uses per pixel alpha (Surface has the SRCALPHA flag).
An optional special_flags is for passing in
new in 1.8.0:
BLEND_ADD, BLEND_SUB, BLEND_MULT, BLEND_MIN, BLEND_MAX
new in 1.8.1:
BLEND_RGBA_ADD, BLEND_RGBA_SUB, BLEND_RGBA_MULT, BLEND_RGBA_MIN, BLEND_RGBA_MAX
BLEND_RGB_ADD, BLEND_RGB_SUB, BLEND_RGB_MULT, BLEND_RGB_MIN, BLEND_RGB_MAX
With other special blitting flags perhaps added in the future.
This will return the affected Surface area.
scroll
Shift the surface image in place
Surface.scroll(dx=0, dy=0): return None
Move the image by dx pixels right and dy pixels down. dx and dy may be negative
for left and up scrolls respectively. Areas of the surface that are not
overwritten retain their original pixel values. Scrolling is contained
by the Surface clip area. It is safe to have dx and dy values that exceed
the surface size.
set_colorkey
Set the transparent colorkey
Surface.set_colorkey(Color, flags=0): return None
Surface.set_colorkey(None): return None
Set the current color key for the Surface. When blitting this Surface onto
a destination, and pixels that have the same color as the colorkey will be
transparent. The color can be an RGB color or a mapped color integer. If None
is passed, the colorkey will be unset.
The colorkey will be ignored if the Surface is formatted to use per pixel
alpha values. The colorkey can be mixed with the full Surface alpha value.
The optional flags argument can be set to pygame.RLEACCEL to provide better
performance on non accelerated displays. An RLEACCEL Surface will be slower
to modify, but quicker to blit as a source.
get_colorkey
Get the current transparent colorkey
Surface.get_colorkey(): return RGB or None
Return the current colorkey value for the Surface. If the colorkey is not
set then None is returned.
set_alpha
set the alpha value for the full Surface image
Surface.set_alpha(value, flags=0): return None
Surface.set_alpha(None): return None
Set the current alpha value fo r the Surface. When blitting this Surface onto
a destination, the pixels will be drawn slightly transparent. The alpha value
is an integer from 0 to 255, 0 is fully transparent and 255 is fully
opaque. If None is passed for the alpha value, then the Surface alpha will
be disabled.
This value is different than the per pixel Surface alpha. If the Surface
format contains per pixel alphas, then this alpha value will be ignored.
If the Surface contains per pixel alphas, setting the alpha value to None
will disable the per pixel transparency.
The optional flags argument can be set to pygame.RLEACCEL to provide better
performance on non accelerated displays. An RLEACCEL Surface will be slower
to modify, but quicker to blit as a source.
get_alpha
get the current Surface transparency value
Surface.get_alpha(): return int_value or None
Return the current alpha value for the Surface. If the alpha value is not
set then None is returned.
lock
lock the Surface memory for pixel access
Surface.lock(): return None
Lock the pixel data of a Surface for access. On accelerated Surfaces, the
pixel data may be stored in volatile video memory or nonlinear compressed
forms. When a Surface is locked the pixel memory becomes available to access
by regular software. Code that reads or writes pixel values will need the
Surface to be locked.
Surfaces should not remain locked for more than necessary. A locked Surface
can often not be displayed or managed by Pygame.
Not all Surfaces require locking. The Surface.mustlock() method can determine
if it is actually required. There is no performance penalty for locking and
unlocking a Surface that does not need it.
All pygame functions will automatically lock and unlock the Surface data as
needed. If a section of code is going to make calls that will repeatedly
lock and unlock the Surface many times, it can be helpful to wrap the block
inside a lock and unlock pair.
It is safe to nest locking and unlocking calls. The surface will only be
unlocked after the final lock is released.
unlock
unlock the Surface memory from pixel access
Surface.unlock(): return None
Unlock the Surface pixel data after it has been locked. The unlocked Surface
can once again be drawn and managed by Pygame. See the Surface.lock()
documentation for more details.
All pygame functions will automatically lock and unlock the Surface data as
needed. If a section of code is going to make calls that will repeatedly
lock and unlock the Surface many times, it can be helpful to wrap the block
inside a lock and unlock pair.
It is safe to nest locking and unlocking calls. The surface will only be
unlocked after the final lock is released.
mustlock
test if the Surface requires locking
Surface.mustlock(): return bool
Returns True if the Surface is required to be locked to access pixel data.
Usually pure software Surfaces do not require locking. This method is
rarely needed, since it is safe and quickest to just lock all Surfaces as
needed.
All pygame functions will automatically lock and unlock the Surface data as
needed. If a section of code is going to make calls that will repeatedly
lock and unlock the Surface many times, it can be helpful to wrap the block
inside a lock and unlock pair.
get_locked
test if the Surface is current locked
Surface.get_locked(): return bool
Returns True when the Surface is locked. It doesn't matter how many times
the Surface is locked.
get_locks
Gets the locks for the Surface
Surface.get_locks(): return tuple
Returns the currently existing locks for the Surface.
get_at
get the color value at a single pixel
Surface.get_at((x, y)): return Color
Return a copy of the RGBA Color value at the given pixel. If the Surface has
no per pixel alpha, then the alpha value will always be 255 (opaque).
If the pixel position is outside the area of the Surface an IndexError
exception will be raised.
Getting and setting pixels one at a time is generally too slow to be used
in a game or realtime situation. It is better to use methods which operate
on many pixels at a time like with the blit, fill and draw methods -
or by using surfarray/PixelArray.
This function will temporarily lock and unlock the Surface as needed.
Returning a Color instead of tuple, New in pygame 1.9.0.
Use tuple(surf.get_at((x,y))) if you want a tuple, and not a Color.
This should only matter if you want to use the color as a key in a dict.
set_at
set the color value for a single pixel
Surface.set_at((x, y), Color): return None
Set the RGBA or mapped integer color value for a single pixel. If the Surface
does not have per pixel alphas, the alpha value is ignored. Settting pixels
outside the Surface area or outside the Surface clipping will have no effect.
Getting and setting pixels one at a time is generally too slow to be used
in a game or realtime situation.
This function will temporarily lock and unlock the Surface as needed.
get_palette
get the color index palette for an 8bit Surface
Surface.get_palette(): return [RGB, RGB, RGB, ...]
Return a list of up to 256 color elements that represent the indexed colors
used in an 8bit Surface. The returned list is a copy of the palette, and
changes will have no effect on the Surface.
Returning a list of Color(with length 3) instances instead of tuples, New in pygame 1.9.0
get_palette_at
get the color for a single entry in a palette
Surface.get_palette_at(index): return RGB
Returns the red, green, and blue color values for a single index in a Surface
palette. The index should be a value from 0 to 255.
Returning Color(with length 3) instance instead of a tuple, New in pygame 1.9.0
set_palette
set the color palette for an 8bit Surface
Surface.set_palette([RGB, RGB, RGB, ...]): return None
Set the full palette for an 8bit Surface. This will replace the colors in
the existing palette. A partial palette can be passed and only the first
colors in the original palette will be changed.
This function has no effect on a Surface with more than 8bits per pixel.
set_palette_at
set the color for a single index in an 8bit Surface palette
Surface.set_at(index, RGB): return None
Set the palette value for a single entry in a Surface palette. The index should
be a value from 0 to 255.
This function has no effect on a Surface with more than 8bits per pixel.
map_rgb
convert a color into a mapped color value
Surface.map_rgb(Color): return mapped_int
Convert an RGBA color into the mapped integer value for this Surface. The
returned integer will contain no more bits than the bit depth of the Surface.
Mapped color values are not often used inside Pygame, but can be passed to
most functions that require a Surface and a color.
See the Surface object documentation for more information about colors
and pixel formats.
unmap_rgb
convert a mapped integer color value into a Color
Surface.map_rgb(mapped_int): return Color
Convert an mapped integer color into the RGB color components for this Surface.
Mapped color values are not often used inside Pygame, but can be passed to
most functions that require a Surface and a color.
See the Surface object documentation for more information about colors
and pixel formats.
set_clip
set the current clipping area of the Surface
Surface.set_clip(rect): return None
Surface.set_clip(None): return None
Each Surface has an active clipping area. This is a rectangle that represents
the only pixels on the Surface that can be modified. If None is passed for the
rectangle the full Surface will be available for changes.
The clipping area is always restricted to the area of the Surface itself. If
the clip rectangle is too large it will be shrunk to fit inside the Surface.
get_clip
get the current clipping area of the Surface
Surface.get_clip(): return Rect
Return a rectangle of the current clipping area. The Surface will always
return a valid rectangle that will never be outside the bounds of the image.
If the Surface has had None set for the clipping area, the Surface will
return a rectangle with the full area of the Surface.
subsurface
create a new surface that references its parent
Surface.subsurface(Rect): return Surface
Returns a new Surface that shares its pixels with its new parent. The new
Surface is considered a child of the original. Modifications to either
Surface pixels will effect each other. Surface information like clipping
area and color keys are unique to each Surface.
The new Surface will inherit the palette, color key, and alpha settings from
its parent.
It is possible to have any number of subsurfaces and subsubsurfaces on the
parent. It is also possible to subsurface the display Surface if the display
mode is not hardware accelerated.
See the Surface.get_offset(), Surface.get_parent() to learn more
about the state of a subsurface.
get_parent
find the parent of a subsurface
Surface.get_parent(): return Surface
Returns the parent Surface of a subsurface. If this is not a subsurface
then None will be returned.
get_abs_parent
find the top level parent of a subsurface
Surface.get_abs_parent(): return Surface
Returns the parent Surface of a subsurface. If this is not a subsurface
then this surface will be returned.
get_offset
find the position of a child subsurface inside a parent
Surface.get_offset(): return (x, y)
Get the offset position of a child subsurface inside of a parent. If the
Surface is not a subsurface this will return (0, 0).
get_abs_offset
find the absolute position of a child subsurface inside its top level parent
Surface.get_abs_offset(): return (x, y)
Get the offset position of a child subsurface inside of its top level
parent Surface. If the Surface is not a subsurface this will return (0, 0).
get_size
get the dimensions of the Surface
Surface.get_size(): return (width, height)
Return the width and height of the Surface in pixels.
get_width
get the width of the Surface
Surface.get_width(): return width
Return the width of the Surface in pixels.
get_height
get the height of the Surface
Surface.get_height(): return height
Return the height of the Surface in pixels.
get_rect
get the rectangular area of the Surface
Surface.get_rect(**kwargs): return Rect
Returns a new rectangle covering the entire surface. This rectangle will
always start at 0, 0 with a width. and height the same size as the image.
You can pass keyword argument values to this function. These named values
will be applied to the attributes of the Rect before it is returned. An
example would be 'mysurf.get_rect(center=(100,100))' to create a rectangle
for the Surface centered at a given position.
get_bitsize
get the bit depth of the Surface pixel format
Surface.get_bitsize(): return int
Returns the number of bits used to represent each pixel. This value may not
exactly fill the number of bytes used per pixel. For example a 15 bit Surface
still requires a full 2 bytes.
get_bytesize
get the bytes used per Surface pixel
Surface.get_bytesize(): return int
Return the number of bytes used per pixel.
get_flags
get the additional flags used for the Surface
Surface.get_flags(): return int
Returns a set of current Surface features. Each feature is a bit in the
flags bitmask. Typical flags are HWSURFACE, RLEACCEL, SRCALPHA, and SRCCOLORKEY.
Here is a more complete list of flags. A full list can be found in SDL_video.h
SWSURFACE 0x00000000 # Surface is in system memory
HWSURFACE 0x00000001 # Surface is in video memory
ASYNCBLIT 0x00000004 # Use asynchronous blits if possible
Available for pygame.display.set_mode()
ANYFORMAT 0x10000000 # Allow any video depth/pixel-format
HWPALETTE 0x20000000 # Surface has exclusive palette
DOUBLEBUF 0x40000000 # Set up double-buffered video mode
FULLSCREEN 0x80000000 # Surface is a full screen display
OPENGL 0x00000002 # Create an OpenGL rendering context
OPENGLBLIT 0x0000000A # Create an OpenGL rendering context
# and use it for blitting. Obsolete.
RESIZABLE 0x00000010 # This video mode may be resized
NOFRAME 0x00000020 # No window caption or edge frame
Used internally (read-only)
HWACCEL 0x00000100 # Blit uses hardware acceleration
SRCCOLORKEY 0x00001000 # Blit uses a source color key
RLEACCELOK 0x00002000 # Private flag
RLEACCEL 0x00004000 # Surface is RLE encoded
SRCALPHA 0x00010000 # Blit uses source alpha blending
PREALLOC 0x01000000 # Surface uses preallocated memory
get_pitch
get the number of bytes used per Surface row
Surface.get_pitch(): return int
Return the number of bytes separating each row in the Surface. Surfaces
in video memory are not always linearly packed. Subsurfaces will also have a
larger pitch than their real width.
This value is not needed for normal Pygame usage.
get_masks
the bitmasks needed to convert between a color and a mapped integer
Surface.get_masks(): return (R, G, B, A)
Returns the bitmasks used to isolate each color in a mapped integer.
This value is not needed for normal Pygame usage.
set_masks
set the bitmasks needed to convert between a color and a mapped integer
Surface.set_masks((r,g,b,a)): return None
This is not needed for normal Pygame usage.
New in pygame 1.8.1
get_shifts
the bit shifts needed to convert between a color and a mapped integer
Surface.get_shifts(): return (R, G, B, A)
Returns the pixel shifts need to convert between each color and a mapped
integer.
This value is not needed for normal Pygame usage.
set_shifts
sets the bit shifts needed to convert between a color and a mapped integer
Surface.get_shifts((r,g,b,a)): return None
This is not needed for normal Pygame usage.
New in pygame 1.8.1
get_losses
the significant bits used to convert between a color and a mapped integer
Surface.get_losses(): return (R, G, B, A)
Return the least significant number of bits stripped from each color
in a mapped integer.
This value is not needed for normal Pygame usage.
get_bounding_rect
find the smallest rect containing data
Surface.get_bounding_rect(min_alpha = 1): return Rect
Returns the smallest rectangular region that contains all the pixels
in the surface that have an alpha value greater than or equal to the
minimum alpha value.
This function will temporarily lock and unlock the Surface as needed.
New in pygame 1.8.
get_buffer
acquires a buffer object for the pixels of the Surface.
Surface.get_buffer(): return BufferProxy
Return a buffer object for the pixels of the Surface. The buffer can be
used for direct pixel access and manipulation.
This method implicitly locks the Surface. The lock will be released,
once the returned BufferProxy object is deleted.
New in pygame 1.8.
pygame-1.9.1release/src/surface.c 0000644 0001750 0001750 00000210256 11224767753 016652 0 ustar vincent vincent /*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
Copyright (C) 2007 Marcus von Appen
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
#define PYGAMEAPI_SURFACE_INTERNAL
#include "surface.h"
#include "pygamedocs.h"
#include "structmember.h"
#include "pgcompat.h"
int
PySurface_Blit (PyObject * dstobj, PyObject * srcobj, SDL_Rect * dstrect,
SDL_Rect * srcrect, int the_args);
/* statics */
static PyObject *PySurface_New (SDL_Surface * info);
static PyObject *surface_new (PyTypeObject *type, PyObject *args,
PyObject *kwds);
static intptr_t surface_init (PySurfaceObject *self, PyObject *args,
PyObject *kwds);
static PyObject* surface_str (PyObject *self);
static void surface_dealloc (PyObject *self);
static void surface_cleanup (PySurfaceObject * self);
static void surface_move (Uint8 *src, Uint8 *dst, int h,
int span, int srcpitch, int dstpitch);
static PyObject *surf_get_at (PyObject *self, PyObject *args);
static PyObject *surf_set_at (PyObject *self, PyObject *args);
static PyObject *surf_map_rgb (PyObject *self, PyObject *args);
static PyObject *surf_unmap_rgb (PyObject *self, PyObject *arg);
static PyObject *surf_lock (PyObject *self);
static PyObject *surf_unlock (PyObject *self);
static PyObject *surf_mustlock (PyObject *self);
static PyObject *surf_get_locked (PyObject *self);
static PyObject *surf_get_locks (PyObject *self);
static PyObject *surf_get_palette (PyObject *self);
static PyObject *surf_get_palette_at (PyObject *self, PyObject *args);
static PyObject *surf_set_palette (PyObject *self, PyObject *args);
static PyObject *surf_set_palette_at (PyObject *self, PyObject *args);
static PyObject *surf_set_colorkey (PyObject *self, PyObject *args);
static PyObject *surf_get_colorkey (PyObject *self);
static PyObject *surf_set_alpha (PyObject *self, PyObject *args);
static PyObject *surf_get_alpha (PyObject *self);
static PyObject *surf_copy (PyObject *self);
static PyObject *surf_convert (PyObject *self, PyObject *args);
static PyObject *surf_convert_alpha (PyObject *self, PyObject *args);
static PyObject *surf_set_clip (PyObject *self, PyObject *args);
static PyObject *surf_get_clip (PyObject *self);
static PyObject *surf_blit (PyObject *self, PyObject *args, PyObject *keywds);
static PyObject *surf_fill (PyObject *self, PyObject *args, PyObject *keywds);
static PyObject *surf_scroll (PyObject *self,
PyObject *args, PyObject *keywds);
static PyObject *surf_get_abs_offset (PyObject *self);
static PyObject *surf_get_abs_parent (PyObject *self);
static PyObject *surf_get_bitsize (PyObject *self);
static PyObject *surf_get_bytesize (PyObject *self);
static PyObject *surf_get_flags (PyObject *self);
static PyObject *surf_get_height (PyObject *self);
static PyObject *surf_get_pitch (PyObject *self);
static PyObject *surf_get_rect (PyObject *self, PyObject *args,
PyObject *kwargs);
static PyObject *surf_get_width (PyObject *self);
static PyObject *surf_get_shifts (PyObject *self);
static PyObject *surf_set_shifts (PyObject *self, PyObject *args);
static PyObject *surf_get_size (PyObject *self);
static PyObject *surf_get_losses (PyObject *self);
static PyObject *surf_get_masks (PyObject *self);
static PyObject *surf_set_masks (PyObject *self, PyObject *args);
static PyObject *surf_get_offset (PyObject *self);
static PyObject *surf_get_parent (PyObject *self);
static PyObject *surf_subsurface (PyObject *self, PyObject *args);
static PyObject *surf_get_buffer (PyObject *self);
static PyObject *surf_get_bounding_rect (PyObject *self, PyObject *args,
PyObject *kwargs);
static struct PyMethodDef surface_methods[] =
{
{ "get_at", surf_get_at, METH_VARARGS, DOC_SURFACEGETAT },
{ "set_at", surf_set_at, METH_VARARGS, DOC_SURFACESETAT },
{ "map_rgb", surf_map_rgb, METH_VARARGS, DOC_SURFACEMAPRGB },
{ "unmap_rgb", surf_unmap_rgb, METH_O, DOC_SURFACEUNMAPRGB },
{ "get_palette", (PyCFunction) surf_get_palette, METH_NOARGS,
DOC_SURFACEGETPALETTE },
{ "get_palette_at", surf_get_palette_at, METH_VARARGS,
DOC_SURFACEGETPALETTEAT },
{ "set_palette", surf_set_palette, METH_VARARGS, DOC_SURFACESETPALETTE },
{ "set_palette_at", surf_set_palette_at, METH_VARARGS,
DOC_SURFACESETPALETTEAT },
{ "lock", (PyCFunction) surf_lock, METH_NOARGS, DOC_SURFACELOCK },
{ "unlock", (PyCFunction) surf_unlock, METH_NOARGS, DOC_SURFACEUNLOCK },
{ "mustlock", (PyCFunction) surf_mustlock, METH_NOARGS,
DOC_SURFACEMUSTLOCK },
{ "get_locked", (PyCFunction) surf_get_locked, METH_NOARGS,
DOC_SURFACEGETLOCKED },
{ "get_locks", (PyCFunction) surf_get_locks, METH_NOARGS,
DOC_SURFACEGETLOCKS },
{ "set_colorkey", surf_set_colorkey, METH_VARARGS, DOC_SURFACESETCOLORKEY },
{ "get_colorkey", (PyCFunction) surf_get_colorkey, METH_NOARGS,
DOC_SURFACEGETCOLORKEY },
{ "set_alpha", surf_set_alpha, METH_VARARGS, DOC_SURFACESETALPHA },
{ "get_alpha", (PyCFunction) surf_get_alpha, METH_NOARGS,
DOC_SURFACEGETALPHA },
{ "copy", (PyCFunction) surf_copy, METH_NOARGS, DOC_SURFACECOPY },
{ "__copy__", (PyCFunction) surf_copy, METH_NOARGS, DOC_SURFACECOPY },
{ "convert", surf_convert, METH_VARARGS, DOC_SURFACECONVERT },
{ "convert_alpha", surf_convert_alpha, METH_VARARGS,
DOC_SURFACECONVERTALPHA },
{ "set_clip", surf_set_clip, METH_VARARGS, DOC_SURFACESETCLIP },
{ "get_clip", (PyCFunction) surf_get_clip, METH_NOARGS,
DOC_SURFACEGETCLIP },
{ "fill", (PyCFunction) surf_fill, METH_VARARGS | METH_KEYWORDS,
DOC_SURFACEFILL },
{ "blit", (PyCFunction) surf_blit, METH_VARARGS | METH_KEYWORDS,
DOC_SURFACEBLIT },
{ "scroll", (PyCFunction) surf_scroll, METH_VARARGS | METH_KEYWORDS,
DOC_SURFACESCROLL },
{ "get_flags", (PyCFunction) surf_get_flags, METH_NOARGS,
DOC_SURFACEGETFLAGS },
{ "get_size", (PyCFunction) surf_get_size, METH_NOARGS,
DOC_SURFACEGETSIZE },
{ "get_width", (PyCFunction) surf_get_width, METH_NOARGS,
DOC_SURFACEGETWIDTH },
{ "get_height", (PyCFunction) surf_get_height, METH_NOARGS,
DOC_SURFACEGETHEIGHT },
{ "get_rect", (PyCFunction) surf_get_rect, METH_VARARGS | METH_KEYWORDS,
DOC_SURFACEGETRECT },
{ "get_pitch", (PyCFunction) surf_get_pitch, METH_NOARGS,
DOC_SURFACEGETPITCH },
{ "get_bitsize", (PyCFunction) surf_get_bitsize, METH_NOARGS,
DOC_SURFACEGETBITSIZE },
{ "get_bytesize", (PyCFunction) surf_get_bytesize, METH_NOARGS,
DOC_SURFACEGETBYTESIZE },
{ "get_masks", (PyCFunction) surf_get_masks, METH_NOARGS,
DOC_SURFACEGETMASKS },
{ "get_shifts", (PyCFunction) surf_get_shifts, METH_NOARGS,
DOC_SURFACEGETSHIFTS },
{ "set_masks", (PyCFunction) surf_set_masks, METH_VARARGS,
DOC_SURFACESETMASKS },
{ "set_shifts", (PyCFunction) surf_set_shifts, METH_VARARGS,
DOC_SURFACESETSHIFTS },
{ "get_losses", (PyCFunction) surf_get_losses, METH_NOARGS,
DOC_SURFACEGETLOSSES },
{ "subsurface", surf_subsurface, METH_VARARGS, DOC_SURFACESUBSURFACE },
{ "get_offset", (PyCFunction) surf_get_offset, METH_NOARGS,
DOC_SURFACEGETOFFSET },
{ "get_abs_offset", (PyCFunction) surf_get_abs_offset, METH_NOARGS,
DOC_SURFACEGETABSOFFSET },
{ "get_parent", (PyCFunction) surf_get_parent, METH_NOARGS,
DOC_SURFACEGETPARENT },
{ "get_abs_parent", (PyCFunction) surf_get_abs_parent, METH_NOARGS,
DOC_SURFACEGETABSPARENT },
{ "get_bounding_rect", (PyCFunction) surf_get_bounding_rect,
METH_VARARGS | METH_KEYWORDS,
DOC_SURFACEGETBOUNDINGRECT},
{ "get_buffer", (PyCFunction) surf_get_buffer, METH_NOARGS,
DOC_SURFACEGETBUFFER},
{ NULL, NULL, 0, NULL }
};
static PyTypeObject PySurface_Type =
{
TYPE_HEAD (NULL, 0)
"pygame.Surface", /* name */
sizeof (PySurfaceObject), /* basic size */
0, /* itemsize */
surface_dealloc, /* dealloc */
0, /* print */
NULL, /* getattr */
NULL, /* setattr */
NULL, /* compare */
surface_str, /* repr */
NULL, /* as_number */
NULL, /* as_sequence */
NULL, /* as_mapping */
(hashfunc) NULL, /* hash */
(ternaryfunc) NULL, /* call */
(reprfunc) NULL, /* str */
0,
0L, 0L,
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
DOC_PYGAMESURFACE, /* Documentation string */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
offsetof (PySurfaceObject, weakreflist), /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
surface_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc) surface_init, /* tp_init */
0, /* tp_alloc */
surface_new, /* tp_new */
};
#define PySurface_Check(x) ((x)->ob_type == &PySurface_Type)
static PyObject*
PySurface_New (SDL_Surface *s)
{
PySurfaceObject *self;
if (!s)
return RAISE (PyExc_SDLError, SDL_GetError ());
self = (PySurfaceObject *)
PySurface_Type.tp_new (&PySurface_Type, NULL, NULL);
if (self)
self->surf = s;
return (PyObject *) self;
}
static PyObject*
surface_new (PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PySurfaceObject *self;
self = (PySurfaceObject *) type->tp_alloc (type, 0);
if (self)
{
self->surf = NULL;
self->subsurface = NULL;
self->weakreflist = NULL;
self->dependency = NULL;
self->locklist = NULL;
}
return (PyObject *) self;
}
/* surface object internals */
static void
surface_cleanup (PySurfaceObject *self)
{
if (self->surf)
{
if (!(self->surf->flags & SDL_HWSURFACE) ||
SDL_WasInit (SDL_INIT_VIDEO))
{
/* unsafe to free hardware surfaces without video init */
/* i question SDL's ability to free a locked hardware surface */
SDL_FreeSurface (self->surf);
}
self->surf = NULL;
}
if (self->subsurface)
{
Py_XDECREF (self->subsurface->owner);
PyMem_Del (self->subsurface);
self->subsurface = NULL;
}
if (self->dependency)
{
Py_DECREF (self->dependency);
self->dependency = NULL;
}
if (self->locklist)
{
Py_DECREF (self->locklist);
self->locklist = NULL;
}
}
static void
surface_dealloc (PyObject *self)
{
if (((PySurfaceObject *) self)->weakreflist)
PyObject_ClearWeakRefs (self);
surface_cleanup ((PySurfaceObject *) self);
self->ob_type->tp_free (self);
}
static PyObject*
surface_str (PyObject *self)
{
char str[1024];
SDL_Surface *surf = PySurface_AsSurface (self);
const char *type;
if (surf)
{
type = (surf->flags & SDL_HWSURFACE) ? "HW" : "SW";
sprintf (str, "", surf->w,
surf->h, surf->format->BitsPerPixel, type);
}
else
{
strcpy (str, "");
}
return Text_FromUTF8 (str);
}
static intptr_t
surface_init (PySurfaceObject *self, PyObject *args, PyObject *kwds)
{
Uint32 flags = 0;
int width, height;
PyObject *depth = NULL, *masks = NULL, *size = NULL;
int bpp;
Uint32 Rmask, Gmask, Bmask, Amask;
SDL_Surface *surface;
SDL_PixelFormat default_format, *format;
int length;
char *kwids[] = { "size", "flags", "depth", "masks", NULL };
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|iOO", kwids, &size, &flags, &depth, &masks))
return -1;
if (PySequence_Check (size) && (length = PySequence_Length (size)) == 2) {
if ( (!IntFromObjIndex (size, 0, &width)) ||
(!IntFromObjIndex (size, 1, &height)) ) {
RAISE (PyExc_ValueError, "size needs to be (int width, int height)");
return -1;
}
} else {
RAISE (PyExc_ValueError, "size needs to be (int width, int height)");
return -1;
}
if (width < 0 || height < 0)
{
RAISE (PyExc_SDLError, "Invalid resolution for Surface");
return -1;
}
surface_cleanup (self);
if (depth && masks) /* all info supplied, most errorchecking
* needed */
{
if (PySurface_Check (depth)) {
RAISE (PyExc_ValueError, "cannot pass surface for depth and color masks");
return -1;
}
if (!IntFromObj (depth, &bpp)) {
RAISE (PyExc_ValueError, "invalid bits per pixel depth argument");
return -1;
}
if (!PySequence_Check (masks) || PySequence_Length (masks) != 4) {
RAISE (PyExc_ValueError, "masks argument must be sequence of four numbers");
return -1;
}
if (!UintFromObjIndex (masks, 0, &Rmask) ||
!UintFromObjIndex (masks, 1, &Gmask) ||
!UintFromObjIndex (masks, 2, &Bmask) ||
!UintFromObjIndex (masks, 3, &Amask)) {
RAISE (PyExc_ValueError, "invalid mask values in masks sequence");
return -1;
}
}
else if (depth && PyNumber_Check (depth)) /* use default masks */
{
if (!IntFromObj (depth, &bpp)) {
RAISE (PyExc_ValueError, "invalid bits per pixel depth argument");
return -1;
}
if (flags & SDL_SRCALPHA)
{
switch (bpp)
{
case 16:
Rmask = 0xF << 8;
Gmask = 0xF << 4;
Bmask = 0xF;
Amask = 0xF << 12;
break;
case 32:
Rmask = 0xFF << 16;
Gmask = 0xFF << 8;
Bmask = 0xFF;
Amask = 0xFF << 24;
break;
default:
RAISE (PyExc_ValueError, "no standard masks exist for given bitdepth with alpha");
return -1;
}
}
else
{
Amask = 0;
switch (bpp)
{
case 8:
Rmask = 0xFF >> 6 << 5;
Gmask = 0xFF >> 5 << 2;
Bmask = 0xFF >> 6;
break;
case 12:
Rmask = 0xFF >> 4 << 8;
Gmask = 0xFF >> 4 << 4;
Bmask = 0xFF >> 4;
break;
case 15:
Rmask = 0xFF >> 3 << 10;
Gmask = 0xFF >> 3 << 5;
Bmask = 0xFF >> 3;
break;
case 16:
Rmask = 0xFF >> 3 << 11;
Gmask = 0xFF >> 2 << 5;
Bmask = 0xFF >> 3;
break;
case 24:
case 32:
Rmask = 0xFF << 16;
Gmask = 0xFF << 8;
Bmask = 0xFF;
break;
default:
RAISE (PyExc_ValueError, "nonstandard bit depth given");
return -1;
}
}
}
else /* no depth or surface */
{
SDL_PixelFormat* pix;
if (depth && PySurface_Check (depth))
pix = ((PySurfaceObject*) depth)->surf->format;
else if (SDL_GetVideoSurface ())
pix = SDL_GetVideoSurface ()->format;
else if (SDL_WasInit (SDL_INIT_VIDEO))
pix = SDL_GetVideoInfo ()->vfmt;
else
{
pix = &default_format;
pix->BitsPerPixel = 32;
pix->Amask = 0;
pix->Rmask = 0xFF0000;
pix->Gmask = 0xFF00;
pix->Bmask = 0xFF;
}
bpp = pix->BitsPerPixel;
if (flags & SDL_SRCALPHA)
{
switch (bpp)
{
case 16:
Rmask = 0xF << 8;
Gmask = 0xF << 4;
Bmask = 0xF;
Amask = 0xF << 12;
break;
case 24:
bpp = 32;
// we automatically step up to 32 if video is 24, fall through to case below
case 32:
Rmask = 0xFF << 16;
Gmask = 0xFF << 8;
Bmask = 0xFF;
Amask = 0xFF << 24;
break;
default:
RAISE (PyExc_ValueError, "no standard masks exist for given bitdepth with alpha");
return -1;
}
} else {
Rmask = pix->Rmask;
Gmask = pix->Gmask;
Bmask = pix->Bmask;
Amask = pix->Amask;
}
}
surface = SDL_CreateRGBSurface (flags, width, height, bpp, Rmask, Gmask,
Bmask, Amask);
if (!surface)
{
RAISE (PyExc_SDLError, SDL_GetError ());
return -1;
}
if (masks)
{
/* Confirm the surface was created correctly (masks were valid).
Also ensure that 24 and 32 bit surfaces have 8 bit fields
(no losses).
*/
format = surface->format;
Rmask = (0xFF >> format->Rloss) << format->Rshift;
Gmask = (0xFF >> format->Gloss) << format->Gshift;
Bmask = (0xFF >> format->Bloss) << format->Bshift;
Amask = (0xFF >> format->Aloss) << format->Ashift;
if (format->Rmask != Rmask ||
format->Gmask != Gmask ||
format->Bmask != Bmask ||
format->Amask != Amask ||
(format->BytesPerPixel >= 3 &&
(format->Rloss || format->Gloss || format->Bloss ||
(surface->flags & SDL_SRCALPHA ?
format->Aloss : format->Aloss != 8))))
{
SDL_FreeSurface (surface);
RAISE (PyExc_ValueError, "Invalid mask values");
return -1;
}
}
if (surface)
{
self->surf = surface;
self->subsurface = NULL;
}
return 0;
}
/* surface object methods */
static PyObject*
surf_get_at (PyObject *self, PyObject *args)
{
SDL_Surface *surf = PySurface_AsSurface (self);
SDL_PixelFormat *format = surf->format;
Uint8 *pixels = (Uint8 *) surf->pixels;
int x, y;
Uint32 color;
Uint8 *pix;
Uint8 rgba[4];
if (!PyArg_ParseTuple (args, "(ii)", &x, &y))
return NULL;
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
if (surf->flags & SDL_OPENGL)
return RAISE (PyExc_SDLError, "Cannot call on OPENGL Surfaces");
if (x < 0 || x >= surf->w || y < 0 || y >= surf->h)
return RAISE (PyExc_IndexError, "pixel index out of range");
if (format->BytesPerPixel < 1 || format->BytesPerPixel > 4)
return RAISE (PyExc_RuntimeError, "invalid color depth for surface");
if (!PySurface_Lock (self))
return NULL;
pixels = (Uint8 *) surf->pixels;
switch (format->BytesPerPixel)
{
case 1:
color = (Uint32)*((Uint8 *) pixels + y * surf->pitch + x);
break;
case 2:
color = (Uint32)*((Uint16 *) (pixels + y * surf->pitch) + x);
break;
case 3:
pix = ((Uint8 *) (pixels + y * surf->pitch) + x * 3);
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
color = (pix[0]) + (pix[1] << 8) + (pix[2] << 16);
#else
color = (pix[2]) + (pix[1] << 8) + (pix[0] << 16);
#endif
break;
default: /* case 4: */
color = *((Uint32 *) (pixels + y * surf->pitch) + x);
break;
}
if (!PySurface_Unlock (self))
return NULL;
SDL_GetRGBA (color, format, rgba, rgba+1, rgba+2, rgba+3);
return PyColor_New (rgba);
}
static PyObject*
surf_set_at (PyObject *self, PyObject *args)
{
SDL_Surface *surf = PySurface_AsSurface (self);
SDL_PixelFormat *format = surf->format;
Uint8 *pixels;
int x, y;
Uint32 color;
Uint8 rgba[4] = {0, 0, 0, 0 };
PyObject *rgba_obj;
Uint8 *byte_buf;
if (!PyArg_ParseTuple (args, "(ii)O", &x, &y, &rgba_obj))
return NULL;
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
if (surf->flags & SDL_OPENGL)
return RAISE (PyExc_SDLError, "Cannot call on OPENGL Surfaces");
if (format->BytesPerPixel < 1 || format->BytesPerPixel > 4)
return RAISE (PyExc_RuntimeError, "invalid color depth for surface");
if (x < surf->clip_rect.x || x >= surf->clip_rect.x + surf->clip_rect.w ||
y < surf->clip_rect.y || y >= surf->clip_rect.y + surf->clip_rect.h)
{
/* out of clip area */
Py_RETURN_NONE;
}
if (PyInt_Check (rgba_obj))
{
color = (Uint32) PyInt_AsLong (rgba_obj);
if (PyErr_Occurred () && (Sint32) color == -1)
return RAISE (PyExc_TypeError, "invalid color argument");
}
else if (PyLong_Check (rgba_obj))
{
color = (Uint32) PyLong_AsUnsignedLong (rgba_obj);
if (PyErr_Occurred () && (Sint32) color == -1)
return RAISE (PyExc_TypeError, "invalid color argument");
}
else if (RGBAFromColorObj (rgba_obj, rgba))
color = SDL_MapRGBA (surf->format, rgba[0], rgba[1], rgba[2], rgba[3]);
else
return RAISE (PyExc_TypeError, "invalid color argument");
if (!PySurface_Lock (self))
return NULL;
pixels = (Uint8 *) surf->pixels;
switch (format->BytesPerPixel)
{
case 1:
*((Uint8 *) pixels + y * surf->pitch + x) = (Uint8) color;
break;
case 2:
*((Uint16 *) (pixels + y * surf->pitch) + x) = (Uint16) color;
break;
case 3:
byte_buf = (Uint8 *) (pixels + y * surf->pitch) + x * 3;
#if (SDL_BYTEORDER == SDL_LIL_ENDIAN)
*(byte_buf + (format->Rshift >> 3)) = (Uint8) (color >> 16);
*(byte_buf + (format->Gshift >> 3)) = (Uint8) (color >> 8);
*(byte_buf + (format->Bshift >> 3)) = (Uint8) color;
#else
*(byte_buf + 2 - (format->Rshift >> 3)) = (Uint8) (color >> 16);
*(byte_buf + 2 - (format->Gshift >> 3)) = (Uint8) (color >> 8);
*(byte_buf + 2 - (format->Bshift >> 3)) = (Uint8) color;
#endif
break;
default: /* case 4: */
*((Uint32 *) (pixels + y * surf->pitch) + x) = color;
break;
}
if (!PySurface_Unlock (self))
return NULL;
Py_RETURN_NONE;
}
static PyObject*
surf_map_rgb (PyObject *self, PyObject *args)
{
SDL_Surface *surf = PySurface_AsSurface (self);
Uint8 rgba[4];
int color;
if (!RGBAFromColorObj (args, rgba))
return RAISE (PyExc_TypeError, "Invalid RGBA argument");
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
color = SDL_MapRGBA (surf->format, rgba[0], rgba[1], rgba[2], rgba[3]);
return PyInt_FromLong (color);
}
static PyObject*
surf_unmap_rgb (PyObject *self, PyObject *arg)
{
SDL_Surface *surf = PySurface_AsSurface (self);
Uint32 col;
Uint8 rgba[4];
col = (Uint32)PyInt_AsLong (arg);
if (col == (Uint32) -1 && PyErr_Occurred()) {
PyErr_Clear();
return RAISE (PyExc_TypeError, "unmap_rgb expects 1 number argument");
}
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
SDL_GetRGBA (col, surf->format, rgba, rgba+1, rgba+2, rgba+3);
return PyColor_New (rgba);
}
static PyObject*
surf_lock (PyObject *self)
{
if (!PySurface_Lock (self))
return NULL;
Py_RETURN_NONE;
}
static PyObject*
surf_unlock (PyObject *self)
{
PySurface_Unlock (self);
Py_RETURN_NONE;
}
static PyObject*
surf_mustlock (PyObject *self)
{
SDL_Surface *surf = PySurface_AsSurface (self);
return PyInt_FromLong (SDL_MUSTLOCK (surf) ||
((PySurfaceObject *) self)->subsurface);
}
static PyObject*
surf_get_locked (PyObject *self)
{
PySurfaceObject *surf = (PySurfaceObject *) self;
if (surf->locklist && PyList_Size (surf->locklist) > 0)
Py_RETURN_TRUE;
Py_RETURN_FALSE;
}
static PyObject*
surf_get_locks (PyObject *self)
{
PySurfaceObject *surf = (PySurfaceObject *) self;
Py_ssize_t len, i = 0;
PyObject *tuple, *tmp;
if (!surf->locklist)
return PyTuple_New (0);
len = PyList_Size (surf->locklist);
tuple = PyTuple_New (len);
if (!tuple)
return NULL;
for (i = 0; i < len; i++)
{
tmp = PyWeakref_GetObject (PyList_GetItem (surf->locklist, i));
Py_INCREF (tmp);
PyTuple_SetItem (tuple, i, tmp);
}
return tuple;
}
static PyObject*
surf_get_palette (PyObject *self)
{
SDL_Surface *surf = PySurface_AsSurface (self);
SDL_Palette *pal = surf->format->palette;
PyObject *list;
int i;
PyObject *color;
SDL_Color *c;
Uint8 rgba[4] = {0, 0, 0, 255};
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
if (!pal)
return RAISE (PyExc_SDLError, "Surface has no palette to get\n");
list = PyTuple_New (pal->ncolors);
if (!list)
return NULL;
for (i = 0; i < pal->ncolors; i++)
{
c = &pal->colors[i];
rgba[0] = c->r;
rgba[1] = c->g;
rgba[2] = c->b;
color = PyColor_NewLength (rgba, 3);
if (!color)
{
Py_DECREF (list);
return NULL;
}
PyTuple_SET_ITEM (list, i, color);
}
return list;
}
static PyObject*
surf_get_palette_at (PyObject * self, PyObject * args)
{
SDL_Surface *surf = PySurface_AsSurface (self);
SDL_Palette *pal = surf->format->palette;
SDL_Color *c;
int _index;
Uint8 rgba[4];
if (!PyArg_ParseTuple (args, "i", &_index))
return NULL;
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
if (!pal)
return RAISE (PyExc_SDLError, "Surface has no palette to set\n");
if (_index >= pal->ncolors || _index < 0)
return RAISE (PyExc_IndexError, "index out of bounds");
c = &pal->colors[_index];
rgba[0] = c->r;
rgba[1] = c->g;
rgba[2] = c->b;
rgba[3] = 255;
return PyColor_NewLength (rgba, 3);
}
static PyObject*
surf_set_palette (PyObject *self, PyObject *args)
{
SDL_Surface *surf = PySurface_AsSurface (self);
SDL_Palette *pal = surf->format->palette;
SDL_Color *colors;
PyObject *list, *item;
int i, len;
Uint8 rgba[4];
int ecode;
if (!PyArg_ParseTuple (args, "O", &list))
return NULL;
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
if (!PySequence_Check (list))
return RAISE (PyExc_ValueError, "Argument must be a sequence type");
if (!pal)
return RAISE (PyExc_SDLError, "Surface has no palette\n");
if (!SDL_WasInit (SDL_INIT_VIDEO))
return RAISE (PyExc_SDLError,
"cannot set palette without pygame.display initialized");
len = MIN (pal->ncolors, PySequence_Length (list));
colors = (SDL_Color *) malloc (len * sizeof (SDL_Color));
if (!colors)
return NULL;
for (i = 0; i < len; i++)
{
item = PySequence_GetItem (list, i);
ecode = RGBAFromObj (item, rgba);
Py_DECREF (item);
if (!ecode)
{
free (colors);
return RAISE (PyExc_ValueError,
"takes a sequence of integers of RGB");
}
if (rgba[3] != 255)
{
free (colors);
return RAISE (PyExc_ValueError,
"takes an alpha value of 255");
}
colors[i].r = (unsigned char) rgba[0];
colors[i].g = (unsigned char) rgba[1];
colors[i].b = (unsigned char) rgba[2];
}
SDL_SetColors (surf, colors, 0, len);
free (colors);
Py_RETURN_NONE;
}
static PyObject*
surf_set_palette_at (PyObject *self, PyObject *args)
{
SDL_Surface *surf = PySurface_AsSurface (self);
SDL_Palette *pal = surf->format->palette;
SDL_Color color;
int _index;
PyObject *color_obj;
Uint8 rgba[4];
if (!PyArg_ParseTuple (args, "iO", &_index, &color_obj))
return NULL;
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
if (!RGBAFromObj (color_obj, rgba))
{
return RAISE (PyExc_ValueError,
"takes a sequence of integers of RGB for argument 2");
}
if (!pal)
{
PyErr_SetString (PyExc_SDLError, "Surface is not palettized\n");
return NULL;
}
if (_index >= pal->ncolors || _index < 0)
{
PyErr_SetString (PyExc_IndexError, "index out of bounds");
return NULL;
}
if (!SDL_WasInit (SDL_INIT_VIDEO))
return RAISE (PyExc_SDLError,
"cannot set palette without pygame.display initialized");
color.r = rgba[0];
color.g = rgba[1];
color.b = rgba[2];
SDL_SetColors (surf, &color, _index, 1);
Py_RETURN_NONE;
}
static PyObject*
surf_set_colorkey (PyObject *self, PyObject *args)
{
SDL_Surface *surf = PySurface_AsSurface (self);
Uint32 flags = 0, color = 0;
PyObject *rgba_obj = NULL;
Uint8 rgba[4];
int result, hascolor = 0;
if (!PyArg_ParseTuple (args, "|Oi", &rgba_obj, &flags))
return NULL;
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
if (surf->flags & SDL_OPENGL)
return RAISE (PyExc_SDLError, "Cannot call on OPENGL Surfaces");
if (rgba_obj && rgba_obj != Py_None)
{
if (PyInt_Check (rgba_obj))
{
color = (Uint32) PyInt_AsLong (rgba_obj);
if (PyErr_Occurred () && (Sint32) color == -1)
return RAISE (PyExc_TypeError, "invalid color argument");
}
else if (PyLong_Check (rgba_obj))
{
color = (Uint32) PyLong_AsUnsignedLong (rgba_obj);
if (PyErr_Occurred () && (Sint32) color == -1)
return RAISE (PyExc_TypeError, "invalid color argument");
}
else if (RGBAFromColorObj (rgba_obj, rgba))
{
color = SDL_MapRGBA (surf->format, rgba[0], rgba[1], rgba[2],
rgba[3]);
}
else
return RAISE (PyExc_TypeError, "invalid color argument");
hascolor = 1;
}
if (hascolor)
flags |= SDL_SRCCOLORKEY;
PySurface_Prep (self);
result = SDL_SetColorKey (surf, flags, color);
PySurface_Unprep (self);
if (result == -1)
return RAISE (PyExc_SDLError, SDL_GetError ());
Py_RETURN_NONE;
}
static PyObject*
surf_get_colorkey (PyObject *self)
{
SDL_Surface *surf = PySurface_AsSurface (self);
Uint8 r, g, b, a;
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
if (surf->flags & SDL_OPENGL)
return RAISE (PyExc_SDLError, "Cannot call on OPENGL Surfaces");
if (!(surf->flags & SDL_SRCCOLORKEY))
Py_RETURN_NONE;
SDL_GetRGBA (surf->format->colorkey, surf->format, &r, &g, &b, &a);
return Py_BuildValue ("(bbbb)", r, g, b, a);
}
static PyObject*
surf_set_alpha (PyObject *self, PyObject *args)
{
SDL_Surface *surf = PySurface_AsSurface (self);
Uint32 flags = 0;
PyObject *alpha_obj = NULL, *intobj = NULL;
Uint8 alpha;
int result, alphaval = 255, hasalpha = 0;
if (!PyArg_ParseTuple (args, "|Oi", &alpha_obj, &flags))
return NULL;
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
if (surf->flags & SDL_OPENGL)
return RAISE (PyExc_SDLError, "Cannot call on OPENGL Surfaces");
if (alpha_obj && alpha_obj != Py_None)
{
if (PyNumber_Check (alpha_obj) && (intobj = PyNumber_Int (alpha_obj)))
{
if (PyInt_Check (intobj))
{
alphaval = (int) PyInt_AsLong (intobj);
Py_DECREF (intobj);
}
else
return RAISE (PyExc_TypeError, "invalid alpha argument");
}
else
return RAISE (PyExc_TypeError, "invalid alpha argument");
hasalpha = 1;
}
if (hasalpha)
flags |= SDL_SRCALPHA;
if (alphaval > 255)
alpha = 255;
else if (alphaval < 0)
alpha = 0;
else
alpha = (Uint8) alphaval;
PySurface_Prep (self);
result = SDL_SetAlpha (surf, flags, alpha);
PySurface_Unprep (self);
if (result == -1)
return RAISE (PyExc_SDLError, SDL_GetError ());
Py_RETURN_NONE;
}
static PyObject*
surf_get_alpha (PyObject *self)
{
SDL_Surface *surf = PySurface_AsSurface (self);
if (surf->flags & SDL_OPENGL)
return RAISE (PyExc_SDLError, "Cannot call on OPENGL Surfaces");
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
if (surf->flags & SDL_SRCALPHA)
return PyInt_FromLong (surf->format->alpha);
Py_RETURN_NONE;
}
static PyObject*
surf_copy (PyObject *self)
{
SDL_Surface *surf = PySurface_AsSurface (self);
PyObject *final;
SDL_Surface *newsurf;
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
if (surf->flags & SDL_OPENGL)
return RAISE (PyExc_SDLError, "Cannot copy opengl display");
PySurface_Prep (self);
newsurf = SDL_ConvertSurface (surf, surf->format, surf->flags);
PySurface_Unprep (self);
final = PySurface_New (newsurf);
if (!final)
SDL_FreeSurface (newsurf);
return final;
}
static PyObject*
surf_convert (PyObject *self, PyObject *args)
{
SDL_Surface *surf = PySurface_AsSurface (self);
PyObject *final;
PyObject *argobject = NULL;
SDL_Surface *src;
SDL_Surface *newsurf;
Uint32 flags = -1;
if (!SDL_WasInit (SDL_INIT_VIDEO))
return RAISE (PyExc_SDLError,
"cannot convert without pygame.display initialized");
if (!PyArg_ParseTuple (args, "|Oi", &argobject, &flags))
return NULL;
if (surf->flags & SDL_OPENGL)
return RAISE (PyExc_SDLError, "Cannot convert opengl display");
PySurface_Prep (self);
if (argobject)
{
if (PySurface_Check (argobject))
{
src = PySurface_AsSurface (argobject);
flags = src->flags |
(surf->flags & (SDL_SRCCOLORKEY | SDL_SRCALPHA));
newsurf = SDL_ConvertSurface (surf, src->format, flags);
}
else
{
int bpp;
SDL_PixelFormat format;
memcpy (&format, surf->format, sizeof (format));
if (IntFromObj (argobject, &bpp))
{
Uint32 Rmask, Gmask, Bmask, Amask;
if (flags != -1 && flags & SDL_SRCALPHA)
{
switch (bpp)
{
case 16:
Rmask = 0xF << 8;
Gmask = 0xF << 4;
Bmask = 0xF;
Amask = 0xF << 12;
break;
case 32:
Rmask = 0xFF << 16;
Gmask = 0xFF << 8;
Bmask = 0xFF;
Amask = 0xFF << 24;
break;
default:
return RAISE (PyExc_ValueError,
"no standard masks exist for given "
"bitdepth with alpha");
}
}
else
{
Amask = 0;
switch (bpp)
{
case 8:
Rmask = 0xFF >> 6 << 5;
Gmask = 0xFF >> 5 << 2;
Bmask = 0xFF >> 6;
break;
case 12:
Rmask = 0xFF >> 4 << 8;
Gmask = 0xFF >> 4 << 4;
Bmask = 0xFF >> 4;
break;
case 15:
Rmask = 0xFF >> 3 << 10;
Gmask = 0xFF >> 3 << 5;
Bmask = 0xFF >> 3;
break;
case 16:
Rmask = 0xFF >> 3 << 11;
Gmask = 0xFF >> 2 << 5;
Bmask = 0xFF >> 3;
break;
case 24:
case 32:
Rmask = 0xFF << 16;
Gmask = 0xFF << 8;
Bmask = 0xFF;
break;
default:
return RAISE (PyExc_ValueError,
"nonstandard bit depth given");
}
}
format.Rmask = Rmask;
format.Gmask = Gmask;
format.Bmask = Bmask;
format.Amask = Amask;
}
else if (PySequence_Check (argobject) &&
PySequence_Size (argobject) == 4)
{
Uint32 mask;
if (!UintFromObjIndex (argobject, 0, &format.Rmask) ||
!UintFromObjIndex (argobject, 1, &format.Gmask) ||
!UintFromObjIndex (argobject, 2, &format.Bmask) ||
!UintFromObjIndex (argobject, 3, &format.Amask))
{
PySurface_Unprep (self);
return RAISE (PyExc_ValueError,
"invalid color masks given");
}
mask = format.Rmask | format.Gmask | format.Bmask |
format.Amask;
for (bpp = 0; bpp < 32; ++bpp)
if (!(mask >> bpp))
break;
}
else
{
PySurface_Unprep (self);
return RAISE
(PyExc_ValueError,
"invalid argument specifying new format to convert to");
}
format.BitsPerPixel = (Uint8) bpp;
format.BytesPerPixel = (bpp + 7) / 8;
if (flags == -1)
flags = surf->flags;
if (format.Amask)
flags |= SDL_SRCALPHA;
newsurf = SDL_ConvertSurface (surf, &format, flags);
}
}
else
{
if (SDL_WasInit (SDL_INIT_VIDEO))
newsurf = SDL_DisplayFormat (surf);
else
newsurf = SDL_ConvertSurface (surf, surf->format, surf->flags);
}
PySurface_Unprep (self);
final = PySurface_New (newsurf);
if (!final)
SDL_FreeSurface (newsurf);
return final;
}
static PyObject*
surf_convert_alpha (PyObject *self, PyObject *args)
{
SDL_Surface *surf = PySurface_AsSurface (self);
PyObject *final;
PySurfaceObject *srcsurf = NULL;
SDL_Surface *newsurf, *src;
if (!SDL_WasInit (SDL_INIT_VIDEO))
return RAISE (PyExc_SDLError,
"cannot convert without pygame.display initialized");
if (!PyArg_ParseTuple (args, "|O!", &PySurface_Type, &srcsurf))
return NULL;
PySurface_Prep (self);
if (srcsurf)
{
/*
* hmm, we have to figure this out, not all depths have good
* support for alpha
*/
src = PySurface_AsSurface (srcsurf);
newsurf = SDL_DisplayFormatAlpha (surf);
}
else
newsurf = SDL_DisplayFormatAlpha (surf);
PySurface_Unprep (self);
final = PySurface_New (newsurf);
if (!final)
SDL_FreeSurface (newsurf);
return final;
}
static PyObject*
surf_set_clip (PyObject *self, PyObject *args)
{
SDL_Surface *surf = PySurface_AsSurface (self);
PyObject *item;
GAME_Rect *rect = NULL, temp;
SDL_Rect sdlrect;
int result;
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
if (PyTuple_Size (args))
{
item = PyTuple_GET_ITEM (args, 0);
if (item == Py_None && PyTuple_Size (args) == 1)
{
result = SDL_SetClipRect (surf, NULL);
}
else
{
rect = GameRect_FromObject (args, &temp);
if (!rect)
return RAISE (PyExc_ValueError, "invalid rectstyle object");
sdlrect.x = rect->x;
sdlrect.y = rect->y;
sdlrect.h = rect->h;
sdlrect.w = rect->w;
result = SDL_SetClipRect (surf, &sdlrect);
}
}
else
{
result = SDL_SetClipRect (surf, NULL);
}
if (result == -1)
{
return RAISE (PyExc_SDLError, SDL_GetError ());
}
Py_RETURN_NONE;
}
static PyObject*
surf_get_clip (PyObject *self)
{
SDL_Surface *surf = PySurface_AsSurface (self);
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
return PyRect_New (&surf->clip_rect);
}
static PyObject*
surf_fill (PyObject *self, PyObject *args, PyObject *keywds)
{
SDL_Surface *surf = PySurface_AsSurface (self);
GAME_Rect *rect, temp;
PyObject *r = NULL;
Uint32 color;
int result;
PyObject *rgba_obj;
Uint8 rgba[4];
SDL_Rect sdlrect;
int blendargs = 0;
static char *kwids[] = {"color", "rect", "special_flags", NULL};
if (!PyArg_ParseTupleAndKeywords (args, keywds, "O|Oi", kwids,
&rgba_obj, &r, &blendargs))
return NULL;
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
if (surf->flags & SDL_OPENGL)
return RAISE (PyExc_SDLError, "Cannot call on OPENGL Surfaces");
if (PyInt_Check (rgba_obj))
color = (Uint32) PyInt_AsLong (rgba_obj);
else if (PyLong_Check (rgba_obj))
color = (Uint32) PyLong_AsUnsignedLong (rgba_obj);
else if (RGBAFromColorObj (rgba_obj, rgba))
color = SDL_MapRGBA (surf->format, rgba[0], rgba[1], rgba[2], rgba[3]);
else
return RAISE (PyExc_TypeError, "invalid color argument");
if (!r || r == Py_None)
{
rect = &temp;
temp.x = temp.y = 0;
temp.w = surf->w;
temp.h = surf->h;
}
else if (!(rect = GameRect_FromObject (r, &temp)))
return RAISE (PyExc_ValueError, "invalid rectstyle object");
/* we need a fresh copy so our Rect values don't get munged */
if (rect != &temp)
{
memcpy (&temp, rect, sizeof (temp));
rect = &temp;
}
if (rect->w < 0 || rect->h < 0)
{
sdlrect.x = sdlrect.y = 0;
sdlrect.w = sdlrect.h = 0;
}
else
{
sdlrect.x = rect->x;
sdlrect.y = rect->y;
sdlrect.w = rect->w;
sdlrect.h = rect->h;
if (blendargs != 0)
{
/*
printf ("Using blendargs: %d\n", blendargs);
*/
result = surface_fill_blend (surf, &sdlrect, color, blendargs);
}
else
{
PySurface_Prep (self);
result = SDL_FillRect (surf, &sdlrect, color);
PySurface_Unprep (self);
}
if (result == -1)
return RAISE (PyExc_SDLError, SDL_GetError ());
}
return PyRect_New (&sdlrect);
}
static PyObject*
surf_blit (PyObject *self, PyObject *args, PyObject *keywds)
{
SDL_Surface *src, *dest = PySurface_AsSurface (self);
GAME_Rect *src_rect, temp;
PyObject *srcobject, *argpos, *argrect = NULL;
int dx, dy, result;
SDL_Rect dest_rect, sdlsrc_rect;
int sx, sy;
int the_args = 0;
static char *kwids[] = {"source", "dest", "area", "special_flags", NULL};
if (!PyArg_ParseTupleAndKeywords (args, keywds, "O!O|Oi", kwids,
&PySurface_Type, &srcobject, &argpos,
&argrect, &the_args))
return NULL;
src = PySurface_AsSurface (srcobject);
if (!dest || !src)
return RAISE (PyExc_SDLError, "display Surface quit");
if (dest->flags & SDL_OPENGL &&
!(dest->flags & (SDL_OPENGLBLIT & ~SDL_OPENGL)))
return RAISE (PyExc_SDLError,
"Cannot blit to OPENGL Surfaces (OPENGLBLIT is ok)");
if ((src_rect = GameRect_FromObject (argpos, &temp)))
{
dx = src_rect->x;
dy = src_rect->y;
}
else if (TwoIntsFromObj (argpos, &sx, &sy))
{
dx = sx;
dy = sy;
}
else
return RAISE (PyExc_TypeError, "invalid destination position for blit");
if (argrect && argrect != Py_None)
{
if (!(src_rect = GameRect_FromObject (argrect, &temp)))
return RAISE (PyExc_TypeError, "Invalid rectstyle argument");
}
else
{
temp.x = temp.y = 0;
temp.w = src->w;
temp.h = src->h;
src_rect = &temp;
}
dest_rect.x = (short) dx;
dest_rect.y = (short) dy;
dest_rect.w = (unsigned short) src_rect->w;
dest_rect.h = (unsigned short) src_rect->h;
sdlsrc_rect.x = (short) src_rect->x;
sdlsrc_rect.y = (short) src_rect->y;
sdlsrc_rect.w = (unsigned short) src_rect->w;
sdlsrc_rect.h = (unsigned short) src_rect->h;
if (!the_args)
the_args = 0;
result = PySurface_Blit (self, srcobject, &dest_rect, &sdlsrc_rect,
the_args);
if (result != 0)
return NULL;
return PyRect_New (&dest_rect);
}
static PyObject*
surf_scroll (PyObject *self, PyObject *args, PyObject *keywds)
{
int dx = 0, dy = 0;
SDL_Surface *surf;
int bpp;
int pitch;
SDL_Rect *clip_rect;
int w, h;
Uint8 *src, *dst;
static char *kwids[] = {"dx", "dy", NULL};
if (!PyArg_ParseTupleAndKeywords (args, keywds, "|ii", kwids, &dx, &dy))
{
return NULL;
}
surf = PySurface_AsSurface (self);
if (!surf)
{
return RAISE (PyExc_SDLError, "display Surface quit");
}
if (surf->flags & SDL_OPENGL &&
!(surf->flags & (SDL_OPENGLBLIT & ~SDL_OPENGL)))
{
return RAISE (PyExc_SDLError,
"Cannot scroll an OPENGL Surfaces (OPENGLBLIT is ok)");
}
if (dx == 0 && dy == 0)
{
Py_RETURN_NONE;
}
clip_rect = &surf->clip_rect;
w = clip_rect->w;
h = clip_rect->h;
if (dx >= w || dx <= -w || dy >= h || dy <= -h)
{
Py_RETURN_NONE;
}
if (!PySurface_Lock (self))
{
return NULL;
}
bpp = surf->format->BytesPerPixel;
pitch = surf->pitch;
src = dst = (Uint8 *) surf->pixels +
clip_rect->y * pitch + clip_rect->x * bpp;
if (dx >= 0)
{
w -= dx;
if (dy > 0)
{
h -= dy;
dst += dy * pitch + dx * bpp;
}
else
{
h += dy;
src -= dy * pitch;
dst += dx * bpp;
}
}
else
{
w += dx;
if (dy > 0)
{
h -= dy;
src -= dx * bpp;
dst += dy * pitch;
}
else
{
h += dy;
src -= dy * pitch + dx * bpp;
}
}
surface_move (src, dst, h, w * bpp, pitch, pitch);
if (!PySurface_Unlock (self))
{
return NULL;
}
Py_RETURN_NONE;
}
static PyObject*
surf_get_flags (PyObject *self)
{
SDL_Surface *surf = PySurface_AsSurface (self);
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
return PyInt_FromLong ((long)surf->flags);
}
static PyObject*
surf_get_pitch (PyObject *self)
{
SDL_Surface *surf = PySurface_AsSurface (self);
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
return PyInt_FromLong (surf->pitch);
}
static PyObject*
surf_get_size (PyObject *self)
{
SDL_Surface *surf = PySurface_AsSurface (self);
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
return Py_BuildValue ("(ii)", surf->w, surf->h);
}
static PyObject*
surf_get_width (PyObject *self)
{
SDL_Surface *surf = PySurface_AsSurface (self);
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
return PyInt_FromLong (surf->w);
}
static PyObject*
surf_get_height (PyObject *self)
{
SDL_Surface *surf = PySurface_AsSurface (self);
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
return PyInt_FromLong (surf->h);
}
static PyObject*
surf_get_rect (PyObject *self, PyObject *args, PyObject *kwargs)
{
PyObject *rect;
SDL_Surface *surf = PySurface_AsSurface (self);
if (PyTuple_GET_SIZE (args) > 0) {
return RAISE (PyExc_TypeError,
"get_rect only accepts keyword arguments");
}
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
rect = PyRect_New4 (0, 0, surf->w, surf->h);
if (rect && kwargs)
{
PyObject *key, *value;
Py_ssize_t pos = 0;
while (PyDict_Next (kwargs, &pos, &key, &value))
{
if ((PyObject_SetAttr (rect, key, value) == -1))
{
Py_DECREF (rect);
return NULL;
}
}
}
return rect;
}
static PyObject*
surf_get_bitsize (PyObject *self)
{
SDL_Surface *surf = PySurface_AsSurface (self);
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
return PyInt_FromLong (surf->format->BitsPerPixel);
}
static PyObject*
surf_get_bytesize (PyObject *self)
{
SDL_Surface *surf = PySurface_AsSurface (self);
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
return PyInt_FromLong (surf->format->BytesPerPixel);
}
static PyObject*
surf_get_masks (PyObject *self)
{
SDL_Surface *surf = PySurface_AsSurface (self);
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
return Py_BuildValue ("(IIII)", surf->format->Rmask, surf->format->Gmask,
surf->format->Bmask, surf->format->Amask);
}
static PyObject*
surf_set_masks (PyObject *self, PyObject *args)
{
SDL_Surface *surf = PySurface_AsSurface (self);
/* Need to use 64bit vars so this works on 64 bit pythons. */
Uint64 r, g, b, a;
if (!PyArg_ParseTuple (args, "(kkkk)", &r, &g, &b, &a))
return NULL;
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
/*
printf("passed in: %d, %d, %d, %d\n", r,g,b,a );
printf("what are: %d, %d, %d, %d\n", surf->format->Rmask, surf->format->Gmask, surf->format->Bmask, surf->format->Amask);
*/
surf->format->Rmask = (Uint32)r;
surf->format->Gmask = (Uint32)g;
surf->format->Bmask = (Uint32)b;
surf->format->Amask = (Uint32)a;
Py_RETURN_NONE;
}
static PyObject*
surf_get_shifts (PyObject *self)
{
SDL_Surface *surf = PySurface_AsSurface (self);
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
return Py_BuildValue ("(iiii)", surf->format->Rshift, surf->format->Gshift,
surf->format->Bshift, surf->format->Ashift);
}
static PyObject*
surf_set_shifts (PyObject *self, PyObject *args)
{
SDL_Surface *surf = PySurface_AsSurface (self);
Uint64 r, g, b, a;
if (!PyArg_ParseTuple (args, "(kkkk)", &r, &g, &b, &a))
return NULL;
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
surf->format->Rshift = (Uint8)r;
surf->format->Gshift = (Uint8)g;
surf->format->Bshift = (Uint8)b;
surf->format->Ashift = (Uint8)a;
Py_RETURN_NONE;
}
static PyObject*
surf_get_losses (PyObject *self)
{
SDL_Surface *surf = PySurface_AsSurface (self);
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
return Py_BuildValue ("(iiii)", surf->format->Rloss, surf->format->Gloss,
surf->format->Bloss, surf->format->Aloss);
}
static PyObject*
surf_subsurface (PyObject *self, PyObject *args)
{
SDL_Surface *surf = PySurface_AsSurface (self);
SDL_PixelFormat *format = surf->format;
GAME_Rect *rect, temp;
SDL_Surface *sub;
PyObject *subobj;
int pixeloffset;
char *startpixel;
struct SubSurface_Data *data;
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
if (surf->flags & SDL_OPENGL)
return RAISE (PyExc_SDLError, "Cannot call on OPENGL Surfaces");
if (!(rect = GameRect_FromObject (args, &temp)))
return RAISE (PyExc_ValueError, "invalid rectstyle argument");
if (rect->x < 0 || rect->y < 0 || rect->x + rect->w > surf->w
|| rect->y + rect->h > surf->h)
return RAISE (PyExc_ValueError,
"subsurface rectangle outside surface area");
PySurface_Lock (self);
pixeloffset = rect->x * format->BytesPerPixel + rect->y * surf->pitch;
startpixel = ((char *) surf->pixels) + pixeloffset;
sub = SDL_CreateRGBSurfaceFrom (startpixel, rect->w, rect->h,
format->BitsPerPixel, surf->pitch,
format->Rmask, format->Gmask,
format->Bmask, format->Amask);
PySurface_Unlock (self);
if (!sub)
return RAISE (PyExc_SDLError, SDL_GetError ());
/* copy the colormap if we need it */
if (surf->format->BytesPerPixel == 1 && surf->format->palette)
SDL_SetPalette (sub, SDL_LOGPAL, surf->format->palette->colors, 0,
surf->format->palette->ncolors);
if (surf->flags & SDL_SRCALPHA)
SDL_SetAlpha (sub, surf->flags & SDL_SRCALPHA, format->alpha);
if (surf->flags & SDL_SRCCOLORKEY)
SDL_SetColorKey (sub, surf->flags & (SDL_SRCCOLORKEY | SDL_RLEACCEL),
format->colorkey);
data = PyMem_New (struct SubSurface_Data, 1);
if (!data)
return NULL;
subobj = PySurface_New (sub);
if (!subobj)
{
PyMem_Del (data);
return NULL;
}
Py_INCREF (self);
data->owner = self;
data->pixeloffset = pixeloffset;
data->offsetx = rect->x;
data->offsety = rect->y;
((PySurfaceObject *) subobj)->subsurface = data;
return subobj;
}
static PyObject*
surf_get_offset (PyObject *self)
{
struct SubSurface_Data *subdata;
subdata = ((PySurfaceObject *) self)->subsurface;
if (!subdata)
return Py_BuildValue ("(ii)", 0, 0);
return Py_BuildValue ("(ii)", subdata->offsetx, subdata->offsety);
}
static PyObject*
surf_get_abs_offset (PyObject *self)
{
struct SubSurface_Data *subdata;
PyObject *owner;
int offsetx, offsety;
subdata = ((PySurfaceObject *) self)->subsurface;
if (!subdata)
return Py_BuildValue ("(ii)", 0, 0);
subdata = ((PySurfaceObject *) self)->subsurface;
owner = subdata->owner;
offsetx = subdata->offsetx;
offsety = subdata->offsety;
while (((PySurfaceObject *) owner)->subsurface)
{
subdata = ((PySurfaceObject *) owner)->subsurface;
owner = subdata->owner;
offsetx += subdata->offsetx;
offsety += subdata->offsety;
}
return Py_BuildValue ("(ii)", offsetx, offsety);
}
static PyObject*
surf_get_parent (PyObject *self)
{
struct SubSurface_Data *subdata;
subdata = ((PySurfaceObject *) self)->subsurface;
if (!subdata)
Py_RETURN_NONE;
Py_INCREF (subdata->owner);
return subdata->owner;
}
static PyObject*
surf_get_abs_parent (PyObject *self)
{
struct SubSurface_Data *subdata;
PyObject *owner;
subdata = ((PySurfaceObject *) self)->subsurface;
if (!subdata)
{
Py_INCREF (self);
return self;
}
subdata = ((PySurfaceObject *) self)->subsurface;
owner = subdata->owner;
while (((PySurfaceObject *) owner)->subsurface)
{
subdata = ((PySurfaceObject *) owner)->subsurface;
owner = subdata->owner;
}
Py_INCREF (owner);
return owner;
}
static PyObject *
surf_get_bounding_rect (PyObject *self, PyObject *args, PyObject *kwargs)
{
PyObject *rect;
SDL_Surface *surf = PySurface_AsSurface (self);
SDL_PixelFormat *format = surf->format;
Uint8 *pixels = (Uint8 *) surf->pixels;
Uint8 *pixel;
int x, y;
int min_x, min_y, max_x, max_y;
int min_alpha = 1;
int found_alpha = 0;
Uint8 r, g, b, a;
int has_colorkey = 0;
Uint8 keyr, keyg, keyb;
char *kwids[] = { "min_alpha", NULL };
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i", kwids, &min_alpha))
return RAISE (PyExc_ValueError,
"get_bounding_rect only accepts a single optional min_alpha argument");
if (!surf)
return RAISE (PyExc_SDLError, "display Surface quit");
if (!PySurface_Lock (self))
return RAISE (PyExc_SDLError, "could not lock surface");
if (surf->flags & SDL_SRCCOLORKEY)
{
has_colorkey = 1;
SDL_GetRGBA (surf->format->colorkey,
surf->format,
&keyr, &keyg, &keyb, &a);
}
pixels = (Uint8 *) surf->pixels;
min_y = 0;
min_x = 0;
max_x = surf->w;
max_y = surf->h;
found_alpha = 0;
for (y = max_y - 1; y >= min_y; --y)
{
for (x = min_x; x < max_x; ++x)
{
pixel = (pixels + y * surf->pitch) + x*format->BytesPerPixel;
SDL_GetRGBA (*((Uint32*)pixel), surf->format, &r, &g, &b, &a);
if ((a >= min_alpha && has_colorkey == 0) ||
(has_colorkey != 0 && (r != keyr || g != keyg || b != keyb)))
{
found_alpha = 1;
break;
}
}
if (found_alpha == 1)
{
break;
}
max_y = y;
}
found_alpha = 0;
for (x = max_x - 1; x >= min_x; --x)
{
for (y = min_y; y < max_y; ++y)
{
pixel = (pixels + y * surf->pitch) + x*format->BytesPerPixel;
SDL_GetRGBA (*((Uint32*)pixel), surf->format, &r, &g, &b, &a);
if ((a >= min_alpha && has_colorkey == 0) ||
(has_colorkey != 0 && (r != keyr || g != keyg || b != keyb)))
{
found_alpha = 1;
break;
}
}
if (found_alpha == 1)
{
break;
}
max_x = x;
}
found_alpha = 0;
for (y = min_y; y < max_y; ++y)
{
min_y = y;
for (x = min_x; x < max_x; ++x)
{
pixel = (pixels + y * surf->pitch) + x*format->BytesPerPixel;
SDL_GetRGBA (*((Uint32*)pixel), surf->format, &r, &g, &b, &a);
if ((a >= min_alpha && has_colorkey == 0) ||
(has_colorkey != 0 && (r != keyr || g != keyg || b != keyb)))
{
found_alpha = 1;
break;
}
}
if (found_alpha == 1)
{
break;
}
}
found_alpha = 0;
for (x = min_x; x < max_x; ++x)
{
min_x = x;
for (y = min_y; y < max_y; ++y)
{
pixel = (pixels + y * surf->pitch) + x*format->BytesPerPixel;
SDL_GetRGBA (*((Uint32*)pixel), surf->format, &r, &g, &b, &a);
if ((a >= min_alpha && has_colorkey == 0) ||
(has_colorkey != 0 && (r != keyr || g != keyg || b != keyb)))
{
found_alpha = 1;
break;
}
}
if (found_alpha == 1)
{
break;
}
}
if (!PySurface_Unlock (self))
return RAISE (PyExc_SDLError, "could not unlock surface");
rect = PyRect_New4 (min_x, min_y, max_x - min_x, max_y - min_y);
return rect;
}
static PyObject
*surf_get_buffer (PyObject *self)
{
PyObject *buffer;
PyObject *lock;
SDL_Surface *surface = PySurface_AsSurface (self);
Py_ssize_t length;
length = (Py_ssize_t) surface->pitch * surface->h;
buffer = PyBufferProxy_New (self, NULL, length, NULL);
if (!buffer)
{
return RAISE (PyExc_SDLError,
"could not acquire a buffer for the surface");
}
lock = PySurface_LockLifetime (self, buffer);
if (!lock)
{
Py_DECREF (buffer);
return RAISE (PyExc_SDLError, "could not lock surface");
}
((PyBufferProxy *) buffer)->buffer = surface->pixels;
((PyBufferProxy *) buffer)->lock = lock;
return buffer;
}
static void
surface_move (Uint8 *src, Uint8 *dst, int h, int span,
int srcpitch, int dstpitch)
{
if (src < dst)
{
src += (h - 1) * srcpitch;
dst += (h - 1) * dstpitch;
srcpitch = -srcpitch;
dstpitch = -dstpitch;
}
while (h--)
{
memmove(dst, src, span);
src += srcpitch;
dst += dstpitch;
}
}
static int
surface_do_overlap (SDL_Surface *src, SDL_Rect *srcrect,
SDL_Surface *dst, SDL_Rect *dstrect)
{
Uint8 *srcpixels;
Uint8 *dstpixels;
int srcx = srcrect->x, srcy = srcrect->y;
int dstx = dstrect->x, dsty = dstrect->y;
int x, y;
int w = srcrect-> w, h= srcrect->h;
int maxw, maxh;
SDL_Rect *clip = &dst->clip_rect;
int span;
int dstoffset;
/* clip the source rectangle to the source surface */
if (srcx < 0)
{
w += srcx;
dstx -= srcx;
srcx = 0;
}
maxw = src->w - srcx;
if (maxw < w)
{
w = maxw;
}
srcy = srcrect->y;
if (srcy < 0)
{
h += srcy;
dsty -= srcy;
srcy = 0;
}
maxh = src->h - srcy;
if (maxh < h)
{
h = maxh;
}
/* clip the destination rectangle against the clip rectangle */
x = clip->x - dstx;
if (x > 0)
{
w -= x;
dstx += x;
srcx += x;
}
x = dstx + w - clip->x - clip->w;
if (x > 0)
{
w -= x;
}
y = clip->y - dsty;
if (y > 0)
{
h -= y;
dsty += y;
srcy += y;
}
y = dsty + h - clip->y - clip->h;
if (y > 0)
{
h -= y;
}
if (w <= 0 || h <= 0)
{
return 0;
}
srcpixels = ((Uint8 *) src->pixels + src->offset +
srcy * src->pitch +
srcx * src->format->BytesPerPixel);
dstpixels = ((Uint8 *) dst->pixels + src->offset +
dsty * dst->pitch +
dstx * dst->format->BytesPerPixel);
if (dstpixels <= srcpixels)
{
return 0;
}
span = w * src->format->BytesPerPixel;
if (dstpixels >= srcpixels + (h - 1) * src->pitch + span)
{
return 0;
}
dstoffset = (dstpixels - srcpixels) % src->pitch;
return dstoffset < span || dstoffset > src->pitch - span;
}
/*this internal blit function is accessable through the C api*/
int
PySurface_Blit (PyObject * dstobj, PyObject * srcobj, SDL_Rect * dstrect,
SDL_Rect * srcrect, int the_args)
{
SDL_Surface *src = PySurface_AsSurface (srcobj);
SDL_Surface *dst = PySurface_AsSurface (dstobj);
SDL_Surface *subsurface = NULL;
int result, suboffsetx = 0, suboffsety = 0;
SDL_Rect orig_clip, sub_clip;
/* passthrough blits to the real surface */
if (((PySurfaceObject *) dstobj)->subsurface)
{
PyObject *owner;
struct SubSurface_Data *subdata;
subdata = ((PySurfaceObject *) dstobj)->subsurface;
owner = subdata->owner;
subsurface = PySurface_AsSurface (owner);
suboffsetx = subdata->offsetx;
suboffsety = subdata->offsety;
while (((PySurfaceObject *) owner)->subsurface)
{
subdata = ((PySurfaceObject *) owner)->subsurface;
owner = subdata->owner;
subsurface = PySurface_AsSurface (owner);
suboffsetx += subdata->offsetx;
suboffsety += subdata->offsety;
}
SDL_GetClipRect (subsurface, &orig_clip);
SDL_GetClipRect (dst, &sub_clip);
sub_clip.x += suboffsetx;
sub_clip.y += suboffsety;
SDL_SetClipRect (subsurface, &sub_clip);
dstrect->x += suboffsetx;
dstrect->y += suboffsety;
dst = subsurface;
}
else
{
PySurface_Prep (dstobj);
subsurface = NULL;
}
PySurface_Prep (srcobj);
/* see if we should handle alpha ourselves */
if (dst->format->Amask && (dst->flags & SDL_SRCALPHA) &&
!(src->format->Amask && !(src->flags & SDL_SRCALPHA)) &&
/* special case, SDL works */
(dst->format->BytesPerPixel == 2 || dst->format->BytesPerPixel == 4))
{
/* Py_BEGIN_ALLOW_THREADS */
result = pygame_AlphaBlit (src, srcrect, dst, dstrect, the_args);
/* Py_END_ALLOW_THREADS */
}
else if (the_args != 0 ||
(src->flags & (SDL_SRCALPHA | SDL_SRCCOLORKEY) &&
/* This simplification is possible because a source subsurface
is converted to its owner with a clip rect and a dst
subsurface cannot be blitted to its owner because the
owner is locked.
*/
dst->pixels == src->pixels &&
surface_do_overlap (src, srcrect, dst, dstrect)))
{
/* Py_BEGIN_ALLOW_THREADS */
result = pygame_Blit (src, srcrect, dst, dstrect, the_args);
/* Py_END_ALLOW_THREADS */
}
/* can't blit alpha to 8bit, crashes SDL */
else if (dst->format->BytesPerPixel == 1 &&
(src->format->Amask || src->flags & SDL_SRCALPHA))
{
/* Py_BEGIN_ALLOW_THREADS */
if (src->format->BytesPerPixel == 1)
{
result = pygame_Blit (src, srcrect, dst, dstrect, 0);
}
else
{
src = SDL_DisplayFormat (src);
if (src)
{
result = SDL_BlitSurface (src, srcrect, dst, dstrect);
SDL_FreeSurface (src);
}
else
{
result = -1;
}
}
/* Py_END_ALLOW_THREADS */
}
else
{
/* Py_BEGIN_ALLOW_THREADS */
result = SDL_BlitSurface (src, srcrect, dst, dstrect);
/* Py_END_ALLOW_THREADS */
}
if (subsurface)
{
SDL_SetClipRect (subsurface, &orig_clip);
dstrect->x -= suboffsetx;
dstrect->y -= suboffsety;
}
else
PySurface_Unprep (dstobj);
PySurface_Unprep (srcobj);
if (result == -1)
RAISE (PyExc_SDLError, SDL_GetError ());
if (result == -2)
RAISE (PyExc_SDLError, "Surface was lost");
return result != 0;
}
static PyMethodDef _surface_methods[] =
{
{ NULL, NULL, 0, NULL }
};
MODINIT_DEFINE (surface)
{
PyObject *module, *dict, *apiobj, *lockmodule;
int ecode;
static void* c_api[PYGAMEAPI_SURFACE_NUMSLOTS];
#if PY3
static struct PyModuleDef _module = {
PyModuleDef_HEAD_INIT,
"surface",
DOC_PYGAMESURFACE,
-1,
_surface_methods,
NULL, NULL, NULL, NULL
};
#endif
/* imported needed apis; Do this first so if there is an error
the module is not loaded.
*/
import_pygame_base ();
if (PyErr_Occurred ()) {
MODINIT_ERROR;
}
import_pygame_color ();
if (PyErr_Occurred ()) {
MODINIT_ERROR;
}
import_pygame_rect ();
if (PyErr_Occurred ()) {
MODINIT_ERROR;
}
import_pygame_bufferproxy();
if (PyErr_Occurred ()) {
MODINIT_ERROR;
}
/* import the surflock module manually */
lockmodule = PyImport_ImportModule (IMPPREFIX "surflock");
if (lockmodule != NULL)
{
PyObject *_dict = PyModule_GetDict (lockmodule);
PyObject *_c_api = PyDict_GetItemString (_dict, PYGAMEAPI_LOCAL_ENTRY);
if (PyCObject_Check (_c_api))
{
int i;
void **localptr = (void *)PyCObject_AsVoidPtr (_c_api);
for (i = 0; i < PYGAMEAPI_SURFLOCK_NUMSLOTS; ++i)
PyGAME_C_API[i + PYGAMEAPI_SURFLOCK_FIRSTSLOT] = localptr[i];
}
Py_DECREF (lockmodule);
}
else
{
MODINIT_ERROR;
}
/* type preparation */
if (PyType_Ready(&PySurface_Type) < 0) {
MODINIT_ERROR;
}
/* create the module */
#if PY3
module = PyModule_Create (&_module);
#else
module = Py_InitModule3 (MODPREFIX "surface", _surface_methods, DOC_PYGAMESURFACE);
#endif
if (module == NULL) {
MODINIT_ERROR;
}
dict = PyModule_GetDict (module);
if (PyDict_SetItemString (dict, "SurfaceType", (PyObject *) &PySurface_Type)) {
DECREF_MOD (module);
MODINIT_ERROR;
}
if (PyDict_SetItemString (dict, "Surface", (PyObject *) &PySurface_Type)) {
DECREF_MOD (module);
MODINIT_ERROR;
}
/* export the c api */
c_api[0] = &PySurface_Type;
c_api[1] = PySurface_New;
c_api[2] = PySurface_Blit;
apiobj = PyCObject_FromVoidPtr (c_api, NULL);
if (apiobj == NULL) {
DECREF_MOD (module);
MODINIT_ERROR;
}
ecode = PyDict_SetItemString (dict, PYGAMEAPI_LOCAL_ENTRY, apiobj);
Py_DECREF (apiobj);
if (ecode) {
DECREF_MOD (module);
MODINIT_ERROR;
}
/* Py_INCREF (PySurface_Type.tp_dict); INCREF's done in SetItemString */
if (PyDict_SetItemString (dict, "_dict", PySurface_Type.tp_dict)) {
DECREF_MOD (module);
MODINIT_ERROR;
}
MODINIT_RETURN (module);
}
pygame-1.9.1release/src/sdlmain_osx.m 0000644 0001750 0001750 00000017276 11225305337 017546 0 ustar vincent vincent /*
pygame - Python Game Library
Copyright (C) 2009 Brian Fisher
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* Mac OS X functions to accommodate the fact SDLMain.m is not included */
#include "pygame.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include "pgcompat.h"
struct CPSProcessSerNum
{
UInt32 lo;
UInt32 hi;
};
typedef struct CPSProcessSerNum CPSProcessSerNum;
extern OSErr CPSGetCurrentProcess( CPSProcessSerNum *psn);
extern OSErr CPSEnableForegroundOperation( CPSProcessSerNum *psn, UInt32 _arg2, UInt32 _arg3, UInt32 _arg4, UInt32 _arg5);
extern OSErr CPSSetFrontProcess( CPSProcessSerNum *psn);
extern OSErr CPSSetProcessName ( CPSProcessSerNum *psn, const char *processname );
static bool HasInstalledApplication = 0;
static NSString *getApplicationName(void)
{
const NSDictionary *dict;
NSString *appName = 0;
/* Determine the application name */
dict = (const NSDictionary *)CFBundleGetInfoDictionary(CFBundleGetMainBundle());
if (dict)
appName = [dict objectForKey: @"CFBundleName"];
if (![appName length])
appName = [[NSProcessInfo processInfo] processName];
return appName;
}
static PyObject*
_WMEnable(PyObject* self)
{
CPSProcessSerNum psn;
OSErr err;
const char* nameString;
NSString* nameNSString;
err = CPSGetCurrentProcess(&psn);
if (err == 0)
{
nameNSString = getApplicationName();
nameString = [nameNSString UTF8String];
CPSSetProcessName(&psn, nameString);
err = CPSEnableForegroundOperation(&psn,0x03,0x3C,0x2C,0x1103);
if (err == 0)
{
err = CPSSetFrontProcess(&psn);
if (err != 0)
{
return RAISE (PyExc_SDLError, "CPSSetFrontProcess failed");
}
}
else
{
return RAISE (PyExc_SDLError, "CPSEnableForegroundOperation failed");
}
}
else
{
return RAISE (PyExc_SDLError, "CPSGetCurrentProcess failed");
}
Py_RETURN_TRUE;
}
static PyObject*
_RunningFromBundleWithNSApplication(PyObject* self)
{
if (HasInstalledApplication)
{
Py_RETURN_TRUE;
}
CFBundleRef MainBundle = CFBundleGetMainBundle();
if (MainBundle != NULL)
{
if (CFBundleGetDataPointerForName(MainBundle, CFSTR("NSApp")) != NULL)
{
Py_RETURN_TRUE;
}
}
Py_RETURN_FALSE;
}
//#############################################################################
// Defining the NSApplication class we will use
//#############################################################################
@interface SDLApplication : NSApplication
@end
/* For some reaon, Apple removed setAppleMenu from the headers in 10.4,
but the method still is there and works. To avoid warnings, we declare
it ourselves here. */
@interface NSApplication(SDL_Missing_Methods)
- (void)setAppleMenu:(NSMenu *)menu;
@end
@implementation SDLApplication
/* Invoked from the Quit menu item */
- (void)terminate:(id)sender
{
SDL_Event event;
event.type = SDL_QUIT;
SDL_PushEvent(&event);
}
@end
static void setApplicationMenu(void)
{
NSMenu *appleMenu;
NSMenuItem *menuItem;
NSString *title;
NSString *appName;
appName = getApplicationName();
appleMenu = [[NSMenu alloc] initWithTitle:@""];
title = [@"About " stringByAppendingString:appName];
[appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""];
[appleMenu addItem:[NSMenuItem separatorItem]];
title = [@"Hide " stringByAppendingString:appName];
[appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
[menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
[appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
[appleMenu addItem:[NSMenuItem separatorItem]];
title = [@"Quit " stringByAppendingString:appName];
[appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
[menuItem setSubmenu:appleMenu];
[[NSApp mainMenu] addItem:menuItem];
[NSApp setAppleMenu:appleMenu];
[appleMenu release];
[menuItem release];
}
static void setupWindowMenu(void)
{
NSMenu *windowMenu;
NSMenuItem *windowMenuItem;
NSMenuItem *menuItem;
windowMenu = [[NSMenu alloc] initWithTitle:@"Window"];
menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"];
[windowMenu addItem:menuItem];
[menuItem release];
windowMenuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""];
[windowMenuItem setSubmenu:windowMenu];
[[NSApp mainMenu] addItem:windowMenuItem];
[NSApp setWindowsMenu:windowMenu];
[windowMenu release];
[windowMenuItem release];
}
static PyObject*
_InstallNSApplication(PyObject* self, PyObject* arg)
{
char* icon_data = NULL;
int data_len = 0;
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[SDLApplication sharedApplication];
if (PyArg_ParseTuple (arg, "|z#", &icon_data, &data_len))
{
NSData *image_data = [NSData dataWithBytes:icon_data length:data_len];
NSImage *icon_img = [[NSImage alloc] initWithData:image_data];
if (icon_img != NULL)
{
[NSApp setApplicationIconImage:icon_img];
}
}
[NSApp setMainMenu:[[NSMenu alloc] init]];
setApplicationMenu();
setupWindowMenu();
[NSApp finishLaunching];
[NSApp updateWindows];
[NSApp activateIgnoringOtherApps:true];
HasInstalledApplication = 1;
Py_RETURN_TRUE;
}
static PyMethodDef macosx_builtins[] =
{
{ "WMEnable", (PyCFunction) _WMEnable, METH_NOARGS, "Enables Foreground Operation when Window Manager is not available" },
{ "RunningFromBundleWithNSApplication", (PyCFunction) _RunningFromBundleWithNSApplication, METH_NOARGS, "Returns true if we are running from an AppBundle with a variable named NSApp" },
{ "InstallNSApplication", _InstallNSApplication, METH_VARARGS, "Creates an NSApplication with the right behaviors for SDL" },
{ NULL, NULL, 0, NULL}
};
MODINIT_DEFINE (sdlmain_osx)
{
PyObject *module;
/* create the module */
#if PY3
static struct PyModuleDef _module = {
PyModuleDef_HEAD_INIT,
MODPREFIX "sdlmain_osx",
NULL,
-1,
macosx_builtins,
NULL, NULL, NULL, NULL
};
#endif
#if PY3
module = PyModule_Create (&_module);
#else
module = Py_InitModule3 (MODPREFIX "sdlmain_osx", macosx_builtins, NULL);
#endif
/*imported needed apis*/
import_pygame_base ();
if (PyErr_Occurred ()) {
MODINIT_ERROR;
}
MODINIT_RETURN (module);
}
pygame-1.9.1release/src/scrap_x11.c 0000644 0001750 0001750 00000060771 10777222010 017010 0 ustar vincent vincent /*
pygame - Python Game Library
Copyright (C) 2006, 2007 Rene Dudfield, Marcus von Appen
Originally written and put in the public domain by Sam Lantinga.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include
static Display *SDL_Display;
static Window SDL_Window;
static void (*Lock_Display)(void);
static void (*Unlock_Display)(void);
/* Atoms used. */
static Atom _atom_UTF8;
static Atom _atom_TEXT;
static Atom _atom_COMPOUND;
static Atom _atom_MIME_PLAIN;
static Atom _atom_MIME_UTF8;
static Atom _atom_TARGETS;
static Atom _atom_TIMESTAMP;
static Atom _atom_SDL;
static Atom _atom_BMP;
static Atom _atom_CLIPBOARD;
/* Timestamps for the requests. */
static Time _cliptime = CurrentTime;
static Time _selectiontime = CurrentTime;
/* Maximum size to send or receive per request. */
#define MAX_CHUNK_SIZE(display) \
MIN(262144, /* 65536 * 4 */ \
(XExtendedMaxRequestSize (display)) == 0 \
? XMaxRequestSize (display) - 100 \
: XExtendedMaxRequestSize (display) - 100)
#define GET_CLIPATOM(x) ((x == SCRAP_SELECTION) ? XA_PRIMARY : _atom_CLIPBOARD)
static Atom _convert_format (char *type);
static void _init_atom_types (void);
static char* _atom_to_string (Atom a);
static void _add_clip_data (Atom type, char *data, int srclen);
static int _clipboard_filter (const SDL_Event *event);
static void _set_targets (PyObject *data, Display *display, Window window,
Atom property);
static int _set_data (PyObject *dict, Display *display, Window window,
Atom property, Atom target);
static Window _get_scrap_owner (Atom *selection);
static char* _get_data_as (Atom source, Atom format, unsigned long *length);
/**
* \brief Converts the passed type into a system specific type to use
* for the clipboard.
*
* \param type The type to convert.
* \return A system specific type.
*/
static Atom
_convert_format (char *type)
{
if (strcmp (type, PYGAME_SCRAP_PPM) == 0)
return XA_PIXMAP;
if (strcmp (type, PYGAME_SCRAP_PBM) == 0)
return XA_BITMAP;
return XInternAtom (SDL_Display, type, False);
}
/**
* \brief Initializes the used atom types.
*/
static void
_init_atom_types (void)
{
_atom_UTF8 = XInternAtom (SDL_Display, "UTF8_STRING", False);
_atom_TEXT = XInternAtom (SDL_Display, "TEXT", False);
_atom_COMPOUND = XInternAtom (SDL_Display, "COMPOUND_TEXT", False);
_atom_MIME_PLAIN = XInternAtom (SDL_Display, "text/plain", False);
_atom_MIME_UTF8 = XInternAtom (SDL_Display, "text/plain;charset=utf-8",
False);
_atom_TARGETS = XInternAtom (SDL_Display, "TARGETS", False);
_atom_TIMESTAMP = XInternAtom (SDL_Display, "TIMESTAMP", False);
_atom_SDL = XInternAtom (SDL_Display, "SDL_SELECTION", False);
_atom_BMP = XInternAtom (SDL_Display, PYGAME_SCRAP_BMP, False);
_atom_CLIPBOARD = XInternAtom (SDL_Display, "CLIPBOARD", False);
}
/**
* \brief Returns the name of the passed Atom. The result has to be
* freed by the caller using free().
*
* \param a The Atom to get the name for.
* \return The name of the Atom.
*/
static char*
_atom_to_string (Atom a)
{
char *name;
char *retval;
if (!a)
return NULL;
name = XGetAtomName (SDL_Display, a);
retval = strdup (name);
XFree (name);
return retval;
}
/**
* Adds additional data to the currently selected clipboard and Window
* if it does not already exist.
*
* \param cliptype The Atom to set the data for.
* \param data The data to set.
* \param srclen The length of the data.
*/
static void
_add_clip_data (Atom cliptype, char *data, int srclen)
{
Atom clip = GET_CLIPATOM(_currentmode);
PyObject* dict = (_currentmode == SCRAP_CLIPBOARD) ? _clipdata :
_selectiondata;
PyObject *tmp;
char *key = _atom_to_string (cliptype);
tmp = PyString_FromStringAndSize (data, srclen);
PyDict_SetItemString (dict, key, tmp);
Py_DECREF (tmp);
XChangeProperty (SDL_Display, SDL_Window, clip, cliptype,
8, PropModeReplace, (unsigned char *) data, srclen);
free (key);
}
/**
* \brief System message filter function -- handles X11 clipboard messages.
*
* \param event The SDL_Event to check.
* \return Always 1.
*/
static int
_clipboard_filter (const SDL_Event *event)
{
PyObject *dict = NULL;
Time timestamp = CurrentTime;
/* Post all non-window manager specific events */
if (event->type != SDL_SYSWMEVENT)
return 1;
XEvent xevent = event->syswm.msg->event.xevent;
/* Handle window-manager specific clipboard events */
switch (xevent.type)
{
case PropertyNotify:
{
/* Handled in pygame_scrap_put(). */
break;
}
case SelectionClear:
{
XSelectionClearEvent *clear = &xevent.xselectionclear;
/* Looks like another window takes control over the clipboard.
* Release the internally saved buffer, if any.
*/
if (clear->selection == XA_PRIMARY)
timestamp = _selectiontime;
else if(clear->selection == _atom_CLIPBOARD)
timestamp = _cliptime;
else
break;
/* Do not do anything, if the times do not match. */
if (timestamp != CurrentTime && xevent.xselectionclear.time < timestamp)
break;
/* Clean the dictionaries. */
if (clear->selection == XA_PRIMARY)
PyDict_Clear (_selectiondata);
else if (clear->selection != _atom_CLIPBOARD)
PyDict_Clear (_clipdata);
break;
}
case SelectionNotify:
/* This one will be handled directly in the pygame_scrap_get ()
* function.
*/
break;
case SelectionRequest:
{
XSelectionRequestEvent *req = &xevent.xselectionrequest;
XEvent ev;
/* Prepare answer. */
ev.xselection.type = SelectionNotify;
ev.xselection.display = req->display;
ev.xselection.requestor = req->requestor;
ev.xselection.selection = req->selection;
ev.xselection.target = req->target;
ev.xselection.property = None;
ev.xselection.time = req->time;
/* Which clipboard type was requested? */
if (req->selection == XA_PRIMARY)
{
dict = _selectiondata;
timestamp = _selectiontime;
}
else if (req->selection == _atom_CLIPBOARD)
{
dict = _clipdata;
timestamp = _cliptime;
}
else /* Anything else's not supported. */
{
XSendEvent (req->display, req->requestor, False, NoEventMask, &ev);
return 1;
}
/* No data? */
if (PyDict_Size (dict) == 0)
{
XSendEvent (req->display, req->requestor, False, NoEventMask, &ev);
return 1;
}
/* We do not own the selection anymore. */
if (timestamp == CurrentTime
|| (req->time != CurrentTime && timestamp > req->time))
{
XSendEvent (req->display, req->requestor, False, NoEventMask, &ev);
return 1;
}
/*
* TODO: We have to make it ICCCM compatible at some point by
* implementing the MULTIPLE atom request.
*/
/* Old client? */
if (req->property == None)
ev.xselection.property = req->target;
if (req->target == _atom_TARGETS)
{
/* The requestor wants to know, what we've got. */
_set_targets (dict, req->display, req->requestor, req->property);
}
else
{
_set_data (dict, req->display, req->requestor, req->property,
req->target);
}
ev.xselection.property = req->property;
/* Post the event for X11 clipboard reading above */
XSendEvent (req->display, req->requestor, False, 0, &ev);
break;
}
}
return 1;
}
/**
* Sets the list of target atoms available in the clipboard.
*
* \param data The clipboard dictionary.
* \param display The requesting Display.
* \param window The requesting Window.
* \param property The request property to place the list into.
*/
static void
_set_targets (PyObject *data, Display *display, Window window, Atom property)
{
int i;
char *format;
PyObject *list = PyDict_Keys (data);
int amount = PyList_Size (list);
/* All types plus the TARGETS and a TIMESTAMP atom. */
Atom *targets = malloc ((amount + 2) * sizeof (Atom));
if (targets == NULL)
return;
memset (targets, 0, (amount + 2) * sizeof (Atom));
targets[0] = _atom_TARGETS;
targets[1] = _atom_TIMESTAMP;
for (i = 0; i < amount; i++)
{
format = PyString_AsString (PyList_GetItem(list, i));
targets[i + 2] = _convert_format (format);
}
XChangeProperty (display, window, property, XA_ATOM, 32, PropModeReplace,
(unsigned char*) targets, amount + 2);
}
/**
* Places the requested Atom data into a Window.
*
* \param data The clipboard dictionary.
* \param display The requesting Display.
* \param window The requesting Window.
* \param property The request property to place the list into.
* \param target The target porperty to place the list into.
* \return 0 if no data for the target is available, 1 on success.
*/
static int
_set_data (PyObject *data, Display *display, Window window, Atom property,
Atom target)
{
char *name = _atom_to_string (target);
PyObject *val = PyDict_GetItemString (data, name);
char *value = NULL;
int size;
if (!val)
{
XFree (name);
return 0;
}
size = PyString_Size (val);
value = PyString_AsString (val);
/* Send data. */
XChangeProperty (display, window, property, target, 8, PropModeReplace,
(unsigned char *) value, size);
XFree (name);
return 1;
}
/**
* \brief Tries to determine the X window with a valid selection.
* Default is to check
* - passed parameter
* - CLIPBOARD
* - XA_PRIMARY
* - XA_SECONDARY
* - XA_CUT_BUFFER0 - 7
*
* in this order.
*
* \param selection The Atom type, that should be tried before any of the
* fixed XA_* buffers.
* \return The Window handle, that owns the selection or None if none was
* found.
*/
static Window
_get_scrap_owner (Atom *selection)
{
int i = 0;
static Atom buffers[] = { XA_PRIMARY, XA_SECONDARY, XA_CUT_BUFFER0,
XA_CUT_BUFFER1, XA_CUT_BUFFER2, XA_CUT_BUFFER3,
XA_CUT_BUFFER4, XA_CUT_BUFFER5, XA_CUT_BUFFER6,
XA_CUT_BUFFER7 };
Window owner = XGetSelectionOwner (SDL_Display, *selection);
if (owner != None)
return owner;
owner = XGetSelectionOwner (SDL_Display, _atom_CLIPBOARD);
if (owner != None)
return owner;
while (i < 10)
{
owner = XGetSelectionOwner (SDL_Display, buffers[i]);
if (owner != None)
{
*selection = buffers[i];
return owner;
}
i++;
}
return None;
}
/**
* Retrieves the data from a certain source Atom using a specific
* format.
*
* \param source The currently active clipboard Atom to get the data from.
* \param format The format of the data to get.
* \param length Out parameter that contains the length of the returned
* buffer.
* \return The requested content or NULL in case no content exists or an
* error occured.
*/
static char*
_get_data_as (Atom source, Atom format, unsigned long *length)
{
char *retval = NULL;
Window owner;
time_t start;
Atom sel_type;
int sel_format;
unsigned long nbytes;
unsigned long overflow;
*length = 0;
unsigned char *src;
unsigned long offset = 0;
unsigned long chunk = 0;
int step = 1;
XEvent ev;
Time timestamp;
/* If we are the owner, simply return the clip buffer, if it matches
* the request type.
*/
if (!pygame_scrap_lost ())
{
char *fmt;
char *data;
fmt = _atom_to_string (format);
if (_currentmode == SCRAP_SELECTION)
data = PyString_AsString
(PyDict_GetItemString (_selectiondata, fmt));
else
data = PyString_AsString (PyDict_GetItemString (_clipdata, fmt));
free (fmt);
return data;
}
Lock_Display ();
/* Find a selection owner. */
owner = _get_scrap_owner (&source);
if (owner == None)
{
Unlock_Display ();
return NULL;
}
timestamp = (source == XA_PRIMARY) ? _selectiontime : _cliptime;
/* Copy and convert the selection into our SDL_SELECTION atom of the
* window.
* Flush afterwards, so we have an immediate effect and do not receive
* the old buffer anymore.
*/
XConvertSelection (SDL_Display, source, format, _atom_SDL, SDL_Window,
timestamp);
XSync (SDL_Display, False);
/* Let's wait for the SelectionNotify event from the callee and
* react upon it as soon as it is received.
*/
for (start = time (0);;)
{
if (XCheckTypedWindowEvent (SDL_Display, SDL_Window,
SelectionNotify, &ev))
break;
if (time (0) - start >= 5)
{
/* Timeout, damn. */
Unlock_Display ();
return NULL;
}
}
/* Get any property type and check the sel_type afterwards to decide
* what to do.
*/
if (XGetWindowProperty (SDL_Display, ev.xselection.requestor,
_atom_SDL, 0, 0, True,
AnyPropertyType, &sel_type, &sel_format,
&nbytes, &overflow, &src) != Success)
{
XFree (src);
Unlock_Display ();
return NULL;
}
/* In case we requested a SCRAP_TEXT, any property type of
* XA_STRING, XA_COMPOUND_TEXT, UTF8_STRING and TEXT is valid.
*/
if (format == _atom_MIME_PLAIN &&
(sel_type != _atom_UTF8 && sel_type != _atom_TEXT
&& sel_type != _atom_COMPOUND && sel_type != XA_STRING))
{
/* No matching text type found. Return nothing then. */
XFree (src);
Unlock_Display ();
return NULL;
}
/* Anything is fine, so copy the buffer and return it. */
switch (sel_format)
{
case 16:
step = sizeof (short) / 2;
break;
case 32:
step = sizeof (long) / 4;
break;
case 8:
default:
step = sizeof (char);
*length = overflow; /* 8 bit size is already correctly set in nbytes.*/
break;
}
/* X11 guarantees NULL termination, add an extra byte. */
*length = step * overflow;
retval = malloc (*length + 1);
if (retval)
{
unsigned long boffset = 0;
chunk = MAX_CHUNK_SIZE(SDL_Display);
memset (retval, 0, (size_t) (*length + 1));
/* Read as long as there is data. */
while (overflow)
{
if (XGetWindowProperty (SDL_Display, ev.xselection.requestor,
_atom_SDL, offset, chunk, True,
AnyPropertyType, &sel_type, &sel_format,
&nbytes, &overflow, &src) != Success)
{
break;
}
offset += nbytes / (32 / sel_format);
nbytes *= step * sel_format / 8;
memcpy (retval + boffset, src, nbytes);
boffset += nbytes;
XFree (src);
}
}
else
{
/* ENOMEM */
return NULL;
}
/* In case we've got a COMPOUND_TEXT, convert it to the current
* multibyte locale.
*/
if (sel_type == _atom_COMPOUND && sel_format == 8)
{
char **list = NULL;
int count;
int status = 0;
XTextProperty p;
p.encoding = sel_type;
p.format = sel_format;
p.nitems = nbytes;
p.value = retval;
status = XmbTextPropertyToTextList (SDL_Display, &p, &list, &count);
if (status == XLocaleNotSupported || status == XConverterNotFound)
{
free (retval);
PyErr_SetString (PyExc_SDLError,
"current locale is not supported for conversion.");
return NULL;
}
else if (status == XNoMemory)
{
free (retval);
return NULL;
}
else if (status == Success)
{
if (count && list)
{
int i = 0;
int ioffset = 0;
char *tmp;
free (retval);
retval = NULL;
for (i = 0; i < count; i++)
{
*length = strlen (list[i]);
tmp = retval;
retval = realloc (retval, (*length) + 1);
if (!retval)
{
free (tmp);
return NULL;
}
ioffset += *length;
memcpy (retval, list[i], *length);
memset (retval + ioffset, '\n', 1);
}
memset (retval + ioffset, 0, 1);
}
}
if (list)
XFreeStringList (list);
}
Unlock_Display ();
return retval;
}
int
pygame_scrap_init (void)
{
SDL_SysWMinfo info;
int retval = 0;
/* Grab the window manager specific information */
SDL_SetError ("SDL is not running on known window manager");
SDL_VERSION (&info.version);
if (SDL_GetWMInfo (&info))
{
/* Save the information for later use */
if (info.subsystem == SDL_SYSWM_X11)
{
XWindowAttributes setattrs;
XSetWindowAttributes newattrs;
newattrs.event_mask = PropertyChangeMask;
SDL_Display = info.info.x11.display;
SDL_Window = info.info.x11.window;
Lock_Display = info.info.x11.lock_func;
Unlock_Display = info.info.x11.unlock_func;
Lock_Display ();
/* We need the PropertyNotify event for the timestap, so
* modify the event attributes.
*/
XGetWindowAttributes (SDL_Display, SDL_Window, &setattrs);
newattrs.event_mask |= setattrs.all_event_masks;
XChangeWindowAttributes
(SDL_Display, SDL_Window, CWEventMask, &newattrs);
Unlock_Display ();
/* Enable the special window hook events */
SDL_EventState (SDL_SYSWMEVENT, SDL_ENABLE);
SDL_SetEventFilter (_clipboard_filter);
/* Create the atom types we need. */
_init_atom_types ();
retval = 1;
}
else
SDL_SetError ("SDL is not running on X11");
}
if (retval)
_scrapinitialized = 1;
return retval;
}
int
pygame_scrap_lost (void)
{
int retval;
if (!pygame_scrap_initialized ())
{
PyErr_SetString (PyExc_SDLError, "scrap system not initialized.");
return 0;
}
Lock_Display ();
retval = (XGetSelectionOwner (SDL_Display, GET_CLIPATOM (_currentmode))
!= SDL_Window);
Unlock_Display ();
return retval;
}
int
pygame_scrap_put (char *type, int srclen, char *src)
{
Atom clip;
Atom cliptype;
Time timestamp = CurrentTime;
time_t start;
XEvent ev;
if (!pygame_scrap_initialized ())
{
PyErr_SetString (PyExc_SDLError, "scrap system not initialized.");
return 0;
}
Lock_Display ();
clip = GET_CLIPATOM (_currentmode);
cliptype = _convert_format (type);
/* We've some types which should not be set by the user. */
if (cliptype == _atom_TARGETS || cliptype == _atom_SDL
|| cliptype == _atom_TIMESTAMP)
{
PyErr_SetString (PyExc_ValueError, "the requested type is reserved.");
Unlock_Display ();
return 0;
}
/* Update the clipboard property with the buffer. */
XChangeProperty (SDL_Display, SDL_Window, clip, cliptype,
8, PropModeReplace, (unsigned char *) src, srclen);
if (cliptype == _atom_MIME_PLAIN)
{
/* Set PYGAME_SCRAP_TEXT. Also set XA_STRING, TEXT and
* UTF8_STRING if they are not set in the dictionary.
*/
_add_clip_data (XA_STRING, src, srclen);
_add_clip_data (_atom_UTF8, src, srclen);
_add_clip_data (_atom_TEXT, src, srclen);
}
XSync (SDL_Display, False);
/* Update the timestamp */
for (start = time (0);;)
{
if (XCheckTypedWindowEvent (SDL_Display, SDL_Window,
PropertyNotify, &ev))
break;
if (time (0) - start >= 5)
{
/* Timeout, damn. */
Unlock_Display ();
goto SETSELECTIONOWNER;
}
}
if (ev.xproperty.atom == clip)
{
timestamp = ev.xproperty.time;
if (cliptype == XA_PRIMARY)
_selectiontime = timestamp;
else
_cliptime = timestamp;
}
else
timestamp = (cliptype == XA_PRIMARY) ? _selectiontime : _cliptime;
SETSELECTIONOWNER:
/* Set the selection owner to the own window. */
XSetSelectionOwner (SDL_Display, clip, SDL_Window, timestamp);
if (XGetSelectionOwner (SDL_Display, clip) != SDL_Window)
{
/* Ouch, we could not toggle the selection owner. Raise an
* error, as it's not guaranteed, that the clipboard
* contains valid data.
*/
Unlock_Display ();
return 0;
}
Unlock_Display ();
return 1;
}
char*
pygame_scrap_get (char *type, unsigned long *count)
{
if (!pygame_scrap_initialized ())
{
PyErr_SetString (PyExc_SDLError, "scrap system not initialized.");
return NULL;
}
return _get_data_as (GET_CLIPATOM (_currentmode),
_convert_format (type), count);
}
int
pygame_scrap_contains (char *type)
{
int i = 0;
char **types = pygame_scrap_get_types ();
while (types[i])
{
if (strcmp (type, types[i]) == 0)
return 1;
i++;
}
return 0;
}
char**
pygame_scrap_get_types (void)
{
char **types;
Atom *targetdata;
unsigned long length;
if (!pygame_scrap_lost ())
{
PyObject *key;
int pos = 0;
int i = 0;
PyObject *dict = (_currentmode == SCRAP_SELECTION) ? _selectiondata :
_clipdata;
types = malloc (sizeof (char*) * (PyDict_Size (dict) + 1));
if (!types)
return NULL;
memset (types, 0, (size_t) (PyDict_Size (dict) + 1));
while (PyDict_Next (dict, &pos, &key, NULL))
{
types[i] = strdup (PyString_AsString (key));
if (!types[i])
{
/* Could not allocate memory, free anything. */
int j = 0;
while (types[j])
{
free (types[j]);
j++;
}
free (types);
return NULL;
}
i++;
}
types[i] = NULL;
return types;
}
targetdata = (Atom *) _get_data_as (GET_CLIPATOM (_currentmode),
_atom_TARGETS, &length);
if (length > 0 && targetdata != NULL)
{
Atom *data = targetdata;
int count = length / sizeof (Atom);
int i;
char **targets = malloc (sizeof (char *) * (count + 1));
if (targets == NULL)
{
free (targetdata);
return NULL;
}
memset (targets, 0, sizeof (char *) * (count + 1));
for (i = 0; i < count; i++)
targets[i] = _atom_to_string (data[i]);
free (targetdata);
return targets;
}
return NULL;
}
pygame-1.9.1release/src/scrap_win.c 0000644 0001750 0001750 00000024766 11115660462 017204 0 ustar vincent vincent /*
pygame - Python Game Library
Copyright (C) 2006, 2007 Rene Dudfield, Marcus von Appen
Originally written and put in the public domain by Sam Lantinga.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include
#if !defined(CF_DIBV5)
/* Missing from the MinGW win32api-3.11 winuser.h header */
#define CF_DIBV5 17
#endif
static HWND SDL_Window;
#define MAX_CHUNK_SIZE INT_MAX
static UINT _format_MIME_PLAIN;
/**
* \brief Converts the passed type into a system specific clipboard type
* to use for the clipboard.
*
* \param type The type to convert.
* \return A system specific type.
*/
static UINT
_convert_format (char *type)
{
return RegisterClipboardFormat (type);
}
/**
* \brief Gets a system specific clipboard format type for a certain type.
*
* \param type The name of the format to get the mapped format type for.
* \return The format type or -1 if no such type was found.
*/
static UINT
_convert_internal_type (char *type)
{
if (strcmp (type, PYGAME_SCRAP_TEXT) == 0)
return CF_TEXT;
if (strcmp (type, "text/plain;charset=utf-8") == 0)
return CF_UNICODETEXT;
if (strcmp (type, "image/tiff") == 0)
return CF_TIFF;
if (strcmp (type, PYGAME_SCRAP_BMP) == 0)
return CF_DIB;
if (strcmp (type, "audio/wav") == 0)
return CF_WAVE;
return -1;
}
/**
* \brief Looks up the name for the specific clipboard format type.
*
* \param format The format to get the name for.
* \param buf The buffer to copy the name into.
* \param size The size of the buffer.
* \return The length of the format name.
*/
static int
_lookup_clipboard_format (UINT format, char *buf, int size)
{
int len;
char *cpy;
memset (buf, 0, size);
switch (format)
{
case CF_TEXT:
len = strlen (PYGAME_SCRAP_TEXT);
cpy = PYGAME_SCRAP_TEXT;
break;
case CF_UNICODETEXT:
len = 24;
cpy = "text/plain;charset=utf-8";
break;
case CF_TIFF:
len = 10;
cpy = "image/tiff";
break;
case CF_DIB:
len = strlen (PYGAME_SCRAP_BMP);
cpy = PYGAME_SCRAP_BMP;
break;
case CF_WAVE:
len = 9;
cpy = "audio/wav";
break;
default:
len = GetClipboardFormatName (format, buf, size);
return len;
}
if (len != 0)
memcpy (buf, cpy, len);
return len;
}
/**
* \brief Creates a BMP character buffer with all headers from a DIB
* HANDLE. The caller has to free the returned buffer.
* \param data The DIB handle data.
* \param count The size of the DIB handle.
* \return The character buffer containing the BMP information.
*/
static char*
_create_dib_buffer (char* data, unsigned long *count)
{
BITMAPFILEHEADER hdr;
LPBITMAPINFOHEADER bihdr;
char *buf;
if (!data)
return NULL;
bihdr = (LPBITMAPINFOHEADER) data;
/* Create the BMP header. */
hdr.bfType = 'M' << 8 | 'B'; /* Specs say, it is always BM */
hdr.bfReserved1 = 0;
hdr.bfReserved2 = 0;
hdr.bfSize = (DWORD) (sizeof (BITMAPFILEHEADER) + bihdr->biSize
+ bihdr->biClrUsed * sizeof (RGBQUAD)
+ bihdr->biSizeImage);
hdr.bfOffBits = (DWORD) (sizeof (BITMAPFILEHEADER) + bihdr->biSize
+ bihdr->biClrUsed * sizeof (RGBQUAD));
/* Copy both to the buffer. */
buf = malloc (sizeof (hdr) + (*count));
if (!buf)
return NULL;
memcpy (buf, &hdr, sizeof (hdr));
memcpy (buf + sizeof (BITMAPFILEHEADER), data, *count);
/* Increase count for the correct size. */
*count += sizeof (hdr);
return buf;
}
int
pygame_scrap_init (void)
{
SDL_SysWMinfo info;
int retval = 0;
/* Grab the window manager specific information */
SDL_SetError ("SDL is not running on known window manager");
SDL_VERSION (&info.version);
if (SDL_GetWMInfo (&info))
{
/* Save the information for later use */
SDL_Window = info.window;
retval = 1;
}
if (retval)
_scrapinitialized = 1;
_format_MIME_PLAIN = RegisterClipboardFormat (PYGAME_SCRAP_TEXT);
return retval;
}
int
pygame_scrap_lost (void)
{
if (!pygame_scrap_initialized ())
{
PyErr_SetString (PyExc_SDLError, "scrap system not initialized.");
return 0;
}
return (GetClipboardOwner () != SDL_Window);
}
int
pygame_scrap_put (char *type, int srclen, char *src)
{
UINT format;
int nulledlen = srclen + 1;
HANDLE hMem;
if (!pygame_scrap_initialized ())
{
PyErr_SetString (PyExc_SDLError, "scrap system not initialized.");
return 0;
}
format = _convert_internal_type (type);
if (format == -1)
format = _convert_format (type);
if (!OpenClipboard (SDL_Window))
return 0; /* Could not open the clipboard. */
if (format == CF_DIB || format == CF_DIBV5)
nulledlen -= sizeof (BITMAPFILEHEADER); /* We won't copy the header */
hMem = GlobalAlloc ((GMEM_MOVEABLE | GMEM_DDESHARE), nulledlen);
if (hMem)
{
char *dst = GlobalLock (hMem);
memset (dst, 0, nulledlen);
if (format == CF_DIB || format == CF_DIBV5)
memcpy (dst, src + sizeof (BITMAPFILEHEADER), nulledlen - 1);
else
memcpy (dst, src, srclen);
GlobalUnlock (hMem);
EmptyClipboard ();
SetClipboardData (format, hMem);
if (format == _format_MIME_PLAIN)
{
/* Setting SCRAP_TEXT, also set CF_TEXT. */
SetClipboardData (CF_TEXT, hMem);
}
}
else
{
/* Could not access the clipboard, raise an error. */
CloseClipboard ();
return 0;
}
CloseClipboard ();
return 1;
}
char*
pygame_scrap_get (char *type, unsigned long *count)
{
UINT format = _convert_format (type);
char *retval = NULL;
if (!pygame_scrap_initialized ())
{
PyErr_SetString (PyExc_SDLError, "scrap system not initialized.");
return NULL;
}
if (!pygame_scrap_lost ())
return PyString_AsString (PyDict_GetItemString (_clipdata, type));
if (!OpenClipboard (SDL_Window))
return NULL;
if (!IsClipboardFormatAvailable (format))
{
/* The format was not found - was it a mapped type? */
format = _convert_internal_type (type);
if (format == -1)
{
CloseClipboard ();
return NULL;
}
}
if (IsClipboardFormatAvailable (format))
{
HANDLE hMem;
char *src;
src = NULL;
hMem = GetClipboardData (format);
if (hMem)
{
*count = 0;
/* CF_BITMAP is not a global, so do not lock it. */
if (format != CF_BITMAP)
{
src = GlobalLock (hMem);
if (!src)
{
CloseClipboard ();
return NULL;
}
*count = GlobalSize (hMem);
}
if (format == CF_DIB || format == CF_DIBV5)
{
/* Count will be increased accordingly in
* _create_dib_buffer.
*/
src = _create_dib_buffer (src, count);
GlobalUnlock (hMem);
CloseClipboard ();
return src;
}
else if (*count != 0)
{
/* weird error, shouldn't get here. */
if(!src) {
return NULL;
}
retval = malloc (*count);
if (retval)
{
memset (retval, 0, *count);
memcpy (retval, src, *count);
}
}
GlobalUnlock (hMem);
}
}
CloseClipboard ();
return retval;
}
char**
pygame_scrap_get_types (void)
{
UINT format = 0;
char **types = NULL;
char **tmptypes;
int i = 0;
int count = -1;
int len;
char tmp[100] = { '\0' };
int size = 0;
if (!OpenClipboard (SDL_Window))
return NULL;
size = CountClipboardFormats ();
if (size == 0)
{
CloseClipboard ();
return NULL; /* No clipboard data. */
}
for (i = 0; i < size; i++)
{
format = EnumClipboardFormats (format);
if (format == 0)
{
/* Something wicked happened. */
while (i > 0)
free (types[i]);
free (types);
CloseClipboard ();
return NULL;
}
/* No predefined name, get the (truncated) name. */
len = _lookup_clipboard_format (format, tmp, 100);
if (len == 0)
continue;
count++;
tmptypes = realloc (types, sizeof (char *) * (count + 1));
if (!tmptypes)
{
while (count > 0)
{
free (types[count]);
count--;
}
free (types);
CloseClipboard ();
return NULL;
}
types = tmptypes;
types[count] = malloc (sizeof (char) * (len + 1));
if (!types[count])
{
while (count > 0)
{
free (types[count]);
count--;
}
free (types);
CloseClipboard ();
return NULL;
}
memset (types[count], 0, len + 1);
memcpy (types[count], tmp, len);
}
tmptypes = realloc (types, sizeof (char *) * (count + 1));
if (!tmptypes)
{
while (count > 0)
{
free (types[count]);
count--;
}
free (types);
CloseClipboard ();
return NULL;
}
types = tmptypes;
types[count] = NULL;
CloseClipboard ();
return types;
}
int
pygame_scrap_contains (char *type)
{
return IsClipboardFormatAvailable (_convert_format(type));
}
pygame-1.9.1release/src/scrap_qnx.c 0000644 0001750 0001750 00000014405 10613762403 017202 0 ustar vincent vincent /*
pygame - Python Game Library
Copyright (C) 2006, 2007 Rene Dudfield, Marcus von Appen
Originally written and put in the public domain by Sam Lantinga.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
static unsigned short InputGroup;
#define MAX_CHUNK_SIZE INT_MAX
/**
* \brief Converts the passed type into a system specific type to use
* for the clipboard.
*
* \param type The type to convert.
* \return A system specific type.
*/
static uint32_t
_convert_format (char *type)
{
switch (type)
{
case PYGAME_SCRAP_TEXT:
return Ph_CL_TEXT;
default: /* PYGAME_SCRAP_BMP et al. */
{
/* TODO */
return 0;
}
}
}
int
pygame_scrap_init (void)
{
SDL_SysWMinfo info;
int retval = 0;
/* Grab the window manager specific information */
SDL_SetError ("SDL is not running on known window manager");
SDL_VERSION (&info.version);
if (SDL_GetWMInfo (&info))
{
/* Save the information for later use */
InputGroup = PhInputGroup (NULL);
retval = 1;
}
if (retval)
_scrapinitialized = 1;
return retval;
}
int
pygame_scrap_lost (void)
{
if (!pygame_scrap_initialized ())
{
PyErr_SetString (PyExc_SDLError, "scrap system not initialized.");
return 0;
}
return (PhInputGroup (NULL) != InputGroup);
}
int
pygame_scrap_put (char *type, int srclen, char *src)
{
uint32_t format;
int nulledlen = srclen + 1;
if (!pygame_scrap_initialized ())
{
PyErr_SetString (PyExc_SDLError, "scrap system not initialized.");
return 0;
}
format = _convert_format (type);
/* Clear old buffer and copy the new content. */
if (_clipbuffer)
free (_clipbuffer);
_clipbuffer = malloc (nulledlen);
if (!_clipbuffer)
return 0; /* Allocation failed. */
memset (_clipbuffer, 0, nulledlen);
memcpy (_clipbuffer, src, srclen);
_clipsize = srclen;
_cliptype = format;
#if (_NTO_VERSION < 620) /* Before 6.2.0 releases. */
{
PhClipHeader clheader = { Ph_CLIPBOARD_TYPE_TEXT, 0, NULL };
int* cldata;
int status;
cldata = (int *) _clipbuffer;
*cldata = type;
clheader.data = _clipbuffer;
if (dstlen > 65535)
clheader.length = 65535; /* Maximum photon clipboard size. :( */
else
clheader.length = nulledlen;
status = PhClipboardCopy (InputGroup, 1, &clheader);
if (status == -1)
{
/* Could not access the clipboard, raise an error. */
CLEAN_CLIP_BUFFER ();
return 0;
}
}
#else /* 6.2.0 and 6.2.1 and future releases. */
{
PhClipboardHdr clheader = { Ph_CLIPBOARD_TYPE_TEXT, 0, NULL };
int* cldata;
int status;
cldata = (int *) _clipbuffer;
*cldata = type;
clheader.data = _clipbuffer;
clheader.length = nulledlen;
status = PhClipboardWrite (InputGroup, 1, &clheader);
if (status == -1)
{
/* Could not access the clipboard, raise an error. */
CLEAN_CLIP_BUFFER ();
return 0;
}
}
#endif
return 1;
}
char*
pygame_get_scrap (char *type)
{
uint32_t format = _convert_format (type);
char *retval = NULL;
if (!pygame_scrap_initialized ())
{
PyErr_SetString (PyExc_SDLError, "scrap system not initialized.");
return 0;
}
/* If we are the owner, simply return the clip buffer, if it matches
* the request type. */
if (!pygame_scrap_lost ())
{
if (format != _cliptype)
return NULL;
if (_clipbuffer)
{
retval = malloc (_clipsize + 1);
if (!retval)
return NULL;
memset (retval, 0, _clipsize + 1);
memcpy (retval, _clipbuffer, _clipsize + 1);
return retval;
}
return NULL;
}
#if (_NTO_VERSION < 620) /* before 6.2.0 releases */
{
void *clhandle;
PhClipHeader *clheader;
int *cldata;
clhandle = PhClipboardPasteStart (InputGroup);
if (clhandle)
{
clheader = PhClipboardPasteType (clhandle, Ph_CLIPBOARD_TYPE_TEXT);
if (clheader)
{
cldata = clheader->data;
if (*cldata == type)
retval = malloc (clheader->length + 1);
if (retval)
{
memset (retval, 0, clheader->length + 1);
memcpy (retval, cldata, clheader->length + 1);
}
}
PhClipboardPasteFinish (clhandle);
}
}
#else /* 6.2.0 and 6.2.1 and future releases */
{
void* clhandle;
PhClipboardHdr* clheader;
int* cldata;
clheader = PhClipboardRead (InputGroup, Ph_CLIPBOARD_TYPE_TEXT);
if (clheader)
{
cldata = clheader->data;
if (*cldata == type)
retval = malloc (clheader->length + 1);
if (retval)
{
memset (retval, 0, clheader->length + 1);
memcpy (retval, cldata, clheader->length + 1);
}
/* According to the QNX 6.x docs, the clheader pointer is a
* newly created one that must be freed manually. */
free (clheader->data);
free (clheader);
}
}
#endif
return retval;
}
char**
pygame_scrap_get_types (void)
{
return NULL;
}
int
pygame_scrap_contains (char *type)
{
return 0;
}
pygame-1.9.1release/src/scrap_mac.c 0000644 0001750 0001750 00000004241 10615735766 017147 0 ustar vincent vincent /*
pygame - Python Game Library
Copyright (C) 2006, 2007 Rene Dudfield, Marcus von Appen
Originally written and put in the public domain by Sam Lantinga.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
static PyObject*
mac_scrap_call (char *name, PyObject *args)
{
static PyObject *mac_scrap_module = NULL;
PyObject *method;
PyObject *result;
if (!mac_scrap_module)
mac_scrap_module = PyImport_ImportModule ("pygame.mac_scrap");
if (!mac_scrap_module)
return NULL;
method = PyObject_GetAttrString (mac_scrap_module, name);
if (!method)
return NULL;
result = PyObject_CallObject (method, args);
Py_DECREF (method);
return result;
}
static PyObject*
_scrap_init (PyObject *self, PyObject *args)
{
return mac_scrap_call ("init", args);
}
static PyObject*
_scrap_get_scrap (PyObject *self, PyObject *args)
{
return mac_scrap_call ("get", args);
}
static PyObject*
_scrap_put_scrap (PyObject *self, PyObject *args)
{
return mac_scrap_call ("put", args);
}
static PyObject*
_scrap_lost_scrap (PyObject *self, PyObject *args)
{
return mac_scrap_call ("lost", args);
}
static PyObject*
_scrap_get_types (PyObject *self, PyObject *args)
{
return mac_scrap_call ("get_types", args);
}
static PyObject*
_scrap_contains (PyObject *self, PyObject *args)
{
return mac_scrap_call ("contains", args);
}
static PyObject*
_scrap_set_mode (PyObject *self, PyObject *args)
{
return mac_scrap_call ("set_mode", args);
}
pygame-1.9.1release/src/scrap.h 0000644 0001750 0001750 00000010606 10740376474 016332 0 ustar vincent vincent /*
pygame - Python Game Library
Copyright (C) 2006, 2007 Rene Dudfield, Marcus von Appen
Originally put in the public domain by Sam Lantinga.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include
/* Handle clipboard text and data in arbitrary formats */
/**
* Predefined supported pygame scrap types.
*/
#define PYGAME_SCRAP_TEXT "text/plain"
#define PYGAME_SCRAP_BMP "image/bmp"
#define PYGAME_SCRAP_PPM "image/ppm"
#define PYGAME_SCRAP_PBM "image/pbm"
/**
* The supported scrap clipboard types.
*
* This is only relevant in a X11 environment, which supports mouse
* selections as well. For Win32 and MacOS environments the default
* clipboard is used, no matter what value is passed.
*/
typedef enum
{
SCRAP_CLIPBOARD,
SCRAP_SELECTION /* only supported in X11 environments. */
} ScrapClipType;
/**
* Macro for initialization checks.
*/
#define PYGAME_SCRAP_INIT_CHECK() \
if(!pygame_scrap_initialized()) \
return (PyErr_SetString (PyExc_SDLError, \
"scrap system not initialized."), NULL)
/**
* \brief Checks, whether the pygame scrap module was initialized.
*
* \return 1 if the modules was initialized, 0 otherwise.
*/
extern int
pygame_scrap_initialized (void);
/**
* \brief Initializes the pygame scrap module internals. Call this before any
* other method.
*
* \return 1 on successful initialization, 0 otherwise.
*/
extern int
pygame_scrap_init (void);
/**
* \brief Checks, whether the pygame window lost the clipboard focus or not.
*
* \return 1 if the window lost the focus, 0 otherwise.
*/
extern int
pygame_scrap_lost (void);
/**
* \brief Places content of a specific type into the clipboard.
*
* \note For X11 the following notes are important: The following types
* are reserved for internal usage and thus will throw an error on
* setting them: "TIMESTAMP", "TARGETS", "SDL_SELECTION".
* Setting PYGAME_SCRAP_TEXT ("text/plain") will also automatically
* set the X11 types "STRING" (XA_STRING), "TEXT" and "UTF8_STRING".
*
* For Win32 the following notes are important: Setting
* PYGAME_SCRAP_TEXT ("text/plain") will also automatically set
* the Win32 type "TEXT" (CF_TEXT).
*
* For QNX the following notes are important: Setting
* PYGAME_SCRAP_TEXT ("text/plain") will also automatically set
* the QNX type "TEXT" (Ph_CL_TEXT).
*
* \param type The type of the content.
* \param srclen The length of the content.
* \param src The NULL terminated content.
* \return 1, if the content could be successfully pasted into the clipboard,
* 0 otherwise.
*/
extern int
pygame_scrap_put (char *type, int srclen, char *src);
/**
* \brief Gets the current content from the clipboard.
*
* \note The received content does not need to be the content previously
* placed in the clipboard using pygame_put_scrap(). See the
* pygame_put_scrap() notes for more details.
*
* \param type The type of the content to receive.
* \param count The size of the returned content.
* \return The content or NULL in case of an error or if no content of the
* specified type was available.
*/
extern char*
pygame_scrap_get (char *type, unsigned long *count);
/**
* \brief Gets the currently available content types from the clipboard.
*
* \return The different available content types or NULL in case of an
* error or if no content type is available.
*/
extern char**
pygame_scrap_get_types (void);
/**
* \brief Checks whether content for the specified scrap type is currently
* available in the clipboard.
*
* \param type The type to check for.
* \return 1, if there is content and 0 otherwise.
*/
extern int
pygame_scrap_contains (char *type);
pygame-1.9.1release/src/scrap.doc 0000644 0001750 0001750 00000012547 11204402244 016633 0 ustar vincent vincent pygame.scrap
pygame module for clipboard support.
EXPERIMENTAL!: meaning this api may change, or dissapear in later
pygame releases. If you use this, your code will break with the
next pygame release.
The scrap module is for getting and putting stuff from the clipboard.
So you can copy and paste things between pygame, and other application
types. It defines some basic own data types
SCRAP_PPM
SCRAP_PBM
SCRAP_BMP
SCRAP_TEXT
to be placed into the clipboard and allows to use define own clipboard
types. SCRAP_PPM, SCRAP_PBM and SCRAP_BMP are suitable for surface
buffers to be shared with other applications, while SCRAP_TEXT is an
alias for the plain text clipboard type.
The SCRAP_* types refer to the following MIME types and register those
as well as the default operating system type for this type of data:
SCRAP_TEXT text/plain for plain text
SCRAP_PBM image/pbm for PBM encoded image data
SCRAP_PPM image/ppm for PPM encoded image data
SCRAP_BMP image/bmp for BMP encoded image data
Depending on the platform additional types are automatically registered
when data is placed into the clipboard to guarantee a consistent sharing
behaviour with other applications. The following listed types can be
used as string to be passed to the respective pygame.scrap module
functions.
For Windows platforms, the additional types are supported automatically
and resolve to their internal definitions:
text/plain;charset=utf-8 for UTF-8 encoded text
audio/wav for WAV encoded audio
image/tiff for TIFF encoded image data
For X11 platforms, the additional types are supported automatically
and resolve to their internal definitions:
UTF8_STRING for UTF-8 encoded text
text/plain;charset=utf-8 for UTF-8 encoded text
COMPOUND_TEXT for COMPOUND text
As stated before you can define own types for the clipboard, those
however might not be usable by other applications. Thus data pasted into
the clipboard using
pygame.scrap.put ("own_data", data)
can only be used by applications, which query the clipboard for the
"own_data" type.
New in pygame 1.8. Only works for Windows, X11 and Mac OS X so far. On
Mac OSX only text works at the moment - other types will be supported in
the next release.
init
Initializes the scrap module.
scrap.init () -> None
Tries to initialize the scrap module and raises an exception, if it
fails. Note that this module requires a set display surface, so you have
to make sure, you acquired one earlier using pygame.display.set_mode().
get
Gets the data for the specified type from the clipboard.
scrap.get (type) -> string
Returns the data for the specified type from the clipboard.
The data is returned as string and might need further processing.
If no data for the passed type is available, None is returned.
text = pygame.scrap.get (SCRAP_TEXT)
if text:
# Do stuff with it.
else:
print "There does not seem to be text in the clipboard."
get_types
Gets a list of the available clipboard types.
scrap.get_types () -> list
Gets a list of strings with the identifiers for the available
clipboard types. Each identifier can be used in the scrap.get()
method to get the clipboard content of the specific type.
If there is no data in the clipboard, an empty list is returned.
types = pygame.scrap.get_types ()
for t in types:
if "text" in t:
# There is some content with the word "text" in it. It's
# possibly text, so print it.
print pygame.scrap.get (t)
put
Places data into the clipboard.
scrap.put(type, data) -> None
Places data for a specific clipboard type into the clipboard.
The data must be a string buffer. The type is a string identifying
the type of data placed into the clipboard. This can be one of the
native SCRAP_PBM, SCRAP_PPM, SCRAP_BMP or SCRAP_TEXT values or an own
string identifier.
The method raises an exception, if the content could not be placed
into the clipboard.
fp = open ("example.bmp", "rb")
pygame.scrap.put (SCRAP_BMP, fp.read ())
fp.close ()
# Now you can acquire the image data from the clipboard in other
# applications.
pygame.scrap.put (SCRAP_TEXT, "A text to copy")
pygame.scrap.put ("Plain text", "A text to copy")
contains
Checks, whether a certain type is available in the clipboard.
scrap.contains (type) -> bool
Returns True, if data for the passed type is available in the
clipboard, False otherwise.
if pygame.scrap.contains (SCRAP_TEXT):
print "There is text in the clipboard."
if pygame.scrap.contains ("own_data_type"):
print "There is stuff in the clipboard."
lost
Checks whether the clipboard is currently owned by the application.
scrap.lost() -> bool
Returns True, if the clipboard is currently owned by the pygame
application, False otherwise.
if pygame.scrap.lost ():
print "No content from me anymore. The clipboard is used by someone else."
set_mode
Sets the clipboard access mode.
scrap.set_mode(mode) -> None
Sets the access mode for the clipboard. This is only of interest for X11
environments, where clipboard modes for mouse selections
(SRAP_SELECTION) and the clipboard (SCRAP_CLIPBOARD) are
available. Setting the mode to SCRAP_SELECTION in other environments
will not cause any difference.
If a value different from SCRAP_CLIPBOARD or SCRAP_SELECTION is passed,
a ValueError will be raised.
pygame-1.9.1release/src/scrap.c 0000644 0001750 0001750 00000020635 11226552737 016326 0 ustar vincent vincent /*
pygame - Python Game Library
Copyright (C) 2006, 2007 Rene Dudfield, Marcus von Appen
Originally written and put in the public domain by Sam Lantinga.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* Handle clipboard text and data in arbitrary formats */
#include
#include
#include "SDL.h"
#include "SDL_syswm.h"
#include "scrap.h"
#include "pygame.h"
#include "pygamedocs.h"
/**
* Indicates, whether pygame.scrap was initialized or not.
*/
static int _scrapinitialized = 0;
/**
* Currently active Clipboard object.
*/
static ScrapClipType _currentmode;
static PyObject* _selectiondata;
static PyObject* _clipdata;
/* Forward declarations. */
static PyObject* _scrap_get_types (PyObject *self, PyObject *args);
static PyObject* _scrap_contains (PyObject *self, PyObject *args);
static PyObject* _scrap_get_scrap (PyObject* self, PyObject* args);
static PyObject* _scrap_put_scrap (PyObject* self, PyObject* args);
static PyObject* _scrap_lost_scrap (PyObject* self, PyObject* args);
static PyObject* _scrap_set_mode (PyObject* self, PyObject* args);
/* Determine what type of clipboard we are using */
#if defined(__unix__) && defined(SDL_VIDEO_DRIVER_X11)
/*!defined(__QNXNTO__) &&*/
#define X11_SCRAP
#include /* Needed for clipboard timeouts. */
#include "scrap_x11.c"
#elif defined(__WIN32__)
#define WIN_SCRAP
#include "scrap_win.c"
/*
#elif defined(__QNXNTO__)
#define QNX_SCRAP
static uint32_t _cliptype = 0;
#include "scrap_qnx.c"
*/
#elif defined(__APPLE__)
#define MAC_SCRAP
#include "scrap_mac.c"
#else
#error Unknown window manager for clipboard handling
#endif /* scrap type */
/**
* \brief Indicates whether the scrap module is already initialized.
*
* \return 0 if the module is not initialized, 1, if it is.
*/
int
pygame_scrap_initialized (void)
{
return _scrapinitialized;
}
#if !defined(MAC_SCRAP)
/*
* Initializes the pygame scrap module.
*/
static PyObject*
_scrap_init (PyObject *self, PyObject *args)
{
VIDEO_INIT_CHECK ();
_clipdata = PyDict_New ();
_selectiondata = PyDict_New ();
/* In case we've got not video surface, we won't initialize
* anything.
*/
if (!SDL_GetVideoSurface())
return RAISE (PyExc_SDLError, "No display mode is set");
if (!pygame_scrap_init ())
return RAISE (PyExc_SDLError, SDL_GetError ());
Py_RETURN_NONE;
}
#endif
#if !defined(MAC_SCRAP)
/*
* Gets the currently available types from the active clipboard.
*/
static PyObject*
_scrap_get_types (PyObject *self, PyObject *args)
{
int i = 0;
char **types;
PyObject *list;
PyObject *tmp;
PYGAME_SCRAP_INIT_CHECK ();
if (!pygame_scrap_lost ())
{
switch (_currentmode)
{
case SCRAP_SELECTION:
return PyDict_Keys (_selectiondata);
case SCRAP_CLIPBOARD:
default:
return PyDict_Keys (_clipdata);
}
}
list = PyList_New (0);
types = pygame_scrap_get_types ();
if (!types)
return list;
while (types[i] != NULL)
{
tmp = PyString_FromString (types[i]);
PyList_Append (list, tmp);
Py_DECREF (tmp);
i++;
}
return list;
}
#endif
#if !defined(MAC_SCRAP)
/*
* Checks whether the active clipboard contains a certain type.
*/
static PyObject*
_scrap_contains (PyObject *self, PyObject *args)
{
char *type = NULL;
if (!PyArg_ParseTuple (args, "s", &type))
return NULL;
if (pygame_scrap_contains (type))
Py_RETURN_TRUE;
Py_RETURN_FALSE;
}
#endif
#if !defined(MAC_SCRAP)
/*
* Gets the content for a certain type from the active clipboard.
*/
static PyObject*
_scrap_get_scrap (PyObject* self, PyObject* args)
{
char *scrap = NULL;
PyObject *retval;
char *scrap_type;
PyObject *val;
unsigned long count;
PYGAME_SCRAP_INIT_CHECK ();
if(!PyArg_ParseTuple (args, "s", &scrap_type))
return NULL;
if (!pygame_scrap_lost ())
{
/* We are still the active one. */
switch (_currentmode)
{
case SCRAP_SELECTION:
val = PyDict_GetItemString (_selectiondata, scrap_type);
break;
case SCRAP_CLIPBOARD:
default:
val = PyDict_GetItemString (_clipdata, scrap_type);
break;
}
Py_XINCREF (val);
return val;
}
/* pygame_get_scrap() only returns NULL or !NULL, but won't set any
* errors. */
scrap = pygame_scrap_get (scrap_type, &count);
if (!scrap)
Py_RETURN_NONE;
retval = PyString_FromStringAndSize (scrap, count);
return retval;
}
#endif
#if !defined(MAC_SCRAP)
/*
* This will put a python string into the clipboard.
*/
static PyObject*
_scrap_put_scrap (PyObject* self, PyObject* args)
{
int scraplen;
char *scrap = NULL;
char *scrap_type;
PyObject *tmp;
PYGAME_SCRAP_INIT_CHECK ();
if (!PyArg_ParseTuple (args, "st#", &scrap_type, &scrap, &scraplen))
return NULL;
/* Set it in the clipboard. */
if (!pygame_scrap_put (scrap_type, scraplen, scrap))
return RAISE (PyExc_SDLError,
"content could not be placed in clipboard.");
/* Add or replace the set value. */
switch (_currentmode)
{
case SCRAP_SELECTION:
{
tmp = PyString_FromStringAndSize (scrap, scraplen);
PyDict_SetItemString (_selectiondata, scrap_type, tmp);
Py_DECREF (tmp);
break;
}
case SCRAP_CLIPBOARD:
default:
{
tmp = PyString_FromStringAndSize (scrap, scraplen);
PyDict_SetItemString (_clipdata, scrap_type, tmp);
Py_DECREF (tmp);
break;
}
}
Py_RETURN_NONE;
}
#endif
#if !defined(MAC_SCRAP)
/*
* Checks whether the pygame window has lost the clipboard.
*/
static PyObject*
_scrap_lost_scrap (PyObject* self, PyObject* args)
{
PYGAME_SCRAP_INIT_CHECK ();
if (pygame_scrap_lost ())
Py_RETURN_TRUE;
Py_RETURN_FALSE;
}
#endif
#if !defined(MAC_SCRAP)
/*
* Sets the clipboard mode. This only works for the X11 environment, which
* diverses between mouse selections and the clipboard.
*/
static PyObject*
_scrap_set_mode (PyObject* self, PyObject* args)
{
PYGAME_SCRAP_INIT_CHECK ();
if (!PyArg_ParseTuple (args, "i", &_currentmode))
return NULL;
if (_currentmode != SCRAP_CLIPBOARD && _currentmode != SCRAP_SELECTION)
return RAISE (PyExc_ValueError, "invalid clipboard mode");
#ifndef X11_SCRAP
/* Force the clipboard, if not in a X11 environment. */
_currentmode = SCRAP_CLIPBOARD;
#endif
Py_RETURN_NONE;
}
#endif /* !defined(MAC_SCRAP) */
static PyMethodDef scrap_builtins[] =
{
/*
* Only initialise these functions for ones we know about.
*
* Note, the macosx stuff is done in pygame/__init__.py
* by importing pygame.mac_scrap
*/
#if (defined(X11_SCRAP) || defined(WIN_SCRAP) || defined(QNX_SCRAP) \
|| defined(MAC_SCRAP))
{ "init", _scrap_init, 1, DOC_PYGAMESCRAPINIT },
{ "contains", _scrap_contains, METH_VARARGS, DOC_PYGAMESCRAPCONTAINS },
{ "get", _scrap_get_scrap, METH_VARARGS, DOC_PYGAMESCRAPGET },
{ "get_types", _scrap_get_types, METH_NOARGS, DOC_PYGAMESCRAPGETTYPES},
{ "put", _scrap_put_scrap, METH_VARARGS, DOC_PYGAMESCRAPPUT },
{ "lost", _scrap_lost_scrap, METH_NOARGS, DOC_PYGAMESCRAPLOST },
{ "set_mode", _scrap_set_mode, METH_VARARGS, DOC_PYGAMESCRAPSETMODE },
#endif
{ NULL, NULL, 0, NULL}
};
PYGAME_EXPORT
void initscrap (void)
{
PyObject *mod;
/* imported needed apis; Do this first so if there is an error
the module is not loaded.
*/
import_pygame_base ();
if (PyErr_Occurred ()) {
return;
}
/* create the module */
mod = Py_InitModule3 (MODPREFIX "scrap", scrap_builtins, NULL);
}
pygame-1.9.1release/src/scale_mmx64.c 0000644 0001750 0001750 00000076627 11077711443 017347 0 ustar vincent vincent /*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
Copyright (C) 2007 Rene Dudfield, Richard Goedeken
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
/* Pentium 64 bit SSE/MMX smoothscale routines
* These are written for compilation with GCC only.
*
* This file should not depend on anything but the C standard library.
*/
#if !defined(__GNUC__) || !defined(__x86_64__)
#error "Pygame build bug: should not be compiling this file!"
#endif
#include
typedef uint8_t Uint8; /* SDL convension */
typedef uint16_t Uint16; /* SDL convension */
#include
#include
#include "scale.h"
/* These functions implement an area-averaging shrinking filter in the X-dimension.
*/
void
filter_shrink_X_MMX(Uint8 *srcpix, Uint8 *dstpix, int height, int srcpitch, int dstpitch, int srcwidth, int dstwidth)
{
int srcdiff = srcpitch - (srcwidth * 4);
int dstdiff = dstpitch - (dstwidth * 4);
int xspace = 0x04000 * srcwidth / dstwidth; /* must be > 1 */
int xrecip = 0x40000000 / xspace;
long long One64 = 0x4000400040004000ULL;
long long srcdiff64 = srcdiff;
long long dstdiff64 = dstdiff;
asm __volatile__(" /* MMX code for X-shrink area average filter */ "
" pxor %%mm0, %%mm0; "
" movd %6, %%mm7; " /* mm7 == xrecipmmx */
" punpcklwd %%mm7, %%mm7; "
" punpckldq %%mm7, %%mm7; "
"1: " /* outer Y-loop */
" movl %5, %%ecx; " /* ecx == xcounter */
" pxor %%mm1, %%mm1; " /* mm1 == accumulator */
" movl %4, %%edx; " /* edx == width */
"2: " /* inner X-loop */
" cmpl $0x4000, %%ecx; "
" jbe 3f; "
" movd (%0), %%mm2; " /* mm2 = srcpix */
" add $4, %0; "
" punpcklbw %%mm0, %%mm2; "
" paddw %%mm2, %%mm1; " /* accumulator += srcpix */
" subl $0x4000, %%ecx; "
" jmp 4f; "
"3: " /* prepare to output a pixel */
" movd %%ecx, %%mm2; "
" movq %2, %%mm3; " /* mm3 = 2^14 */
" punpcklwd %%mm2, %%mm2; "
" punpckldq %%mm2, %%mm2; "
" movd (%0), %%mm4; " /* mm4 = srcpix */
" add $4, %0; "
" punpcklbw %%mm0, %%mm4; "
" psubw %%mm2, %%mm3; " /* mm3 = xfrac */
" psllw $2, %%mm4; "
" movq %%mm4, %%mm5; " /* mm2 = (srcpix * xcounter >> 16) */
" psraw $15, %%mm5; "
" pand %%mm2, %%mm5; "
" movq %%mm2, %%mm6; "
" psraw $15, %%mm6; "
" pand %%mm4, %%mm6; "
" pmulhw %%mm4, %%mm2; "
" paddw %%mm5, %%mm2; "
" paddw %%mm6, %%mm2; "
" movq %%mm4, %%mm5; " /* mm3 = (srcpix * xfrac) >> 16) */
" psraw $15, %%mm5; "
" pand %%mm3, %%mm5; "
" movq %%mm3, %%mm6; "
" psraw $15, %%mm6; "
" pand %%mm4, %%mm6; "
" pmulhw %%mm4, %%mm3; "
" paddw %%mm5, %%mm3; "
" paddw %%mm6, %%mm3; "
" paddw %%mm1, %%mm2; "
" movq %%mm3, %%mm1; " /* accumulator = (srcpix * xfrac) >> 16 */
" movq %%mm7, %%mm5; "
" psraw $15, %%mm5; "
" pand %%mm2, %%mm5; "
" movq %%mm2, %%mm6; "
" psraw $15, %%mm6; "
" pand %%mm7, %%mm6; "
" pmulhw %%mm7, %%mm2; "
" paddw %%mm5, %%mm2; "
" paddw %%mm6, %%mm2; "
" packuswb %%mm0, %%mm2; "
" movd %%mm2, (%1); "
" add %5, %%ecx; "
" add $4, %1; "
" subl $0x4000, %%ecx; "
"4: " /* tail of inner X-loop */
" decl %%edx; "
" jne 2b; "
" add %7, %0; " /* srcpix += srcdiff */
" add %8, %1; " /* dstpix += dstdiff */
" decl %3; "
" jne 1b; "
" emms; "
: "+r"(srcpix), "+r"(dstpix) /* outputs */
: "m"(One64), "m"(height), "m"(srcwidth),
"m"(xspace), "m"(xrecip), "m"(srcdiff64), "m"(dstdiff64) /* inputs */
: "%ecx","%edx" /* clobbered */
);
}
void
filter_shrink_X_SSE(Uint8 *srcpix, Uint8 *dstpix, int height, int srcpitch, int dstpitch, int srcwidth, int dstwidth)
{
int srcdiff = srcpitch - (srcwidth * 4);
int dstdiff = dstpitch - (dstwidth * 4);
int xspace = 0x04000 * srcwidth / dstwidth; /* must be > 1 */
int xrecip = 0x40000000 / xspace;
long long One64 = 0x4000400040004000ULL;
long long srcdiff64 = srcdiff;
long long dstdiff64 = dstdiff;
asm __volatile__(" /* MMX code for X-shrink area average filter */ "
" pxor %%mm0, %%mm0; "
" movd %6, %%mm7; " /* mm7 == xrecipmmx */
" movq %2, %%mm6; " /* mm6 = 2^14 */
" pshufw $0, %%mm7, %%mm7; "
"1: " /* outer Y-loop */
" movl %5, %%ecx; " /* ecx == xcounter */
" pxor %%mm1, %%mm1; " /* mm1 == accumulator */
" movl %4, %%edx; " /* edx == width */
"2: " /* inner X-loop */
" cmpl $0x4000, %%ecx; "
" jbe 3f; "
" movd (%0), %%mm2; " /* mm2 = srcpix */
" add $4, %0; "
" punpcklbw %%mm0, %%mm2; "
" paddw %%mm2, %%mm1; " /* accumulator += srcpix */
" subl $0x4000, %%ecx; "
" jmp 4f; "
"3: " /* prepare to output a pixel */
" movd %%ecx, %%mm2; "
" movq %%mm6, %%mm3; " /* mm3 = 2^14 */
" pshufw $0, %%mm2, %%mm2; "
" movd (%0), %%mm4; " /* mm4 = srcpix */
" add $4, %0; "
" punpcklbw %%mm0, %%mm4; "
" psubw %%mm2, %%mm3; " /* mm3 = xfrac */
" psllw $2, %%mm4; "
" pmulhuw %%mm4, %%mm2; " /* mm2 = (srcpix * xcounter >> 16) */
" pmulhuw %%mm4, %%mm3; " /* mm3 = (srcpix * xfrac) >> 16 */
" paddw %%mm1, %%mm2; "
" movq %%mm3, %%mm1; " /* accumulator = (srcpix * xfrac) >> 16 */
" pmulhuw %%mm7, %%mm2; "
" packuswb %%mm0, %%mm2; "
" movd %%mm2, (%1); "
" add %5, %%ecx; "
" add $4, %1; "
" subl $0x4000, %%ecx; "
"4: " /* tail of inner X-loop */
" decl %%edx; "
" jne 2b; "
" add %7, %0; " /* srcpix += srcdiff */
" add %8, %1; " /* dstpix += dstdiff */
" decl %3; "
" jne 1b; "
" emms; "
: "+r"(srcpix), "+r"(dstpix) /* outputs */
: "m"(One64), "m"(height), "m"(srcwidth),
"m"(xspace), "m"(xrecip), "m"(srcdiff64), "m"(dstdiff64) /* inputs */
: "%ecx","%edx" /* clobbered */
);
}
/* These functions implement an area-averaging shrinking filter in the Y-dimension.
*/
void
filter_shrink_Y_MMX(Uint8 *srcpix, Uint8 *dstpix, int width, int srcpitch, int dstpitch, int srcheight, int dstheight)
{
Uint16 *templine;
int srcdiff = srcpitch - (width * 4);
int dstdiff = dstpitch - (width * 4);
int yspace = 0x4000 * srcheight / dstheight; /* must be > 1 */
int yrecip = 0x40000000 / yspace;
long long One64 = 0x4000400040004000ULL;
/* allocate and clear a memory area for storing the accumulator line */
templine = (Uint16 *) malloc(dstpitch * 2);
if (templine == 0) return;
memset(templine, 0, dstpitch * 2);
long long srcdiff64 = srcdiff;
long long dstdiff64 = dstdiff;
asm __volatile__(" /* MMX code for Y-shrink area average filter */ "
" movl %5, %%ecx; " /* ecx == ycounter */
" pxor %%mm0, %%mm0; "
" movd %6, %%mm7; " /* mm7 == yrecipmmx */
" punpcklwd %%mm7, %%mm7; "
" punpckldq %%mm7, %%mm7; "
"1: " /* outer Y-loop */
" mov %2, %%rax; " /* rax == accumulate */
" cmpl $0x4000, %%ecx; "
" jbe 3f; "
" movl %4, %%edx; " /* edx == width */
"2: "
" movd (%0), %%mm1; "
" add $4, %0; "
" movq (%%rax), %%mm2; "
" punpcklbw %%mm0, %%mm1; "
" paddw %%mm1, %%mm2; "
" movq %%mm2, (%%rax); "
" add $8, %%rax; "
" decl %%edx; "
" jne 2b; "
" subl $0x4000, %%ecx; "
" jmp 6f; "
"3: " /* prepare to output a line */
" movd %%ecx, %%mm1; "
" movl %4, %%edx; " /* edx = width */
" movq %9, %%mm6; " /* mm6 = 2^14 */
" punpcklwd %%mm1, %%mm1; "
" punpckldq %%mm1, %%mm1; "
" psubw %%mm1, %%mm6; " /* mm6 = yfrac */
"4: "
" movd (%0), %%mm4; " /* mm4 = srcpix */
" add $4, %0; "
" punpcklbw %%mm0, %%mm4; "
" movq (%%rax), %%mm5; " /* mm5 = accumulate */
" movq %%mm6, %%mm3; "
" psllw $2, %%mm4; "
" movq %%mm4, %%mm0; " /* mm3 = (srcpix * yfrac) >> 16) */
" psraw $15, %%mm0; "
" pand %%mm3, %%mm0; "
" movq %%mm3, %%mm2; "
" psraw $15, %%mm2; "
" pand %%mm4, %%mm2; "
" pmulhw %%mm4, %%mm3; "
" paddw %%mm0, %%mm3; "
" paddw %%mm2, %%mm3; "
" movq %%mm1, %%mm0; " /* mm4 = (srcpix * ycounter >> 16) */
" psraw $15, %%mm0; "
" pand %%mm4, %%mm0; "
" movq %%mm4, %%mm2; "
" psraw $15, %%mm2; "
" pand %%mm1, %%mm2; "
" pmulhw %%mm1, %%mm4; "
" paddw %%mm0, %%mm4; "
" paddw %%mm2, %%mm4; "
" movq %%mm3, (%%rax); "
" paddw %%mm5, %%mm4; "
" add $8, %%rax; "
" movq %%mm7, %%mm0; "
" psraw $15, %%mm0; "
" pand %%mm4, %%mm0; "
" movq %%mm4, %%mm2; "
" psraw $15, %%mm2; "
" pand %%mm7, %%mm2; "
" pmulhw %%mm7, %%mm4; "
" paddw %%mm0, %%mm4; "
" paddw %%mm2, %%mm4; "
" pxor %%mm0, %%mm0; "
" packuswb %%mm0, %%mm4; "
" movd %%mm4, (%1); "
" add $4, %1; "
" decl %%edx; "
" jne 4b; "
" add %8, %1; " /* dstpix += dstdiff */
" addl %5, %%ecx; "
" subl $0x4000, %%ecx; "
"6: " /* tail of outer Y-loop */
" add %7, %0; " /* srcpix += srcdiff */
" decl %3; "
" jne 1b; "
" emms; "
: "+r"(srcpix), "+r"(dstpix) /* outputs */
: "m"(templine),"m"(srcheight), "m"(width), "m"(yspace),
"m"(yrecip), "m"(srcdiff64), "m"(dstdiff64), "m"(One64) /* input */
: "%ecx","%edx","%rax" /* clobbered */
);
/* free the temporary memory */
free(templine);
}
void
filter_shrink_Y_SSE(Uint8 *srcpix, Uint8 *dstpix, int width, int srcpitch, int dstpitch, int srcheight, int dstheight)
{
Uint16 *templine;
int srcdiff = srcpitch - (width * 4);
int dstdiff = dstpitch - (width * 4);
int yspace = 0x4000 * srcheight / dstheight; /* must be > 1 */
int yrecip = 0x40000000 / yspace;
long long One64 = 0x4000400040004000ULL;
/* allocate and clear a memory area for storing the accumulator line */
templine = (Uint16 *) malloc(dstpitch * 2);
if (templine == 0) return;
memset(templine, 0, dstpitch * 2);
long long srcdiff64 = srcdiff;
long long dstdiff64 = dstdiff;
asm __volatile__(" /* MMX code for Y-shrink area average filter */ "
" movl %5, %%ecx; " /* ecx == ycounter */
" pxor %%mm0, %%mm0; "
" movd %6, %%mm7; " /* mm7 == yrecipmmx */
" pshufw $0, %%mm7, %%mm7; "
"1: " /* outer Y-loop */
" mov %2, %%rax; " /* rax == accumulate */
" cmpl $0x4000, %%ecx; "
" jbe 3f; "
" movl %4, %%edx; " /* edx == width */
"2: "
" movd (%0), %%mm1; "
" add $4, %0; "
" movq (%%rax), %%mm2; "
" punpcklbw %%mm0, %%mm1; "
" paddw %%mm1, %%mm2; "
" movq %%mm2, (%%rax); "
" add $8, %%rax; "
" decl %%edx; "
" jne 2b; "
" subl $0x4000, %%ecx; "
" jmp 6f; "
"3: " /* prepare to output a line */
" movd %%ecx, %%mm1; "
" movl %4, %%edx; " /* edx = width */
" movq %9, %%mm6; " /* mm6 = 2^14 */
" pshufw $0, %%mm1, %%mm1; "
" psubw %%mm1, %%mm6; " /* mm6 = yfrac */
"4: "
" movd (%0), %%mm4; " /* mm4 = srcpix */
" add $4, %0; "
" punpcklbw %%mm0, %%mm4; "
" movq (%%rax), %%mm5; " /* mm5 = accumulate */
" movq %%mm6, %%mm3; "
" psllw $2, %%mm4; "
" pmulhuw %%mm4, %%mm3; " /* mm3 = (srcpix * yfrac) >> 16 */
" pmulhuw %%mm1, %%mm4; " /* mm4 = (srcpix * ycounter >> 16) */
" movq %%mm3, (%%rax); "
" paddw %%mm5, %%mm4; "
" add $8, %%rax; "
" pmulhuw %%mm7, %%mm4; "
" packuswb %%mm0, %%mm4; "
" movd %%mm4, (%1); "
" add $4, %1; "
" decl %%edx; "
" jne 4b; "
" add %8, %1; " /* dstpix += dstdiff */
" addl %5, %%ecx; "
" subl $0x4000, %%ecx; "
"6: " /* tail of outer Y-loop */
" add %7, %0; " /* srcpix += srcdiff */
" decl %3; "
" jne 1b; "
" emms; "
: "+r"(srcpix), "+r"(dstpix) /* outputs */
: "m"(templine),"m"(srcheight), "m"(width), "m"(yspace),
"m"(yrecip), "m"(srcdiff64), "m"(dstdiff64), "m"(One64) /* input */
: "%ecx","%edx","%rax" /* clobbered */
);
/* free the temporary memory */
free(templine);
}
/* These functions implement a bilinear filter in the X-dimension.
*/
void
filter_expand_X_MMX(Uint8 *srcpix, Uint8 *dstpix, int height, int srcpitch, int dstpitch, int srcwidth, int dstwidth)
{
int *xidx0, *xmult0, *xmult1;
int x, y;
int factorwidth = 8;
/* Allocate memory for factors */
xidx0 = malloc(dstwidth * 4);
if (xidx0 == 0) return;
xmult0 = (int *) malloc(dstwidth * factorwidth);
xmult1 = (int *) malloc(dstwidth * factorwidth);
if (xmult0 == 0 || xmult1 == 0)
{
free(xidx0);
if (xmult0) free(xmult0);
if (xmult1) free(xmult1);
}
/* Create multiplier factors and starting indices and put them in arrays */
for (x = 0; x < dstwidth; x++)
{
int xm1 = 0x100 * ((x * (srcwidth - 1)) % dstwidth) / dstwidth;
int xm0 = 0x100 - xm1;
xidx0[x] = x * (srcwidth - 1) / dstwidth;
xmult1[x*2] = xm1 | (xm1 << 16);
xmult1[x*2+1] = xm1 | (xm1 << 16);
xmult0[x*2] = xm0 | (xm0 << 16);
xmult0[x*2+1] = xm0 | (xm0 << 16);
}
/* Do the scaling in raster order so we don't trash the cache */
for (y = 0; y < height; y++)
{
Uint8 *srcrow0 = srcpix + y * srcpitch;
Uint8 *dstrow = dstpix + y * dstpitch;
int *xm0 = xmult0;
int *xm1 = xmult1;
int *x0 = xidx0;
asm __volatile__( " /* MMX code for inner loop of X bilinear filter */ "
" movl %5, %%ecx; "
" pxor %%mm0, %%mm0; "
"1: "
" movsxl (%3), %%rax; " /* get xidx0[x] */
" add $4, %3; "
" movq (%0), %%mm1; " /* load mult0 */
" add $8, %0; "
" movq (%1), %%mm2; " /* load mult1 */
" add $8, %1; "
" movd (%4,%%rax,4), %%mm4; "
" movd 4(%4,%%rax,4), %%mm5; "
" punpcklbw %%mm0, %%mm4; "
" punpcklbw %%mm0, %%mm5; "
" pmullw %%mm1, %%mm4; "
" pmullw %%mm2, %%mm5; "
" paddw %%mm4, %%mm5; "
" psrlw $8, %%mm5; "
" packuswb %%mm0, %%mm5; "
" movd %%mm5, (%2); "
" add $4, %2; "
" decl %%ecx; "
" jne 1b; "
" emms; "
: "+r"(xm0), "+r"(xm1), "+r"(dstrow), "+r"(x0) /* outputs */
: "r"(srcrow0),"m"(dstwidth) /* input */
: "%ecx","%rax" /* clobbered */
);
}
/* free memory */
free(xidx0);
free(xmult0);
free(xmult1);
}
void
filter_expand_X_SSE(Uint8 *srcpix, Uint8 *dstpix, int height, int srcpitch, int dstpitch, int srcwidth, int dstwidth)
{
int *xidx0, *xmult0, *xmult1;
int x, y;
int factorwidth = 8;
/* Allocate memory for factors */
xidx0 = malloc(dstwidth * 4);
if (xidx0 == 0) return;
xmult0 = (int *) malloc(dstwidth * factorwidth);
xmult1 = (int *) malloc(dstwidth * factorwidth);
if (xmult0 == 0 || xmult1 == 0)
{
free(xidx0);
if (xmult0) free(xmult0);
if (xmult1) free(xmult1);
}
/* Create multiplier factors and starting indices and put them in arrays */
for (x = 0; x < dstwidth; x++)
{
int xm1 = 0x100 * ((x * (srcwidth - 1)) % dstwidth) / dstwidth;
int xm0 = 0x100 - xm1;
xidx0[x] = x * (srcwidth - 1) / dstwidth;
xmult1[x*2] = xm1 | (xm1 << 16);
xmult1[x*2+1] = xm1 | (xm1 << 16);
xmult0[x*2] = xm0 | (xm0 << 16);
xmult0[x*2+1] = xm0 | (xm0 << 16);
}
/* Do the scaling in raster order so we don't trash the cache */
for (y = 0; y < height; y++)
{
Uint8 *srcrow0 = srcpix + y * srcpitch;
Uint8 *dstrow = dstpix + y * dstpitch;
int *xm0 = xmult0;
int *xm1 = xmult1;
int *x0 = xidx0;
asm __volatile__( " /* MMX code for inner loop of X bilinear filter */ "
" movl %5, %%ecx; "
" pxor %%mm0, %%mm0; "
"1: "
" movsxl (%3), %%rax; " /* get xidx0[x] */
" add $4, %3; "
" movq (%0), %%mm1; " /* load mult0 */
" add $8, %0; "
" movq (%1), %%mm2; " /* load mult1 */
" add $8, %1; "
" movd (%4,%%rax,4), %%mm4; "
" movd 4(%4,%%rax,4), %%mm5; "
" punpcklbw %%mm0, %%mm4; "
" punpcklbw %%mm0, %%mm5; "
" pmullw %%mm1, %%mm4; "
" pmullw %%mm2, %%mm5; "
" paddw %%mm4, %%mm5; "
" psrlw $8, %%mm5; "
" packuswb %%mm0, %%mm5; "
" movd %%mm5, (%2); "
" add $4, %2; "
" decl %%ecx; "
" jne 1b; "
" emms; "
: "+r"(xm0), "+r"(xm1), "+r"(dstrow), "+r"(x0) /* outputs */
: "r"(srcrow0),"m"(dstwidth) /* input */
: "%ecx","%rax" /* clobbered */
);
}
/* free memory */
free(xidx0);
free(xmult0);
free(xmult1);
}
/* These functions implement a bilinear filter in the Y-dimension
*/
void
filter_expand_Y_MMX(Uint8 *srcpix, Uint8 *dstpix, int width, int srcpitch, int dstpitch, int srcheight, int dstheight)
{
int y;
for (y = 0; y < dstheight; y++)
{
int yidx0 = y * (srcheight - 1) / dstheight;
Uint8 *srcrow0 = srcpix + yidx0 * srcpitch;
Uint8 *srcrow1 = srcrow0 + srcpitch;
int ymult1 = 0x0100 * ((y * (srcheight - 1)) % dstheight) / dstheight;
int ymult0 = 0x0100 - ymult1;
Uint8 *dstrow = dstpix + y * dstpitch;
asm __volatile__( " /* MMX code for inner loop of Y bilinear filter */ "
" movl %5, %%ecx; "
" movd %3, %%mm1; "
" movd %4, %%mm2; "
" pxor %%mm0, %%mm0; "
" punpcklwd %%mm1, %%mm1; "
" punpckldq %%mm1, %%mm1; "
" punpcklwd %%mm2, %%mm2; "
" punpckldq %%mm2, %%mm2; "
"1: "
" movd (%0), %%mm4; "
" add $4, %0; "
" movd (%1), %%mm5; "
" add $4, %1; "
" punpcklbw %%mm0, %%mm4; "
" punpcklbw %%mm0, %%mm5; "
" pmullw %%mm1, %%mm4; "
" pmullw %%mm2, %%mm5; "
" paddw %%mm4, %%mm5; "
" psrlw $8, %%mm5; "
" packuswb %%mm0, %%mm5; "
" movd %%mm5, (%2); "
" add $4, %2; "
" decl %%ecx; "
" jne 1b; "
" emms; "
: "+r"(srcrow0), "+r"(srcrow1), "+r"(dstrow) /* outputs */
: "m"(ymult0), "m"(ymult1), "m"(width) /* input */
: "%ecx" /* clobbered */
);
}
}
void
filter_expand_Y_SSE(Uint8 *srcpix, Uint8 *dstpix, int width, int srcpitch, int dstpitch, int srcheight, int dstheight)
{
int y;
for (y = 0; y < dstheight; y++)
{
int yidx0 = y * (srcheight - 1) / dstheight;
Uint8 *srcrow0 = srcpix + yidx0 * srcpitch;
Uint8 *srcrow1 = srcrow0 + srcpitch;
int ymult1 = 0x0100 * ((y * (srcheight - 1)) % dstheight) / dstheight;
int ymult0 = 0x0100 - ymult1;
Uint8 *dstrow = dstpix + y * dstpitch;
asm __volatile__( " /* MMX code for inner loop of Y bilinear filter */ "
" movl %5, %%ecx; "
" movd %3, %%mm1; "
" movd %4, %%mm2; "
" pxor %%mm0, %%mm0; "
" pshufw $0, %%mm1, %%mm1; "
" pshufw $0, %%mm2, %%mm2; "
"1: "
" movd (%0), %%mm4; "
" add $4, %0; "
" movd (%1), %%mm5; "
" add $4, %1; "
" punpcklbw %%mm0, %%mm4; "
" punpcklbw %%mm0, %%mm5; "
" pmullw %%mm1, %%mm4; "
" pmullw %%mm2, %%mm5; "
" paddw %%mm4, %%mm5; "
" psrlw $8, %%mm5; "
" packuswb %%mm0, %%mm5; "
" movd %%mm5, (%2); "
" add $4, %2; "
" decl %%ecx; "
" jne 1b; "
" emms; "
: "+r"(srcrow0), "+r"(srcrow1), "+r"(dstrow) /* outputs */
: "m"(ymult0), "m"(ymult1), "m"(width) /* input */
: "%ecx" /* clobbered */
);
}
}
pygame-1.9.1release/src/scale_mmx32.c 0000644 0001750 0001750 00000076350 11207055754 017334 0 ustar vincent vincent /*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
Copyright (C) 2007 Rene Dudfield, Richard Goedeken
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
/* Pentium 32 bit SSE/MMX smoothscale filter routines
* These are written for compilation with GCC only.
*
* This file should not depend on anything but the C standard library.
*/
#if !defined(__GNUC__) || !defined(__i386__) || defined(__x86_64__)
#error "Pygame build bug: should not be compiling this file!"
#endif
#include
typedef uint8_t Uint8; /* SDL convension */
typedef uint16_t Uint16; /* SDL convension */
#include
#include
#include "scale.h"
/* These functions implement an area-averaging shrinking filter in the X-dimension.
*/
void
filter_shrink_X_MMX(Uint8 *srcpix, Uint8 *dstpix, int height, int srcpitch, int dstpitch, int srcwidth, int dstwidth)
{
int srcdiff = srcpitch - (srcwidth * 4);
int dstdiff = dstpitch - (dstwidth * 4);
int xspace = 0x04000 * srcwidth / dstwidth; /* must be > 1 */
int xrecip = 0x40000000 / xspace;
long long One64 = 0x4000400040004000ULL;
asm __volatile__(" /* MMX code for X-shrink area average filter */ "
" pxor %%mm0, %%mm0; "
" movd %6, %%mm7; " /* mm7 == xrecipmmx */
" punpcklwd %%mm7, %%mm7; "
" punpckldq %%mm7, %%mm7; "
"1: " /* outer Y-loop */
" movl %5, %%ecx; " /* ecx == xcounter */
" pxor %%mm1, %%mm1; " /* mm1 == accumulator */
" movl %4, %%edx; " /* edx == width */
"2: " /* inner X-loop */
" cmpl $0x4000, %%ecx; "
" jbe 3f; "
" movd (%0), %%mm2; " /* mm2 = srcpix */
" add $4, %0; "
" punpcklbw %%mm0, %%mm2; "
" paddw %%mm2, %%mm1; " /* accumulator += srcpix */
" subl $0x4000, %%ecx; "
" jmp 4f; "
"3: " /* prepare to output a pixel */
" movd %%ecx, %%mm2; "
" movq %2, %%mm3; " /* mm3 = 2^14 */
" punpcklwd %%mm2, %%mm2; "
" punpckldq %%mm2, %%mm2; "
" movd (%0), %%mm4; " /* mm4 = srcpix */
" add $4, %0; "
" punpcklbw %%mm0, %%mm4; "
" psubw %%mm2, %%mm3; " /* mm3 = xfrac */
" psllw $2, %%mm4; "
" movq %%mm4, %%mm5; " /* mm2 = (srcpix * xcounter >> 16) */
" psraw $15, %%mm5; "
" pand %%mm2, %%mm5; "
" movq %%mm2, %%mm6; "
" psraw $15, %%mm6; "
" pand %%mm4, %%mm6; "
" pmulhw %%mm4, %%mm2; "
" paddw %%mm5, %%mm2; "
" paddw %%mm6, %%mm2; "
" movq %%mm4, %%mm5; " /* mm3 = (srcpix * xfrac) >> 16) */
" psraw $15, %%mm5; "
" pand %%mm3, %%mm5; "
" movq %%mm3, %%mm6; "
" psraw $15, %%mm6; "
" pand %%mm4, %%mm6; "
" pmulhw %%mm4, %%mm3; "
" paddw %%mm5, %%mm3; "
" paddw %%mm6, %%mm3; "
" paddw %%mm1, %%mm2; "
" movq %%mm3, %%mm1; " /* accumulator = (srcpix * xfrac) >> 16 */
" movq %%mm7, %%mm5; "
" psraw $15, %%mm5; "
" pand %%mm2, %%mm5; "
" movq %%mm2, %%mm6; "
" psraw $15, %%mm6; "
" pand %%mm7, %%mm6; "
" pmulhw %%mm7, %%mm2; "
" paddw %%mm5, %%mm2; "
" paddw %%mm6, %%mm2; "
" packuswb %%mm0, %%mm2; "
" movd %%mm2, (%1); "
" add %5, %%ecx; "
" add $4, %1; "
" subl $0x4000, %%ecx; "
"4: " /* tail of inner X-loop */
" decl %%edx; "
" jne 2b; "
" add %7, %0; " /* srcpix += srcdiff */
" add %8, %1; " /* dstpix += dstdiff */
" decl %3; "
" jne 1b; "
" emms; "
: "+r"(srcpix), "+r"(dstpix) /* outputs */
: "m"(One64), "m"(height), "m"(srcwidth),
"m"(xspace), "m"(xrecip), "m"(srcdiff), "m"(dstdiff) /* input */
: "%ecx","%edx" /* clobbered */
);
}
void
filter_shrink_X_SSE(Uint8 *srcpix, Uint8 *dstpix, int height, int srcpitch, int dstpitch, int srcwidth, int dstwidth)
{
int srcdiff = srcpitch - (srcwidth * 4);
int dstdiff = dstpitch - (dstwidth * 4);
int xspace = 0x04000 * srcwidth / dstwidth; /* must be > 1 */
int xrecip = 0x40000000 / xspace;
long long One64 = 0x4000400040004000ULL;
asm __volatile__(" /* MMX code for X-shrink area average filter */ "
" pxor %%mm0, %%mm0; "
" movd %6, %%mm7; " /* mm7 == xrecipmmx */
" movq %2, %%mm6; " /* mm6 = 2^14 */
" pshufw $0, %%mm7, %%mm7; "
"1: " /* outer Y-loop */
" movl %5, %%ecx; " /* ecx == xcounter */
" pxor %%mm1, %%mm1; " /* mm1 == accumulator */
" movl %4, %%edx; " /* edx == width */
"2: " /* inner X-loop */
" cmpl $0x4000, %%ecx; "
" jbe 3f; "
" movd (%0), %%mm2; " /* mm2 = srcpix */
" add $4, %0; "
" punpcklbw %%mm0, %%mm2; "
" paddw %%mm2, %%mm1; " /* accumulator += srcpix */
" subl $0x4000, %%ecx; "
" jmp 4f; "
"3: " /* prepare to output a pixel */
" movd %%ecx, %%mm2; "
" movq %%mm6, %%mm3; " /* mm3 = 2^14 */
" pshufw $0, %%mm2, %%mm2; "
" movd (%0), %%mm4; " /* mm4 = srcpix */
" add $4, %0; "
" punpcklbw %%mm0, %%mm4; "
" psubw %%mm2, %%mm3; " /* mm3 = xfrac */
" psllw $2, %%mm4; "
" pmulhuw %%mm4, %%mm2; " /* mm2 = (srcpix * xcounter >> 16) */
" pmulhuw %%mm4, %%mm3; " /* mm3 = (srcpix * xfrac) >> 16 */
" paddw %%mm1, %%mm2; "
" movq %%mm3, %%mm1; " /* accumulator = (srcpix * xfrac) >> 16 */
" pmulhuw %%mm7, %%mm2; "
" packuswb %%mm0, %%mm2; "
" movd %%mm2, (%1); "
" add %5, %%ecx; "
" add $4, %1; "
" subl $0x4000, %%ecx; "
"4: " /* tail of inner X-loop */
" decl %%edx; "
" jne 2b; "
" add %7, %0; " /* srcpix += srcdiff */
" add %8, %1; " /* dstpix += dstdiff */
" decl %3; "
" jne 1b; "
" emms; "
: "+r"(srcpix), "+r"(dstpix) /* outputs */
: "m"(One64), "m"(height), "m"(srcwidth),
"m"(xspace), "m"(xrecip), "m"(srcdiff), "m"(dstdiff) /* input */
: "%ecx","%edx" /* clobbered */
);
}
/* These functions implement an area-averaging shrinking filter in the Y-dimension.
*/
void
filter_shrink_Y_MMX(Uint8 *srcpix, Uint8 *dstpix, int width, int srcpitch, int dstpitch, int srcheight, int dstheight)
{
Uint16 *templine;
int srcdiff = srcpitch - (width * 4);
int dstdiff = dstpitch - (width * 4);
int yspace = 0x4000 * srcheight / dstheight; /* must be > 1 */
int yrecip = 0x40000000 / yspace;
long long One64 = 0x4000400040004000ULL;
/* allocate and clear a memory area for storing the accumulator line */
templine = (Uint16 *) malloc(dstpitch * 2);
if (templine == 0) return;
memset(templine, 0, dstpitch * 2);
asm __volatile__(" /* MMX code for Y-shrink area average filter */ "
" movl %5, %%ecx; " /* ecx == ycounter */
" pxor %%mm0, %%mm0; "
" movd %6, %%mm7; " /* mm7 == yrecipmmx */
" punpcklwd %%mm7, %%mm7; "
" punpckldq %%mm7, %%mm7; "
"1: " /* outer Y-loop */
" movl %2, %%eax; " /* rax == accumulate */
" cmpl $0x4000, %%ecx; "
" jbe 3f; "
" movl %4, %%edx; " /* edx == width */
"2: "
" movd (%0), %%mm1; "
" add $4, %0; "
" movq (%%eax), %%mm2; "
" punpcklbw %%mm0, %%mm1; "
" paddw %%mm1, %%mm2; "
" movq %%mm2, (%%eax); "
" add $8, %%eax; "
" decl %%edx; "
" jne 2b; "
" subl $0x4000, %%ecx; "
" jmp 6f; "
"3: " /* prepare to output a line */
" movd %%ecx, %%mm1; "
" movl %4, %%edx; " /* edx = width */
" movq %9, %%mm6; " /* mm6 = 2^14 */
" punpcklwd %%mm1, %%mm1; "
" punpckldq %%mm1, %%mm1; "
" psubw %%mm1, %%mm6; " /* mm6 = yfrac */
"4: "
" movd (%0), %%mm4; " /* mm4 = srcpix */
" add $4, %0; "
" punpcklbw %%mm0, %%mm4; "
" movq (%%eax), %%mm5; " /* mm5 = accumulate */
" movq %%mm6, %%mm3; "
" psllw $2, %%mm4; "
" movq %%mm4, %%mm0; " /* mm3 = (srcpix * yfrac) >> 16) */
" psraw $15, %%mm0; "
" pand %%mm3, %%mm0; "
" movq %%mm3, %%mm2; "
" psraw $15, %%mm2; "
" pand %%mm4, %%mm2; "
" pmulhw %%mm4, %%mm3; "
" paddw %%mm0, %%mm3; "
" paddw %%mm2, %%mm3; "
" movq %%mm1, %%mm0; " /* mm4 = (srcpix * ycounter >> 16) */
" psraw $15, %%mm0; "
" pand %%mm4, %%mm0; "
" movq %%mm4, %%mm2; "
" psraw $15, %%mm2; "
" pand %%mm1, %%mm2; "
" pmulhw %%mm1, %%mm4; "
" paddw %%mm0, %%mm4; "
" paddw %%mm2, %%mm4; "
" movq %%mm3, (%%eax); "
" paddw %%mm5, %%mm4; "
" add $8, %%eax; "
" movq %%mm7, %%mm0; "
" psraw $15, %%mm0; "
" pand %%mm4, %%mm0; "
" movq %%mm4, %%mm2; "
" psraw $15, %%mm2; "
" pand %%mm7, %%mm2; "
" pmulhw %%mm7, %%mm4; "
" paddw %%mm0, %%mm4; "
" paddw %%mm2, %%mm4; "
" pxor %%mm0, %%mm0; "
" packuswb %%mm0, %%mm4; "
" movd %%mm4, (%1); "
" add $4, %1; "
" decl %%edx; "
" jne 4b; "
" add %8, %1; " /* dstpix += dstdiff */
" addl %5, %%ecx; "
" subl $0x4000, %%ecx; "
"6: " /* tail of outer Y-loop */
" add %7, %0; " /* srcpix += srcdiff */
" decl %3; "
" jne 1b; "
" emms; "
: "+r"(srcpix), "+r"(dstpix) /* outputs */
: "m"(templine), "m"(srcheight), "m"(width), "m"(yspace),
"m"(yrecip), "m"(srcdiff), "m"(dstdiff),"m"(One64) /* input */
: "%ecx","%edx","%eax" /* clobbered */
);
/* free the temporary memory */
free(templine);
}
void
filter_shrink_Y_SSE(Uint8 *srcpix, Uint8 *dstpix, int width, int srcpitch, int dstpitch, int srcheight, int dstheight)
{
Uint16 *templine;
int srcdiff = srcpitch - (width * 4);
int dstdiff = dstpitch - (width * 4);
int yspace = 0x4000 * srcheight / dstheight; /* must be > 1 */
int yrecip = 0x40000000 / yspace;
long long One64 = 0x4000400040004000ULL;
/* allocate and clear a memory area for storing the accumulator line */
templine = (Uint16 *) malloc(dstpitch * 2);
if (templine == 0) return;
memset(templine, 0, dstpitch * 2);
asm __volatile__(" /* MMX code for Y-shrink area average filter */ "
" movl %5, %%ecx; " /* ecx == ycounter */
" pxor %%mm0, %%mm0; "
" movd %6, %%mm7; " /* mm7 == yrecipmmx */
" pshufw $0, %%mm7, %%mm7; "
"1: " /* outer Y-loop */
" movl %2, %%eax; " /* rax == accumulate */
" cmpl $0x4000, %%ecx; "
" jbe 3f; "
" movl %4, %%edx; " /* edx == width */
"2: "
" movd (%0), %%mm1; "
" add $4, %0; "
" movq (%%eax), %%mm2; "
" punpcklbw %%mm0, %%mm1; "
" paddw %%mm1, %%mm2; "
" movq %%mm2, (%%eax); "
" add $8, %%eax; "
" decl %%edx; "
" jne 2b; "
" subl $0x4000, %%ecx; "
" jmp 6f; "
"3: " /* prepare to output a line */
" movd %%ecx, %%mm1; "
" movl %4, %%edx; " /* edx = width */
" movq %9, %%mm6; " /* mm6 = 2^14 */
" pshufw $0, %%mm1, %%mm1; "
" psubw %%mm1, %%mm6; " /* mm6 = yfrac */
"4: "
" movd (%0), %%mm4; " /* mm4 = srcpix */
" add $4, %0; "
" punpcklbw %%mm0, %%mm4; "
" movq (%%eax), %%mm5; " /* mm5 = accumulate */
" movq %%mm6, %%mm3; "
" psllw $2, %%mm4; "
" pmulhuw %%mm4, %%mm3; " /* mm3 = (srcpix * yfrac) >> 16 */
" pmulhuw %%mm1, %%mm4; " /* mm4 = (srcpix * ycounter >> 16) */
" movq %%mm3, (%%eax); "
" paddw %%mm5, %%mm4; "
" add $8, %%eax; "
" pmulhuw %%mm7, %%mm4; "
" packuswb %%mm0, %%mm4; "
" movd %%mm4, (%1); "
" add $4, %1; "
" decl %%edx; "
" jne 4b; "
" add %8, %1; " /* dstpix += dstdiff */
" addl %5, %%ecx; "
" subl $0x4000, %%ecx; "
"6: " /* tail of outer Y-loop */
" add %7, %0; " /* srcpix += srcdiff */
" decl %3; "
" jne 1b; "
" emms; "
: "+r"(srcpix), "+r"(dstpix) /* outputs */
: "m"(templine), "m"(srcheight), "m"(width), "m"(yspace),
"m"(yrecip), "m"(srcdiff), "m"(dstdiff),"m"(One64) /* input */
: "%ecx","%edx","%eax" /* clobbered */
);
/* free the temporary memory */
free(templine);
}
/* These functions implement a bilinear filter in the X-dimension.
*/
void
filter_expand_X_MMX(Uint8 *srcpix, Uint8 *dstpix, int height, int srcpitch, int dstpitch, int srcwidth, int dstwidth)
{
int *xidx0, *xmult0, *xmult1;
int x, y;
int factorwidth = 8;
long long One64 = 0x0100010001000100ULL;
/* Allocate memory for factors */
xidx0 = malloc(dstwidth * 4);
if (xidx0 == 0) return;
xmult0 = (int *) malloc(dstwidth * factorwidth);
xmult1 = (int *) malloc(dstwidth * factorwidth);
if (xmult0 == 0 || xmult1 == 0)
{
free(xidx0);
if (xmult0) free(xmult0);
if (xmult1) free(xmult1);
}
/* Create multiplier factors and starting indices and put them in arrays */
for (x = 0; x < dstwidth; x++)
{
int xm1 = 0x100 * ((x * (srcwidth - 1)) % dstwidth) / dstwidth;
int xm0 = 0x100 - xm1;
xidx0[x] = x * (srcwidth - 1) / dstwidth;
xmult1[x*2] = xm1 | (xm1 << 16);
xmult1[x*2+1] = xm1 | (xm1 << 16);
xmult0[x*2] = xm0 | (xm0 << 16);
xmult0[x*2+1] = xm0 | (xm0 << 16);
}
/* Do the scaling in raster order so we don't trash the cache */
for (y = 0; y < height; y++)
{
Uint8 *srcrow0 = srcpix + y * srcpitch;
Uint8 *dstrow = dstpix + y * dstpitch;
int *xm0 = xmult0;
int *x0 = xidx0;
int width = dstwidth;
asm __volatile__( " /* MMX code for inner loop of X bilinear filter */ "
" pxor %%mm0, %%mm0; "
" movq %5, %%mm7; "
"1: "
" movl (%2), %%eax; " /* get xidx0[x] */
" add $4, %2; "
" movq %%mm7, %%mm2; "
" movq (%0), %%mm1; " /* load mult0 */
" add $8, %0; "
" psubw %%mm1, %%mm2; " /* load mult1 */
" movd (%4,%%eax,4), %%mm4; "
" movd 4(%4,%%eax,4), %%mm5; "
" punpcklbw %%mm0, %%mm4; "
" punpcklbw %%mm0, %%mm5; "
" pmullw %%mm1, %%mm4; "
" pmullw %%mm2, %%mm5; "
" paddw %%mm4, %%mm5; "
" psrlw $8, %%mm5; "
" packuswb %%mm0, %%mm5; "
" movd %%mm5, (%1); "
" add $4, %1; "
" decl %3; "
" jne 1b; "
" emms; "
: "+r"(xm0), "+r"(dstrow), "+r"(x0), "+m"(width) /* outputs */
: "S"(srcrow0), "m"(One64) /* input */
: "%eax" /* clobbered */
);
}
/* free memory */
free(xidx0);
free(xmult0);
free(xmult1);
}
void
filter_expand_X_SSE(Uint8 *srcpix, Uint8 *dstpix, int height, int srcpitch, int dstpitch, int srcwidth, int dstwidth)
{
int *xidx0, *xmult0, *xmult1;
int x, y;
int factorwidth = 8;
long long One64 = 0x0100010001000100ULL;
/* Allocate memory for factors */
xidx0 = malloc(dstwidth * 4);
if (xidx0 == 0) return;
xmult0 = (int *) malloc(dstwidth * factorwidth);
xmult1 = (int *) malloc(dstwidth * factorwidth);
if (xmult0 == 0 || xmult1 == 0)
{
free(xidx0);
if (xmult0) free(xmult0);
if (xmult1) free(xmult1);
}
/* Create multiplier factors and starting indices and put them in arrays */
for (x = 0; x < dstwidth; x++)
{
int xm1 = 0x100 * ((x * (srcwidth - 1)) % dstwidth) / dstwidth;
int xm0 = 0x100 - xm1;
xidx0[x] = x * (srcwidth - 1) / dstwidth;
xmult1[x*2] = xm1 | (xm1 << 16);
xmult1[x*2+1] = xm1 | (xm1 << 16);
xmult0[x*2] = xm0 | (xm0 << 16);
xmult0[x*2+1] = xm0 | (xm0 << 16);
}
/* Do the scaling in raster order so we don't trash the cache */
for (y = 0; y < height; y++)
{
Uint8 *srcrow0 = srcpix + y * srcpitch;
Uint8 *dstrow = dstpix + y * dstpitch;
int *xm0 = xmult0;
int *x0 = xidx0;
int width = dstwidth;
asm __volatile__( " /* MMX code for inner loop of X bilinear filter */ "
" pxor %%mm0, %%mm0; "
" movq %5, %%mm7; "
"1: "
" movl (%2), %%eax; " /* get xidx0[x] */
" add $4, %2; "
" movq %%mm7, %%mm2; "
" movq (%0), %%mm1; " /* load mult0 */
" add $8, %0; "
" psubw %%mm1, %%mm2; " /* load mult1 */
" movd (%4,%%eax,4), %%mm4; "
" movd 4(%4,%%eax,4), %%mm5; "
" punpcklbw %%mm0, %%mm4; "
" punpcklbw %%mm0, %%mm5; "
" pmullw %%mm1, %%mm4; "
" pmullw %%mm2, %%mm5; "
" paddw %%mm4, %%mm5; "
" psrlw $8, %%mm5; "
" packuswb %%mm0, %%mm5; "
" movd %%mm5, (%1); "
" add $4, %1; "
" decl %3; "
" jne 1b; "
" emms; "
: "+r"(xm0), "+r"(dstrow), "+r"(x0), "+m"(width) /* outputs */
: "S"(srcrow0), "m"(One64) /* input */
: "%eax" /* clobbered */
);
}
/* free memory */
free(xidx0);
free(xmult0);
free(xmult1);
}
/* These functions implement a bilinear filter in the Y-dimension.
*/
void filter_expand_Y_MMX(Uint8 *srcpix, Uint8 *dstpix, int width, int srcpitch, int dstpitch, int srcheight, int dstheight)
{
int y;
for (y = 0; y < dstheight; y++)
{
int yidx0 = y * (srcheight - 1) / dstheight;
Uint8 *srcrow0 = srcpix + yidx0 * srcpitch;
Uint8 *srcrow1 = srcrow0 + srcpitch;
int ymult1 = 0x0100 * ((y * (srcheight - 1)) % dstheight) / dstheight;
int ymult0 = 0x0100 - ymult1;
Uint8 *dstrow = dstpix + y * dstpitch;
asm __volatile__( " /* MMX code for inner loop of Y bilinear filter */ "
" movl %5, %%eax; "
" movd %3, %%mm1; "
" movd %4, %%mm2; "
" pxor %%mm0, %%mm0; "
" punpcklwd %%mm1, %%mm1; "
" punpckldq %%mm1, %%mm1; "
" punpcklwd %%mm2, %%mm2; "
" punpckldq %%mm2, %%mm2; "
"1: "
" movd (%0), %%mm4; "
" add $4, %0; "
" movd (%1), %%mm5; "
" add $4, %1; "
" punpcklbw %%mm0, %%mm4; "
" punpcklbw %%mm0, %%mm5; "
" pmullw %%mm1, %%mm4; "
" pmullw %%mm2, %%mm5; "
" paddw %%mm4, %%mm5; "
" psrlw $8, %%mm5; "
" packuswb %%mm0, %%mm5; "
" movd %%mm5, (%2); "
" add $4, %2; "
" decl %%eax; "
" jne 1b; "
" emms; "
: "+r"(srcrow0), "+r"(srcrow1),"+r"(dstrow) /* no outputs */
: "m"(ymult0), "m"(ymult1), "m"(width) /* input */
: "%eax" /* clobbered */
);
}
}
void filter_expand_Y_SSE(Uint8 *srcpix, Uint8 *dstpix, int width, int srcpitch, int dstpitch, int srcheight, int dstheight)
{
int y;
for (y = 0; y < dstheight; y++)
{
int yidx0 = y * (srcheight - 1) / dstheight;
Uint8 *srcrow0 = srcpix + yidx0 * srcpitch;
Uint8 *srcrow1 = srcrow0 + srcpitch;
int ymult1 = 0x0100 * ((y * (srcheight - 1)) % dstheight) / dstheight;
int ymult0 = 0x0100 - ymult1;
Uint8 *dstrow = dstpix + y * dstpitch;
asm __volatile__( " /* MMX code for inner loop of Y bilinear filter */ "
" movl %5, %%eax; "
" movd %3, %%mm1; "
" movd %4, %%mm2; "
" pxor %%mm0, %%mm0; "
" pshufw $0, %%mm1, %%mm1; "
" pshufw $0, %%mm2, %%mm2; "
"1: "
" movd (%0), %%mm4; "
" add $4, %0; "
" movd (%1), %%mm5; "
" add $4, %1; "
" punpcklbw %%mm0, %%mm4; "
" punpcklbw %%mm0, %%mm5; "
" pmullw %%mm1, %%mm4; "
" pmullw %%mm2, %%mm5; "
" paddw %%mm4, %%mm5; "
" psrlw $8, %%mm5; "
" packuswb %%mm0, %%mm5; "
" movd %%mm5, (%2); "
" add $4, %2; "
" decl %%eax; "
" jne 1b; "
" emms; "
: "+r"(srcrow0), "+r"(srcrow1),"+r"(dstrow) /* no outputs */
: "m"(ymult0), "m"(ymult1), "m"(width) /* input */
: "%eax" /* clobbered */
);
}
}
pygame-1.9.1release/src/scale_mmx.c 0000644 0001750 0001750 00000002476 11207055754 017165 0 ustar vincent vincent /*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
Copyright (C) 2007 Rene Dudfield, Richard Goedeken
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
/* Pentium MMX/SSE smoothscale routines
* These are only compiled with GCC.
*/
#if defined(__GNUC__)
/* Choose between the 32 bit and 64 bit versions.
* Including source code like this may be frowned upon by some,
* but the alternative is ungainly conditionally compiled code.
*/
# if defined(__x86_64__)
# include "scale_mmx64.c"
# elif defined(__i386__)
# include "scale_mmx32.c"
# endif
#endif
pygame-1.9.1release/src/scale2x.c 0000644 0001750 0001750 00000013474 11207055754 016556 0 ustar vincent vincent /*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
/*
This implements the AdvanceMAME Scale2x feature found on this page,
http://advancemame.sourceforge.net/scale2x.html
It is an incredibly simple and powerful image doubling routine that does
an astonishing job of doubling game graphic data while interpolating out
the jaggies. Congrats to the AdvanceMAME team, I'm very impressed and
surprised with this code!
*/
#include
#define MAX(a,b) (((a) > (b)) ? (a) : (b))
#define MIN(a,b) (((a) < (b)) ? (a) : (b))
#define READINT24(x) ((x)[0]<<16 | (x)[1]<<8 | (x)[2])
#define WRITEINT24(x, i) {(x)[0]=i>>16; (x)[1]=(i>>8)&0xff; x[2]=i&0xff; }
/*
this requires a destination surface already setup to be twice as
large as the source. oh, and formats must match too. this will just
blindly assume you didn't flounder.
*/
void scale2x(SDL_Surface *src, SDL_Surface *dst)
{
int looph, loopw;
Uint8* srcpix = (Uint8*)src->pixels;
Uint8* dstpix = (Uint8*)dst->pixels;
const int srcpitch = src->pitch;
const int dstpitch = dst->pitch;
const int width = src->w;
const int height = src->h;
switch(src->format->BytesPerPixel)
{
case 1: {
Uint8 E0, E1, E2, E3, B, D, E, F, H;
for(looph = 0; looph < height; ++looph)
{
for(loopw = 0; loopw < width; ++ loopw)
{
B = *(Uint8*)(srcpix + (MAX(0,looph-1)*srcpitch) + (1*loopw));
D = *(Uint8*)(srcpix + (looph*srcpitch) + (1*MAX(0,loopw-1)));
E = *(Uint8*)(srcpix + (looph*srcpitch) + (1*loopw));
F = *(Uint8*)(srcpix + (looph*srcpitch) + (1*MIN(width-1,loopw+1)));
H = *(Uint8*)(srcpix + (MIN(height-1,looph+1)*srcpitch) + (1*loopw));
E0 = D == B && B != F && D != H ? D : E;
E1 = B == F && B != D && F != H ? F : E;
E2 = D == H && D != B && H != F ? D : E;
E3 = H == F && D != H && B != F ? F : E;
*(Uint8*)(dstpix + looph*2*dstpitch + loopw*2*1) = E0;
*(Uint8*)(dstpix + looph*2*dstpitch + (loopw*2+1)*1) = E1;
*(Uint8*)(dstpix + (looph*2+1)*dstpitch + loopw*2*1) = E2;
*(Uint8*)(dstpix + (looph*2+1)*dstpitch + (loopw*2+1)*1) = E3;
}
}break;}
case 2: {
Uint16 E0, E1, E2, E3, B, D, E, F, H;
for(looph = 0; looph < height; ++looph)
{
for(loopw = 0; loopw < width; ++ loopw)
{
B = *(Uint16*)(srcpix + (MAX(0,looph-1)*srcpitch) + (2*loopw));
D = *(Uint16*)(srcpix + (looph*srcpitch) + (2*MAX(0,loopw-1)));
E = *(Uint16*)(srcpix + (looph*srcpitch) + (2*loopw));
F = *(Uint16*)(srcpix + (looph*srcpitch) + (2*MIN(width-1,loopw+1)));
H = *(Uint16*)(srcpix + (MIN(height-1,looph+1)*srcpitch) + (2*loopw));
E0 = D == B && B != F && D != H ? D : E;
E1 = B == F && B != D && F != H ? F : E;
E2 = D == H && D != B && H != F ? D : E;
E3 = H == F && D != H && B != F ? F : E;
*(Uint16*)(dstpix + looph*2*dstpitch + loopw*2*2) = E0;
*(Uint16*)(dstpix + looph*2*dstpitch + (loopw*2+1)*2) = E1;
*(Uint16*)(dstpix + (looph*2+1)*dstpitch + loopw*2*2) = E2;
*(Uint16*)(dstpix + (looph*2+1)*dstpitch + (loopw*2+1)*2) = E3;
}
}break;}
case 3: {
int E0, E1, E2, E3, B, D, E, F, H;
for(looph = 0; looph < height; ++looph)
{
for(loopw = 0; loopw < width; ++ loopw)
{
B = READINT24(srcpix + (MAX(0,looph-1)*srcpitch) + (3*loopw));
D = READINT24(srcpix + (looph*srcpitch) + (3*MAX(0,loopw-1)));
E = READINT24(srcpix + (looph*srcpitch) + (3*loopw));
F = READINT24(srcpix + (looph*srcpitch) + (3*MIN(width-1,loopw+1)));
H = READINT24(srcpix + (MIN(height-1,looph+1)*srcpitch) + (3*loopw));
E0 = D == B && B != F && D != H ? D : E;
E1 = B == F && B != D && F != H ? F : E;
E2 = D == H && D != B && H != F ? D : E;
E3 = H == F && D != H && B != F ? F : E;
WRITEINT24((dstpix + looph*2*dstpitch + loopw*2*3), E0);
WRITEINT24((dstpix + looph*2*dstpitch + (loopw*2+1)*3), E1);
WRITEINT24((dstpix + (looph*2+1)*dstpitch + loopw*2*3), E2);
WRITEINT24((dstpix + (looph*2+1)*dstpitch + (loopw*2+1)*3), E3);
}
}break;}
default: { /*case 4:*/
Uint32 E0, E1, E2, E3, B, D, E, F, H;
for(looph = 0; looph < height; ++looph)
{
for(loopw = 0; loopw < width; ++ loopw)
{
B = *(Uint32*)(srcpix + (MAX(0,looph-1)*srcpitch) + (4*loopw));
D = *(Uint32*)(srcpix + (looph*srcpitch) + (4*MAX(0,loopw-1)));
E = *(Uint32*)(srcpix + (looph*srcpitch) + (4*loopw));
F = *(Uint32*)(srcpix + (looph*srcpitch) + (4*MIN(width-1,loopw+1)));
H = *(Uint32*)(srcpix + (MIN(height-1,looph+1)*srcpitch) + (4*loopw));
E0 = D == B && B != F && D != H ? D : E;
E1 = B == F && B != D && F != H ? F : E;
E2 = D == H && D != B && H != F ? D : E;
E3 = H == F && D != H && B != F ? F : E;
*(Uint32*)(dstpix + looph*2*dstpitch + loopw*2*4) = E0;
*(Uint32*)(dstpix + looph*2*dstpitch + (loopw*2+1)*4) = E1;
*(Uint32*)(dstpix + (looph*2+1)*dstpitch + loopw*2*4) = E2;
*(Uint32*)(dstpix + (looph*2+1)*dstpitch + (loopw*2+1)*4) = E3;
}
}break;}
}
}
pygame-1.9.1release/src/scale.h 0000644 0001750 0001750 00000005235 11223035224 016271 0 ustar vincent vincent /*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
Copyright (C) 2007 Rene Dudfield, Richard Goedeken
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
/* Pentium MMX/SSE smoothscale routines
* Available on Win32 or GCC on a Pentium.
* Sorry, no Win64 support yet for Visual C builds, but it can be added.
*/
#if !defined(SCALE_HEADER)
#define SCALE_HEADER
#if (defined(__GNUC__) && ((defined(__x86_64__) && !defined(_NO_MMX_FOR_X86_64)) || defined(__i386__))) || defined(MS_WIN32)
#define SCALE_MMX_SUPPORT
/* These functions implement an area-averaging shrinking filter in the X-dimension.
*/
void filter_shrink_X_MMX(Uint8 *srcpix, Uint8 *dstpix, int height, int srcpitch, int dstpitch, int srcwidth, int dstwidth);
void filter_shrink_X_SSE(Uint8 *srcpix, Uint8 *dstpix, int height, int srcpitch, int dstpitch, int srcwidth, int dstwidth);
/* These functions implement an area-averaging shrinking filter in the Y-dimension.
*/
void filter_shrink_Y_MMX(Uint8 *srcpix, Uint8 *dstpix, int width, int srcpitch, int dstpitch, int srcheight, int dstheight);
void filter_shrink_Y_SSE(Uint8 *srcpix, Uint8 *dstpix, int width, int srcpitch, int dstpitch, int srcheight, int dstheight);
/* These functions implement a bilinear filter in the X-dimension.
*/
void filter_expand_X_MMX(Uint8 *srcpix, Uint8 *dstpix, int height, int srcpitch, int dstpitch, int srcwidth, int dstwidth);
void filter_expand_X_SSE(Uint8 *srcpix, Uint8 *dstpix, int height, int srcpitch, int dstpitch, int srcwidth, int dstwidth);
/* These functions implement a bilinear filter in the Y-dimension.
*/
void filter_expand_Y_MMX(Uint8 *srcpix, Uint8 *dstpix, int width, int srcpitch, int dstpitch, int srcheight, int dstheight);
void filter_expand_Y_SSE(Uint8 *srcpix, Uint8 *dstpix, int width, int srcpitch, int dstpitch, int srcheight, int dstheight);
#endif /* #if (defined(__GNUC__) && .....) */
#endif /* #if !defined(SCALE_HEADER) */
pygame-1.9.1release/src/rwobject.c 0000644 0001750 0001750 00000031533 11207055754 017030 0 ustar vincent vincent /*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
/*
* SDL_RWops support for python objects
*/
#define NO_PYGAME_C_API
#define PYGAMEAPI_RWOBJECT_INTERNAL
#include "pygame.h"
#include "pgcompat.h"
typedef struct
{
PyObject* read;
PyObject* write;
PyObject* seek;
PyObject* tell;
PyObject* close;
#ifdef WITH_THREAD
PyThreadState* thread;
#endif
} RWHelper;
static int rw_seek (SDL_RWops* context, int offset, int whence);
static int rw_read (SDL_RWops* context, void* ptr, int size, int maxnum);
static int rw_write (SDL_RWops* context, const void* ptr, int size, int maxnum);
static int rw_close (SDL_RWops* context);
#ifdef WITH_THREAD
static int rw_seek_th (SDL_RWops* context, int offset, int whence);
static int rw_read_th (SDL_RWops* context, void* ptr, int size, int maxnum);
static int rw_write_th (SDL_RWops* context, const void* ptr, int size,
int maxnum);
static int rw_close_th (SDL_RWops* context);
#endif
static SDL_RWops*
get_standard_rwop (PyObject* obj)
{
#if PY3
if (PyUnicode_Check (obj)) {
int result;
char* name;
PyObject* tuple = PyTuple_New (1);
if (!tuple) {
return NULL;
}
Py_INCREF (obj);
PyTuple_SET_ITEM (tuple, 0, obj);
result = PyArg_ParseTuple (tuple, "s", &name);
Py_DECREF (tuple);
if (!result)
return NULL;
return SDL_RWFromFile (name, "rb");
}
else if (PyBytes_Check (obj)) {
int result;
char* name;
PyObject* tuple = PyTuple_New (1);
if (!tuple)
return NULL;
Py_INCREF (obj);
PyTuple_SET_ITEM (tuple, 0, obj);
result = PyArg_ParseTuple (tuple, "y", &name);
Py_DECREF (tuple);
if (!result)
return NULL;
return SDL_RWFromFile (name, "rb");
}
#else
if (PyString_Check (obj) || PyUnicode_Check (obj))
{
int result;
char* name;
PyObject* tuple = PyTuple_New (1);
if (!tuple)
return NULL;
Py_INCREF (obj);
PyTuple_SET_ITEM (tuple, 0, obj);
result = PyArg_ParseTuple (tuple, "s", &name);
Py_DECREF (tuple);
if (!result)
return NULL;
return SDL_RWFromFile (name, "rb");
}
else if (PyFile_Check(obj))
return SDL_RWFromFP (PyFile_AsFile (obj), 0);
#endif
return NULL;
}
static void
fetch_object_methods (RWHelper* helper, PyObject* obj)
{
helper->read = helper->write = helper->seek = helper->tell =
helper->close = NULL;
if (PyObject_HasAttrString (obj, "read"))
{
helper->read = PyObject_GetAttrString (obj, "read");
if(helper->read && !PyCallable_Check (helper->read))
{
Py_DECREF (helper->read);
helper->read = NULL;
}
}
if (PyObject_HasAttrString (obj, "write"))
{
helper->write = PyObject_GetAttrString (obj, "write");
if (helper->write && !PyCallable_Check (helper->write))
{
Py_DECREF (helper->write);
helper->write = NULL;
}
}
if (PyObject_HasAttrString (obj, "seek"))
{
helper->seek = PyObject_GetAttrString (obj, "seek");
if (helper->seek && !PyCallable_Check (helper->seek))
{
Py_DECREF (helper->seek);
helper->seek = NULL;
}
}
if (PyObject_HasAttrString (obj, "tell"))
{
helper->tell = PyObject_GetAttrString (obj, "tell");
if (helper->tell && !PyCallable_Check (helper->tell))
{
Py_DECREF (helper->tell);
helper->tell = NULL;
}
}
if(PyObject_HasAttrString(obj, "close"))
{
helper->close = PyObject_GetAttrString (obj, "close");
if (helper->close && !PyCallable_Check (helper->close))
{
Py_DECREF (helper->close);
helper->close = NULL;
}
}
}
static SDL_RWops*
RWopsFromPython (PyObject* obj)
{
SDL_RWops* rw;
RWHelper* helper;
if (!obj)
return (SDL_RWops*) RAISE (PyExc_TypeError, "Invalid filetype object");
rw = get_standard_rwop (obj);
if (rw)
return rw;
helper = PyMem_New (RWHelper, 1);
fetch_object_methods (helper, obj);
rw = SDL_AllocRW ();
rw->hidden.unknown.data1 = (void*) helper;
rw->seek = rw_seek;
rw->read = rw_read;
rw->write = rw_write;
rw->close = rw_close;
return rw;
}
static int
RWopsCheckPython (SDL_RWops* rw)
{
return rw->close == rw_close;
}
static int
rw_seek (SDL_RWops* context, int offset, int whence)
{
RWHelper* helper = (RWHelper*) context->hidden.unknown.data1;
PyObject* result;
int retval;
if (!helper->seek || !helper->tell)
return -1;
if (!(offset == 0 && whence == SEEK_CUR)) /*being called only for 'tell'*/
{
result = PyObject_CallFunction (helper->seek, "ii", offset, whence);
if (!result)
return -1;
Py_DECREF (result);
}
result = PyObject_CallFunction (helper->tell, NULL);
if (!result)
return -1;
retval = PyInt_AsLong (result);
Py_DECREF (result);
return retval;
}
static int
rw_read (SDL_RWops* context, void* ptr, int size, int maxnum)
{
RWHelper* helper = (RWHelper*) context->hidden.unknown.data1;
PyObject* result;
int retval;
if (!helper->read)
return -1;
result = PyObject_CallFunction (helper->read, "i", size * maxnum);
if (!result)
return -1;
if (!Bytes_Check (result))
{
Py_DECREF (result);
return -1;
}
retval = Bytes_GET_SIZE (result);
memcpy (ptr, Bytes_AsString (result), retval);
retval /= size;
Py_DECREF (result);
return retval;
}
static int
rw_write (SDL_RWops* context, const void* ptr, int size, int num)
{
RWHelper* helper = (RWHelper*) context->hidden.unknown.data1;
PyObject* result;
if (!helper->write)
return -1;
result = PyObject_CallFunction (helper->write, "s#", ptr, size * num);
if(!result)
return -1;
Py_DECREF (result);
return num;
}
static int
rw_close (SDL_RWops* context)
{
RWHelper* helper = (RWHelper*) context->hidden.unknown.data1;
PyObject* result;
int retval = 0;
if (helper->close)
{
result = PyObject_CallFunction (helper->close, NULL);
if (result)
retval = -1;
Py_XDECREF (result);
}
Py_XDECREF (helper->seek);
Py_XDECREF (helper->tell);
Py_XDECREF (helper->write);
Py_XDECREF (helper->read);
Py_XDECREF (helper->close);
PyMem_Del (helper);
SDL_FreeRW (context);
return retval;
}
static SDL_RWops*
RWopsFromPythonThreaded (PyObject* obj)
{
SDL_RWops* rw;
RWHelper* helper;
PyInterpreterState* interp;
PyThreadState* thread;
if (!obj)
return (SDL_RWops*) RAISE (PyExc_TypeError, "Invalid filetype object");
#ifndef WITH_THREAD
return (SDL_RWops*) RAISE (PyExc_NotImplementedError,
"Python built without thread support");
#else
helper = PyMem_New (RWHelper, 1);
fetch_object_methods (helper, obj);
rw = SDL_AllocRW ();
rw->hidden.unknown.data1 = (void*) helper;
rw->seek = rw_seek_th;
rw->read = rw_read_th;
rw->write = rw_write_th;
rw->close = rw_close_th;
PyEval_InitThreads ();
thread = PyThreadState_Get ();
interp = thread->interp;
helper->thread = PyThreadState_New (interp);
return rw;
#endif
}
static int
RWopsCheckPythonThreaded (SDL_RWops* rw)
{
#ifdef WITH_THREAD
return rw->close == rw_close_th;
#else
return 0;
#endif
}
#ifdef WITH_THREAD
static int
rw_seek_th (SDL_RWops* context, int offset, int whence)
{
RWHelper* helper = (RWHelper*) context->hidden.unknown.data1;
PyObject* result;
int retval;
PyThreadState* oldstate;
if (!helper->seek || !helper->tell)
return -1;
PyEval_AcquireLock ();
oldstate = PyThreadState_Swap (helper->thread);
if (!(offset == 0 && whence == SEEK_CUR)) /* being seek'd, not just tell'd */
{
result = PyObject_CallFunction (helper->seek, "ii", offset, whence);
if(!result)
{
PyErr_Print();
retval = -1;
goto end;
}
Py_DECREF (result);
}
result = PyObject_CallFunction (helper->tell, NULL);
if (!result)
{
PyErr_Print();
retval = -1;
goto end;
}
retval = PyInt_AsLong (result);
Py_DECREF (result);
end:
PyThreadState_Swap (oldstate);
PyEval_ReleaseLock ();
return retval;
}
static int
rw_read_th (SDL_RWops* context, void* ptr, int size, int maxnum)
{
RWHelper* helper = (RWHelper*) context->hidden.unknown.data1;
PyObject* result;
int retval;
PyThreadState* oldstate;
if (!helper->read)
return -1;
PyEval_AcquireLock ();
oldstate = PyThreadState_Swap (helper->thread);
result = PyObject_CallFunction (helper->read, "i", size * maxnum);
if (!result)
{
PyErr_Print();
retval = -1;
goto end;
}
if (!Bytes_Check (result))
{
Py_DECREF (result);
PyErr_Print();
retval = -1;
goto end;
}
retval = Bytes_GET_SIZE (result);
memcpy (ptr, Bytes_AsString (result), retval);
retval /= size;
Py_DECREF (result);
end:
PyThreadState_Swap (oldstate);
PyEval_ReleaseLock ();
return retval;
}
static int
rw_write_th (SDL_RWops* context, const void* ptr, int size, int num)
{
RWHelper* helper = (RWHelper*) context->hidden.unknown.data1;
PyObject* result;
int retval;
PyThreadState* oldstate;
if (!helper->write)
return -1;
PyEval_AcquireLock ();
oldstate = PyThreadState_Swap (helper->thread);
result = PyObject_CallFunction (helper->write, "s#", ptr, size * num);
if (!result)
{
PyErr_Print();
retval = -1;
goto end;
}
Py_DECREF (result);
retval = num;
end:
PyThreadState_Swap (oldstate);
PyEval_ReleaseLock ();
return retval;
}
static int
rw_close_th (SDL_RWops* context)
{
RWHelper* helper = (RWHelper*) context->hidden.unknown.data1;
PyObject* result;
int retval = 0;
PyThreadState* oldstate;
PyEval_AcquireLock ();
oldstate = PyThreadState_Swap (helper->thread);
if (helper->close)
{
result = PyObject_CallFunction (helper->close, NULL);
if (!result)
{
PyErr_Print();
retval = -1;
}
Py_XDECREF (result);
}
Py_XDECREF (helper->seek);
Py_XDECREF (helper->tell);
Py_XDECREF (helper->write);
Py_XDECREF (helper->read);
Py_XDECREF (helper->close);
PyThreadState_Swap (oldstate);
PyThreadState_Clear (helper->thread);
PyThreadState_Delete (helper->thread);
PyMem_Del (helper);
PyEval_ReleaseLock ();
SDL_FreeRW (context);
return retval;
}
#endif
static PyMethodDef _rwobject_methods[] =
{
{ NULL, NULL }
};
/*DOC*/ static char _rwobject_doc[] =
/*DOC*/ "SDL_RWops support";
MODINIT_DEFINE (rwobject)
{
PyObject *module, *dict, *apiobj;
int ecode;
static void* c_api[PYGAMEAPI_RWOBJECT_NUMSLOTS];
#if PY3
static struct PyModuleDef _module = {
PyModuleDef_HEAD_INIT,
"rwobject",
_rwobject_doc,
-1,
_rwobject_methods,
NULL, NULL, NULL, NULL
};
#endif
/* Create the module and add the functions */
#if PY3
module = PyModule_Create (&_module);
#else
module = Py_InitModule3 (MODPREFIX "rwobject",
_rwobject_methods,
_rwobject_doc);
#endif
if (module == NULL) {
MODINIT_ERROR;
}
dict = PyModule_GetDict (module);
/* export the c api */
c_api[0] = RWopsFromPython;
c_api[1] = RWopsCheckPython;
c_api[2] = RWopsFromPythonThreaded;
c_api[3] = RWopsCheckPythonThreaded;
apiobj = PyCObject_FromVoidPtr (c_api, NULL);
if (apiobj == NULL) {
DECREF_MOD (module);
MODINIT_ERROR;
}
ecode = PyDict_SetItemString (dict, PYGAMEAPI_LOCAL_ENTRY, apiobj);
Py_DECREF (apiobj);
if (ecode == -1) {
DECREF_MOD (module);
MODINIT_ERROR;
}
MODINIT_RETURN (module);
}
pygame-1.9.1release/src/rotozoom.c 0000644 0001750 0001750 00000035672 11207055754 017111 0 ustar vincent vincent /*
SDL_rotozoom.c - rotozoomer for 32bit or 8bit surfaces
LGPL (c) A. Schiffler
This is a trimmed down version of SDL_rotozoom, from the
SDL_gfx library. This source is from version 2.0.3. What's
left is only what's needed for the rotozoom function.
*/
#define NO_PYGAME_C_API
#include "pygame.h"
#include "math.h"
typedef struct tColorRGBA {
Uint8 r; Uint8 g; Uint8 b; Uint8 a;
} tColorRGBA;
#define VALUE_LIMIT 0.001
#ifndef MAX
#define MAX(a,b) (((a) > (b)) ? (a) : (b))
#endif
#ifndef M_PI
#define M_PI 3.141592654
#endif
/*
32bit Zoomer with optional anti-aliasing by bilinear interpolation.
Zoomes 32bit RGBA/ABGR 'src' surface to 'dst' surface.
*/
int zoomSurfaceRGBA(SDL_Surface * src, SDL_Surface * dst, int smooth)
{
int x, y, sx, sy, *sax, *say, *csax, *csay, csx, csy, ex, ey, t1, t2, sstep;
tColorRGBA *c00, *c01, *c10, *c11;
tColorRGBA *sp, *csp, *dp;
int sgap, dgap;
/*
* Variable setup
*/
if (smooth) {
/*
* For interpolation: assume source dimension is one pixel
*/
/*
* smaller to avoid overflow on right and bottom edge.
*/
sx = (int) (65536.0 * (float) (src->w - 1) / (float) dst->w);
sy = (int) (65536.0 * (float) (src->h - 1) / (float) dst->h);
} else {
sx = (int) (65536.0 * (float) src->w / (float) dst->w);
sy = (int) (65536.0 * (float) src->h / (float) dst->h);
}
/*
* Allocate memory for row increments
*/
if ((sax = (int *) malloc((dst->w + 1) * sizeof(Uint32))) == NULL) {
return (-1);
}
if ((say = (int *) malloc((dst->h + 1) * sizeof(Uint32))) == NULL) {
free(sax);
return (-1);
}
/*
* Precalculate row increments
*/
csx = 0;
csax = sax;
for (x = 0; x <= dst->w; x++) {
*csax = csx;
csax++;
csx &= 0xffff;
csx += sx;
}
csy = 0;
csay = say;
for (y = 0; y <= dst->h; y++) {
*csay = csy;
csay++;
csy &= 0xffff;
csy += sy;
}
/*
* Pointer setup
*/
sp = csp = (tColorRGBA *) src->pixels;
dp = (tColorRGBA *) dst->pixels;
sgap = src->pitch - src->w * 4;
dgap = dst->pitch - dst->w * 4;
/*
* Switch between interpolating and non-interpolating code
*/
if (smooth) {
/*
* Interpolating Zoom
*/
/*
* Scan destination
*/
csay = say;
for (y = 0; y < dst->h; y++) {
/*
* Setup color source pointers
*/
c00 = csp;
c01 = csp;
c01++;
c10 = (tColorRGBA *) ((Uint8 *) csp + src->pitch);
c11 = c10;
c11++;
csax = sax;
for (x = 0; x < dst->w; x++) {
/*
* Interpolate colors
*/
ex = (*csax & 0xffff);
ey = (*csay & 0xffff);
t1 = ((((c01->r - c00->r) * ex) >> 16) + c00->r) & 0xff;
t2 = ((((c11->r - c10->r) * ex) >> 16) + c10->r) & 0xff;
dp->r = (((t2 - t1) * ey) >> 16) + t1;
t1 = ((((c01->g - c00->g) * ex) >> 16) + c00->g) & 0xff;
t2 = ((((c11->g - c10->g) * ex) >> 16) + c10->g) & 0xff;
dp->g = (((t2 - t1) * ey) >> 16) + t1;
t1 = ((((c01->b - c00->b) * ex) >> 16) + c00->b) & 0xff;
t2 = ((((c11->b - c10->b) * ex) >> 16) + c10->b) & 0xff;
dp->b = (((t2 - t1) * ey) >> 16) + t1;
t1 = ((((c01->a - c00->a) * ex) >> 16) + c00->a) & 0xff;
t2 = ((((c11->a - c10->a) * ex) >> 16) + c10->a) & 0xff;
dp->a = (((t2 - t1) * ey) >> 16) + t1;
/*
* Advance source pointers
*/
csax++;
sstep = (*csax >> 16);
c00 += sstep;
c01 += sstep;
c10 += sstep;
c11 += sstep;
/*
* Advance destination pointer
*/
dp++;
}
/*
* Advance source pointer
*/
csay++;
csp = (tColorRGBA *) ((Uint8 *) csp + (*csay >> 16) * src->pitch);
/*
* Advance destination pointers
*/
dp = (tColorRGBA *) ((Uint8 *) dp + dgap);
}
} else {
/*
* Non-Interpolating Zoom
*/
csay = say;
for (y = 0; y < dst->h; y++) {
sp = csp;
csax = sax;
for (x = 0; x < dst->w; x++) {
/*
* Draw
*/
*dp = *sp;
/*
* Advance source pointers
*/
csax++;
sp += (*csax >> 16);
/*
* Advance destination pointer
*/
dp++;
}
/*
* Advance source pointer
*/
csay++;
csp = (tColorRGBA *) ((Uint8 *) csp + (*csay >> 16) * src->pitch);
/*
* Advance destination pointers
*/
dp = (tColorRGBA *) ((Uint8 *) dp + dgap);
}
}
/*
* Remove temp arrays
*/
free(sax);
free(say);
return (0);
}
/*
32bit Rotozoomer with optional anti-aliasing by bilinear interpolation.
Rotates and zoomes 32bit RGBA/ABGR 'src' surface to 'dst' surface.
*/
void transformSurfaceRGBA(SDL_Surface * src, SDL_Surface * dst, int cx,
int cy, int isin, int icos, int smooth)
{
int x, y, t1, t2, dx, dy, xd, yd, sdx, sdy, ax, ay, ex, ey, sw, sh;
tColorRGBA c00, c01, c10, c11;
tColorRGBA *pc, *sp;
int gap;
/*
* Variable setup
*/
xd = ((src->w - dst->w) << 15);
yd = ((src->h - dst->h) << 15);
ax = (cx << 16) - (icos * cx);
ay = (cy << 16) - (isin * cx);
sw = src->w - 1;
sh = src->h - 1;
pc = dst->pixels;
gap = dst->pitch - dst->w * 4;
/*
* Switch between interpolating and non-interpolating code
*/
if (smooth) {
for (y = 0; y < dst->h; y++) {
dy = cy - y;
sdx = (ax + (isin * dy)) + xd;
sdy = (ay - (icos * dy)) + yd;
for (x = 0; x < dst->w; x++) {
dx = (sdx >> 16);
dy = (sdy >> 16);
if ((dx >= -1) && (dy >= -1) && (dx < src->w) && (dy < src->h)) {
if ((dx >= 0) && (dy >= 0) && (dx < sw) && (dy < sh)) {
sp = (tColorRGBA *) ((Uint8 *) src->pixels + src->pitch * dy);
sp += dx;
c00 = *sp;
sp += 1;
c01 = *sp;
sp = (tColorRGBA *) ((Uint8 *) sp + src->pitch);
sp -= 1;
c10 = *sp;
sp += 1;
c11 = *sp;
} else if ((dx == sw) && (dy == sh)) {
sp = (tColorRGBA *) ((Uint8 *) src->pixels + src->pitch * dy);
sp += dx;
c00 = *sp;
c01 = *sp;
c10 = *sp;
c11 = *sp;
} else if ((dx == -1) && (dy == -1)) {
sp = (tColorRGBA *) (src->pixels);
c00 = *sp;
c01 = *sp;
c10 = *sp;
c11 = *sp;
} else if ((dx == -1) && (dy == sh)) {
sp = (tColorRGBA *) (src->pixels);
sp = (tColorRGBA *) ((Uint8 *) src->pixels + src->pitch * dy);
c00 = *sp;
c01 = *sp;
c10 = *sp;
c11 = *sp;
} else if ((dx == sw) && (dy == -1)) {
sp = (tColorRGBA *) (src->pixels);
sp += dx;
c00 = *sp;
c01 = *sp;
c10 = *sp;
c11 = *sp;
} else if (dx == -1) {
sp = (tColorRGBA *) ((Uint8 *) src->pixels + src->pitch * dy);
c00 = *sp;
c01 = *sp;
c10 = *sp;
sp = (tColorRGBA *) ((Uint8 *) sp + src->pitch);
c11 = *sp;
} else if (dy == -1) {
sp = (tColorRGBA *) (src->pixels);
sp += dx;
c00 = *sp;
c01 = *sp;
c10 = *sp;
sp += 1;
c11 = *sp;
} else if (dx == sw) {
sp = (tColorRGBA *) ((Uint8 *) src->pixels + src->pitch * dy);
sp += dx;
c00 = *sp;
c01 = *sp;
sp = (tColorRGBA *) ((Uint8 *) sp + src->pitch);
c10 = *sp;
c11 = *sp;
} else if (dy == sh) {
sp = (tColorRGBA *) ((Uint8 *) src->pixels + src->pitch * dy);
sp += dx;
c00 = *sp;
sp += 1;
c01 = *sp;
c10 = *sp;
c11 = *sp;
} else {
// NOTE: a catchall to appease gcc4 warnings...
// Probably should not get here. we'll see.
// old behaviour would be to use the previous pixel, from the previous loop.
sp = (tColorRGBA *) (src->pixels);
c00 = *sp;
c01 = *sp;
c10 = *sp;
c11 = *sp;
}
/*
* Interpolate colors
*/
ex = (sdx & 0xffff);
ey = (sdy & 0xffff);
t1 = ((((c01.r - c00.r) * ex) >> 16) + c00.r) & 0xff;
t2 = ((((c11.r - c10.r) * ex) >> 16) + c10.r) & 0xff;
pc->r = (((t2 - t1) * ey) >> 16) + t1;
t1 = ((((c01.g - c00.g) * ex) >> 16) + c00.g) & 0xff;
t2 = ((((c11.g - c10.g) * ex) >> 16) + c10.g) & 0xff;
pc->g = (((t2 - t1) * ey) >> 16) + t1;
t1 = ((((c01.b - c00.b) * ex) >> 16) + c00.b) & 0xff;
t2 = ((((c11.b - c10.b) * ex) >> 16) + c10.b) & 0xff;
pc->b = (((t2 - t1) * ey) >> 16) + t1;
t1 = ((((c01.a - c00.a) * ex) >> 16) + c00.a) & 0xff;
t2 = ((((c11.a - c10.a) * ex) >> 16) + c10.a) & 0xff;
pc->a = (((t2 - t1) * ey) >> 16) + t1;
}
sdx += icos;
sdy += isin;
pc++;
}
pc = (tColorRGBA *) ((Uint8 *) pc + gap);
}
} else {
for (y = 0; y < dst->h; y++) {
dy = cy - y;
sdx = (ax + (isin * dy)) + xd;
sdy = (ay - (icos * dy)) + yd;
for (x = 0; x < dst->w; x++) {
dx = (short) (sdx >> 16);
dy = (short) (sdy >> 16);
if ((dx >= 0) && (dy >= 0) && (dx < src->w) && (dy < src->h)) {
sp = (tColorRGBA *) ((Uint8 *) src->pixels + src->pitch * dy);
sp += dx;
*pc = *sp;
}
sdx += icos;
sdy += isin;
pc++;
}
pc = (tColorRGBA *) ((Uint8 *) pc + gap);
}
}
}
/*
rotozoomSurface()
Rotates and zoomes a 32bit or 8bit 'src' surface to newly created 'dst' surface.
'angle' is the rotation in degrees. 'zoom' a scaling factor. If 'smooth' is 1
then the destination 32bit surface is anti-aliased. If the surface is not 8bit
or 32bit RGBA/ABGR it will be converted into a 32bit RGBA format on the fly.
*/
#define VALUE_LIMIT 0.001
/* Local rotozoom-size function with trig result return */
void rotozoomSurfaceSizeTrig(int width, int height, double angle,
double zoom, int *dstwidth, int *dstheight,
double *canglezoom, double *sanglezoom)
{
double x, y, cx, cy, sx, sy;
double radangle;
int dstwidthhalf, dstheighthalf;
/*
* Determine destination width and height by rotating a centered source box
*/
radangle = angle * (M_PI / 180.0);
*sanglezoom = sin(radangle);
*canglezoom = cos(radangle);
*sanglezoom *= zoom;
*canglezoom *= zoom;
x = width / 2;
y = height / 2;
cx = *canglezoom * x;
cy = *canglezoom * y;
sx = *sanglezoom * x;
sy = *sanglezoom * y;
dstwidthhalf = MAX((int)
ceil(MAX(MAX(MAX(fabs(cx + sy), fabs(cx - sy)), fabs(-cx + sy)), fabs(-cx - sy))), 1);
dstheighthalf = MAX((int)
ceil(MAX(MAX(MAX(fabs(sx + cy), fabs(sx - cy)), fabs(-sx + cy)), fabs(-sx - cy))), 1);
*dstwidth = 2 * dstwidthhalf;
*dstheight = 2 * dstheighthalf;
}
/* Publically available rotozoom-size function */
void rotozoomSurfaceSize(int width, int height, double angle,
double zoom, int *dstwidth, int *dstheight)
{
double dummy_sanglezoom, dummy_canglezoom;
rotozoomSurfaceSizeTrig(width, height, angle, zoom, dstwidth, dstheight, &dummy_sanglezoom, &dummy_canglezoom);
}
/*
zoomSurface()
Zoomes a 32bit or 8bit 'src' surface to newly created 'dst' surface.
'zoomx' and 'zoomy' are scaling factors for width and height. If 'smooth' is 1
then the destination 32bit surface is anti-aliased. If the surface is not 8bit
or 32bit RGBA/ABGR it will be converted into a 32bit RGBA format on the fly.
*/
void zoomSurfaceSize(int width, int height, double zoomx, double zoomy,
int *dstwidth, int *dstheight)
{
/*
* Sanity check zoom factors
*/
if (zoomx < VALUE_LIMIT) {
zoomx = VALUE_LIMIT;
}
if (zoomy < VALUE_LIMIT) {
zoomy = VALUE_LIMIT;
}
/*
* Calculate target size
*/
*dstwidth = (int) ((double) width * zoomx);
*dstheight = (int) ((double) height * zoomy);
if (*dstwidth < 1) {
*dstwidth = 1;
}
if (*dstheight < 1) {
*dstheight = 1;
}
}
/* Publically available rotozoom function */
SDL_Surface *rotozoomSurface(SDL_Surface * src, double angle,
double zoom, int smooth)
{
SDL_Surface *rz_src;
SDL_Surface *rz_dst;
double zoominv;
double sanglezoom, canglezoom, sanglezoominv, canglezoominv;
int dstwidthhalf, dstwidth, dstheighthalf, dstheight;
int is32bit;
int src_converted;
/*
* Sanity check
*/
if (src == NULL)
return (NULL);
/*
* Determine if source surface is 32bit or 8bit
*/
is32bit = (src->format->BitsPerPixel == 32);
if ((is32bit) || (src->format->BitsPerPixel == 8)) {
/*
* Use source surface 'as is'
*/
rz_src = src;
src_converted = 0;
} else {
/*
* New source surface is 32bit with a defined RGBA ordering
*/
rz_src =
SDL_CreateRGBSurface(SDL_SWSURFACE, src->w, src->h, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000);
SDL_BlitSurface(src, NULL, rz_src, NULL);
src_converted = 1;
is32bit = 1;
}
/*
* Sanity check zoom factor
*/
if (zoom < VALUE_LIMIT) {
zoom = VALUE_LIMIT;
}
zoominv = 65536.0 / (zoom * zoom);
/*
* Check if we have a rotozoom or just a zoom
*/
if (fabs(angle) > VALUE_LIMIT) {
/*
* Angle!=0: full rotozoom
*/
/*
* -----------------------
*/
/* Determine target size */
rotozoomSurfaceSizeTrig(rz_src->w, rz_src->h, angle, zoom, &dstwidth, &dstheight, &canglezoom, &sanglezoom);
/*
* Calculate target factors from sin/cos and zoom
*/
sanglezoominv = sanglezoom;
canglezoominv = canglezoom;
sanglezoominv *= zoominv;
canglezoominv *= zoominv;
/* Calculate half size */
dstwidthhalf = dstwidth / 2;
dstheighthalf = dstheight / 2;
/*
* Alloc space to completely contain the rotated surface
*/
rz_dst = NULL;
/*
* Target surface is 32bit with source RGBA/ABGR ordering
*/
rz_dst =
SDL_CreateRGBSurface(SDL_SWSURFACE, dstwidth, dstheight, 32,
rz_src->format->Rmask, rz_src->format->Gmask,
rz_src->format->Bmask, rz_src->format->Amask);
/*
* Lock source surface
*/
SDL_LockSurface(rz_src);
/*
* Check which kind of surface we have
*/
/*
* Call the 32bit transformation routine to do the rotation (using alpha)
*/
transformSurfaceRGBA(rz_src, rz_dst, dstwidthhalf, dstheighthalf,
(int) (sanglezoominv), (int) (canglezoominv), smooth);
/*
* Turn on source-alpha support
*/
SDL_SetAlpha(rz_dst, SDL_SRCALPHA, 255);
/*
* Unlock source surface
*/
SDL_UnlockSurface(rz_src);
} else {
/*
* Angle=0: Just a zoom
*/
/*
* --------------------
*/
/*
* Calculate target size
*/
zoomSurfaceSize(rz_src->w, rz_src->h, zoom, zoom, &dstwidth, &dstheight);
/*
* Alloc space to completely contain the zoomed surface
*/
rz_dst = NULL;
/*
* Target surface is 32bit with source RGBA/ABGR ordering
*/
rz_dst =
SDL_CreateRGBSurface(SDL_SWSURFACE, dstwidth, dstheight, 32,
rz_src->format->Rmask, rz_src->format->Gmask,
rz_src->format->Bmask, rz_src->format->Amask);
/*
* Lock source surface
*/
SDL_LockSurface(rz_src);
/*
* Check which kind of surface we have
*/
/*
* Call the 32bit transformation routine to do the zooming (using alpha)
*/
zoomSurfaceRGBA(rz_src, rz_dst, smooth);
/*
* Turn on source-alpha support
*/
SDL_SetAlpha(rz_dst, SDL_SRCALPHA, 255);
/*
* Unlock source surface
*/
SDL_UnlockSurface(rz_src);
}
/*
* Cleanup temp surface
*/
if (src_converted) {
SDL_FreeSurface(rz_src);
}
/*
* Return destination surface
*/
return (rz_dst);
}
pygame-1.9.1release/src/rect.doc 0000644 0001750 0001750 00000016071 11210363734 016463 0 ustar vincent vincent pygame.Rect
pygame object for storing rectangular coordinates
pygame.Rect(left, top, width, height): return Rect
pygame.Rect((left, top), (width, height)): return Rect
pygame.Rect(object): return Rect
Pygame uses Rect objects to store and manipulate rectangular areas. A Rect
can be created from a combination of left, top, width, and height values.
Rects can also be created from python objects that are already a Rect or
have an attribute named "rect".
Any Pygame function that requires a Rect argument also accepts any of
these values to construct a Rect. This makes it easier to create Rects
on the fly as arguments to functions.
The Rect functions that change the position or size of a Rect return
a new copy of the Rect with the affected changes. The original Rect
is not modified. Some methods have an alternate "in-place" version that
returns None but effects the original Rect. These "in-place" methods
are denoted with the "ip" suffix.
The Rect object has several virtual attributes which can be used to move
and align the Rect:
top, left, bottom, right
topleft, bottomleft, topright, bottomright
midtop, midleft, midbottom, midright
center, centerx, centery
size, width, height
w,h
All of these attributes can be assigned to:
rect1.right = 10
rect2.center = (20,30)
Assigning to size, width or height changes the dimensions of the
rectangle; all other assignments move the rectangle without
resizing it. Notice that some attributes are integers and
others are pairs of integers.
If a Rect has a nonzero width or height, it will return True for a
nonzero test. Some methods return a Rect with 0 size to represent an
invalid rectangle.
The coordinates for Rect objects are all integers. The size values
can be programmed to have negative values, but these are considered
illegal Rects for most operations.
There are several collision tests between other rectangles. Most
python containers can be searched for collisions against a single Rect.
The area covered by a Rect does not include the right- and bottom-most
edge of pixels. If one Rect's bottom border is another Rect's top border
(i.e., rect1.bottom=rect2.top), the two meet exactly on the screen
but do not overlap, and rect1.colliderect(rect2) returns false.
Though Rect can be subclassed, methods that return new rectangles are not
subclass aware. That is, move or copy return a new pygame.Rect instance,
not an instance of the subclass. This may change. To make subclass awareness
work though, subclasses may have to maintain the same constructor signature
as Rect.
copy
copy the rectangle
Rect.copy(): return Rect
Returns a new rectangle having the same position and size as the orginal.
move
moves the rectangle
Rect.move(x, y): return Rect
Returns a new rectangle that is moved by the given offset. The x and y
arguments can be any integer value, positive or negative.
move_ip
moves the rectangle, in place
Rect.move_ip(x, y): return None
Same as the Rect.move() method, but operates in place.
inflate
grow or shrink the rectangle size
Rect.inflate(x, y): return Rect
Returns a new rectangle with the size changed by the given offset. The
rectangle remains centered around its current center. Negative values
will shrink the rectangle.
inflate_ip
grow or shrink the rectangle size, in place
Rect.inflate_ip(x, y): return None
Same as the Rect.inflate() method, but operates in place.
clamp
moves the rectangle inside another
Rect.clamp(Rect): return Rect
Returns a new rectangle that is moved to be completely inside the argument
Rect. If the rectangle is too large to fit inside, it is centered inside
the argument Rect, but its size is not changed.
clamp_ip
moves the rectangle inside another, in place
Rect.clamp_ip(Rect): return None
Same as the Rect.clamp() method, but operates in place.
clip
crops a rectangle inside another
Rect.clip(Rect): return Rect
Returns a new rectangle that is cropped to be completely inside the
argument Rect. If the two rectangles do not overlap to begin with, a
Rect with 0 size is returned.
union
joins two rectangles into one
Rect.union(Rect): return Rect
Returns a new rectangle that completely covers the area of the two
provided rectangles. There may be area inside the new Rect that is
not covered by the originals.
union_ip
joins two rectangles into one, in place
Rect.union_ip(Rect): return None
Same as the Rect.union() method, but operates in place.
unionall
the union of many rectangles
Rect.unionall(Rect_sequence): return Rect
Returns the union of one rectangle with a sequence of many rectangles.
unionall_ip
the union of many rectangles, in place
Rect.unionall_ip(Rect_sequence): return None
The same as the Rect.unionall() method, but operates in place.
fit
resize and move a rectangle with aspect ratio
Rect.fit(Rect): return Rect
Returns a new rectangle that is moved and resized to fit another. The
aspect ratio of the original Rect is preserved, so the new rectangle may
be smaller than the target in either width or height.
normalize
correct negative sizes
Rect.normalize(): return None
This will flip the width or height of a rectangle if it has a negative
size. The rectangle will remain in the same place, with only the sides
swapped.
contains
test if one rectangle is inside another
Rect.contains(Rect): return bool
Returns true when the argument is completely inside the Rect.
collidepoint
test if a point is inside a rectangle
Rect.collidepoint(x, y): return bool
Rect.collidepoint((x,y)): return bool
Returns true if the given point is inside the rectangle. A point along
the right or bottom edge is not considered to be inside the rectangle.
colliderect
test if two rectangles overlap
Rect.colliderect(Rect): return bool
Returns true if any portion of either rectangle overlap (except
the top+bottom or left+right edges).
collidelist
test if one rectangle in a list intersects
Rect.collidelist(list): return index
Test whether the rectangle collides with any in a sequence of rectangles.
The index of the first collision found is returned. If no collisions are
found an index of -1 is returned.
collidelistall
test if all rectangles in a list intersect
Rect.collidelistall(list): return indices
Returns a list of all the indices that contain rectangles that collide
with the Rect. If no intersecting rectangles are found, an empty list
is returned.
collidedict
test if one rectangle in a dictionary intersects
Rect.collidedict(dict): return (key, value)
Returns the key and value of the first dictionary value that collides
with the Rect. If no collisions are found, None is returned.
Rect objects are not hashable and cannot be used as keys in a dictionary,
only as values.
collidedictall
test if all rectangles in a dictionary intersect
Rect.collidedictall(dict): return [(key, value), ...]
Returns a list of all the key and value pairs that intersect with the
Rect. If no collisions are found an empty dictionary is returned.
Rect objects are not hashable and cannot be used as keys in a dictionary,
only as values.
pygame-1.9.1release/src/rect.c 0000644 0001750 0001750 00000123715 11207055754 016152 0 ustar vincent vincent /*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
/*
* Python Rect Object -- useful 2d rectangle class
*/
#define PYGAMEAPI_RECT_INTERNAL
#include "pygame.h"
#include "pygamedocs.h"
#include "structmember.h"
#include "pgcompat.h"
static PyTypeObject PyRect_Type;
#define PyRect_Check(x) ((x)->ob_type == &PyRect_Type)
static PyObject* rect_new (PyTypeObject *type, PyObject *args, PyObject *kwds);
static int rect_init (PyRectObject *self, PyObject *args, PyObject *kwds);
GAME_Rect*
GameRect_FromObject (PyObject* obj, GAME_Rect* temp)
{
int val;
int length;
if (PyRect_Check (obj))
return &((PyRectObject*) obj)->r;
if (PySequence_Check (obj) && (length = PySequence_Length (obj)) > 0)
{
if (length == 4)
{
if (!IntFromObjIndex (obj, 0, &val))
return NULL;
temp->x = val;
if (!IntFromObjIndex (obj, 1, &val))
return NULL;
temp->y = val;
if (!IntFromObjIndex (obj, 2, &val))
return NULL;
temp->w = val;
if (!IntFromObjIndex (obj, 3, &val))
return NULL;
temp->h = val;
return temp;
}
if (length == 2)
{
PyObject* sub = PySequence_GetItem (obj, 0);
if (!sub || !PySequence_Check (sub) || PySequence_Length (sub) != 2)
{
Py_XDECREF (sub);
return NULL;
}
if (!IntFromObjIndex (sub, 0, &val))
{
Py_DECREF (sub);
return NULL;
}
temp->x = val;
if (!IntFromObjIndex (sub, 1, &val))
{
Py_DECREF (sub);
return NULL;
}
temp->y = val;
Py_DECREF (sub);
sub = PySequence_GetItem (obj, 1);
if (!sub || !PySequence_Check (sub) || PySequence_Length (sub) != 2)
{
Py_XDECREF (sub);
return NULL;
}
if (!IntFromObjIndex (sub, 0, &val))
{
Py_DECREF (sub);
return NULL;
}
temp->w = val;
if (!IntFromObjIndex (sub, 1, &val))
{
Py_DECREF (sub);
return NULL;
}
temp->h = val;
Py_DECREF (sub);
return temp;
}
if (PyTuple_Check (obj) && length == 1) /*looks like an arg?*/
{
PyObject* sub = PyTuple_GET_ITEM (obj, 0);
if (sub)
return GameRect_FromObject (sub, temp);
}
}
if (PyObject_HasAttrString (obj, "rect"))
{
PyObject *rectattr;
GAME_Rect *returnrect;
rectattr = PyObject_GetAttrString (obj, "rect");
if (PyCallable_Check (rectattr)) /*call if it's a method*/
{
PyObject *rectresult = PyObject_CallObject (rectattr, NULL);
Py_DECREF (rectattr);
if (!rectresult)
return NULL;
rectattr = rectresult;
}
returnrect = GameRect_FromObject (rectattr, temp);
Py_DECREF (rectattr);
return returnrect;
}
return NULL;
}
PyObject*
PyRect_New (SDL_Rect* r)
{
PyRectObject* rect;
rect = (PyRectObject *) PyRect_Type.tp_new (&PyRect_Type, NULL, NULL);
if (rect)
{
rect->r.x = r->x;
rect->r.y = r->y;
rect->r.w = r->w;
rect->r.h = r->h;
}
return (PyObject*)rect;
}
PyObject*
PyRect_New4 (int x, int y, int w, int h)
{
PyRectObject* rect;
rect = (PyRectObject *) PyRect_Type.tp_new (&PyRect_Type, NULL, NULL);
if (rect)
{
rect->r.x = x;
rect->r.y = y;
rect->r.w = w;
rect->r.h = h;
}
return (PyObject*)rect;
}
static int
DoRectsIntersect (GAME_Rect *A, GAME_Rect *B)
{
return ((A->x >= B->x && A->x < B->x + B->w) ||
(B->x >= A->x && B->x < A->x + A->w)) &&
((A->y >= B->y && A->y < B->y + B->h) ||
(B->y >= A->y && B->y < A->y + A->h));
}
static PyObject*
rect_normalize (PyObject* oself)
{
PyRectObject* self = (PyRectObject*)oself;
if (self->r.w < 0)
{
self->r.x += self->r.w;
self->r.w = -self->r.w;
}
if (self->r.h < 0)
{
self->r.y += self->r.h;
self->r.h = -self->r.h;
}
Py_RETURN_NONE;
}
static PyObject*
rect_move (PyObject* oself, PyObject* args)
{
PyRectObject* self = (PyRectObject*)oself;
int x, y;
if (!TwoIntsFromObj (args, &x, &y))
return RAISE (PyExc_TypeError, "argument must contain two numbers");
return PyRect_New4 (self->r.x + x, self->r.y + y, self->r.w, self->r.h);
}
static PyObject*
rect_move_ip (PyObject* oself, PyObject* args)
{
PyRectObject* self = (PyRectObject*)oself;
int x, y;
if (!TwoIntsFromObj (args, &x, &y))
return RAISE (PyExc_TypeError, "argument must contain two numbers");
self->r.x += x;
self->r.y += y;
Py_RETURN_NONE;
}
static PyObject*
rect_inflate (PyObject* oself, PyObject* args)
{
PyRectObject* self = (PyRectObject*)oself;
int x, y;
if (!TwoIntsFromObj (args, &x, &y))
return RAISE (PyExc_TypeError, "argument must contain two numbers");
return PyRect_New4 (self->r.x - x / 2, self->r.y - y / 2,
self->r.w + x, self->r.h + y);
}
static PyObject*
rect_inflate_ip (PyObject* oself, PyObject* args)
{
PyRectObject* self = (PyRectObject*)oself;
int x, y;
if (!TwoIntsFromObj (args, &x, &y))
return RAISE (PyExc_TypeError, "argument must contain two numbers");
self->r.x -= x / 2;
self->r.y -= y / 2;
self->r.w += x;
self->r.h += y;
Py_RETURN_NONE;
}
static PyObject*
rect_union (PyObject* oself, PyObject* args)
{
PyRectObject* self = (PyRectObject*)oself;
GAME_Rect *argrect, temp;
int x, y, w, h;
if (!(argrect = GameRect_FromObject (args, &temp)))
return RAISE (PyExc_TypeError, "Argument must be rect style object");
x = MIN (self->r.x, argrect->x);
y = MIN (self->r.y, argrect->y);
w = MAX (self->r.x + self->r.w, argrect->x + argrect->w) - x;
h = MAX (self->r.y + self->r.h, argrect->y + argrect->h) - y;
return PyRect_New4 (x, y, w, h);
}
static PyObject*
rect_union_ip (PyObject* oself, PyObject* args)
{
PyRectObject* self = (PyRectObject*)oself;
GAME_Rect *argrect, temp;
int x, y, w, h;
if (!(argrect = GameRect_FromObject (args, &temp)))
return RAISE (PyExc_TypeError, "Argument must be rect style object");
x = MIN (self->r.x, argrect->x);
y = MIN (self->r.y, argrect->y);
w = MAX (self->r.x + self->r.w, argrect->x + argrect->w) - x;
h = MAX (self->r.y + self->r.h, argrect->y + argrect->h) - y;
self->r.x = x;
self->r.y = y;
self->r.w = w;
self->r.h = h;
Py_RETURN_NONE;
}
static PyObject*
rect_unionall (PyObject* oself, PyObject* args)
{
PyRectObject* self = (PyRectObject*)oself;
GAME_Rect *argrect, temp;
int loop, size;
PyObject* list, *obj;
int t, l, b, r;
if (!PyArg_ParseTuple (args, "O", &list))
return NULL;
if (!PySequence_Check (list))
return RAISE (PyExc_TypeError,
"Argument must be a sequence of rectstyle objects.");
l = self->r.x;
t = self->r.y;
r = self->r.x + self->r.w;
b = self->r.y + self->r.h;
size = PySequence_Length (list); /*warning, size could be -1 on error?*/
if (size < 1)
return PyRect_New4 (l, t, r-l, b-t);
for (loop = 0; loop < size; ++loop)
{
obj = PySequence_GetItem (list, loop);
if(!obj || !(argrect = GameRect_FromObject (obj, &temp)))
{
RAISE (PyExc_TypeError,
"Argument must be a sequence of rectstyle objects.");
Py_XDECREF (obj);
break;
}
l = MIN (l, argrect->x);
t = MIN (t, argrect->y);
r = MAX (r, argrect->x + argrect->w);
b = MAX (b, argrect->y + argrect->h);
Py_DECREF (obj);
}
return PyRect_New4 (l, t, r-l, b-t);
}
static PyObject*
rect_unionall_ip (PyObject* oself, PyObject* args)
{
PyRectObject* self = (PyRectObject*)oself;
GAME_Rect *argrect, temp;
int loop, size;
PyObject* list, *obj;
int t, l, b, r;
if (!PyArg_ParseTuple (args, "O", &list))
return NULL;
if (!PySequence_Check (list))
return RAISE (PyExc_TypeError,
"Argument must be a sequence of rectstyle objects.");
l = self->r.x;
t = self->r.y;
r = self->r.x + self->r.w;
b = self->r.y + self->r.h;
size = PySequence_Length (list); /*warning, size could be -1 on error?*/
if (size < 1)
return PyRect_New4 (l, t, r-l, b-t);
for (loop = 0; loop < size; ++loop)
{
obj = PySequence_GetItem (list, loop);
if (!obj || !(argrect = GameRect_FromObject (obj, &temp)))
{
RAISE (PyExc_TypeError,
"Argument must be a sequence of rectstyle objects.");
Py_XDECREF (obj);
break;
}
l = MIN (l, argrect->x);
t = MIN (t, argrect->y);
r = MAX (r, argrect->x + argrect->w);
b = MAX (b, argrect->y + argrect->h);
Py_DECREF (obj);
}
self->r.x = l;
self->r.y = t;
self->r.w = r - l;
self->r.h = b - t;
Py_RETURN_NONE;
}
static PyObject*
rect_collidepoint (PyObject* oself, PyObject* args)
{
PyRectObject* self = (PyRectObject*)oself;
int x, y;
int inside;
if (!TwoIntsFromObj (args, &x, &y))
return RAISE (PyExc_TypeError, "argument must contain two numbers");
inside = x >= self->r.x && x < self->r.x + self->r.w &&
y >= self->r.y && y < self->r.y + self->r.h;
return PyInt_FromLong (inside);
}
static PyObject*
rect_colliderect (PyObject* oself, PyObject* args)
{
PyRectObject* self = (PyRectObject*)oself;
GAME_Rect *argrect, temp;
if (!(argrect = GameRect_FromObject (args, &temp)))
return RAISE (PyExc_TypeError, "Argument must be rect style object");
return PyInt_FromLong (DoRectsIntersect (&self->r, argrect));
}
static PyObject*
rect_collidelist (PyObject* oself, PyObject* args)
{
PyRectObject* self = (PyRectObject*)oself;
GAME_Rect *argrect, temp;
int loop, size;
PyObject* list, *obj;
PyObject* ret = NULL;
if (!PyArg_ParseTuple (args, "O", &list))
return NULL;
if (!PySequence_Check (list))
return RAISE (PyExc_TypeError,
"Argument must be a sequence of rectstyle objects.");
size = PySequence_Length (list); /*warning, size could be -1 on error?*/
for (loop = 0; loop < size; ++loop)
{
obj = PySequence_GetItem (list, loop);
if (!obj || !(argrect = GameRect_FromObject (obj, &temp)))
{
RAISE (PyExc_TypeError,
"Argument must be a sequence of rectstyle objects.");
Py_XDECREF (obj);
break;
}
if (DoRectsIntersect (&self->r, argrect))
{
ret = PyInt_FromLong (loop);
Py_DECREF (obj);
break;
}
Py_DECREF (obj);
}
if (loop == size)
ret = PyInt_FromLong (-1);
return ret;
}
static PyObject*
rect_collidelistall (PyObject* oself, PyObject* args)
{
PyRectObject* self = (PyRectObject*)oself;
GAME_Rect *argrect, temp;
int loop, size;
PyObject* list, *obj;
PyObject* ret = NULL;
if (!PyArg_ParseTuple (args, "O", &list))
return NULL;
if (!PySequence_Check (list))
return RAISE (PyExc_TypeError,
"Argument must be a sequence of rectstyle objects.");
ret = PyList_New (0);
if (!ret)
return NULL;
size = PySequence_Length (list); /*warning, size could be -1?*/
for (loop = 0; loop < size; ++loop)
{
obj = PySequence_GetItem (list, loop);
if(!obj || !(argrect = GameRect_FromObject (obj, &temp)))
{
Py_XDECREF (obj);
Py_DECREF (ret);
return RAISE (PyExc_TypeError,
"Argument must be a sequence of rectstyle objects.");
}
if (DoRectsIntersect (&self->r, argrect))
{
PyObject* num = PyInt_FromLong (loop);
if (!num)
{
Py_DECREF (obj);
return NULL;
}
PyList_Append (ret, num);
Py_DECREF (num);
}
Py_DECREF (obj);
}
return ret;
}
static PyObject*
rect_collidedict (PyObject* oself, PyObject* args)
{
PyRectObject* self = (PyRectObject*)oself;
GAME_Rect *argrect, temp;
Py_ssize_t loop=0;
Py_ssize_t values=0;
PyObject* dict, *key, *val;
PyObject* ret = NULL;
if (!PyArg_ParseTuple (args, "O|i", &dict, &values))
return NULL;
if (!PyDict_Check (dict))
return RAISE (PyExc_TypeError,
"Argument must be a dict with rectstyle keys.");
while (PyDict_Next (dict, &loop, &key, &val))
{
if(values) {
if (!(argrect = GameRect_FromObject (val, &temp)))
{
RAISE (PyExc_TypeError,
"Argument must be a dict with rectstyle values.");
break;
}
} else {
if (!(argrect = GameRect_FromObject (key, &temp)))
{
RAISE (PyExc_TypeError,
"Argument must be a dict with rectstyle keys.");
break;
}
}
if (DoRectsIntersect (&self->r, argrect))
{
ret = Py_BuildValue ("(OO)", key, val);
break;
}
}
if (!ret)
Py_RETURN_NONE;
return ret;
}
static PyObject*
rect_collidedictall (PyObject* oself, PyObject* args)
{
PyRectObject* self = (PyRectObject*)oself;
GAME_Rect *argrect, temp;
Py_ssize_t loop=0;
/* should we use values or keys? */
Py_ssize_t values=0;
PyObject* dict, *key, *val;
PyObject* ret = NULL;
if (!PyArg_ParseTuple (args, "O|i", &dict, &values))
return NULL;
if (!PyDict_Check (dict))
return RAISE (PyExc_TypeError,
"Argument must be a dict with rectstyle keys.");
ret = PyList_New (0);
if(!ret)
return NULL;
while (PyDict_Next (dict, &loop, &key, &val))
{
if (values) {
if (!(argrect = GameRect_FromObject (val, &temp)))
{
Py_DECREF (ret);
return RAISE (PyExc_TypeError,
"Argument must be a dict with rectstyle values.");
}
} else {
if (!(argrect = GameRect_FromObject (key, &temp)))
{
Py_DECREF (ret);
return RAISE (PyExc_TypeError,
"Argument must be a dict with rectstyle keys.");
}
}
if (DoRectsIntersect (&self->r, argrect))
{
PyObject* num = Py_BuildValue ("(OO)", key, val);
if(!num)
return NULL;
PyList_Append (ret, num);
Py_DECREF (num);
}
}
return ret;
}
static PyObject*
rect_clip (PyObject* self, PyObject* args)
{
GAME_Rect *A, *B, temp;
int x, y, w, h;
A = &((PyRectObject*) self)->r;
if (!(B = GameRect_FromObject (args, &temp)))
return RAISE (PyExc_TypeError, "Argument must be rect style object");
/* Left */
if ((A->x >= B->x) && (A->x < (B->x + B->w)))
x = A->x;
else if ((B->x >= A->x) && (B->x < (A->x + A->w)))
x = B->x;
else
goto nointersect;
/* Right */
if (((A->x + A->w) > B->x) && ((A->x + A->w) <= (B->x + B->w)))
w = (A->x + A->w) - x;
else if (((B->x + B->w) > A->x) && ((B->x + B->w) <= (A->x + A->w)))
w = (B->x + B->w) - x;
else
goto nointersect;
/* Top */
if ((A->y >= B->y) && (A->y < (B->y + B->h)))
y = A->y;
else if ((B->y >= A->y) && (B->y < (A->y + A->h)))
y = B->y;
else
goto nointersect;
/* Bottom */
if (((A->y + A->h) > B->y) && ((A->y + A->h) <= (B->y + B->h)))
h = (A->y + A->h) - y;
else if (((B->y + B->h) > A->y) && ((B->y + B->h) <= (A->y + A->h)))
h = (B->y + B->h) - y;
else
goto nointersect;
return PyRect_New4 (x, y, w, h);
nointersect:
return PyRect_New4 (A->x, A->y, 0, 0);
}
static PyObject*
rect_contains (PyObject* oself, PyObject* args)
{
int contained;
PyRectObject* self = (PyRectObject*)oself;
GAME_Rect *argrect, temp;
if (!(argrect = GameRect_FromObject (args, &temp)))
return RAISE (PyExc_TypeError, "Argument must be rect style object");
contained = (self->r.x <= argrect->x) && (self->r.y <= argrect->y) &&
(self->r.x + self->r.w >= argrect->x + argrect->w) &&
(self->r.y + self->r.h >= argrect->y + argrect->h) &&
(self->r.x + self->r.w > argrect->x) &&
(self->r.y + self->r.h > argrect->y);
return PyInt_FromLong (contained);
}
static PyObject*
rect_clamp (PyObject* oself, PyObject* args)
{
PyRectObject* self = (PyRectObject*)oself;
GAME_Rect *argrect, temp;
int x, y;
if (!(argrect = GameRect_FromObject (args, &temp)))
return RAISE (PyExc_TypeError, "Argument must be rect style object");
if (self->r.w >= argrect->w)
x = argrect->x + argrect->w / 2 - self->r.w / 2;
else if (self->r.x < argrect->x)
x = argrect->x;
else if (self->r.x + self->r.w > argrect->x + argrect->w)
x = argrect->x + argrect->w - self->r.w;
else
x = self->r.x;
if (self->r.h >= argrect->h)
y = argrect->y + argrect->h / 2 - self->r.h / 2;
else if (self->r.y < argrect->y)
y = argrect->y;
else if (self->r.y + self->r.h > argrect->y + argrect->h)
y = argrect->y + argrect->h - self->r.h;
else
y = self->r.y;
return PyRect_New4 (x, y, self->r.w, self->r.h);
}
static PyObject*
rect_fit (PyObject* oself, PyObject* args)
{
PyRectObject* self = (PyRectObject*)oself;
GAME_Rect *argrect, temp;
int w, h, x, y;
float xratio, yratio, maxratio;
if (!(argrect = GameRect_FromObject (args, &temp)))
return RAISE (PyExc_TypeError, "Argument must be rect style object");
xratio = (float) self->r.w / (float) argrect->w;
yratio = (float) self->r.h / (float) argrect->h;
maxratio = (xratio > yratio) ? xratio : yratio;
w = (int) (self->r.w / maxratio);
h = (int) (self->r.h / maxratio);
x = argrect->x + (argrect->w - w)/2;
y = argrect->y + (argrect->h - h)/2;
return PyRect_New4 (x, y, w, h);
}
static PyObject*
rect_clamp_ip (PyObject* oself, PyObject* args)
{
PyRectObject* self = (PyRectObject*)oself;
GAME_Rect *argrect, temp;
int x, y;
if (!(argrect = GameRect_FromObject (args, &temp)))
return RAISE (PyExc_TypeError, "Argument must be rect style object");
if (self->r.w >= argrect->w)
x = argrect->x + argrect->w / 2 - self->r.w / 2;
else if (self->r.x < argrect->x)
x = argrect->x;
else if (self->r.x + self->r.w > argrect->x + argrect->w)
x = argrect->x + argrect->w - self->r.w;
else
x = self->r.x;
if (self->r.h >= argrect->h)
y = argrect->y + argrect->h / 2 - self->r.h / 2;
else if (self->r.y < argrect->y)
y = argrect->y;
else if (self->r.y + self->r.h > argrect->y + argrect->h)
y = argrect->y + argrect->h - self->r.h;
else
y = self->r.y;
self->r.x = x;
self->r.y = y;
Py_RETURN_NONE;
}
/* for pickling */
static PyObject*
rect_reduce (PyObject* oself)
{
PyRectObject* self = (PyRectObject*)oself;
return Py_BuildValue ("(O(iiii))", oself->ob_type,
(int)self->r.x, (int)self->r.y,
(int)self->r.w, (int)self->r.h);
}
/* for copy module */
static PyObject*
rect_copy (PyObject* oself)
{
PyRectObject* self = (PyRectObject*)oself;
return PyRect_New4 (self->r.x, self->r.y, self->r.w, self->r.h);
}
static struct PyMethodDef rect_methods[] =
{
{ "normalize", (PyCFunction) rect_normalize, METH_NOARGS,
DOC_RECTNORMALIZE },
{ "clip", rect_clip, METH_VARARGS, DOC_RECTCLIP},
{ "clamp", rect_clamp, METH_VARARGS, DOC_RECTCLAMP},
{ "clamp_ip", rect_clamp_ip, METH_VARARGS, DOC_RECTCLAMPIP},
{ "copy", (PyCFunction) rect_copy, METH_NOARGS, DOC_RECTCOPY},
{ "fit", rect_fit, METH_VARARGS, DOC_RECTFIT},
{ "move", rect_move, METH_VARARGS, DOC_RECTMOVE},
{ "inflate", rect_inflate, METH_VARARGS, DOC_RECTINFLATE},
{ "union", rect_union, METH_VARARGS, DOC_RECTUNION},
{ "unionall", rect_unionall, METH_VARARGS, DOC_RECTUNIONALL},
{ "move_ip", rect_move_ip, METH_VARARGS, DOC_RECTMOVEIP},
{ "inflate_ip", rect_inflate_ip, METH_VARARGS, DOC_RECTINFLATEIP},
{ "union_ip", rect_union_ip, METH_VARARGS, DOC_RECTUNIONIP},
{ "unionall_ip", rect_unionall_ip, METH_VARARGS, DOC_RECTUNIONALLIP},
{ "collidepoint", rect_collidepoint, METH_VARARGS, DOC_RECTCOLLIDEPOINT},
{ "colliderect", rect_colliderect, METH_VARARGS, DOC_RECTCOLLIDERECT},
{ "collidelist", rect_collidelist, METH_VARARGS, DOC_RECTCOLLIDELIST},
{ "collidelistall", rect_collidelistall, METH_VARARGS,
DOC_RECTCOLLIDELISTALL},
{ "collidedict", rect_collidedict, METH_VARARGS, DOC_RECTCOLLIDEDICT},
{ "collidedictall", rect_collidedictall, METH_VARARGS,
DOC_RECTCOLLIDEDICTALL},
{ "contains", rect_contains, METH_VARARGS, DOC_RECTCONTAINS},
{ "__reduce__", (PyCFunction) rect_reduce, METH_NOARGS, NULL},
{ "__copy__", (PyCFunction) rect_copy, METH_NOARGS, NULL},
{ NULL, NULL, 0, NULL }
};
/* sequence functions */
static Py_ssize_t
rect_length (PyObject *_self)
{
return 4;
}
static PyObject*
rect_item (PyObject *_self, Py_ssize_t i)
{
PyRectObject *self = (PyRectObject *) _self;
int* data = (int*)&self->r;
if (i < 0 || i > 3)
return RAISE (PyExc_IndexError, "Invalid rect Index");
return PyInt_FromLong (data[i]);
}
static int
rect_ass_item (PyObject *_self, Py_ssize_t i, PyObject *v)
{
PyRectObject *self = (PyRectObject *) _self;
int val;
int* data = (int*)&self->r;
if (i < 0 || i > 3)
{
RAISE (PyExc_IndexError, "Invalid rect Index");
return -1;
}
if (!IntFromObj (v, &val))
{
RAISE (PyExc_TypeError, "Must assign numeric values");
return -1;
}
data[i] = val;
return 0;
}
static PyObject*
rect_slice (PyObject *_self, Py_ssize_t ilow, Py_ssize_t ihigh)
{
PyRectObject *self = (PyRectObject *) _self;
PyObject *list;
int* data = (int*)&self->r;
int numitems, loop, l = 4;
if (ihigh < 0)
ihigh += l;
if (ilow < 0)
ilow += l;
if (ilow < 0)
ilow = 0;
else if (ilow > l)
ilow = l;
if (ihigh < 0)
ihigh = 0;
else if (ihigh > l)
ihigh = l;
if (ihigh < ilow)
ihigh = ilow;
numitems = ihigh - ilow;
list = PyList_New (numitems);
for (loop = 0; loop < numitems; ++loop)
PyList_SET_ITEM (list, loop, PyInt_FromLong (data[loop + ilow]));
return list;
}
static int
rect_ass_slice(PyObject *_self, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
{
PyRectObject *self = (PyRectObject *) _self;
int* data = (int*)&self->r;
int numitems, loop, l = 4;
int val;
if (!PySequence_Check (v))
{
RAISE (PyExc_TypeError, "Assigned slice must be a sequence");
return -1;
}
if (ihigh < 0)
ihigh += l;
if (ilow < 0)
ilow += l;
if (ilow < 0)
ilow = 0;
else if (ilow > l)
ilow = l;
if (ihigh < 0)
ihigh = 0;
else if (ihigh > l)
ihigh = l;
if (ihigh < ilow)
ihigh = ilow;
numitems = ihigh - ilow;
if (numitems != PySequence_Length (v))
{
RAISE (PyExc_ValueError, "Assigned slice must be same length");
return -1;
}
for (loop = 0; loop < numitems; ++loop)
{
if (!IntFromObjIndex (v, loop, &val))
return -1;
data[loop + ilow] = val;
}
return 0;
}
static PySequenceMethods rect_as_sequence =
{
rect_length, /*length*/
NULL, /*concat*/
NULL, /*repeat*/
rect_item, /*item*/
rect_slice, /*slice*/
rect_ass_item, /*ass_item*/
rect_ass_slice, /*ass_slice*/
};
/* numeric functions */
static int
rect_nonzero (PyRectObject *self)
{
return self->r.w != 0 && self->r.h != 0;
}
#if !PY3
static int
rect_coerce (PyObject** o1, PyObject** o2)
{
PyObject* new1;
PyObject* new2;
GAME_Rect* r, temp;
if (PyRect_Check (*o1))
{
new1 = *o1;
Py_INCREF (new1);
}
else if ((r = GameRect_FromObject (*o1, &temp)))
new1 = PyRect_New4 (r->x, r->y, r->w, r->h);
else
return 1;
if (PyRect_Check (*o2))
{
new2 = *o2;
Py_INCREF (new2);
}
else if ((r = GameRect_FromObject (*o2, &temp)))
new2 = PyRect_New4 (r->x, r->y, r->w, r->h);
else
{
Py_DECREF (new1);
return 1;
}
*o1 = new1;
*o2 = new2;
return 0;
}
#endif
static PyNumberMethods rect_as_number =
{
(binaryfunc)NULL, /*add*/
(binaryfunc)NULL, /*subtract*/
(binaryfunc)NULL, /*multiply*/
#if !PY3
(binaryfunc)NULL, /*divide*/
#endif
(binaryfunc)NULL, /*remainder*/
(binaryfunc)NULL, /*divmod*/
(ternaryfunc)NULL, /*power*/
(unaryfunc)NULL, /*negative*/
(unaryfunc)NULL, /*pos*/
(unaryfunc)NULL, /*abs*/
(inquiry)rect_nonzero, /*nonzero / bool*/
(unaryfunc)NULL, /*invert*/
(binaryfunc)NULL, /*lshift*/
(binaryfunc)NULL, /*rshift*/
(binaryfunc)NULL, /*and*/
(binaryfunc)NULL, /*xor*/
(binaryfunc)NULL, /*or*/
#if !PY3
(coercion)rect_coerce, /*coerce*/
#endif
(unaryfunc)NULL, /*int*/
#if !PY3
(unaryfunc)NULL, /*long*/
#endif
(unaryfunc)NULL, /*float*/
};
/* object type functions */
static void
rect_dealloc (PyRectObject *self)
{
if (self->weakreflist)
PyObject_ClearWeakRefs ((PyObject*)self);
Py_TYPE(self)->tp_free ((PyObject*)self);
}
static PyObject*
rect_repr (PyRectObject *self)
{
char string[256];
sprintf (string, "", self->r.x, self->r.y,
self->r.w, self->r.h);
return Text_FromUTF8 (string);
}
static PyObject*
rect_str (PyRectObject *self)
{
return rect_repr (self);
}
static PyObject*
rect_richcompare(PyObject *o1, PyObject *o2, int opid)
{
GAME_Rect *o1rect, *o2rect, temp1, temp2;
int cmp;
o1rect = GameRect_FromObject (o1, &temp1);
if (!o1rect) {
goto Unimplemented;
}
o2rect = GameRect_FromObject (o2, &temp2);
if (!o2rect)
{
goto Unimplemented;
}
if (o1rect->x != o2rect->x) {
cmp = o1rect->x < o2rect->x ? -1 : 1;
}
else if (o1rect->y != o2rect->y) {
cmp = o1rect->y < o2rect->y ? -1 : 1;
}
else if (o1rect->w != o2rect->w) {
cmp = o1rect->w < o2rect->w ? -1 : 1;
}
else if (o1rect->h != o2rect->h) {
cmp = o1rect->h < o2rect->h ? -1 : 1;
}
else {
cmp = 0;
}
switch (opid)
{
case Py_LT:
return PyBool_FromLong (cmp < 0);
case Py_LE:
return PyBool_FromLong (cmp <= 0);
case Py_EQ:
return PyBool_FromLong (cmp == 0);
case Py_NE:
return PyBool_FromLong (cmp != 0);
case Py_GT:
return PyBool_FromLong (cmp > 0);
case Py_GE:
return PyBool_FromLong (cmp >= 0);
default:
break;
}
Unimplemented:
Py_INCREF (Py_NotImplemented);
return Py_NotImplemented;
}
/*width*/
static PyObject*
rect_getwidth (PyRectObject *self, void *closure)
{
return PyInt_FromLong (self->r.w);
}
static int
rect_setwidth (PyRectObject *self, PyObject* value, void *closure)
{
int val1;
if (!IntFromObj (value, &val1))
return -1;
self->r.w = val1;
return 0;
}
/*height*/
static PyObject*
rect_getheight (PyRectObject *self, void *closure)
{
return PyInt_FromLong (self->r.h);
}
static int
rect_setheight (PyRectObject *self, PyObject* value, void *closure)
{
int val1;
if (!IntFromObj (value, &val1))
{
RAISE (PyExc_TypeError, "invalid rect assignment");
return -1;
}
self->r.h = val1;
return 0;
}
/*top*/
static PyObject*
rect_gettop (PyRectObject *self, void *closure)
{
return PyInt_FromLong (self->r.y);
}
static int
rect_settop (PyRectObject *self, PyObject* value, void *closure)
{
int val1;
if (!IntFromObj (value, &val1))
{
RAISE (PyExc_TypeError, "invalid rect assignment");
return -1;
}
self->r.y = val1;
return 0;
}
/*left*/
static PyObject*
rect_getleft (PyRectObject *self, void *closure)
{
return PyInt_FromLong (self->r.x);
}
static int
rect_setleft (PyRectObject *self, PyObject* value, void *closure)
{
int val1;
if (!IntFromObj (value, &val1))
{
RAISE (PyExc_TypeError, "invalid rect assignment");
return -1;
}
self->r.x = val1;
return 0;
}
/*right*/
static PyObject*
rect_getright (PyRectObject *self, void *closure)
{
return PyInt_FromLong (self->r.x + self->r.w);
}
static int
rect_setright (PyRectObject *self, PyObject* value, void *closure)
{
int val1;
if (!IntFromObj (value, &val1))
{
RAISE (PyExc_TypeError, "invalid rect assignment");
return -1;
}
self->r.x = val1-self->r.w;
return 0;
}
/*bottom*/
static PyObject*
rect_getbottom (PyRectObject *self, void *closure)
{
return PyInt_FromLong (self->r.y + self->r.h);
}
static int
rect_setbottom (PyRectObject *self, PyObject* value, void *closure)
{
int val1;
if (!IntFromObj (value, &val1))
{
RAISE (PyExc_TypeError, "invalid rect assignment");
return -1;
}
self->r.y = val1-self->r.h;
return 0;
}
/*centerx*/
static PyObject*
rect_getcenterx (PyRectObject *self, void *closure)
{
return PyInt_FromLong (self->r.x + (self->r.w >> 1));
}
static int
rect_setcenterx (PyRectObject *self, PyObject* value, void *closure)
{
int val1;
if (!IntFromObj (value, &val1))
{
RAISE (PyExc_TypeError, "invalid rect assignment");
return -1;
}
self->r.x = val1 - (self->r.w >> 1);
return 0;
}
/*centery*/
static PyObject*
rect_getcentery (PyRectObject *self, void *closure)
{
return PyInt_FromLong (self->r.y + (self->r.h >> 1));
}
static int
rect_setcentery (PyRectObject *self, PyObject* value, void *closure)
{
int val1;
if (!IntFromObj (value, &val1))
{
RAISE (PyExc_TypeError, "invalid rect assignment");
return -1;
}
self->r.y = val1 - (self->r.h >> 1);
return 0;
}
/*topleft*/
static PyObject*
rect_gettopleft (PyRectObject *self, void *closure)
{
return Py_BuildValue ("(ii)", self->r.x, self->r.y);
}
static int
rect_settopleft (PyRectObject *self, PyObject* value, void *closure)
{
int val1, val2;
if (!TwoIntsFromObj (value, &val1, &val2))
{
RAISE (PyExc_TypeError, "invalid rect assignment");
return -1;
}
self->r.x = val1;
self->r.y = val2;
return 0;
}
/*topright*/
static PyObject*
rect_gettopright (PyRectObject *self, void *closure)
{
return Py_BuildValue ("(ii)", self->r.x+self->r.w, self->r.y);
}
static int
rect_settopright (PyRectObject *self, PyObject* value, void *closure)
{
int val1, val2;
if (!TwoIntsFromObj (value, &val1, &val2))
{
RAISE (PyExc_TypeError, "invalid rect assignment");
return -1;
}
self->r.x = val1-self->r.w;
self->r.y = val2;
return 0;
}
/*bottomleft*/
static PyObject*
rect_getbottomleft (PyRectObject *self, void *closure)
{
return Py_BuildValue ("(ii)", self->r.x, self->r.y+self->r.h);
}
static int
rect_setbottomleft (PyRectObject *self, PyObject* value, void *closure)
{
int val1, val2;
if (!TwoIntsFromObj (value, &val1, &val2))
{
RAISE (PyExc_TypeError, "invalid rect assignment");
return -1;
}
self->r.x = val1;
self->r.y = val2-self->r.h;
return 0;
}
/*bottomright*/
static PyObject*
rect_getbottomright (PyRectObject *self, void *closure)
{
return Py_BuildValue ("(ii)", self->r.x+self->r.w, self->r.y+self->r.h);
}
static int
rect_setbottomright (PyRectObject *self, PyObject* value, void *closure)
{
int val1, val2;
if (!TwoIntsFromObj (value, &val1, &val2))
{
RAISE (PyExc_TypeError, "invalid rect assignment");
return -1;
}
self->r.x = val1-self->r.w;
self->r.y = val2-self->r.h;
return 0;
}
/*midtop*/
static PyObject*
rect_getmidtop (PyRectObject *self, void *closure)
{
return Py_BuildValue ("(ii)", self->r.x + (self->r.w >> 1), self->r.y);
}
static int
rect_setmidtop (PyRectObject *self, PyObject* value, void *closure)
{
int val1, val2;
if (!TwoIntsFromObj (value, &val1, &val2))
{
RAISE (PyExc_TypeError, "invalid rect assignment");
return -1;
}
self->r.x += val1 - (self->r.x + (self->r.w >> 1));
self->r.y = val2;
return 0;
}
/*midleft*/
static PyObject*
rect_getmidleft (PyRectObject *self, void *closure)
{
return Py_BuildValue ("(ii)", self->r.x, self->r.y+(self->r.h>>1));
}
static int
rect_setmidleft (PyRectObject *self, PyObject* value, void *closure)
{
int val1, val2;
if (!TwoIntsFromObj (value, &val1, &val2))
{
RAISE (PyExc_TypeError, "invalid rect assignment");
return -1;
}
self->r.x = val1;
self->r.y += val2 - (self->r.y + (self->r.h >> 1));
return 0;
}
/*midbottom*/
static PyObject*
rect_getmidbottom (PyRectObject *self, void *closure)
{
return Py_BuildValue ("(ii)", self->r.x + (self->r.w >> 1),
self->r.y + self->r.h);
}
static int
rect_setmidbottom (PyRectObject *self, PyObject* value, void *closure)
{
int val1, val2;
if (!TwoIntsFromObj (value, &val1, &val2))
{
RAISE (PyExc_TypeError, "invalid rect assignment");
return -1;
}
self->r.x += val1 - (self->r.x + (self->r.w >> 1));
self->r.y = val2 - self->r.h;
return 0;
}
/*midright*/
static PyObject*
rect_getmidright (PyRectObject *self, void *closure)
{
return Py_BuildValue ("(ii)", self->r.x + self->r.w,
self->r.y + (self->r.h >> 1));
}
static int
rect_setmidright (PyRectObject *self, PyObject* value, void *closure)
{
int val1, val2;
if (!TwoIntsFromObj (value, &val1, &val2))
{
RAISE (PyExc_TypeError, "invalid rect assignment");
return -1;
}
self->r.x = val1 - self->r.w;
self->r.y += val2 -(self->r.y + (self->r.h >> 1));
return 0;
}
/*center*/
static PyObject*
rect_getcenter (PyRectObject *self, void *closure)
{
return Py_BuildValue ("(ii)", self->r.x + (self->r.w >> 1),
self->r.y + (self->r.h >> 1));
}
static int
rect_setcenter (PyRectObject *self, PyObject* value, void *closure)
{
int val1, val2;
if (!TwoIntsFromObj (value, &val1, &val2))
{
RAISE (PyExc_TypeError, "invalid rect assignment");
return -1;
}
self->r.x += val1 - (self->r.x + (self->r.w >> 1));
self->r.y += val2 - (self->r.y + (self->r.h >> 1));
return 0;
}
/*size*/
static PyObject*
rect_getsize (PyRectObject *self, void *closure)
{
return Py_BuildValue ("(ii)", self->r.w, self->r.h);
}
static int
rect_setsize (PyRectObject *self, PyObject* value, void *closure)
{
int val1, val2;
if (!TwoIntsFromObj (value, &val1, &val2))
{
RAISE (PyExc_TypeError, "invalid rect assignment");
return -1;
}
self->r.w = val1;
self->r.h = val2;
return 0;
}
static PyObject*
rect_getsafepickle (PyRectObject *self, void *closure)
{
Py_RETURN_TRUE;
}
static PyGetSetDef rect_getsets[] = {
{ "x", (getter)rect_getleft, (setter)rect_setleft, NULL, NULL },
{ "y", (getter)rect_gettop, (setter)rect_settop, NULL, NULL },
{ "w", (getter)rect_getwidth, (setter)rect_setwidth, NULL, NULL },
{ "h", (getter)rect_getheight, (setter)rect_setheight, NULL, NULL },
{ "width", (getter)rect_getwidth, (setter)rect_setwidth, NULL, NULL },
{ "height", (getter)rect_getheight, (setter)rect_setheight, NULL, NULL },
{ "top", (getter)rect_gettop, (setter)rect_settop, NULL, NULL },
{ "left", (getter)rect_getleft, (setter)rect_setleft, NULL, NULL },
{ "bottom", (getter)rect_getbottom, (setter)rect_setbottom, NULL, NULL },
{ "right", (getter)rect_getright, (setter)rect_setright, NULL, NULL },
{ "centerx", (getter)rect_getcenterx, (setter)rect_setcenterx, NULL, NULL },
{ "centery", (getter)rect_getcentery, (setter)rect_setcentery, NULL, NULL },
{ "topleft", (getter)rect_gettopleft, (setter)rect_settopleft, NULL, NULL },
{ "topright", (getter)rect_gettopright, (setter)rect_settopright, NULL,
NULL },
{ "bottomleft", (getter)rect_getbottomleft, (setter)rect_setbottomleft,
NULL, NULL },
{ "bottomright", (getter)rect_getbottomright, (setter)rect_setbottomright,
NULL, NULL },
{ "midtop", (getter)rect_getmidtop, (setter)rect_setmidtop, NULL, NULL },
{ "midleft", (getter)rect_getmidleft, (setter)rect_setmidleft, NULL, NULL },
{ "midbottom", (getter)rect_getmidbottom, (setter)rect_setmidbottom, NULL,
NULL },
{ "midright", (getter)rect_getmidright, (setter)rect_setmidright, NULL,
NULL },
{ "size", (getter)rect_getsize, (setter)rect_setsize, NULL, NULL },
{ "center", (getter)rect_getcenter, (setter)rect_setcenter, NULL, NULL },
{ "__safe_for_unpickling__", (getter)rect_getsafepickle, NULL, NULL, NULL },
{ NULL, 0, NULL, NULL, NULL } /* Sentinel */
};
static PyTypeObject PyRect_Type =
{
TYPE_HEAD (NULL, 0)
"pygame.Rect", /*name*/
sizeof(PyRectObject), /*basicsize*/
0, /*itemsize*/
/* methods */
(destructor)rect_dealloc, /*dealloc*/
(printfunc)NULL, /*print*/
NULL, /*getattr*/
NULL, /*setattr*/
NULL, /*compare/reserved*/
(reprfunc)rect_repr, /*repr*/
&rect_as_number, /*as_number*/
&rect_as_sequence, /*as_sequence*/
NULL, /*as_mapping*/
(hashfunc)NULL, /*hash*/
(ternaryfunc)NULL, /*call*/
(reprfunc)rect_str, /*str*/
/* Space for future expansion */
0L,0L,0L,
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
DOC_PYGAMERECT, /* Documentation string */
0, /* tp_traverse */
0, /* tp_clear */
(richcmpfunc)rect_richcompare, /* tp_richcompare */
offsetof(PyRectObject, weakreflist), /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
rect_methods, /* tp_methods */
0, /* tp_members */
rect_getsets, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)rect_init, /* tp_init */
0, /* tp_alloc */
rect_new, /* tp_new */
};
static PyObject*
rect_new (PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PyRectObject *self;
self = (PyRectObject *)type->tp_alloc (type, 0);
if (self)
{
self->r.x = self->r.y = 0;
self->r.w = self->r.h = 0;
self->weakreflist = NULL;
}
return (PyObject*)self;
}
static int
rect_init (PyRectObject *self, PyObject *args, PyObject *kwds)
{
GAME_Rect *argrect, temp;
if (!(argrect = GameRect_FromObject (args, &temp)))
{
RAISE (PyExc_TypeError, "Argument must be rect style object");
return -1;
}
self->r.x = argrect->x;
self->r.y = argrect->y;
self->r.w = argrect->w;
self->r.h = argrect->h;
return 0;
}
static PyMethodDef _rect_methods[] =
{
{NULL, NULL, 0, NULL}
};
/*DOC*/ static char _rectangle_doc[] =
/*DOC*/ "Module for the rectangle object\n";
MODINIT_DEFINE (rect)
{
PyObject *module, *dict, *apiobj;
int ecode;
static void* c_api[PYGAMEAPI_RECT_NUMSLOTS];
#if PY3
static struct PyModuleDef _module = {
PyModuleDef_HEAD_INIT,
"rect",
_rectangle_doc,
-1,
_rect_methods,
NULL, NULL, NULL, NULL
};
#endif
/* imported needed apis; Do this first so if there is an error
the module is not loaded.
*/
import_pygame_base ();
if (PyErr_Occurred ()) {
MODINIT_ERROR;
}
/* Create the module and add the functions */
if (PyType_Ready (&PyRect_Type) < 0) {
MODINIT_ERROR;
}
#if PY3
module = PyModule_Create (&_module);
#else
module = Py_InitModule3 (MODPREFIX "rect", _rect_methods, _rectangle_doc);
#endif
if (module == NULL) {
MODINIT_ERROR;
}
dict = PyModule_GetDict (module);
if (PyDict_SetItemString (dict, "RectType", (PyObject *)&PyRect_Type)) {
DECREF_MOD (module);
MODINIT_ERROR;
}
if (PyDict_SetItemString (dict, "Rect", (PyObject *)&PyRect_Type)) {
DECREF_MOD (module);
MODINIT_ERROR;
}
/* export the c api */
c_api[0] = &PyRect_Type;
c_api[1] = PyRect_New;
c_api[2] = PyRect_New4;
c_api[3] = GameRect_FromObject;
apiobj = PyCObject_FromVoidPtr (c_api, NULL);
if (apiobj == NULL) {
DECREF_MOD (module);
MODINIT_ERROR;
}
ecode = PyDict_SetItemString (dict, PYGAMEAPI_LOCAL_ENTRY, apiobj);
Py_DECREF (apiobj);
if (ecode) {
DECREF_MOD (module);
MODINIT_ERROR;
}
MODINIT_RETURN (module);
}
pygame-1.9.1release/src/pypm.pyx 0000644 0001750 0001750 00000041730 11210671750 016566 0 ustar vincent vincent # pyPortMidi
# Python bindings for PortMidi
# John Harrison
# http://sound.media.mit.edu/~harrison
# harrison@media.mit.edu
# written in Pyrex
__version__="0.05"
import array
# CHANGES:
# 0.0.5: (June 1st, 2009)
# Output no longer calls abort when it deallocates.
# Added abort and close methods.
# Need to call Abort() explicityly if you want that to happen.
#
# 0.0.3: (March 15, 2005)
# changed everything from tuples to lists
# return 4 values for PmRead instead of 3 (for SysEx)
# minor fixes for flexibility and error checking
# flushed out DistUtils package and added Mac and Linux compile support
# Markus Pfaff: added ability for WriteSysEx to accept lists as well
# as strings
# 0.0.2:
# fixed pointer to function calls to avoid necessity of pyport library
# 0.0.1:
# initial release
cdef extern from "portmidi.h":
ctypedef enum PmError:
pmNoError = 0,
pmHostError = -10000,
pmInvalidDeviceId, #/* out of range or output device when input is requested or vice versa */
pmInsufficientMemory,
pmBufferTooSmall,
pmBufferOverflow,
pmBadPtr,
pmBadData, #/* illegal midi data, e.g. missing EOX */
pmInternalError,
pmBufferMaxSize, #/* buffer is already as large as it can be */
PmError Pm_Initialize()
PmError Pm_Terminate()
ctypedef void PortMidiStream
ctypedef PortMidiStream PmStream # CHECK THIS!
ctypedef int PmDeviceID
int Pm_HasHostError( PortMidiStream * stream )
char *Pm_GetErrorText( PmError errnum )
Pm_GetHostErrorText(char * msg, unsigned int len)
ctypedef struct PmDeviceInfo:
int structVersion
char *interf #/* underlying MIDI API, e.g. MMSystem or DirectX */
char *name #/* device name, e.g. USB MidiSport 1x1 */
int input #/* true iff input is available */
int output #/* true iff output is available */
int opened #/* used by generic PortMidi code to do error checking on arguments */
int Pm_CountDevices()
PmDeviceID Pm_GetDefaultInputDeviceID()
PmDeviceID Pm_GetDefaultOutputDeviceID()
ctypedef long PmTimestamp
ctypedef PmTimestamp (*PmTimeProcPtr)(void *time_info)
#PmBefore is not defined...
PmDeviceInfo* Pm_GetDeviceInfo( PmDeviceID id )
PmError Pm_OpenInput( PortMidiStream** stream,
PmDeviceID inputDevice,
void *inputDriverInfo,
long bufferSize,
long (*PmPtr) (), # long = PtTimestamp
void *time_info )
PmError Pm_OpenOutput( PortMidiStream** stream,
PmDeviceID outputDevice,
void *outputDriverInfo,
long bufferSize,
#long (*PmPtr) (), # long = PtTimestamp
PmTimeProcPtr time_proc, # long = PtTimestamp
void *time_info,
long latency )
PmError Pm_SetFilter( PortMidiStream* stream, long filters )
PmError Pm_Abort( PortMidiStream* stream )
PmError Pm_Close( PortMidiStream* stream )
ctypedef long PmMessage
ctypedef struct PmEvent:
PmMessage message
PmTimestamp timestamp
PmError Pm_Read( PortMidiStream *stream, PmEvent *buffer, long length )
PmError Pm_Poll( PortMidiStream *stream)
int Pm_Channel(int channel)
PmError Pm_SetChannelMask(PortMidiStream *stream, int mask)
PmError Pm_Write( PortMidiStream *stream, PmEvent *buffer, long length )
PmError Pm_WriteSysEx( PortMidiStream *stream, PmTimestamp when, unsigned char *msg)
cdef extern from "porttime.h":
ctypedef enum PtError:
ptNoError = 0,
ptHostError = -10000,
ptAlreadyStarted,
ptAlreadyStopped,
ptInsufficientMemory
ctypedef long PtTimestamp
ctypedef void (* PtCallback)( PtTimestamp timestamp, void *userData )
PtError Pt_Start(int resolution, PtCallback *callback, void *userData)
PtTimestamp Pt_Time()
FILT_ACTIVE=0x1
FILT_SYSEX=0x2
FILT_CLOCK=0x4
FILT_PLAY=0x8
FILT_F9=0x10
FILT_TICK=0x10
FILT_FD=0x20
FILT_UNDEFINED=0x30
FILT_RESET=0x40
FILT_REALTIME=0x7F
FILT_NOTE=0x80
FILT_CHANNEL_AFTERTOUCH=0x100
FILT_POLY_AFTERTOUCH=0x200
FILT_AFTERTOUCH=0x300
FILT_PROGRAM=0x400
FILT_CONTROL=0x800
FILT_PITCHBEND=0x1000
FILT_MTC=0x2000
FILT_SONG_POSITION=0x4000
FILT_SONG_SELECT=0x8000
FILT_TUNE=0x10000
FALSE=0
TRUE=1
def Initialize():
"""
Initialize: call this first
"""
Pm_Initialize()
Pt_Start(1, NULL, NULL) # /* equiv to TIME_START: start timer w/ ms accuracy */
def Terminate():
"""
Terminate: call this to clean up Midi streams when done.
If you do not call this on Windows machines when you are
done with MIDI, your system may crash.
"""
Pm_Terminate()
def GetDefaultInputDeviceID():
return Pm_GetDefaultInputDeviceID()
def GetDefaultOutputDeviceID():
return Pm_GetDefaultOutputDeviceID()
def CountDevices():
return Pm_CountDevices()
def GetDeviceInfo(i):
"""
GetDeviceInfo(): returns 5 parameters
- underlying MIDI API
- device name
- TRUE iff input is available
- TRUE iff output is available
- TRUE iff device stream is already open
"""
cdef PmDeviceInfo *info
# disregarding the constness from Pm_GetDeviceInfo, since pyrex doesn't do const.
info = Pm_GetDeviceInfo(i)
if info <> NULL: return info.interf, info.name, info.input, info.output, info.opened
else: return
def Time():
"""
Time() returns the current time in ms
of the PortMidi timer
"""
return Pt_Time()
def GetErrorText(err):
"""
GetErrorText() returns human-readable error
messages translated from error numbers
"""
return Pm_GetErrorText(err)
def Channel(chan):
"""
Channel() is used with ChannelMask on input MIDI streams.
Example: to receive input on channels 1 and 10 on a MIDI
stream called MidiIn:
MidiIn.SetChannelMask(pypm.Channel(1) | pypm.Channel(10))
note: PyPortMidi Channel function has been altered from
the original PortMidi c call to correct for what
seems to be a bug --- i.e. channel filters were
all numbered from 0 to 15 instead of 1 to 16.
"""
return Pm_Channel(chan-1)
cdef class Output:
"""
class Output:
define an output MIDI stream. Takes the form:
x = pypm.Output(MidiOutputDevice, latency)
latency is in ms.
If latency = 0 then timestamps for output are ignored.
"""
cdef int i
cdef PmStream *midi
cdef int debug
cdef int _aborted
def __init__(self, OutputDevice, latency=0):
cdef PmError err
#cdef PtTimestamp (*PmPtr) ()
cdef PmTimeProcPtr PmPtr
self.i = OutputDevice
self.debug = 0
self._aborted = 0
if latency == 0:
PmPtr = NULL
else:
PmPtr = &Pt_Time
if self.debug: print "Opening Midi Output"
# Why is bufferSize 0 here?
err = Pm_OpenOutput(&(self.midi), self.i, NULL, 0, PmPtr, NULL, latency)
if err < 0:
s = Pm_GetErrorText(err)
# Something's amiss here - if we try to throw an Exception
# here, we crash.
if not err == -10000:
raise Exception,s
else:
print "Unable to open Midi OutputDevice=",OutputDevice," err=",s
def __dealloc__(self):
if self.debug: print "Closing MIDI output stream and destroying instance"
#err = Pm_Abort(self.midi)
#if err < 0: raise Exception, Pm_GetErrorText(err)
err = Pm_Close(self.midi)
if err < 0: raise Exception, Pm_GetErrorText(err)
def _check_open(self):
""" checks to see if the midi is open, and if not, raises an error.
"""
if self.midi == NULL:
raise Exception, "midi Output not open."
if self._aborted:
raise Exception, "midi Output aborted. Need to call Close after Abort."
def Close(self):
"""
Close()
closes a midi stream, flushing any pending buffers.
(PortMidi attempts to close open streams when the application
exits -- this is particularly difficult under Windows.)
"""
#if not self.midi:
# return
err = Pm_Close(self.midi)
if err < 0:
raise Exception, Pm_GetErrorText(err)
#self.midi = NULL
def Abort(self):
"""
Abort() terminates outgoing messages immediately
The caller should immediately close the output port;
this call may result in transmission of a partial midi message.
There is no abort for Midi input because the user can simply
ignore messages in the buffer and close an input device at
any time.
"""
#if not self.midi:
# return
err = Pm_Abort(self.midi)
if err < 0:
raise Exception, Pm_GetErrorText(err)
self._aborted = 1
def Write(self, data):
"""
Write(data)
output a series of MIDI information in the form of a list:
Write([[[status <,data1><,data2><,data3>],timestamp],
[[status <,data1><,data2><,data3>],timestamp],...])
fields are optional
example: choose program change 1 at time 20000 and
send note 65 with velocity 100 500 ms later.
Write([[[0xc0,0,0],20000],[[0x90,60,100],20500]])
notes:
1. timestamps will be ignored if latency = 0.
2. To get a note to play immediately, send MIDI info with
timestamp read from function Time.
3. understanding optional data fields:
Write([[[0xc0,0,0],20000]]) is equivalent to
Write([[[0xc0],20000]])
"""
cdef PmEvent buffer[1024]
cdef PmError err
cdef int i
self._check_open()
if len(data) > 1024: raise IndexError, 'maximum list length is 1024'
else:
for loop1 in range(len(data)):
if ((len(data[loop1][0]) > 4) |
(len(data[loop1][0]) < 1)):
raise IndexError, str(len(data[loop1][0]))+' arguments in event list'
buffer[loop1].message = 0
for i in range(len(data[loop1][0])):
buffer[loop1].message = buffer[loop1].message + ((data[loop1][0][i]&0xFF) << (8*i))
buffer[loop1].timestamp = data[loop1][1]
if self.debug: print loop1," : ",buffer[loop1].message," : ",buffer[loop1].timestamp
if self.debug: print "writing to midi buffer"
err= Pm_Write(self.midi, buffer, len(data))
if err < 0: raise Exception, Pm_GetErrorText(err)
def WriteShort(self, status, data1 = 0, data2 = 0):
"""
WriteShort(status <, data1><, data2>)
output MIDI information of 3 bytes or less.
data fields are optional
status byte could be:
0xc0 = program change
0x90 = note on
etc.
data bytes are optional and assumed 0 if omitted
example: note 65 on with velocity 100
WriteShort(0x90,65,100)
"""
cdef PmEvent buffer[1]
cdef PmError err
self._check_open()
buffer[0].timestamp = Pt_Time()
buffer[0].message = ((((data2) << 16) & 0xFF0000) | (((data1) << 8) & 0xFF00) | ((status) & 0xFF))
if self.debug: print "Writing to MIDI buffer"
err = Pm_Write(self.midi, buffer, 1) # stream, buffer, length
if err < 0 : raise Exception, Pm_GetErrorText(err)
def WriteSysEx(self, when, msg):
"""
WriteSysEx(,)
writes a timestamped system-exclusive midi message.
can be a *list* or a *string*
example:
(assuming y is an input MIDI stream)
y.WriteSysEx(0,'\\xF0\\x7D\\x10\\x11\\x12\\x13\\xF7')
is equivalent to
y.WriteSysEx(pypm.Time,
[0xF0, 0x7D, 0x10, 0x11, 0x12, 0x13, 0xF7])
"""
cdef PmError err
cdef char *cmsg
cdef PtTimestamp CurTime
self._check_open()
if type(msg) is list:
msg = array.array('B',msg).tostring() # Markus Pfaff contribution
cmsg = msg
CurTime = Pt_Time()
err = Pm_WriteSysEx(self.midi, when, cmsg)
if err < 0 : raise Exception, Pm_GetErrorText(err)
while Pt_Time() == CurTime: # wait for SysEx to go thru or...my
pass # win32 machine crashes w/ multiple SysEx
cdef class Input:
"""
class Input:
define an input MIDI stream. Takes the form:
x = pypm.Input(MidiInputDevice)
"""
cdef PmStream *midi
cdef int debug
cdef int i
def __init__(self, InputDevice, buffersize=4096):
cdef PmError err
self.i = InputDevice
self.debug = 0
err= Pm_OpenInput(&(self.midi),self.i,NULL,buffersize,&Pt_Time,NULL)
if err < 0: raise Exception, Pm_GetErrorText(err)
if self.debug: print "MIDI input opened."
def __dealloc__(self):
cdef PmError err
if self.debug: print "Closing MIDI input stream and destroying instance"
err = Pm_Close(self.midi)
if err < 0:
raise Exception, Pm_GetErrorText(err)
def _check_open(self):
""" checks to see if the midi is open, and if not, raises an error.
"""
if self.midi == NULL:
raise Exception, "midi Input not open."
def Close(self):
"""
Close()
closes a midi stream, flushing any pending buffers.
(PortMidi attempts to close open streams when the application
exits -- this is particularly difficult under Windows.)
"""
#if not self.midi:
# return
err = Pm_Close(self.midi)
if err < 0:
raise Exception, Pm_GetErrorText(err)
#self.midi = NULL
def SetFilter(self, filters):
"""
SetFilter() sets filters on an open input stream
to drop selected input types. By default, only active sensing
messages are filtered. To prohibit, say, active sensing and
sysex messages, call
SetFilter(stream, FILT_ACTIVE | FILT_SYSEX);
Filtering is useful when midi routing or midi thru functionality
is being provided by the user application.
For example, you may want to exclude timing messages
(clock, MTC, start/stop/continue), while allowing note-related
messages to pass. Or you may be using a sequencer or drum-machine
for MIDI clock information but want to exclude any notes
it may play.
Note: SetFilter empties the buffer after setting the filter,
just in case anything got through.
"""
cdef PmEvent buffer[1]
cdef PmError err
self._check_open()
err = Pm_SetFilter(self.midi, filters)
if err < 0: raise Exception, Pm_GetErrorText(err)
while(Pm_Poll(self.midi) != pmNoError):
err = Pm_Read(self.midi,buffer,1)
if err < 0: raise Exception, Pm_GetErrorText(err)
def SetChannelMask(self, mask):
"""
SetChannelMask() filters incoming messages based on channel.
The mask is a 16-bit bitfield corresponding to appropriate channels
Channel() can assist in calling this function.
i.e. to set receive only input on channel 1, call with
SetChannelMask(Channel(1))
Multiple channels should be OR'd together, like
SetChannelMask(Channel(10) | Channel(11))
note: PyPortMidi Channel function has been altered from
the original PortMidi c call to correct for what
seems to be a bug --- i.e. channel filters were
all numbered from 0 to 15 instead of 1 to 16.
"""
cdef PmError err
self._check_open()
err = Pm_SetChannelMask(self.midi,mask)
if err < 0: raise Exception, Pm_GetErrorText(err)
def Poll(self):
"""
Poll tests whether input is available,
returning TRUE, FALSE, or an error value.
"""
cdef PmError err
self._check_open()
err = Pm_Poll(self.midi)
if err < 0: raise Exception, Pm_GetErrorText(err)
return err
def Read(self,length):
"""
Read(length): returns up to midi events stored in
the buffer and returns them as a list:
[[[status,data1,data2,data3],timestamp],
[[status,data1,data2,data3],timestamp],...]
example: Read(50) returns all the events in the buffer,
up to 50 events.
"""
cdef PmEvent buffer[1024]
self._check_open()
x = []
if length > 1024: raise IndexError, 'maximum buffer length is 1024'
if length < 1: raise IndexError, 'minimum buffer length is 1'
NumEvents = Pm_Read(self.midi,buffer,length)
if NumEvents < 0: raise Exception, Pm_GetErrorText(NumEvents)
x=[]
if NumEvents >= 1:
for loop in range(NumEvents):
x.append([[buffer[loop].message & 0xff, (buffer[loop].message >> 8) & 0xFF, (buffer[loop].message >> 16) & 0xFF, (buffer[loop].message >> 24) & 0xFF], buffer[loop].timestamp])
return x
pygame-1.9.1release/src/pypm.c 0000644 0001750 0001750 00000630404 11210671750 016172 0 ustar vincent vincent /* Generated by Cython 0.11.2 on Mon Jun 1 16:21:31 2009 */
#define PY_SSIZE_T_CLEAN
#include "Python.h"
#include "structmember.h"
#ifndef Py_PYTHON_H
#error Python headers needed to compile C extensions, please install development version of Python.
#endif
#ifndef PY_LONG_LONG
#define PY_LONG_LONG LONG_LONG
#endif
#ifndef DL_EXPORT
#define DL_EXPORT(t) t
#endif
#if PY_VERSION_HEX < 0x02040000
#define METH_COEXIST 0
#define PyDict_CheckExact(op) (Py_TYPE(op) == &PyDict_Type)
#endif
#if PY_VERSION_HEX < 0x02050000
typedef int Py_ssize_t;
#define PY_SSIZE_T_MAX INT_MAX
#define PY_SSIZE_T_MIN INT_MIN
#define PY_FORMAT_SIZE_T ""
#define PyInt_FromSsize_t(z) PyInt_FromLong(z)
#define PyInt_AsSsize_t(o) PyInt_AsLong(o)
#define PyNumber_Index(o) PyNumber_Int(o)
#define PyIndex_Check(o) PyNumber_Check(o)
#endif
#if PY_VERSION_HEX < 0x02060000
#define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt)
#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
#define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size)
#define PyVarObject_HEAD_INIT(type, size) \
PyObject_HEAD_INIT(type) size,
#define PyType_Modified(t)
typedef struct {
void *buf;
PyObject *obj;
Py_ssize_t len;
Py_ssize_t itemsize;
int readonly;
int ndim;
char *format;
Py_ssize_t *shape;
Py_ssize_t *strides;
Py_ssize_t *suboffsets;
void *internal;
} Py_buffer;
#define PyBUF_SIMPLE 0
#define PyBUF_WRITABLE 0x0001
#define PyBUF_FORMAT 0x0004
#define PyBUF_ND 0x0008
#define PyBUF_STRIDES (0x0010 | PyBUF_ND)
#define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES)
#define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES)
#define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES)
#define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES)
#endif
#if PY_MAJOR_VERSION < 3
#define __Pyx_BUILTIN_MODULE_NAME "__builtin__"
#else
#define __Pyx_BUILTIN_MODULE_NAME "builtins"
#endif
#if PY_MAJOR_VERSION >= 3
#define Py_TPFLAGS_CHECKTYPES 0
#define Py_TPFLAGS_HAVE_INDEX 0
#endif
#if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3)
#define Py_TPFLAGS_HAVE_NEWBUFFER 0
#endif
#if PY_MAJOR_VERSION >= 3
#define PyBaseString_Type PyUnicode_Type
#define PyString_Type PyBytes_Type
#define PyString_CheckExact PyBytes_CheckExact
#define PyInt_Type PyLong_Type
#define PyInt_Check(op) PyLong_Check(op)
#define PyInt_CheckExact(op) PyLong_CheckExact(op)
#define PyInt_FromString PyLong_FromString
#define PyInt_FromUnicode PyLong_FromUnicode
#define PyInt_FromLong PyLong_FromLong
#define PyInt_FromSize_t PyLong_FromSize_t
#define PyInt_FromSsize_t PyLong_FromSsize_t
#define PyInt_AsLong PyLong_AsLong
#define PyInt_AS_LONG PyLong_AS_LONG
#define PyInt_AsSsize_t PyLong_AsSsize_t
#define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask
#define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask
#define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y)
#else
#define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y)
#define PyBytes_Type PyString_Type
#endif
#if PY_MAJOR_VERSION >= 3
#define PyMethod_New(func, self, klass) PyInstanceMethod_New(func)
#endif
#if !defined(WIN32) && !defined(MS_WINDOWS)
#ifndef __stdcall
#define __stdcall
#endif
#ifndef __cdecl
#define __cdecl
#endif
#ifndef __fastcall
#define __fastcall
#endif
#else
#define _USE_MATH_DEFINES
#endif
#if PY_VERSION_HEX < 0x02050000
#define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n)))
#define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a))
#define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),((char *)(n)))
#else
#define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),(n))
#define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a))
#define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n))
#endif
#if PY_VERSION_HEX < 0x02050000
#define __Pyx_NAMESTR(n) ((char *)(n))
#define __Pyx_DOCSTR(n) ((char *)(n))
#else
#define __Pyx_NAMESTR(n) (n)
#define __Pyx_DOCSTR(n) (n)
#endif
#ifdef __cplusplus
#define __PYX_EXTERN_C extern "C"
#else
#define __PYX_EXTERN_C extern
#endif
#include
#define __PYX_HAVE_API__pypm
#include "portmidi.h"
#include "porttime.h"
#define __PYX_USE_C99_COMPLEX defined(_Complex_I)
#ifdef __GNUC__
#define INLINE __inline__
#elif _WIN32
#define INLINE __inline
#else
#define INLINE
#endif
typedef struct {PyObject **p; char *s; long n; char is_unicode; char intern; char is_identifier;} __Pyx_StringTabEntry; /*proto*/
static int __pyx_skip_dispatch = 0;
/* Type Conversion Predeclarations */
#if PY_MAJOR_VERSION < 3
#define __Pyx_PyBytes_FromString PyString_FromString
#define __Pyx_PyBytes_FromStringAndSize PyString_FromStringAndSize
#define __Pyx_PyBytes_AsString PyString_AsString
#else
#define __Pyx_PyBytes_FromString PyBytes_FromString
#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize
#define __Pyx_PyBytes_AsString PyBytes_AsString
#endif
#define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False))
static INLINE int __Pyx_PyObject_IsTrue(PyObject*);
static INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x);
#if !defined(T_PYSSIZET)
#if PY_VERSION_HEX < 0x02050000
#define T_PYSSIZET T_INT
#elif !defined(T_LONGLONG)
#define T_PYSSIZET \
((sizeof(Py_ssize_t) == sizeof(int)) ? T_INT : \
((sizeof(Py_ssize_t) == sizeof(long)) ? T_LONG : -1))
#else
#define T_PYSSIZET \
((sizeof(Py_ssize_t) == sizeof(int)) ? T_INT : \
((sizeof(Py_ssize_t) == sizeof(long)) ? T_LONG : \
((sizeof(Py_ssize_t) == sizeof(PY_LONG_LONG)) ? T_LONGLONG : -1)))
#endif
#endif
#if !defined(T_SIZET)
#if !defined(T_ULONGLONG)
#define T_SIZET \
((sizeof(size_t) == sizeof(unsigned int)) ? T_UINT : \
((sizeof(size_t) == sizeof(unsigned long)) ? T_ULONG : -1))
#else
#define T_SIZET \
((sizeof(size_t) == sizeof(unsigned int)) ? T_UINT : \
((sizeof(size_t) == sizeof(unsigned long)) ? T_ULONG : \
((sizeof(size_t) == sizeof(unsigned PY_LONG_LONG)) ? T_ULONGLONG : -1)))
#endif
#endif
static INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*);
static INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t);
static INLINE size_t __Pyx_PyInt_AsSize_t(PyObject*);
#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x))
#ifdef __GNUC__
/* Test for GCC > 2.95 */
#if __GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
#else /* __GNUC__ > 2 ... */
#define likely(x) (x)
#define unlikely(x) (x)
#endif /* __GNUC__ > 2 ... */
#else /* __GNUC__ */
#define likely(x) (x)
#define unlikely(x) (x)
#endif /* __GNUC__ */
static PyObject *__pyx_m;
static PyObject *__pyx_b;
static PyObject *__pyx_empty_tuple;
static int __pyx_lineno;
static int __pyx_clineno = 0;
static const char * __pyx_cfilenm= __FILE__;
static const char *__pyx_filename;
static const char **__pyx_f;
#ifdef CYTHON_REFNANNY
typedef struct {
void (*INCREF)(void*, PyObject*, int);
void (*DECREF)(void*, PyObject*, int);
void (*GOTREF)(void*, PyObject*, int);
void (*GIVEREF)(void*, PyObject*, int);
void* (*NewContext)(const char*, int, const char*);
void (*FinishContext)(void**);
} __Pyx_RefnannyAPIStruct;
static __Pyx_RefnannyAPIStruct *__Pyx_Refnanny = NULL;
#define __Pyx_ImportRefcountAPI(name) (__Pyx_RefnannyAPIStruct *) PyCObject_Import((char *)name, (char *)"RefnannyAPI")
#define __Pyx_INCREF(r) __Pyx_Refnanny->INCREF(__pyx_refchk, (PyObject *)(r), __LINE__)
#define __Pyx_DECREF(r) __Pyx_Refnanny->DECREF(__pyx_refchk, (PyObject *)(r), __LINE__)
#define __Pyx_GOTREF(r) __Pyx_Refnanny->GOTREF(__pyx_refchk, (PyObject *)(r), __LINE__)
#define __Pyx_GIVEREF(r) __Pyx_Refnanny->GIVEREF(__pyx_refchk, (PyObject *)(r), __LINE__)
#define __Pyx_XDECREF(r) if((r) == NULL) ; else __Pyx_DECREF(r)
#define __Pyx_SetupRefcountContext(name) void* __pyx_refchk = __Pyx_Refnanny->NewContext((name), __LINE__, __FILE__)
#define __Pyx_FinishRefcountContext() __Pyx_Refnanny->FinishContext(&__pyx_refchk)
#else
#define __Pyx_INCREF(r) Py_INCREF(r)
#define __Pyx_DECREF(r) Py_DECREF(r)
#define __Pyx_GOTREF(r)
#define __Pyx_GIVEREF(r)
#define __Pyx_XDECREF(r) Py_XDECREF(r)
#define __Pyx_SetupRefcountContext(name)
#define __Pyx_FinishRefcountContext()
#endif /* CYTHON_REFNANNY */
#define __Pyx_XGIVEREF(r) if((r) == NULL) ; else __Pyx_GIVEREF(r)
#define __Pyx_XGOTREF(r) if((r) == NULL) ; else __Pyx_GOTREF(r)
static void __Pyx_RaiseDoubleKeywordsError(
const char* func_name, PyObject* kw_name); /*proto*/
static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact,
Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/
static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name); /*proto*/
static INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) {
PyObject *r;
if (!j) return NULL;
r = PyObject_GetItem(o, j);
Py_DECREF(j);
return r;
}
#define __Pyx_GetItemInt_List(o, i, size, to_py_func) ((size <= sizeof(Py_ssize_t)) ? \
__Pyx_GetItemInt_List_Fast(o, i, size <= sizeof(long)) : \
__Pyx_GetItemInt_Generic(o, to_py_func(i)))
static INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, int fits_long) {
if (likely(o != Py_None)) {
if (likely((0 <= i) & (i < PyList_GET_SIZE(o)))) {
PyObject *r = PyList_GET_ITEM(o, i);
Py_INCREF(r);
return r;
}
else if ((-PyList_GET_SIZE(o) <= i) & (i < 0)) {
PyObject *r = PyList_GET_ITEM(o, PyList_GET_SIZE(o) + i);
Py_INCREF(r);
return r;
}
}
return __Pyx_GetItemInt_Generic(o, fits_long ? PyInt_FromLong(i) : PyLong_FromLongLong(i));
}
#define __Pyx_GetItemInt_Tuple(o, i, size, to_py_func) ((size <= sizeof(Py_ssize_t)) ? \
__Pyx_GetItemInt_Tuple_Fast(o, i, size <= sizeof(long)) : \
__Pyx_GetItemInt_Generic(o, to_py_func(i)))
static INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, int fits_long) {
if (likely(o != Py_None)) {
if (likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) {
PyObject *r = PyTuple_GET_ITEM(o, i);
Py_INCREF(r);
return r;
}
else if ((-PyTuple_GET_SIZE(o) <= i) & (i < 0)) {
PyObject *r = PyTuple_GET_ITEM(o, PyTuple_GET_SIZE(o) + i);
Py_INCREF(r);
return r;
}
}
return __Pyx_GetItemInt_Generic(o, fits_long ? PyInt_FromLong(i) : PyLong_FromLongLong(i));
}
#define __Pyx_GetItemInt(o, i, size, to_py_func) ((size <= sizeof(Py_ssize_t)) ? \
__Pyx_GetItemInt_Fast(o, i, size <= sizeof(long)) : \
__Pyx_GetItemInt_Generic(o, to_py_func(i)))
static INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int fits_long) {
PyObject *r;
if (PyList_CheckExact(o) && ((0 <= i) & (i < PyList_GET_SIZE(o)))) {
r = PyList_GET_ITEM(o, i);
Py_INCREF(r);
}
else if (PyTuple_CheckExact(o) && ((0 <= i) & (i < PyTuple_GET_SIZE(o)))) {
r = PyTuple_GET_ITEM(o, i);
Py_INCREF(r);
}
else if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_item && (likely(i >= 0))) {
r = PySequence_GetItem(o, i);
}
else {
r = __Pyx_GetItemInt_Generic(o, fits_long ? PyInt_FromLong(i) : PyLong_FromLongLong(i));
}
return r;
}
static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list); /*proto*/
static int __Pyx_Print(PyObject *, int); /*proto*/
#if PY_MAJOR_VERSION >= 3
static PyObject* __pyx_print = 0;
static PyObject* __pyx_print_kwargs = 0;
#endif
static int __Pyx_PrintOne(PyObject *o); /*proto*/
static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/
static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb); /*proto*/
static INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/
static INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/
static INLINE PyObject* __Pyx_PyObject_Append(PyObject* L, PyObject* x) {
if (likely(PyList_CheckExact(L))) {
if (PyList_Append(L, x) < 0) return NULL;
Py_INCREF(Py_None);
return Py_None; /* this is just to have an accurate signature */
}
else {
PyObject *r, *m;
m = __Pyx_GetAttrString(L, "append");
if (!m) return NULL;
r = PyObject_CallFunctionObjArgs(m, x, NULL);
Py_DECREF(m);
return r;
}
}
static INLINE int __Pyx_StrEq(const char *, const char *); /*proto*/
static INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject *);
static INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject *);
static INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject *);
static INLINE char __Pyx_PyInt_AsChar(PyObject *);
static INLINE short __Pyx_PyInt_AsShort(PyObject *);
static INLINE int __Pyx_PyInt_AsInt(PyObject *);
static INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject *);
static INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject *);
static INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject *);
static INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject *);
static INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject *);
static INLINE long __Pyx_PyInt_AsLong(PyObject *);
static INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject *);
static INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject *);
static INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject *);
static void __Pyx_AddTraceback(const char *funcname); /*proto*/
static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/
/* Type declarations */
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":201
* return Pm_Channel(chan-1)
*
* cdef class Output: # <<<<<<<<<<<<<<
* """
* class Output:
*/
struct __pyx_obj_4pypm_Output {
PyObject_HEAD
int i;
PmStream *midi;
int debug;
int _aborted;
};
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":394
*
*
* cdef class Input: # <<<<<<<<<<<<<<
* """
* class Input:
*/
struct __pyx_obj_4pypm_Input {
PyObject_HEAD
PmStream *midi;
int debug;
int i;
};
/* Module declarations from pypm */
static PyTypeObject *__pyx_ptype_4pypm_Output = 0;
static PyTypeObject *__pyx_ptype_4pypm_Input = 0;
#define __Pyx_MODULE_NAME "pypm"
int __pyx_module_is_main_pypm = 0;
/* Implementation of pypm */
static char __pyx_k_3[] = "0.05";
static PyObject *__pyx_int_0x1;
static PyObject *__pyx_int_0x2;
static PyObject *__pyx_int_0x4;
static PyObject *__pyx_int_0x8;
static PyObject *__pyx_int_0x10;
static PyObject *__pyx_int_0x20;
static PyObject *__pyx_int_0x30;
static PyObject *__pyx_int_0x40;
static PyObject *__pyx_int_0x7F;
static PyObject *__pyx_int_0x80;
static PyObject *__pyx_int_0x100;
static PyObject *__pyx_int_0x200;
static PyObject *__pyx_int_0x300;
static PyObject *__pyx_int_0x400;
static PyObject *__pyx_int_0x800;
static PyObject *__pyx_int_0x1000;
static PyObject *__pyx_int_0x2000;
static PyObject *__pyx_int_0x4000;
static PyObject *__pyx_int_0x8000;
static PyObject *__pyx_int_0x10000;
static PyObject *__pyx_int_0;
static PyObject *__pyx_int_1;
static PyObject *__pyx_int_4096;
static PyObject *__pyx_int_0xFF;
static PyObject *__pyx_int_16;
static PyObject *__pyx_int_0xFF0000;
static PyObject *__pyx_int_8;
static PyObject *__pyx_int_0xFF00;
static PyObject *__pyx_int_1024;
static char __pyx_k___main__[] = "__main__";
static PyObject *__pyx_kp___main__;
static char __pyx_k___init__[] = "__init__";
static PyObject *__pyx_kp___init__;
static char __pyx_k___dealloc__[] = "__dealloc__";
static PyObject *__pyx_kp___dealloc__;
static char __pyx_k__check_open[] = "_check_open";
static PyObject *__pyx_kp__check_open;
static char __pyx_k_Close[] = "Close";
static PyObject *__pyx_kp_Close;
static char __pyx_k_Abort[] = "Abort";
static PyObject *__pyx_kp_Abort;
static char __pyx_k_Write[] = "Write";
static PyObject *__pyx_kp_Write;
static char __pyx_k_WriteShort[] = "WriteShort";
static PyObject *__pyx_kp_WriteShort;
static char __pyx_k_WriteSysEx[] = "WriteSysEx";
static PyObject *__pyx_kp_WriteSysEx;
static char __pyx_k_SetFilter[] = "SetFilter";
static PyObject *__pyx_kp_SetFilter;
static char __pyx_k_SetChannelMask[] = "SetChannelMask";
static PyObject *__pyx_kp_SetChannelMask;
static char __pyx_k_Poll[] = "Poll";
static PyObject *__pyx_kp_Poll;
static char __pyx_k_Read[] = "Read";
static PyObject *__pyx_kp_Read;
static char __pyx_k_i[] = "i";
static PyObject *__pyx_kp_i;
static char __pyx_k_err[] = "err";
static PyObject *__pyx_kp_err;
static char __pyx_k_chan[] = "chan";
static PyObject *__pyx_kp_chan;
static char __pyx_k_OutputDevice[] = "OutputDevice";
static PyObject *__pyx_kp_OutputDevice;
static char __pyx_k_latency[] = "latency";
static PyObject *__pyx_kp_latency;
static char __pyx_k_data[] = "data";
static PyObject *__pyx_kp_data;
static char __pyx_k_status[] = "status";
static PyObject *__pyx_kp_status;
static char __pyx_k_1[] = "data1";
static PyObject *__pyx_kp_1;
static char __pyx_k_2[] = "data2";
static PyObject *__pyx_kp_2;
static char __pyx_k_when[] = "when";
static PyObject *__pyx_kp_when;
static char __pyx_k_msg[] = "msg";
static PyObject *__pyx_kp_msg;
static char __pyx_k_InputDevice[] = "InputDevice";
static PyObject *__pyx_kp_InputDevice;
static char __pyx_k_buffersize[] = "buffersize";
static PyObject *__pyx_kp_buffersize;
static char __pyx_k_filters[] = "filters";
static PyObject *__pyx_kp_filters;
static char __pyx_k_mask[] = "mask";
static PyObject *__pyx_kp_mask;
static char __pyx_k_length[] = "length";
static PyObject *__pyx_kp_length;
static char __pyx_k___version__[] = "__version__";
static PyObject *__pyx_kp___version__;
static char __pyx_k_array[] = "array";
static PyObject *__pyx_kp_array;
static char __pyx_k_FILT_ACTIVE[] = "FILT_ACTIVE";
static PyObject *__pyx_kp_FILT_ACTIVE;
static char __pyx_k_FILT_SYSEX[] = "FILT_SYSEX";
static PyObject *__pyx_kp_FILT_SYSEX;
static char __pyx_k_FILT_CLOCK[] = "FILT_CLOCK";
static PyObject *__pyx_kp_FILT_CLOCK;
static char __pyx_k_FILT_PLAY[] = "FILT_PLAY";
static PyObject *__pyx_kp_FILT_PLAY;
static char __pyx_k_4[] = "FILT_F9";
static PyObject *__pyx_kp_4;
static char __pyx_k_FILT_TICK[] = "FILT_TICK";
static PyObject *__pyx_kp_FILT_TICK;
static char __pyx_k_FILT_FD[] = "FILT_FD";
static PyObject *__pyx_kp_FILT_FD;
static char __pyx_k_FILT_UNDEFINED[] = "FILT_UNDEFINED";
static PyObject *__pyx_kp_FILT_UNDEFINED;
static char __pyx_k_FILT_RESET[] = "FILT_RESET";
static PyObject *__pyx_kp_FILT_RESET;
static char __pyx_k_FILT_REALTIME[] = "FILT_REALTIME";
static PyObject *__pyx_kp_FILT_REALTIME;
static char __pyx_k_FILT_NOTE[] = "FILT_NOTE";
static PyObject *__pyx_kp_FILT_NOTE;
static char __pyx_k_5[] = "FILT_CHANNEL_AFTERTOUCH";
static PyObject *__pyx_kp_5;
static char __pyx_k_6[] = "FILT_POLY_AFTERTOUCH";
static PyObject *__pyx_kp_6;
static char __pyx_k_FILT_AFTERTOUCH[] = "FILT_AFTERTOUCH";
static PyObject *__pyx_kp_FILT_AFTERTOUCH;
static char __pyx_k_FILT_PROGRAM[] = "FILT_PROGRAM";
static PyObject *__pyx_kp_FILT_PROGRAM;
static char __pyx_k_FILT_CONTROL[] = "FILT_CONTROL";
static PyObject *__pyx_kp_FILT_CONTROL;
static char __pyx_k_FILT_PITCHBEND[] = "FILT_PITCHBEND";
static PyObject *__pyx_kp_FILT_PITCHBEND;
static char __pyx_k_FILT_MTC[] = "FILT_MTC";
static PyObject *__pyx_kp_FILT_MTC;
static char __pyx_k_FILT_SONG_POSITION[] = "FILT_SONG_POSITION";
static PyObject *__pyx_kp_FILT_SONG_POSITION;
static char __pyx_k_FILT_SONG_SELECT[] = "FILT_SONG_SELECT";
static PyObject *__pyx_kp_FILT_SONG_SELECT;
static char __pyx_k_FILT_TUNE[] = "FILT_TUNE";
static PyObject *__pyx_kp_FILT_TUNE;
static char __pyx_k_FALSE[] = "FALSE";
static PyObject *__pyx_kp_FALSE;
static char __pyx_k_TRUE[] = "TRUE";
static PyObject *__pyx_kp_TRUE;
static char __pyx_k_Exception[] = "Exception";
static PyObject *__pyx_kp_Exception;
static char __pyx_k_IndexError[] = "IndexError";
static PyObject *__pyx_kp_IndexError;
static char __pyx_k_range[] = "range";
static PyObject *__pyx_kp_range;
static char __pyx_k_19[] = "B";
static PyObject *__pyx_kp_19;
static char __pyx_k_tostring[] = "tostring";
static PyObject *__pyx_kp_tostring;
static char __pyx_k_append[] = "append";
static PyObject *__pyx_kp_append;
static PyObject *__pyx_kp_3;
static PyObject *__pyx_builtin_Exception;
static PyObject *__pyx_builtin_IndexError;
static PyObject *__pyx_builtin_range;
static PyObject *__pyx_kp_7;
static PyObject *__pyx_kp_8;
static PyObject *__pyx_kp_9;
static char __pyx_k_7[] = "Opening Midi Output";
static char __pyx_k_8[] = "Unable to open Midi OutputDevice=";
static char __pyx_k_9[] = " err=";
static PyObject *__pyx_kp_10;
static char __pyx_k_10[] = "Closing MIDI output stream and destroying instance";
static PyObject *__pyx_kp_11;
static PyObject *__pyx_kp_12;
static char __pyx_k_11[] = "midi Output not open.";
static char __pyx_k_12[] = "midi Output aborted. Need to call Close after Abort.";
static PyObject *__pyx_kp_13;
static PyObject *__pyx_kp_14;
static PyObject *__pyx_kp_15;
static PyObject *__pyx_kp_16;
static PyObject *__pyx_kp_17;
static char __pyx_k_13[] = "maximum list length is 1024";
static char __pyx_k_14[] = " arguments in event list";
static char __pyx_k_15[] = " : ";
static char __pyx_k_16[] = " : ";
static char __pyx_k_17[] = "writing to midi buffer";
static PyObject *__pyx_kp_18;
static char __pyx_k_18[] = "Writing to MIDI buffer";
static PyObject *__pyx_kp_20;
static char __pyx_k_20[] = "MIDI input opened.";
static PyObject *__pyx_kp_21;
static char __pyx_k_21[] = "Closing MIDI input stream and destroying instance";
static PyObject *__pyx_kp_22;
static char __pyx_k_22[] = "midi Input not open.";
static PyObject *__pyx_kp_23;
static PyObject *__pyx_kp_24;
static char __pyx_k_23[] = "maximum buffer length is 1024";
static char __pyx_k_24[] = "minimum buffer length is 1";
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":132
* TRUE=1
*
* def Initialize(): # <<<<<<<<<<<<<<
* """
* Initialize: call this first
*/
static PyObject *__pyx_pf_4pypm_Initialize(PyObject *__pyx_self, PyObject *unused); /*proto*/
static char __pyx_doc_4pypm_Initialize[] = "\nInitialize: call this first\n ";
static PyObject *__pyx_pf_4pypm_Initialize(PyObject *__pyx_self, PyObject *unused) {
PyObject *__pyx_r = NULL;
__Pyx_SetupRefcountContext("Initialize");
__pyx_self = __pyx_self;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":136
* Initialize: call this first
* """
* Pm_Initialize() # <<<<<<<<<<<<<<
* Pt_Start(1, NULL, NULL) # /[inserted by cython to avoid comment start]* equiv to TIME_START: start timer w/ ms accuracy *[inserted by cython to avoid comment closer]/
*
*/
Pm_Initialize();
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":137
* """
* Pm_Initialize()
* Pt_Start(1, NULL, NULL) # /[inserted by cython to avoid comment start]* equiv to TIME_START: start timer w/ ms accuracy *[inserted by cython to avoid comment closer]/ # <<<<<<<<<<<<<<
*
* def Terminate():
*/
Pt_Start(1, NULL, NULL);
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
__Pyx_XGIVEREF(__pyx_r);
__Pyx_FinishRefcountContext();
return __pyx_r;
}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":139
* Pt_Start(1, NULL, NULL) # /[inserted by cython to avoid comment start]* equiv to TIME_START: start timer w/ ms accuracy *[inserted by cython to avoid comment closer]/
*
* def Terminate(): # <<<<<<<<<<<<<<
* """
* Terminate: call this to clean up Midi streams when done.
*/
static PyObject *__pyx_pf_4pypm_Terminate(PyObject *__pyx_self, PyObject *unused); /*proto*/
static char __pyx_doc_4pypm_Terminate[] = "\nTerminate: call this to clean up Midi streams when done.\nIf you do not call this on Windows machines when you are\ndone with MIDI, your system may crash.\n ";
static PyObject *__pyx_pf_4pypm_Terminate(PyObject *__pyx_self, PyObject *unused) {
PyObject *__pyx_r = NULL;
__Pyx_SetupRefcountContext("Terminate");
__pyx_self = __pyx_self;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":145
* done with MIDI, your system may crash.
* """
* Pm_Terminate() # <<<<<<<<<<<<<<
*
* def GetDefaultInputDeviceID():
*/
Pm_Terminate();
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
__Pyx_XGIVEREF(__pyx_r);
__Pyx_FinishRefcountContext();
return __pyx_r;
}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":147
* Pm_Terminate()
*
* def GetDefaultInputDeviceID(): # <<<<<<<<<<<<<<
* return Pm_GetDefaultInputDeviceID()
*
*/
static PyObject *__pyx_pf_4pypm_GetDefaultInputDeviceID(PyObject *__pyx_self, PyObject *unused); /*proto*/
static PyObject *__pyx_pf_4pypm_GetDefaultInputDeviceID(PyObject *__pyx_self, PyObject *unused) {
PyObject *__pyx_r = NULL;
PyObject *__pyx_t_1 = NULL;
__Pyx_SetupRefcountContext("GetDefaultInputDeviceID");
__pyx_self = __pyx_self;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":148
*
* def GetDefaultInputDeviceID():
* return Pm_GetDefaultInputDeviceID() # <<<<<<<<<<<<<<
*
* def GetDefaultOutputDeviceID():
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = PyInt_FromLong(Pm_GetDefaultInputDeviceID()); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 148; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_r = __pyx_t_1;
__pyx_t_1 = 0;
goto __pyx_L0;
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("pypm.GetDefaultInputDeviceID");
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_FinishRefcountContext();
return __pyx_r;
}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":150
* return Pm_GetDefaultInputDeviceID()
*
* def GetDefaultOutputDeviceID(): # <<<<<<<<<<<<<<
* return Pm_GetDefaultOutputDeviceID()
*
*/
static PyObject *__pyx_pf_4pypm_GetDefaultOutputDeviceID(PyObject *__pyx_self, PyObject *unused); /*proto*/
static PyObject *__pyx_pf_4pypm_GetDefaultOutputDeviceID(PyObject *__pyx_self, PyObject *unused) {
PyObject *__pyx_r = NULL;
PyObject *__pyx_t_1 = NULL;
__Pyx_SetupRefcountContext("GetDefaultOutputDeviceID");
__pyx_self = __pyx_self;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":151
*
* def GetDefaultOutputDeviceID():
* return Pm_GetDefaultOutputDeviceID() # <<<<<<<<<<<<<<
*
* def CountDevices():
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = PyInt_FromLong(Pm_GetDefaultOutputDeviceID()); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_r = __pyx_t_1;
__pyx_t_1 = 0;
goto __pyx_L0;
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("pypm.GetDefaultOutputDeviceID");
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_FinishRefcountContext();
return __pyx_r;
}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":153
* return Pm_GetDefaultOutputDeviceID()
*
* def CountDevices(): # <<<<<<<<<<<<<<
* return Pm_CountDevices()
*
*/
static PyObject *__pyx_pf_4pypm_CountDevices(PyObject *__pyx_self, PyObject *unused); /*proto*/
static PyObject *__pyx_pf_4pypm_CountDevices(PyObject *__pyx_self, PyObject *unused) {
PyObject *__pyx_r = NULL;
PyObject *__pyx_t_1 = NULL;
__Pyx_SetupRefcountContext("CountDevices");
__pyx_self = __pyx_self;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":154
*
* def CountDevices():
* return Pm_CountDevices() # <<<<<<<<<<<<<<
*
* def GetDeviceInfo(i):
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = PyInt_FromLong(Pm_CountDevices()); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_r = __pyx_t_1;
__pyx_t_1 = 0;
goto __pyx_L0;
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("pypm.CountDevices");
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_FinishRefcountContext();
return __pyx_r;
}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":156
* return Pm_CountDevices()
*
* def GetDeviceInfo(i): # <<<<<<<<<<<<<<
* """
* GetDeviceInfo(): returns 5 parameters
*/
static PyObject *__pyx_pf_4pypm_GetDeviceInfo(PyObject *__pyx_self, PyObject *__pyx_v_i); /*proto*/
static char __pyx_doc_4pypm_GetDeviceInfo[] = "\nGetDeviceInfo(): returns 5 parameters\n - underlying MIDI API\n - device name\n - TRUE iff input is available\n - TRUE iff output is available\n - TRUE iff device stream is already open\n ";
static PyObject *__pyx_pf_4pypm_GetDeviceInfo(PyObject *__pyx_self, PyObject *__pyx_v_i) {
PmDeviceInfo *__pyx_v_info;
PyObject *__pyx_r = NULL;
PmDeviceID __pyx_t_1;
int __pyx_t_2;
PyObject *__pyx_t_3 = NULL;
PyObject *__pyx_t_4 = NULL;
PyObject *__pyx_t_5 = NULL;
PyObject *__pyx_t_6 = NULL;
PyObject *__pyx_t_7 = NULL;
PyObject *__pyx_t_8 = NULL;
__Pyx_SetupRefcountContext("GetDeviceInfo");
__pyx_self = __pyx_self;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":168
*
* # disregarding the constness from Pm_GetDeviceInfo, since pyrex doesn't do const.
* info = Pm_GetDeviceInfo(i) # <<<<<<<<<<<<<<
*
* if info <> NULL: return info.interf, info.name, info.input, info.output, info.opened
*/
__pyx_t_1 = __Pyx_PyInt_AsInt(__pyx_v_i); if (unlikely((__pyx_t_1 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 168; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_v_info = ((PmDeviceInfo *)Pm_GetDeviceInfo(__pyx_t_1));
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":170
* info = Pm_GetDeviceInfo(i)
*
* if info <> NULL: return info.interf, info.name, info.input, info.output, info.opened # <<<<<<<<<<<<<<
* else: return
*
*/
__pyx_t_2 = (__pyx_v_info != NULL);
if (__pyx_t_2) {
__Pyx_XDECREF(__pyx_r);
__pyx_t_3 = __Pyx_PyBytes_FromString(__pyx_v_info->interf); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = __Pyx_PyBytes_FromString(__pyx_v_info->name); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_5 = PyInt_FromLong(__pyx_v_info->input); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_5);
__pyx_t_6 = PyInt_FromLong(__pyx_v_info->output); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_6);
__pyx_t_7 = PyInt_FromLong(__pyx_v_info->opened); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_7);
__pyx_t_8 = PyTuple_New(5); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(((PyObject *)__pyx_t_8));
PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_3);
__Pyx_GIVEREF(__pyx_t_3);
PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_t_4);
__Pyx_GIVEREF(__pyx_t_4);
PyTuple_SET_ITEM(__pyx_t_8, 2, __pyx_t_5);
__Pyx_GIVEREF(__pyx_t_5);
PyTuple_SET_ITEM(__pyx_t_8, 3, __pyx_t_6);
__Pyx_GIVEREF(__pyx_t_6);
PyTuple_SET_ITEM(__pyx_t_8, 4, __pyx_t_7);
__Pyx_GIVEREF(__pyx_t_7);
__pyx_t_3 = 0;
__pyx_t_4 = 0;
__pyx_t_5 = 0;
__pyx_t_6 = 0;
__pyx_t_7 = 0;
__pyx_r = ((PyObject *)__pyx_t_8);
__pyx_t_8 = 0;
goto __pyx_L0;
goto __pyx_L5;
}
/*else*/ {
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":171
*
* if info <> NULL: return info.interf, info.name, info.input, info.output, info.opened
* else: return # <<<<<<<<<<<<<<
*
* def Time():
*/
__Pyx_XDECREF(__pyx_r);
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
}
__pyx_L5:;
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_3);
__Pyx_XDECREF(__pyx_t_4);
__Pyx_XDECREF(__pyx_t_5);
__Pyx_XDECREF(__pyx_t_6);
__Pyx_XDECREF(__pyx_t_7);
__Pyx_XDECREF(__pyx_t_8);
__Pyx_AddTraceback("pypm.GetDeviceInfo");
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_FinishRefcountContext();
return __pyx_r;
}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":173
* else: return
*
* def Time(): # <<<<<<<<<<<<<<
* """
* Time() returns the current time in ms
*/
static PyObject *__pyx_pf_4pypm_Time(PyObject *__pyx_self, PyObject *unused); /*proto*/
static char __pyx_doc_4pypm_Time[] = "\nTime() returns the current time in ms\nof the PortMidi timer\n ";
static PyObject *__pyx_pf_4pypm_Time(PyObject *__pyx_self, PyObject *unused) {
PyObject *__pyx_r = NULL;
PyObject *__pyx_t_1 = NULL;
__Pyx_SetupRefcountContext("Time");
__pyx_self = __pyx_self;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":178
* of the PortMidi timer
* """
* return Pt_Time() # <<<<<<<<<<<<<<
*
* def GetErrorText(err):
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = PyInt_FromLong(Pt_Time()); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_r = __pyx_t_1;
__pyx_t_1 = 0;
goto __pyx_L0;
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("pypm.Time");
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_FinishRefcountContext();
return __pyx_r;
}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":180
* return Pt_Time()
*
* def GetErrorText(err): # <<<<<<<<<<<<<<
* """
* GetErrorText() returns human-readable error
*/
static PyObject *__pyx_pf_4pypm_GetErrorText(PyObject *__pyx_self, PyObject *__pyx_v_err); /*proto*/
static char __pyx_doc_4pypm_GetErrorText[] = "\nGetErrorText() returns human-readable error\nmessages translated from error numbers\n ";
static PyObject *__pyx_pf_4pypm_GetErrorText(PyObject *__pyx_self, PyObject *__pyx_v_err) {
PyObject *__pyx_r = NULL;
PmError __pyx_t_1;
PyObject *__pyx_t_2 = NULL;
__Pyx_SetupRefcountContext("GetErrorText");
__pyx_self = __pyx_self;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":185
* messages translated from error numbers
* """
* return Pm_GetErrorText(err) # <<<<<<<<<<<<<<
*
* def Channel(chan):
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = ((PmError)PyInt_AsLong(__pyx_v_err)); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_2 = __Pyx_PyBytes_FromString(Pm_GetErrorText(__pyx_t_1)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__pyx_r = __pyx_t_2;
__pyx_t_2 = 0;
goto __pyx_L0;
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_2);
__Pyx_AddTraceback("pypm.GetErrorText");
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_FinishRefcountContext();
return __pyx_r;
}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":187
* return Pm_GetErrorText(err)
*
* def Channel(chan): # <<<<<<<<<<<<<<
* """
* Channel() is used with ChannelMask on input MIDI streams.
*/
static PyObject *__pyx_pf_4pypm_Channel(PyObject *__pyx_self, PyObject *__pyx_v_chan); /*proto*/
static char __pyx_doc_4pypm_Channel[] = "\nChannel() is used with ChannelMask on input MIDI streams.\nExample: to receive input on channels 1 and 10 on a MIDI\n stream called MidiIn:\nMidiIn.SetChannelMask(pypm.Channel(1) | pypm.Channel(10))\n\nnote: PyPortMidi Channel function has been altered from\n the original PortMidi c call to correct for what\n seems to be a bug --- i.e. channel filters were\n all numbered from 0 to 15 instead of 1 to 16.\n ";
static PyObject *__pyx_pf_4pypm_Channel(PyObject *__pyx_self, PyObject *__pyx_v_chan) {
PyObject *__pyx_r = NULL;
PyObject *__pyx_t_1 = NULL;
int __pyx_t_2;
__Pyx_SetupRefcountContext("Channel");
__pyx_self = __pyx_self;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":199
* all numbered from 0 to 15 instead of 1 to 16.
* """
* return Pm_Channel(chan-1) # <<<<<<<<<<<<<<
*
* cdef class Output:
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = PyNumber_Subtract(__pyx_v_chan, __pyx_int_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_2 = __Pyx_PyInt_AsInt(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_t_1 = PyInt_FromLong(Pm_Channel(__pyx_t_2)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 199; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_r = __pyx_t_1;
__pyx_t_1 = 0;
goto __pyx_L0;
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("pypm.Channel");
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_FinishRefcountContext();
return __pyx_r;
}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":214
* cdef int _aborted
*
* def __init__(self, OutputDevice, latency=0): # <<<<<<<<<<<<<<
*
* cdef PmError err
*/
static int __pyx_pf_4pypm_6Output___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
static int __pyx_pf_4pypm_6Output___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
PyObject *__pyx_v_OutputDevice = 0;
PyObject *__pyx_v_latency = 0;
PmError __pyx_v_err;
PmTimeProcPtr __pyx_v_PmPtr;
PyObject *__pyx_v_s;
int __pyx_r;
int __pyx_t_1;
PyObject *__pyx_t_2 = NULL;
int __pyx_t_3;
long __pyx_t_4;
static PyObject **__pyx_pyargnames[] = {&__pyx_kp_OutputDevice,&__pyx_kp_latency,0};
__Pyx_SetupRefcountContext("__init__");
if (unlikely(__pyx_kwds)) {
Py_ssize_t kw_args = PyDict_Size(__pyx_kwds);
PyObject* values[2] = {0,0};
values[1] = __pyx_int_0;
switch (PyTuple_GET_SIZE(__pyx_args)) {
case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
case 0: break;
default: goto __pyx_L5_argtuple_error;
}
switch (PyTuple_GET_SIZE(__pyx_args)) {
case 0:
values[0] = PyDict_GetItem(__pyx_kwds, __pyx_kp_OutputDevice);
if (likely(values[0])) kw_args--;
else goto __pyx_L5_argtuple_error;
case 1:
if (kw_args > 1) {
PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_kp_latency);
if (unlikely(value)) { values[1] = value; kw_args--; }
}
}
if (unlikely(kw_args > 0)) {
if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "__init__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
__pyx_v_OutputDevice = values[0];
__pyx_v_latency = values[1];
} else {
__pyx_v_latency = __pyx_int_0;
switch (PyTuple_GET_SIZE(__pyx_args)) {
case 2: __pyx_v_latency = PyTuple_GET_ITEM(__pyx_args, 1);
case 1: __pyx_v_OutputDevice = PyTuple_GET_ITEM(__pyx_args, 0);
break;
default: goto __pyx_L5_argtuple_error;
}
}
goto __pyx_L4_argument_unpacking_done;
__pyx_L5_argtuple_error:;
__Pyx_RaiseArgtupleInvalid("__init__", 0, 1, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 214; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_L3_error:;
__Pyx_AddTraceback("pypm.Output.__init__");
return -1;
__pyx_L4_argument_unpacking_done:;
__pyx_v_s = Py_None; __Pyx_INCREF(Py_None);
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":220
* cdef PmTimeProcPtr PmPtr
*
* self.i = OutputDevice # <<<<<<<<<<<<<<
* self.debug = 0
* self._aborted = 0
*/
__pyx_t_1 = __Pyx_PyInt_AsInt(__pyx_v_OutputDevice); if (unlikely((__pyx_t_1 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
((struct __pyx_obj_4pypm_Output *)__pyx_v_self)->i = __pyx_t_1;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":221
*
* self.i = OutputDevice
* self.debug = 0 # <<<<<<<<<<<<<<
* self._aborted = 0
*
*/
((struct __pyx_obj_4pypm_Output *)__pyx_v_self)->debug = 0;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":222
* self.i = OutputDevice
* self.debug = 0
* self._aborted = 0 # <<<<<<<<<<<<<<
*
* if latency == 0:
*/
((struct __pyx_obj_4pypm_Output *)__pyx_v_self)->_aborted = 0;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":224
* self._aborted = 0
*
* if latency == 0: # <<<<<<<<<<<<<<
* PmPtr = NULL
* else:
*/
__pyx_t_2 = PyObject_RichCompare(__pyx_v_latency, __pyx_int_0, Py_EQ); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
if (__pyx_t_3) {
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":225
*
* if latency == 0:
* PmPtr = NULL # <<<<<<<<<<<<<<
* else:
* PmPtr = &Pt_Time
*/
__pyx_v_PmPtr = NULL;
goto __pyx_L6;
}
/*else*/ {
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":227
* PmPtr = NULL
* else:
* PmPtr = &Pt_Time # <<<<<<<<<<<<<<
* if self.debug: print "Opening Midi Output"
* # Why is bufferSize 0 here?
*/
__pyx_v_PmPtr = ((PmTimestamp (*)(void *))(&Pt_Time));
}
__pyx_L6:;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":228
* else:
* PmPtr = &Pt_Time
* if self.debug: print "Opening Midi Output" # <<<<<<<<<<<<<<
* # Why is bufferSize 0 here?
* err = Pm_OpenOutput(&(self.midi), self.i, NULL, 0, PmPtr, NULL, latency)
*/
__pyx_t_1 = ((struct __pyx_obj_4pypm_Output *)__pyx_v_self)->debug;
if (__pyx_t_1) {
if (__Pyx_PrintOne(__pyx_kp_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 228; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L7;
}
__pyx_L7:;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":230
* if self.debug: print "Opening Midi Output"
* # Why is bufferSize 0 here?
* err = Pm_OpenOutput(&(self.midi), self.i, NULL, 0, PmPtr, NULL, latency) # <<<<<<<<<<<<<<
* if err < 0:
* s = Pm_GetErrorText(err)
*/
__pyx_t_4 = __Pyx_PyInt_AsLong(__pyx_v_latency); if (unlikely((__pyx_t_4 == (long)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_v_err = Pm_OpenOutput((&((struct __pyx_obj_4pypm_Output *)__pyx_v_self)->midi), ((struct __pyx_obj_4pypm_Output *)__pyx_v_self)->i, NULL, 0, __pyx_v_PmPtr, NULL, __pyx_t_4);
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":231
* # Why is bufferSize 0 here?
* err = Pm_OpenOutput(&(self.midi), self.i, NULL, 0, PmPtr, NULL, latency)
* if err < 0: # <<<<<<<<<<<<<<
* s = Pm_GetErrorText(err)
* # Something's amiss here - if we try to throw an Exception
*/
__pyx_t_3 = (__pyx_v_err < 0);
if (__pyx_t_3) {
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":232
* err = Pm_OpenOutput(&(self.midi), self.i, NULL, 0, PmPtr, NULL, latency)
* if err < 0:
* s = Pm_GetErrorText(err) # <<<<<<<<<<<<<<
* # Something's amiss here - if we try to throw an Exception
* # here, we crash.
*/
__pyx_t_2 = __Pyx_PyBytes_FromString(Pm_GetErrorText(__pyx_v_err)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 232; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(__pyx_v_s);
__pyx_v_s = __pyx_t_2;
__pyx_t_2 = 0;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":235
* # Something's amiss here - if we try to throw an Exception
* # here, we crash.
* if not err == -10000: # <<<<<<<<<<<<<<
* raise Exception,s
* else:
*/
__pyx_t_3 = (!(__pyx_v_err == -10000));
if (__pyx_t_3) {
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":236
* # here, we crash.
* if not err == -10000:
* raise Exception,s # <<<<<<<<<<<<<<
* else:
* print "Unable to open Midi OutputDevice=",OutputDevice," err=",s
*/
__Pyx_Raise(__pyx_builtin_Exception, __pyx_v_s, 0);
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L9;
}
/*else*/ {
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":238
* raise Exception,s
* else:
* print "Unable to open Midi OutputDevice=",OutputDevice," err=",s # <<<<<<<<<<<<<<
*
* def __dealloc__(self):
*/
__pyx_t_2 = PyTuple_New(4); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 238; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(((PyObject *)__pyx_t_2));
__Pyx_INCREF(__pyx_kp_8);
PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_kp_8);
__Pyx_GIVEREF(__pyx_kp_8);
__Pyx_INCREF(__pyx_v_OutputDevice);
PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_OutputDevice);
__Pyx_GIVEREF(__pyx_v_OutputDevice);
__Pyx_INCREF(__pyx_kp_9);
PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_kp_9);
__Pyx_GIVEREF(__pyx_kp_9);
__Pyx_INCREF(__pyx_v_s);
PyTuple_SET_ITEM(__pyx_t_2, 3, __pyx_v_s);
__Pyx_GIVEREF(__pyx_v_s);
if (__Pyx_Print(((PyObject *)__pyx_t_2), 1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 238; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0;
}
__pyx_L9:;
goto __pyx_L8;
}
__pyx_L8:;
__pyx_r = 0;
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_2);
__Pyx_AddTraceback("pypm.Output.__init__");
__pyx_r = -1;
__pyx_L0:;
__Pyx_DECREF(__pyx_v_s);
__Pyx_FinishRefcountContext();
return __pyx_r;
}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":240
* print "Unable to open Midi OutputDevice=",OutputDevice," err=",s
*
* def __dealloc__(self): # <<<<<<<<<<<<<<
* if self.debug: print "Closing MIDI output stream and destroying instance"
* #err = Pm_Abort(self.midi)
*/
static void __pyx_pf_4pypm_6Output___dealloc__(PyObject *__pyx_v_self); /*proto*/
static void __pyx_pf_4pypm_6Output___dealloc__(PyObject *__pyx_v_self) {
PyObject *__pyx_v_err;
int __pyx_t_1;
PyObject *__pyx_t_2 = NULL;
int __pyx_t_3;
PmError __pyx_t_4;
__Pyx_SetupRefcountContext("__dealloc__");
__pyx_v_err = Py_None; __Pyx_INCREF(Py_None);
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":241
*
* def __dealloc__(self):
* if self.debug: print "Closing MIDI output stream and destroying instance" # <<<<<<<<<<<<<<
* #err = Pm_Abort(self.midi)
* #if err < 0: raise Exception, Pm_GetErrorText(err)
*/
__pyx_t_1 = ((struct __pyx_obj_4pypm_Output *)__pyx_v_self)->debug;
if (__pyx_t_1) {
if (__Pyx_PrintOne(__pyx_kp_10) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L5;
}
__pyx_L5:;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":244
* #err = Pm_Abort(self.midi)
* #if err < 0: raise Exception, Pm_GetErrorText(err)
* err = Pm_Close(self.midi) # <<<<<<<<<<<<<<
* if err < 0: raise Exception, Pm_GetErrorText(err)
*
*/
__pyx_t_2 = PyInt_FromLong(Pm_Close(((struct __pyx_obj_4pypm_Output *)__pyx_v_self)->midi)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 244; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(__pyx_v_err);
__pyx_v_err = __pyx_t_2;
__pyx_t_2 = 0;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":245
* #if err < 0: raise Exception, Pm_GetErrorText(err)
* err = Pm_Close(self.midi)
* if err < 0: raise Exception, Pm_GetErrorText(err) # <<<<<<<<<<<<<<
*
*
*/
__pyx_t_2 = PyObject_RichCompare(__pyx_v_err, __pyx_int_0, Py_LT); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
if (__pyx_t_3) {
__pyx_t_4 = ((PmError)PyInt_AsLong(__pyx_v_err)); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_2 = __Pyx_PyBytes_FromString(Pm_GetErrorText(__pyx_t_4)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_Raise(__pyx_builtin_Exception, __pyx_t_2, 0);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L6;
}
__pyx_L6:;
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_2);
__Pyx_AddTraceback("pypm.Output.__dealloc__");
__pyx_L0:;
__Pyx_DECREF(__pyx_v_err);
__Pyx_FinishRefcountContext();
}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":248
*
*
* def _check_open(self): # <<<<<<<<<<<<<<
* """ checks to see if the midi is open, and if not, raises an error.
* """
*/
static PyObject *__pyx_pf_4pypm_6Output__check_open(PyObject *__pyx_v_self, PyObject *unused); /*proto*/
static char __pyx_doc_4pypm_6Output__check_open[] = " checks to see if the midi is open, and if not, raises an error.\n ";
static PyObject *__pyx_pf_4pypm_6Output__check_open(PyObject *__pyx_v_self, PyObject *unused) {
PyObject *__pyx_r = NULL;
int __pyx_t_1;
int __pyx_t_2;
__Pyx_SetupRefcountContext("_check_open");
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":252
* """
*
* if self.midi == NULL: # <<<<<<<<<<<<<<
* raise Exception, "midi Output not open."
*
*/
__pyx_t_1 = (((struct __pyx_obj_4pypm_Output *)__pyx_v_self)->midi == NULL);
if (__pyx_t_1) {
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":253
*
* if self.midi == NULL:
* raise Exception, "midi Output not open." # <<<<<<<<<<<<<<
*
* if self._aborted:
*/
__Pyx_Raise(__pyx_builtin_Exception, __pyx_kp_11, 0);
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 253; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L5;
}
__pyx_L5:;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":255
* raise Exception, "midi Output not open."
*
* if self._aborted: # <<<<<<<<<<<<<<
* raise Exception, "midi Output aborted. Need to call Close after Abort."
*
*/
__pyx_t_2 = ((struct __pyx_obj_4pypm_Output *)__pyx_v_self)->_aborted;
if (__pyx_t_2) {
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":256
*
* if self._aborted:
* raise Exception, "midi Output aborted. Need to call Close after Abort." # <<<<<<<<<<<<<<
*
* def Close(self):
*/
__Pyx_Raise(__pyx_builtin_Exception, __pyx_kp_12, 0);
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 256; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L6;
}
__pyx_L6:;
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_AddTraceback("pypm.Output._check_open");
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_FinishRefcountContext();
return __pyx_r;
}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":258
* raise Exception, "midi Output aborted. Need to call Close after Abort."
*
* def Close(self): # <<<<<<<<<<<<<<
* """
* Close()
*/
static PyObject *__pyx_pf_4pypm_6Output_Close(PyObject *__pyx_v_self, PyObject *unused); /*proto*/
static char __pyx_doc_4pypm_6Output_Close[] = "\nClose()\n closes a midi stream, flushing any pending buffers.\n (PortMidi attempts to close open streams when the application\n exits -- this is particularly difficult under Windows.)\n ";
static PyObject *__pyx_pf_4pypm_6Output_Close(PyObject *__pyx_v_self, PyObject *unused) {
PyObject *__pyx_v_err;
PyObject *__pyx_r = NULL;
PyObject *__pyx_t_1 = NULL;
int __pyx_t_2;
PmError __pyx_t_3;
__Pyx_SetupRefcountContext("Close");
__pyx_v_err = Py_None; __Pyx_INCREF(Py_None);
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":268
* # return
*
* err = Pm_Close(self.midi) # <<<<<<<<<<<<<<
* if err < 0:
* raise Exception, Pm_GetErrorText(err)
*/
__pyx_t_1 = PyInt_FromLong(Pm_Close(((struct __pyx_obj_4pypm_Output *)__pyx_v_self)->midi)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 268; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_v_err);
__pyx_v_err = __pyx_t_1;
__pyx_t_1 = 0;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":269
*
* err = Pm_Close(self.midi)
* if err < 0: # <<<<<<<<<<<<<<
* raise Exception, Pm_GetErrorText(err)
* #self.midi = NULL
*/
__pyx_t_1 = PyObject_RichCompare(__pyx_v_err, __pyx_int_0, Py_LT); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 269; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 269; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
if (__pyx_t_2) {
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":270
* err = Pm_Close(self.midi)
* if err < 0:
* raise Exception, Pm_GetErrorText(err) # <<<<<<<<<<<<<<
* #self.midi = NULL
*
*/
__pyx_t_3 = ((PmError)PyInt_AsLong(__pyx_v_err)); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_1 = __Pyx_PyBytes_FromString(Pm_GetErrorText(__pyx_t_3)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_Raise(__pyx_builtin_Exception, __pyx_t_1, 0);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 270; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L5;
}
__pyx_L5:;
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("pypm.Output.Close");
__pyx_r = NULL;
__pyx_L0:;
__Pyx_DECREF(__pyx_v_err);
__Pyx_XGIVEREF(__pyx_r);
__Pyx_FinishRefcountContext();
return __pyx_r;
}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":274
*
*
* def Abort(self): # <<<<<<<<<<<<<<
* """
* Abort() terminates outgoing messages immediately
*/
static PyObject *__pyx_pf_4pypm_6Output_Abort(PyObject *__pyx_v_self, PyObject *unused); /*proto*/
static char __pyx_doc_4pypm_6Output_Abort[] = "\nAbort() terminates outgoing messages immediately\n The caller should immediately close the output port;\n this call may result in transmission of a partial midi message.\n There is no abort for Midi input because the user can simply\n ignore messages in the buffer and close an input device at\n any time.\n ";
static PyObject *__pyx_pf_4pypm_6Output_Abort(PyObject *__pyx_v_self, PyObject *unused) {
PyObject *__pyx_v_err;
PyObject *__pyx_r = NULL;
PyObject *__pyx_t_1 = NULL;
int __pyx_t_2;
PmError __pyx_t_3;
__Pyx_SetupRefcountContext("Abort");
__pyx_v_err = Py_None; __Pyx_INCREF(Py_None);
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":286
* # return
*
* err = Pm_Abort(self.midi) # <<<<<<<<<<<<<<
* if err < 0:
* raise Exception, Pm_GetErrorText(err)
*/
__pyx_t_1 = PyInt_FromLong(Pm_Abort(((struct __pyx_obj_4pypm_Output *)__pyx_v_self)->midi)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 286; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_v_err);
__pyx_v_err = __pyx_t_1;
__pyx_t_1 = 0;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":287
*
* err = Pm_Abort(self.midi)
* if err < 0: # <<<<<<<<<<<<<<
* raise Exception, Pm_GetErrorText(err)
*
*/
__pyx_t_1 = PyObject_RichCompare(__pyx_v_err, __pyx_int_0, Py_LT); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 287; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 287; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
if (__pyx_t_2) {
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":288
* err = Pm_Abort(self.midi)
* if err < 0:
* raise Exception, Pm_GetErrorText(err) # <<<<<<<<<<<<<<
*
* self._aborted = 1
*/
__pyx_t_3 = ((PmError)PyInt_AsLong(__pyx_v_err)); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_1 = __Pyx_PyBytes_FromString(Pm_GetErrorText(__pyx_t_3)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_Raise(__pyx_builtin_Exception, __pyx_t_1, 0);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L5;
}
__pyx_L5:;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":290
* raise Exception, Pm_GetErrorText(err)
*
* self._aborted = 1 # <<<<<<<<<<<<<<
*
*
*/
((struct __pyx_obj_4pypm_Output *)__pyx_v_self)->_aborted = 1;
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("pypm.Output.Abort");
__pyx_r = NULL;
__pyx_L0:;
__Pyx_DECREF(__pyx_v_err);
__Pyx_XGIVEREF(__pyx_r);
__Pyx_FinishRefcountContext();
return __pyx_r;
}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":293
*
*
* def Write(self, data): # <<<<<<<<<<<<<<
* """
* Write(data)
*/
static PyObject *__pyx_pf_4pypm_6Output_Write(PyObject *__pyx_v_self, PyObject *__pyx_v_data); /*proto*/
static char __pyx_doc_4pypm_6Output_Write[] = "\nWrite(data)\n output a series of MIDI information in the form of a list:\n Write([[[status <,data1><,data2><,data3>],timestamp],\n [[status <,data1><,data2><,data3>],timestamp],...])\n fields are optional\n example: choose program change 1 at time 20000 and\n send note 65 with velocity 100 500 ms later.\n Write([[[0xc0,0,0],20000],[[0x90,60,100],20500]])\n notes:\n 1. timestamps will be ignored if latency = 0.\n 2. To get a note to play immediately, send MIDI info with\n timestamp read from function Time.\n 3. understanding optional data fields:\n Write([[[0xc0,0,0],20000]]) is equivalent to\n Write([[[0xc0],20000]])\n ";
static PyObject *__pyx_pf_4pypm_6Output_Write(PyObject *__pyx_v_self, PyObject *__pyx_v_data) {
PmEvent __pyx_v_buffer[1024];
PmError __pyx_v_err;
int __pyx_v_i;
PyObject *__pyx_v_loop1;
PyObject *__pyx_r = NULL;
PyObject *__pyx_1 = 0;
PyObject *__pyx_2 = 0;
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
Py_ssize_t __pyx_t_3;
int __pyx_t_4;
Py_ssize_t __pyx_t_5;
Py_ssize_t __pyx_t_6;
PyObject *__pyx_t_7 = NULL;
int __pyx_t_8;
PyObject *__pyx_t_9 = NULL;
PyObject *__pyx_t_10 = NULL;
PmMessage __pyx_t_11;
PmTimestamp __pyx_t_12;
__Pyx_SetupRefcountContext("Write");
__pyx_v_loop1 = Py_None; __Pyx_INCREF(Py_None);
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":315
* cdef int i
*
* self._check_open() # <<<<<<<<<<<<<<
*
*
*/
__pyx_t_1 = PyObject_GetAttr(__pyx_v_self, __pyx_kp__check_open); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 315; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 315; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":318
*
*
* if len(data) > 1024: raise IndexError, 'maximum list length is 1024' # <<<<<<<<<<<<<<
* else:
* for loop1 in range(len(data)):
*/
__pyx_t_3 = PyObject_Length(__pyx_v_data); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 318; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_4 = (__pyx_t_3 > 1024);
if (__pyx_t_4) {
__Pyx_Raise(__pyx_builtin_IndexError, __pyx_kp_13, 0);
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 318; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L5;
}
/*else*/ {
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":320
* if len(data) > 1024: raise IndexError, 'maximum list length is 1024'
* else:
* for loop1 in range(len(data)): # <<<<<<<<<<<<<<
* if ((len(data[loop1][0]) > 4) |
* (len(data[loop1][0]) < 1)):
*/
__pyx_t_5 = PyObject_Length(__pyx_v_data); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 320; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_2 = PyInt_FromSsize_t(__pyx_t_5); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 320; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 320; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(((PyObject *)__pyx_t_1));
PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_2);
__Pyx_GIVEREF(__pyx_t_2);
__pyx_t_2 = 0;
__pyx_t_2 = PyObject_Call(__pyx_builtin_range, ((PyObject *)__pyx_t_1), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 320; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(((PyObject *)__pyx_t_1)); __pyx_t_1 = 0;
if (PyList_CheckExact(__pyx_t_2) || PyTuple_CheckExact(__pyx_t_2)) {
__pyx_t_3 = 0; __pyx_t_1 = __pyx_t_2; __Pyx_INCREF(__pyx_t_1);
} else {
__pyx_t_3 = -1; __pyx_t_1 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 320; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
}
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
for (;;) {
if (likely(PyList_CheckExact(__pyx_t_1))) {
if (__pyx_t_3 >= PyList_GET_SIZE(__pyx_t_1)) break;
__pyx_t_2 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_3); __Pyx_INCREF(__pyx_t_2); __pyx_t_3++;
} else if (likely(PyTuple_CheckExact(__pyx_t_1))) {
if (__pyx_t_3 >= PyTuple_GET_SIZE(__pyx_t_1)) break;
__pyx_t_2 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_3); __Pyx_INCREF(__pyx_t_2); __pyx_t_3++;
} else {
__pyx_t_2 = PyIter_Next(__pyx_t_1);
if (!__pyx_t_2) {
if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 320; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
break;
}
__Pyx_GOTREF(__pyx_t_2);
}
__Pyx_DECREF(__pyx_v_loop1);
__pyx_v_loop1 = __pyx_t_2;
__pyx_t_2 = 0;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":321
* else:
* for loop1 in range(len(data)):
* if ((len(data[loop1][0]) > 4) | # <<<<<<<<<<<<<<
* (len(data[loop1][0]) < 1)):
* raise IndexError, str(len(data[loop1][0]))+' arguments in event list'
*/
__pyx_1 = PyObject_GetItem(__pyx_v_data, __pyx_v_loop1); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 321; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_1);
__pyx_2 = __Pyx_GetItemInt(__pyx_1, 0, sizeof(long), PyInt_FromLong); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 321; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_2);
__Pyx_DECREF(__pyx_1); __pyx_1 = 0;
__pyx_t_5 = PyObject_Length(__pyx_2); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 321; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_2); __pyx_2 = 0;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":322
* for loop1 in range(len(data)):
* if ((len(data[loop1][0]) > 4) |
* (len(data[loop1][0]) < 1)): # <<<<<<<<<<<<<<
* raise IndexError, str(len(data[loop1][0]))+' arguments in event list'
* buffer[loop1].message = 0
*/
__pyx_1 = PyObject_GetItem(__pyx_v_data, __pyx_v_loop1); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 322; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_1);
__pyx_2 = __Pyx_GetItemInt(__pyx_1, 0, sizeof(long), PyInt_FromLong); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 322; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_2);
__Pyx_DECREF(__pyx_1); __pyx_1 = 0;
__pyx_t_6 = PyObject_Length(__pyx_2); if (unlikely(__pyx_t_6 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 322; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_2); __pyx_2 = 0;
__pyx_t_4 = ((__pyx_t_5 > 4) | (__pyx_t_6 < 1));
if (__pyx_t_4) {
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":323
* if ((len(data[loop1][0]) > 4) |
* (len(data[loop1][0]) < 1)):
* raise IndexError, str(len(data[loop1][0]))+' arguments in event list' # <<<<<<<<<<<<<<
* buffer[loop1].message = 0
* for i in range(len(data[loop1][0])):
*/
__pyx_1 = PyObject_GetItem(__pyx_v_data, __pyx_v_loop1); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_1);
__pyx_2 = __Pyx_GetItemInt(__pyx_1, 0, sizeof(long), PyInt_FromLong); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_2);
__Pyx_DECREF(__pyx_1); __pyx_1 = 0;
__pyx_t_6 = PyObject_Length(__pyx_2); if (unlikely(__pyx_t_6 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_2); __pyx_2 = 0;
__pyx_t_2 = PyInt_FromSsize_t(__pyx_t_6); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(((PyObject *)__pyx_t_7));
PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_2);
__Pyx_GIVEREF(__pyx_t_2);
__pyx_t_2 = 0;
__pyx_t_2 = PyObject_Call(((PyObject *)((PyObject*)&PyString_Type)), ((PyObject *)__pyx_t_7), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0;
__pyx_t_7 = PyNumber_Add(__pyx_t_2, __pyx_kp_14); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_7);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
__Pyx_Raise(__pyx_builtin_IndexError, __pyx_t_7, 0);
__Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0;
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L8;
}
__pyx_L8:;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":324
* (len(data[loop1][0]) < 1)):
* raise IndexError, str(len(data[loop1][0]))+' arguments in event list'
* buffer[loop1].message = 0 # <<<<<<<<<<<<<<
* for i in range(len(data[loop1][0])):
* buffer[loop1].message = buffer[loop1].message + ((data[loop1][0][i]&0xFF) << (8*i))
*/
__pyx_t_6 = __Pyx_PyIndex_AsSsize_t(__pyx_v_loop1); if (unlikely((__pyx_t_6 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 324; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
(__pyx_v_buffer[__pyx_t_6]).message = 0;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":325
* raise IndexError, str(len(data[loop1][0]))+' arguments in event list'
* buffer[loop1].message = 0
* for i in range(len(data[loop1][0])): # <<<<<<<<<<<<<<
* buffer[loop1].message = buffer[loop1].message + ((data[loop1][0][i]&0xFF) << (8*i))
* buffer[loop1].timestamp = data[loop1][1]
*/
__pyx_1 = PyObject_GetItem(__pyx_v_data, __pyx_v_loop1); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 325; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_1);
__pyx_2 = __Pyx_GetItemInt(__pyx_1, 0, sizeof(long), PyInt_FromLong); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 325; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_2);
__Pyx_DECREF(__pyx_1); __pyx_1 = 0;
__pyx_t_6 = PyObject_Length(__pyx_2); if (unlikely(__pyx_t_6 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 325; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_2); __pyx_2 = 0;
for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_6; __pyx_t_8+=1) {
__pyx_v_i = __pyx_t_8;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":326
* buffer[loop1].message = 0
* for i in range(len(data[loop1][0])):
* buffer[loop1].message = buffer[loop1].message + ((data[loop1][0][i]&0xFF) << (8*i)) # <<<<<<<<<<<<<<
* buffer[loop1].timestamp = data[loop1][1]
* if self.debug: print loop1," : ",buffer[loop1].message," : ",buffer[loop1].timestamp
*/
__pyx_t_5 = __Pyx_PyIndex_AsSsize_t(__pyx_v_loop1); if (unlikely((__pyx_t_5 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 326; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_7 = PyInt_FromLong((__pyx_v_buffer[__pyx_t_5]).message); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 326; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_7);
__pyx_1 = PyObject_GetItem(__pyx_v_data, __pyx_v_loop1); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 326; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_1);
__pyx_2 = __Pyx_GetItemInt(__pyx_1, 0, sizeof(long), PyInt_FromLong); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 326; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_2);
__Pyx_DECREF(__pyx_1); __pyx_1 = 0;
__pyx_1 = __Pyx_GetItemInt(__pyx_2, __pyx_v_i, sizeof(int), PyInt_FromLong); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 326; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_1);
__Pyx_DECREF(__pyx_2); __pyx_2 = 0;
__pyx_t_2 = PyNumber_And(__pyx_1, __pyx_int_0xFF); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 326; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(__pyx_1); __pyx_1 = 0;
__pyx_t_9 = PyInt_FromLong((8 * __pyx_v_i)); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 326; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__pyx_t_10 = PyNumber_Lshift(__pyx_t_2, __pyx_t_9); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 326; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_10);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
__pyx_t_9 = PyNumber_Add(__pyx_t_7, __pyx_t_10); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 326; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0;
__Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0;
__pyx_t_11 = __Pyx_PyInt_AsLong(__pyx_t_9); if (unlikely((__pyx_t_11 == (long)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 326; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
__pyx_t_5 = __Pyx_PyIndex_AsSsize_t(__pyx_v_loop1); if (unlikely((__pyx_t_5 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 326; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
(__pyx_v_buffer[__pyx_t_5]).message = __pyx_t_11;
}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":327
* for i in range(len(data[loop1][0])):
* buffer[loop1].message = buffer[loop1].message + ((data[loop1][0][i]&0xFF) << (8*i))
* buffer[loop1].timestamp = data[loop1][1] # <<<<<<<<<<<<<<
* if self.debug: print loop1," : ",buffer[loop1].message," : ",buffer[loop1].timestamp
* if self.debug: print "writing to midi buffer"
*/
__pyx_2 = PyObject_GetItem(__pyx_v_data, __pyx_v_loop1); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 327; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_2);
__pyx_1 = __Pyx_GetItemInt(__pyx_2, 1, sizeof(long), PyInt_FromLong); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 327; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_1);
__Pyx_DECREF(__pyx_2); __pyx_2 = 0;
__pyx_t_12 = __Pyx_PyInt_AsLong(__pyx_1); if (unlikely((__pyx_t_12 == (long)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 327; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_1); __pyx_1 = 0;
__pyx_t_6 = __Pyx_PyIndex_AsSsize_t(__pyx_v_loop1); if (unlikely((__pyx_t_6 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 327; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
(__pyx_v_buffer[__pyx_t_6]).timestamp = __pyx_t_12;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":328
* buffer[loop1].message = buffer[loop1].message + ((data[loop1][0][i]&0xFF) << (8*i))
* buffer[loop1].timestamp = data[loop1][1]
* if self.debug: print loop1," : ",buffer[loop1].message," : ",buffer[loop1].timestamp # <<<<<<<<<<<<<<
* if self.debug: print "writing to midi buffer"
* err= Pm_Write(self.midi, buffer, len(data))
*/
__pyx_t_8 = ((struct __pyx_obj_4pypm_Output *)__pyx_v_self)->debug;
if (__pyx_t_8) {
__pyx_t_6 = __Pyx_PyIndex_AsSsize_t(__pyx_v_loop1); if (unlikely((__pyx_t_6 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_9 = PyInt_FromLong((__pyx_v_buffer[__pyx_t_6]).message); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__pyx_t_6 = __Pyx_PyIndex_AsSsize_t(__pyx_v_loop1); if (unlikely((__pyx_t_6 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_10 = PyInt_FromLong((__pyx_v_buffer[__pyx_t_6]).timestamp); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_10);
__pyx_t_7 = PyTuple_New(5); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(((PyObject *)__pyx_t_7));
__Pyx_INCREF(__pyx_v_loop1);
PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_v_loop1);
__Pyx_GIVEREF(__pyx_v_loop1);
__Pyx_INCREF(__pyx_kp_15);
PyTuple_SET_ITEM(__pyx_t_7, 1, __pyx_kp_15);
__Pyx_GIVEREF(__pyx_kp_15);
PyTuple_SET_ITEM(__pyx_t_7, 2, __pyx_t_9);
__Pyx_GIVEREF(__pyx_t_9);
__Pyx_INCREF(__pyx_kp_16);
PyTuple_SET_ITEM(__pyx_t_7, 3, __pyx_kp_16);
__Pyx_GIVEREF(__pyx_kp_16);
PyTuple_SET_ITEM(__pyx_t_7, 4, __pyx_t_10);
__Pyx_GIVEREF(__pyx_t_10);
__pyx_t_9 = 0;
__pyx_t_10 = 0;
if (__Pyx_Print(((PyObject *)__pyx_t_7), 1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(((PyObject *)__pyx_t_7)); __pyx_t_7 = 0;
goto __pyx_L11;
}
__pyx_L11:;
}
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
}
__pyx_L5:;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":329
* buffer[loop1].timestamp = data[loop1][1]
* if self.debug: print loop1," : ",buffer[loop1].message," : ",buffer[loop1].timestamp
* if self.debug: print "writing to midi buffer" # <<<<<<<<<<<<<<
* err= Pm_Write(self.midi, buffer, len(data))
* if err < 0: raise Exception, Pm_GetErrorText(err)
*/
__pyx_t_8 = ((struct __pyx_obj_4pypm_Output *)__pyx_v_self)->debug;
if (__pyx_t_8) {
if (__Pyx_PrintOne(__pyx_kp_17) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 329; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L12;
}
__pyx_L12:;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":330
* if self.debug: print loop1," : ",buffer[loop1].message," : ",buffer[loop1].timestamp
* if self.debug: print "writing to midi buffer"
* err= Pm_Write(self.midi, buffer, len(data)) # <<<<<<<<<<<<<<
* if err < 0: raise Exception, Pm_GetErrorText(err)
*
*/
__pyx_t_3 = PyObject_Length(__pyx_v_data); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 330; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_v_err = Pm_Write(((struct __pyx_obj_4pypm_Output *)__pyx_v_self)->midi, __pyx_v_buffer, __pyx_t_3);
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":331
* if self.debug: print "writing to midi buffer"
* err= Pm_Write(self.midi, buffer, len(data))
* if err < 0: raise Exception, Pm_GetErrorText(err) # <<<<<<<<<<<<<<
*
* def WriteShort(self, status, data1 = 0, data2 = 0):
*/
__pyx_t_4 = (__pyx_v_err < 0);
if (__pyx_t_4) {
__pyx_t_1 = __Pyx_PyBytes_FromString(Pm_GetErrorText(__pyx_v_err)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_Raise(__pyx_builtin_Exception, __pyx_t_1, 0);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L13;
}
__pyx_L13:;
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_1);
__Pyx_XDECREF(__pyx_2);
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_2);
__Pyx_XDECREF(__pyx_t_7);
__Pyx_XDECREF(__pyx_t_9);
__Pyx_XDECREF(__pyx_t_10);
__Pyx_AddTraceback("pypm.Output.Write");
__pyx_r = NULL;
__pyx_L0:;
__Pyx_DECREF(__pyx_v_loop1);
__Pyx_XGIVEREF(__pyx_r);
__Pyx_FinishRefcountContext();
return __pyx_r;
}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":333
* if err < 0: raise Exception, Pm_GetErrorText(err)
*
* def WriteShort(self, status, data1 = 0, data2 = 0): # <<<<<<<<<<<<<<
* """
* WriteShort(status <, data1><, data2>)
*/
static PyObject *__pyx_pf_4pypm_6Output_WriteShort(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
static char __pyx_doc_4pypm_6Output_WriteShort[] = "\nWriteShort(status <, data1><, data2>)\n output MIDI information of 3 bytes or less.\n data fields are optional\n status byte could be:\n 0xc0 = program change\n 0x90 = note on\n etc.\n data bytes are optional and assumed 0 if omitted\n example: note 65 on with velocity 100\n WriteShort(0x90,65,100)\n ";
static PyObject *__pyx_pf_4pypm_6Output_WriteShort(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
PyObject *__pyx_v_status = 0;
PyObject *__pyx_v_data1 = 0;
PyObject *__pyx_v_data2 = 0;
PmEvent __pyx_v_buffer[1];
PmError __pyx_v_err;
PyObject *__pyx_r = NULL;
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
PyObject *__pyx_t_3 = NULL;
PmMessage __pyx_t_4;
int __pyx_t_5;
int __pyx_t_6;
static PyObject **__pyx_pyargnames[] = {&__pyx_kp_status,&__pyx_kp_1,&__pyx_kp_2,0};
__Pyx_SetupRefcountContext("WriteShort");
if (unlikely(__pyx_kwds)) {
Py_ssize_t kw_args = PyDict_Size(__pyx_kwds);
PyObject* values[3] = {0,0,0};
values[1] = __pyx_int_0;
values[2] = __pyx_int_0;
switch (PyTuple_GET_SIZE(__pyx_args)) {
case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
case 0: break;
default: goto __pyx_L5_argtuple_error;
}
switch (PyTuple_GET_SIZE(__pyx_args)) {
case 0:
values[0] = PyDict_GetItem(__pyx_kwds, __pyx_kp_status);
if (likely(values[0])) kw_args--;
else goto __pyx_L5_argtuple_error;
case 1:
if (kw_args > 1) {
PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_kp_1);
if (unlikely(value)) { values[1] = value; kw_args--; }
}
case 2:
if (kw_args > 1) {
PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_kp_2);
if (unlikely(value)) { values[2] = value; kw_args--; }
}
}
if (unlikely(kw_args > 0)) {
if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "WriteShort") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 333; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
__pyx_v_status = values[0];
__pyx_v_data1 = values[1];
__pyx_v_data2 = values[2];
} else {
__pyx_v_data1 = __pyx_int_0;
__pyx_v_data2 = __pyx_int_0;
switch (PyTuple_GET_SIZE(__pyx_args)) {
case 3: __pyx_v_data2 = PyTuple_GET_ITEM(__pyx_args, 2);
case 2: __pyx_v_data1 = PyTuple_GET_ITEM(__pyx_args, 1);
case 1: __pyx_v_status = PyTuple_GET_ITEM(__pyx_args, 0);
break;
default: goto __pyx_L5_argtuple_error;
}
}
goto __pyx_L4_argument_unpacking_done;
__pyx_L5_argtuple_error:;
__Pyx_RaiseArgtupleInvalid("WriteShort", 0, 1, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 333; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_L3_error:;
__Pyx_AddTraceback("pypm.Output.WriteShort");
return NULL;
__pyx_L4_argument_unpacking_done:;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":348
* cdef PmEvent buffer[1]
* cdef PmError err
* self._check_open() # <<<<<<<<<<<<<<
*
* buffer[0].timestamp = Pt_Time()
*/
__pyx_t_1 = PyObject_GetAttr(__pyx_v_self, __pyx_kp__check_open); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 348; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 348; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":350
* self._check_open()
*
* buffer[0].timestamp = Pt_Time() # <<<<<<<<<<<<<<
* buffer[0].message = ((((data2) << 16) & 0xFF0000) | (((data1) << 8) & 0xFF00) | ((status) & 0xFF))
* if self.debug: print "Writing to MIDI buffer"
*/
(__pyx_v_buffer[0]).timestamp = Pt_Time();
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":351
*
* buffer[0].timestamp = Pt_Time()
* buffer[0].message = ((((data2) << 16) & 0xFF0000) | (((data1) << 8) & 0xFF00) | ((status) & 0xFF)) # <<<<<<<<<<<<<<
* if self.debug: print "Writing to MIDI buffer"
* err = Pm_Write(self.midi, buffer, 1) # stream, buffer, length
*/
__pyx_t_2 = PyNumber_Lshift(__pyx_v_data2, __pyx_int_16); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__pyx_t_1 = PyNumber_And(__pyx_t_2, __pyx_int_0xFF0000); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
__pyx_t_2 = PyNumber_Lshift(__pyx_v_data1, __pyx_int_8); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__pyx_t_3 = PyNumber_And(__pyx_t_2, __pyx_int_0xFF00); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
__pyx_t_2 = PyNumber_Or(__pyx_t_1, __pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_3 = PyNumber_And(__pyx_v_status, __pyx_int_0xFF); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_1 = PyNumber_Or(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_4 = __Pyx_PyInt_AsLong(__pyx_t_1); if (unlikely((__pyx_t_4 == (long)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
(__pyx_v_buffer[0]).message = __pyx_t_4;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":352
* buffer[0].timestamp = Pt_Time()
* buffer[0].message = ((((data2) << 16) & 0xFF0000) | (((data1) << 8) & 0xFF00) | ((status) & 0xFF))
* if self.debug: print "Writing to MIDI buffer" # <<<<<<<<<<<<<<
* err = Pm_Write(self.midi, buffer, 1) # stream, buffer, length
* if err < 0 : raise Exception, Pm_GetErrorText(err)
*/
__pyx_t_5 = ((struct __pyx_obj_4pypm_Output *)__pyx_v_self)->debug;
if (__pyx_t_5) {
if (__Pyx_PrintOne(__pyx_kp_18) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 352; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L6;
}
__pyx_L6:;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":353
* buffer[0].message = ((((data2) << 16) & 0xFF0000) | (((data1) << 8) & 0xFF00) | ((status) & 0xFF))
* if self.debug: print "Writing to MIDI buffer"
* err = Pm_Write(self.midi, buffer, 1) # stream, buffer, length # <<<<<<<<<<<<<<
* if err < 0 : raise Exception, Pm_GetErrorText(err)
*
*/
__pyx_v_err = Pm_Write(((struct __pyx_obj_4pypm_Output *)__pyx_v_self)->midi, __pyx_v_buffer, 1);
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":354
* if self.debug: print "Writing to MIDI buffer"
* err = Pm_Write(self.midi, buffer, 1) # stream, buffer, length
* if err < 0 : raise Exception, Pm_GetErrorText(err) # <<<<<<<<<<<<<<
*
* def WriteSysEx(self, when, msg):
*/
__pyx_t_6 = (__pyx_v_err < 0);
if (__pyx_t_6) {
__pyx_t_1 = __Pyx_PyBytes_FromString(Pm_GetErrorText(__pyx_v_err)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 354; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_Raise(__pyx_builtin_Exception, __pyx_t_1, 0);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 354; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L7;
}
__pyx_L7:;
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_2);
__Pyx_XDECREF(__pyx_t_3);
__Pyx_AddTraceback("pypm.Output.WriteShort");
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_FinishRefcountContext();
return __pyx_r;
}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":356
* if err < 0 : raise Exception, Pm_GetErrorText(err)
*
* def WriteSysEx(self, when, msg): # <<<<<<<<<<<<<<
* """
* WriteSysEx(,)
*/
static PyObject *__pyx_pf_4pypm_6Output_WriteSysEx(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
static char __pyx_doc_4pypm_6Output_WriteSysEx[] = "\n WriteSysEx(,)\n writes a timestamped system-exclusive midi message.\n can be a *list* or a *string*\n example:\n (assuming y is an input MIDI stream)\n y.WriteSysEx(0,'\\xF0\\x7D\\x10\\x11\\x12\\x13\\xF7')\n is equivalent to\n y.WriteSysEx(pypm.Time,\n [0xF0, 0x7D, 0x10, 0x11, 0x12, 0x13, 0xF7])\n ";
static PyObject *__pyx_pf_4pypm_6Output_WriteSysEx(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
PyObject *__pyx_v_when = 0;
PyObject *__pyx_v_msg = 0;
PmError __pyx_v_err;
char *__pyx_v_cmsg;
PtTimestamp __pyx_v_CurTime;
PyObject *__pyx_r = NULL;
PyObject *__pyx_1 = 0;
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
int __pyx_t_3;
PyObject *__pyx_t_4 = NULL;
char *__pyx_t_5;
PmTimestamp __pyx_t_6;
static PyObject **__pyx_pyargnames[] = {&__pyx_kp_when,&__pyx_kp_msg,0};
__Pyx_SetupRefcountContext("WriteSysEx");
if (unlikely(__pyx_kwds)) {
Py_ssize_t kw_args = PyDict_Size(__pyx_kwds);
PyObject* values[2] = {0,0};
switch (PyTuple_GET_SIZE(__pyx_args)) {
case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
case 0: break;
default: goto __pyx_L5_argtuple_error;
}
switch (PyTuple_GET_SIZE(__pyx_args)) {
case 0:
values[0] = PyDict_GetItem(__pyx_kwds, __pyx_kp_when);
if (likely(values[0])) kw_args--;
else goto __pyx_L5_argtuple_error;
case 1:
values[1] = PyDict_GetItem(__pyx_kwds, __pyx_kp_msg);
if (likely(values[1])) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("WriteSysEx", 1, 2, 2, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
}
if (unlikely(kw_args > 0)) {
if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "WriteSysEx") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
__pyx_v_when = values[0];
__pyx_v_msg = values[1];
} else if (PyTuple_GET_SIZE(__pyx_args) != 2) {
goto __pyx_L5_argtuple_error;
} else {
__pyx_v_when = PyTuple_GET_ITEM(__pyx_args, 0);
__pyx_v_msg = PyTuple_GET_ITEM(__pyx_args, 1);
}
goto __pyx_L4_argument_unpacking_done;
__pyx_L5_argtuple_error:;
__Pyx_RaiseArgtupleInvalid("WriteSysEx", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_L3_error:;
__Pyx_AddTraceback("pypm.Output.WriteSysEx");
return NULL;
__pyx_L4_argument_unpacking_done:;
__Pyx_INCREF(__pyx_v_msg);
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":372
* cdef PtTimestamp CurTime
*
* self._check_open() # <<<<<<<<<<<<<<
*
* if type(msg) is list:
*/
__pyx_t_1 = PyObject_GetAttr(__pyx_v_self, __pyx_kp__check_open); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 372; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 372; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":374
* self._check_open()
*
* if type(msg) is list: # <<<<<<<<<<<<<<
* msg = array.array('B',msg).tostring() # Markus Pfaff contribution
* cmsg = msg
*/
__pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 374; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(((PyObject *)__pyx_t_2));
__Pyx_INCREF(__pyx_v_msg);
PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_msg);
__Pyx_GIVEREF(__pyx_v_msg);
__pyx_t_1 = PyObject_Call(((PyObject *)((PyObject*)&PyType_Type)), ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 374; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0;
__pyx_t_3 = (__pyx_t_1 == ((PyObject *)((PyObject*)&PyList_Type)));
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
if (__pyx_t_3) {
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":375
*
* if type(msg) is list:
* msg = array.array('B',msg).tostring() # Markus Pfaff contribution # <<<<<<<<<<<<<<
* cmsg = msg
*
*/
__pyx_1 = __Pyx_GetName(__pyx_m, __pyx_kp_array); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_1);
__pyx_t_1 = PyObject_GetAttr(__pyx_1, __pyx_kp_array); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_1); __pyx_1 = 0;
__pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(((PyObject *)__pyx_t_2));
__Pyx_INCREF(__pyx_kp_19);
PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_kp_19);
__Pyx_GIVEREF(__pyx_kp_19);
__Pyx_INCREF(__pyx_v_msg);
PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_msg);
__Pyx_GIVEREF(__pyx_v_msg);
__pyx_t_4 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0;
__pyx_t_2 = PyObject_GetAttr(__pyx_t_4, __pyx_kp_tostring); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__pyx_t_4 = PyObject_Call(__pyx_t_2, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
__Pyx_DECREF(__pyx_v_msg);
__pyx_v_msg = __pyx_t_4;
__pyx_t_4 = 0;
goto __pyx_L6;
}
__pyx_L6:;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":376
* if type(msg) is list:
* msg = array.array('B',msg).tostring() # Markus Pfaff contribution
* cmsg = msg # <<<<<<<<<<<<<<
*
* CurTime = Pt_Time()
*/
__pyx_t_5 = __Pyx_PyBytes_AsString(__pyx_v_msg); if (unlikely((!__pyx_t_5) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_v_cmsg = __pyx_t_5;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":378
* cmsg = msg
*
* CurTime = Pt_Time() # <<<<<<<<<<<<<<
* err = Pm_WriteSysEx(self.midi, when, cmsg)
* if err < 0 : raise Exception, Pm_GetErrorText(err)
*/
__pyx_v_CurTime = Pt_Time();
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":379
*
* CurTime = Pt_Time()
* err = Pm_WriteSysEx(self.midi, when, cmsg) # <<<<<<<<<<<<<<
* if err < 0 : raise Exception, Pm_GetErrorText(err)
* while Pt_Time() == CurTime: # wait for SysEx to go thru or...my
*/
__pyx_t_6 = __Pyx_PyInt_AsLong(__pyx_v_when); if (unlikely((__pyx_t_6 == (long)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_v_err = Pm_WriteSysEx(((struct __pyx_obj_4pypm_Output *)__pyx_v_self)->midi, __pyx_t_6, ((unsigned char *)__pyx_v_cmsg));
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":380
* CurTime = Pt_Time()
* err = Pm_WriteSysEx(self.midi, when, cmsg)
* if err < 0 : raise Exception, Pm_GetErrorText(err) # <<<<<<<<<<<<<<
* while Pt_Time() == CurTime: # wait for SysEx to go thru or...my
* pass # win32 machine crashes w/ multiple SysEx
*/
__pyx_t_3 = (__pyx_v_err < 0);
if (__pyx_t_3) {
__pyx_t_4 = __Pyx_PyBytes_FromString(Pm_GetErrorText(__pyx_v_err)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 380; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__Pyx_Raise(__pyx_builtin_Exception, __pyx_t_4, 0);
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 380; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L7;
}
__pyx_L7:;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":381
* err = Pm_WriteSysEx(self.midi, when, cmsg)
* if err < 0 : raise Exception, Pm_GetErrorText(err)
* while Pt_Time() == CurTime: # wait for SysEx to go thru or...my # <<<<<<<<<<<<<<
* pass # win32 machine crashes w/ multiple SysEx
*
*/
while (1) {
__pyx_t_3 = (Pt_Time() == __pyx_v_CurTime);
if (!__pyx_t_3) break;
}
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_1);
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_2);
__Pyx_XDECREF(__pyx_t_4);
__Pyx_AddTraceback("pypm.Output.WriteSysEx");
__pyx_r = NULL;
__pyx_L0:;
__Pyx_DECREF(__pyx_v_msg);
__Pyx_XGIVEREF(__pyx_r);
__Pyx_FinishRefcountContext();
return __pyx_r;
}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":404
* cdef int i
*
* def __init__(self, InputDevice, buffersize=4096): # <<<<<<<<<<<<<<
* cdef PmError err
* self.i = InputDevice
*/
static int __pyx_pf_4pypm_5Input___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
static int __pyx_pf_4pypm_5Input___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
PyObject *__pyx_v_InputDevice = 0;
PyObject *__pyx_v_buffersize = 0;
PmError __pyx_v_err;
int __pyx_r;
int __pyx_t_1;
long __pyx_t_2;
int __pyx_t_3;
PyObject *__pyx_t_4 = NULL;
static PyObject **__pyx_pyargnames[] = {&__pyx_kp_InputDevice,&__pyx_kp_buffersize,0};
__Pyx_SetupRefcountContext("__init__");
if (unlikely(__pyx_kwds)) {
Py_ssize_t kw_args = PyDict_Size(__pyx_kwds);
PyObject* values[2] = {0,0};
values[1] = __pyx_int_4096;
switch (PyTuple_GET_SIZE(__pyx_args)) {
case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
case 0: break;
default: goto __pyx_L5_argtuple_error;
}
switch (PyTuple_GET_SIZE(__pyx_args)) {
case 0:
values[0] = PyDict_GetItem(__pyx_kwds, __pyx_kp_InputDevice);
if (likely(values[0])) kw_args--;
else goto __pyx_L5_argtuple_error;
case 1:
if (kw_args > 1) {
PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_kp_buffersize);
if (unlikely(value)) { values[1] = value; kw_args--; }
}
}
if (unlikely(kw_args > 0)) {
if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, PyTuple_GET_SIZE(__pyx_args), "__init__") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 404; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
__pyx_v_InputDevice = values[0];
__pyx_v_buffersize = values[1];
} else {
__pyx_v_buffersize = __pyx_int_4096;
switch (PyTuple_GET_SIZE(__pyx_args)) {
case 2: __pyx_v_buffersize = PyTuple_GET_ITEM(__pyx_args, 1);
case 1: __pyx_v_InputDevice = PyTuple_GET_ITEM(__pyx_args, 0);
break;
default: goto __pyx_L5_argtuple_error;
}
}
goto __pyx_L4_argument_unpacking_done;
__pyx_L5_argtuple_error:;
__Pyx_RaiseArgtupleInvalid("__init__", 0, 1, 2, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 404; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_L3_error:;
__Pyx_AddTraceback("pypm.Input.__init__");
return -1;
__pyx_L4_argument_unpacking_done:;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":406
* def __init__(self, InputDevice, buffersize=4096):
* cdef PmError err
* self.i = InputDevice # <<<<<<<<<<<<<<
* self.debug = 0
* err= Pm_OpenInput(&(self.midi),self.i,NULL,buffersize,&Pt_Time,NULL)
*/
__pyx_t_1 = __Pyx_PyInt_AsInt(__pyx_v_InputDevice); if (unlikely((__pyx_t_1 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 406; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
((struct __pyx_obj_4pypm_Input *)__pyx_v_self)->i = __pyx_t_1;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":407
* cdef PmError err
* self.i = InputDevice
* self.debug = 0 # <<<<<<<<<<<<<<
* err= Pm_OpenInput(&(self.midi),self.i,NULL,buffersize,&Pt_Time,NULL)
* if err < 0: raise Exception, Pm_GetErrorText(err)
*/
((struct __pyx_obj_4pypm_Input *)__pyx_v_self)->debug = 0;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":408
* self.i = InputDevice
* self.debug = 0
* err= Pm_OpenInput(&(self.midi),self.i,NULL,buffersize,&Pt_Time,NULL) # <<<<<<<<<<<<<<
* if err < 0: raise Exception, Pm_GetErrorText(err)
* if self.debug: print "MIDI input opened."
*/
__pyx_t_2 = __Pyx_PyInt_AsLong(__pyx_v_buffersize); if (unlikely((__pyx_t_2 == (long)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 408; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_v_err = Pm_OpenInput((&((struct __pyx_obj_4pypm_Input *)__pyx_v_self)->midi), ((struct __pyx_obj_4pypm_Input *)__pyx_v_self)->i, NULL, __pyx_t_2, (&Pt_Time), NULL);
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":409
* self.debug = 0
* err= Pm_OpenInput(&(self.midi),self.i,NULL,buffersize,&Pt_Time,NULL)
* if err < 0: raise Exception, Pm_GetErrorText(err) # <<<<<<<<<<<<<<
* if self.debug: print "MIDI input opened."
*
*/
__pyx_t_3 = (__pyx_v_err < 0);
if (__pyx_t_3) {
__pyx_t_4 = __Pyx_PyBytes_FromString(Pm_GetErrorText(__pyx_v_err)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 409; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__Pyx_Raise(__pyx_builtin_Exception, __pyx_t_4, 0);
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 409; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L6;
}
__pyx_L6:;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":410
* err= Pm_OpenInput(&(self.midi),self.i,NULL,buffersize,&Pt_Time,NULL)
* if err < 0: raise Exception, Pm_GetErrorText(err)
* if self.debug: print "MIDI input opened." # <<<<<<<<<<<<<<
*
* def __dealloc__(self):
*/
__pyx_t_1 = ((struct __pyx_obj_4pypm_Input *)__pyx_v_self)->debug;
if (__pyx_t_1) {
if (__Pyx_PrintOne(__pyx_kp_20) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 410; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L7;
}
__pyx_L7:;
__pyx_r = 0;
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_4);
__Pyx_AddTraceback("pypm.Input.__init__");
__pyx_r = -1;
__pyx_L0:;
__Pyx_FinishRefcountContext();
return __pyx_r;
}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":412
* if self.debug: print "MIDI input opened."
*
* def __dealloc__(self): # <<<<<<<<<<<<<<
* cdef PmError err
* if self.debug: print "Closing MIDI input stream and destroying instance"
*/
static void __pyx_pf_4pypm_5Input___dealloc__(PyObject *__pyx_v_self); /*proto*/
static void __pyx_pf_4pypm_5Input___dealloc__(PyObject *__pyx_v_self) {
PmError __pyx_v_err;
int __pyx_t_1;
int __pyx_t_2;
PyObject *__pyx_t_3 = NULL;
__Pyx_SetupRefcountContext("__dealloc__");
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":414
* def __dealloc__(self):
* cdef PmError err
* if self.debug: print "Closing MIDI input stream and destroying instance" # <<<<<<<<<<<<<<
*
* err = Pm_Close(self.midi)
*/
__pyx_t_1 = ((struct __pyx_obj_4pypm_Input *)__pyx_v_self)->debug;
if (__pyx_t_1) {
if (__Pyx_PrintOne(__pyx_kp_21) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 414; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L5;
}
__pyx_L5:;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":416
* if self.debug: print "Closing MIDI input stream and destroying instance"
*
* err = Pm_Close(self.midi) # <<<<<<<<<<<<<<
* if err < 0:
* raise Exception, Pm_GetErrorText(err)
*/
__pyx_v_err = Pm_Close(((struct __pyx_obj_4pypm_Input *)__pyx_v_self)->midi);
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":417
*
* err = Pm_Close(self.midi)
* if err < 0: # <<<<<<<<<<<<<<
* raise Exception, Pm_GetErrorText(err)
*
*/
__pyx_t_2 = (__pyx_v_err < 0);
if (__pyx_t_2) {
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":418
* err = Pm_Close(self.midi)
* if err < 0:
* raise Exception, Pm_GetErrorText(err) # <<<<<<<<<<<<<<
*
*
*/
__pyx_t_3 = __Pyx_PyBytes_FromString(Pm_GetErrorText(__pyx_v_err)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 418; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__Pyx_Raise(__pyx_builtin_Exception, __pyx_t_3, 0);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 418; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L6;
}
__pyx_L6:;
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_3);
__Pyx_AddTraceback("pypm.Input.__dealloc__");
__pyx_L0:;
__Pyx_FinishRefcountContext();
}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":422
*
*
* def _check_open(self): # <<<<<<<<<<<<<<
* """ checks to see if the midi is open, and if not, raises an error.
* """
*/
static PyObject *__pyx_pf_4pypm_5Input__check_open(PyObject *__pyx_v_self, PyObject *unused); /*proto*/
static char __pyx_doc_4pypm_5Input__check_open[] = " checks to see if the midi is open, and if not, raises an error.\n ";
static PyObject *__pyx_pf_4pypm_5Input__check_open(PyObject *__pyx_v_self, PyObject *unused) {
PyObject *__pyx_r = NULL;
int __pyx_t_1;
__Pyx_SetupRefcountContext("_check_open");
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":426
* """
*
* if self.midi == NULL: # <<<<<<<<<<<<<<
* raise Exception, "midi Input not open."
*
*/
__pyx_t_1 = (((struct __pyx_obj_4pypm_Input *)__pyx_v_self)->midi == NULL);
if (__pyx_t_1) {
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":427
*
* if self.midi == NULL:
* raise Exception, "midi Input not open." # <<<<<<<<<<<<<<
*
*
*/
__Pyx_Raise(__pyx_builtin_Exception, __pyx_kp_22, 0);
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 427; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L5;
}
__pyx_L5:;
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_AddTraceback("pypm.Input._check_open");
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_FinishRefcountContext();
return __pyx_r;
}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":430
*
*
* def Close(self): # <<<<<<<<<<<<<<
* """
* Close()
*/
static PyObject *__pyx_pf_4pypm_5Input_Close(PyObject *__pyx_v_self, PyObject *unused); /*proto*/
static char __pyx_doc_4pypm_5Input_Close[] = "\nClose()\n closes a midi stream, flushing any pending buffers.\n (PortMidi attempts to close open streams when the application\n exits -- this is particularly difficult under Windows.)\n ";
static PyObject *__pyx_pf_4pypm_5Input_Close(PyObject *__pyx_v_self, PyObject *unused) {
PyObject *__pyx_v_err;
PyObject *__pyx_r = NULL;
PyObject *__pyx_t_1 = NULL;
int __pyx_t_2;
PmError __pyx_t_3;
__Pyx_SetupRefcountContext("Close");
__pyx_v_err = Py_None; __Pyx_INCREF(Py_None);
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":440
* # return
*
* err = Pm_Close(self.midi) # <<<<<<<<<<<<<<
* if err < 0:
* raise Exception, Pm_GetErrorText(err)
*/
__pyx_t_1 = PyInt_FromLong(Pm_Close(((struct __pyx_obj_4pypm_Input *)__pyx_v_self)->midi)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 440; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_v_err);
__pyx_v_err = __pyx_t_1;
__pyx_t_1 = 0;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":441
*
* err = Pm_Close(self.midi)
* if err < 0: # <<<<<<<<<<<<<<
* raise Exception, Pm_GetErrorText(err)
* #self.midi = NULL
*/
__pyx_t_1 = PyObject_RichCompare(__pyx_v_err, __pyx_int_0, Py_LT); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 441; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 441; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
if (__pyx_t_2) {
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":442
* err = Pm_Close(self.midi)
* if err < 0:
* raise Exception, Pm_GetErrorText(err) # <<<<<<<<<<<<<<
* #self.midi = NULL
*
*/
__pyx_t_3 = ((PmError)PyInt_AsLong(__pyx_v_err)); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 442; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_1 = __Pyx_PyBytes_FromString(Pm_GetErrorText(__pyx_t_3)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 442; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_Raise(__pyx_builtin_Exception, __pyx_t_1, 0);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 442; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L5;
}
__pyx_L5:;
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("pypm.Input.Close");
__pyx_r = NULL;
__pyx_L0:;
__Pyx_DECREF(__pyx_v_err);
__Pyx_XGIVEREF(__pyx_r);
__Pyx_FinishRefcountContext();
return __pyx_r;
}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":447
*
*
* def SetFilter(self, filters): # <<<<<<<<<<<<<<
* """
* SetFilter() sets filters on an open input stream
*/
static PyObject *__pyx_pf_4pypm_5Input_SetFilter(PyObject *__pyx_v_self, PyObject *__pyx_v_filters); /*proto*/
static char __pyx_doc_4pypm_5Input_SetFilter[] = "\n SetFilter() sets filters on an open input stream\n to drop selected input types. By default, only active sensing\n messages are filtered. To prohibit, say, active sensing and\n sysex messages, call\n SetFilter(stream, FILT_ACTIVE | FILT_SYSEX);\n\n Filtering is useful when midi routing or midi thru functionality\n is being provided by the user application.\n For example, you may want to exclude timing messages\n (clock, MTC, start/stop/continue), while allowing note-related\n messages to pass. Or you may be using a sequencer or drum-machine\n for MIDI clock information but want to exclude any notes\n it may play.\n\n Note: SetFilter empties the buffer after setting the filter,\n just in case anything got through.\n ";
static PyObject *__pyx_pf_4pypm_5Input_SetFilter(PyObject *__pyx_v_self, PyObject *__pyx_v_filters) {
PmEvent __pyx_v_buffer[1];
PmError __pyx_v_err;
PyObject *__pyx_r = NULL;
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
long __pyx_t_3;
int __pyx_t_4;
__Pyx_SetupRefcountContext("SetFilter");
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":469
* cdef PmError err
*
* self._check_open() # <<<<<<<<<<<<<<
*
*
*/
__pyx_t_1 = PyObject_GetAttr(__pyx_v_self, __pyx_kp__check_open); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 469; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":472
*
*
* err = Pm_SetFilter(self.midi, filters) # <<<<<<<<<<<<<<
*
* if err < 0: raise Exception, Pm_GetErrorText(err)
*/
__pyx_t_3 = __Pyx_PyInt_AsLong(__pyx_v_filters); if (unlikely((__pyx_t_3 == (long)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 472; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_v_err = Pm_SetFilter(((struct __pyx_obj_4pypm_Input *)__pyx_v_self)->midi, __pyx_t_3);
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":474
* err = Pm_SetFilter(self.midi, filters)
*
* if err < 0: raise Exception, Pm_GetErrorText(err) # <<<<<<<<<<<<<<
*
* while(Pm_Poll(self.midi) != pmNoError):
*/
__pyx_t_4 = (__pyx_v_err < 0);
if (__pyx_t_4) {
__pyx_t_2 = __Pyx_PyBytes_FromString(Pm_GetErrorText(__pyx_v_err)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 474; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_Raise(__pyx_builtin_Exception, __pyx_t_2, 0);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 474; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L5;
}
__pyx_L5:;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":476
* if err < 0: raise Exception, Pm_GetErrorText(err)
*
* while(Pm_Poll(self.midi) != pmNoError): # <<<<<<<<<<<<<<
*
* err = Pm_Read(self.midi,buffer,1)
*/
while (1) {
__pyx_t_4 = (Pm_Poll(((struct __pyx_obj_4pypm_Input *)__pyx_v_self)->midi) != pmNoError);
if (!__pyx_t_4) break;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":478
* while(Pm_Poll(self.midi) != pmNoError):
*
* err = Pm_Read(self.midi,buffer,1) # <<<<<<<<<<<<<<
* if err < 0: raise Exception, Pm_GetErrorText(err)
*
*/
__pyx_v_err = Pm_Read(((struct __pyx_obj_4pypm_Input *)__pyx_v_self)->midi, __pyx_v_buffer, 1);
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":479
*
* err = Pm_Read(self.midi,buffer,1)
* if err < 0: raise Exception, Pm_GetErrorText(err) # <<<<<<<<<<<<<<
*
* def SetChannelMask(self, mask):
*/
__pyx_t_4 = (__pyx_v_err < 0);
if (__pyx_t_4) {
__pyx_t_2 = __Pyx_PyBytes_FromString(Pm_GetErrorText(__pyx_v_err)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 479; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_Raise(__pyx_builtin_Exception, __pyx_t_2, 0);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 479; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L8;
}
__pyx_L8:;
}
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_2);
__Pyx_AddTraceback("pypm.Input.SetFilter");
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_FinishRefcountContext();
return __pyx_r;
}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":481
* if err < 0: raise Exception, Pm_GetErrorText(err)
*
* def SetChannelMask(self, mask): # <<<<<<<<<<<<<<
* """
* SetChannelMask() filters incoming messages based on channel.
*/
static PyObject *__pyx_pf_4pypm_5Input_SetChannelMask(PyObject *__pyx_v_self, PyObject *__pyx_v_mask); /*proto*/
static char __pyx_doc_4pypm_5Input_SetChannelMask[] = "\n SetChannelMask() filters incoming messages based on channel.\n The mask is a 16-bit bitfield corresponding to appropriate channels\n Channel() can assist in calling this function.\n i.e. to set receive only input on channel 1, call with\n SetChannelMask(Channel(1))\n Multiple channels should be OR'd together, like\n SetChannelMask(Channel(10) | Channel(11))\n note: PyPortMidi Channel function has been altered from\n the original PortMidi c call to correct for what\n seems to be a bug --- i.e. channel filters were\n all numbered from 0 to 15 instead of 1 to 16.\n ";
static PyObject *__pyx_pf_4pypm_5Input_SetChannelMask(PyObject *__pyx_v_self, PyObject *__pyx_v_mask) {
PmError __pyx_v_err;
PyObject *__pyx_r = NULL;
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
int __pyx_t_3;
int __pyx_t_4;
__Pyx_SetupRefcountContext("SetChannelMask");
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":497
* cdef PmError err
*
* self._check_open() # <<<<<<<<<<<<<<
*
* err = Pm_SetChannelMask(self.midi,mask)
*/
__pyx_t_1 = PyObject_GetAttr(__pyx_v_self, __pyx_kp__check_open); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 497; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":499
* self._check_open()
*
* err = Pm_SetChannelMask(self.midi,mask) # <<<<<<<<<<<<<<
* if err < 0: raise Exception, Pm_GetErrorText(err)
*
*/
__pyx_t_3 = __Pyx_PyInt_AsInt(__pyx_v_mask); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 499; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_v_err = Pm_SetChannelMask(((struct __pyx_obj_4pypm_Input *)__pyx_v_self)->midi, __pyx_t_3);
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":500
*
* err = Pm_SetChannelMask(self.midi,mask)
* if err < 0: raise Exception, Pm_GetErrorText(err) # <<<<<<<<<<<<<<
*
* def Poll(self):
*/
__pyx_t_4 = (__pyx_v_err < 0);
if (__pyx_t_4) {
__pyx_t_2 = __Pyx_PyBytes_FromString(Pm_GetErrorText(__pyx_v_err)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 500; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_Raise(__pyx_builtin_Exception, __pyx_t_2, 0);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 500; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L5;
}
__pyx_L5:;
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_2);
__Pyx_AddTraceback("pypm.Input.SetChannelMask");
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_FinishRefcountContext();
return __pyx_r;
}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":502
* if err < 0: raise Exception, Pm_GetErrorText(err)
*
* def Poll(self): # <<<<<<<<<<<<<<
* """
* Poll tests whether input is available,
*/
static PyObject *__pyx_pf_4pypm_5Input_Poll(PyObject *__pyx_v_self, PyObject *unused); /*proto*/
static char __pyx_doc_4pypm_5Input_Poll[] = "\n Poll tests whether input is available,\n returning TRUE, FALSE, or an error value.\n ";
static PyObject *__pyx_pf_4pypm_5Input_Poll(PyObject *__pyx_v_self, PyObject *unused) {
PmError __pyx_v_err;
PyObject *__pyx_r = NULL;
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
int __pyx_t_3;
__Pyx_SetupRefcountContext("Poll");
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":508
* """
* cdef PmError err
* self._check_open() # <<<<<<<<<<<<<<
*
* err = Pm_Poll(self.midi)
*/
__pyx_t_1 = PyObject_GetAttr(__pyx_v_self, __pyx_kp__check_open); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 508; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 508; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":510
* self._check_open()
*
* err = Pm_Poll(self.midi) # <<<<<<<<<<<<<<
* if err < 0: raise Exception, Pm_GetErrorText(err)
* return err
*/
__pyx_v_err = Pm_Poll(((struct __pyx_obj_4pypm_Input *)__pyx_v_self)->midi);
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":511
*
* err = Pm_Poll(self.midi)
* if err < 0: raise Exception, Pm_GetErrorText(err) # <<<<<<<<<<<<<<
* return err
*
*/
__pyx_t_3 = (__pyx_v_err < 0);
if (__pyx_t_3) {
__pyx_t_2 = __Pyx_PyBytes_FromString(Pm_GetErrorText(__pyx_v_err)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 511; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_Raise(__pyx_builtin_Exception, __pyx_t_2, 0);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 511; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L5;
}
__pyx_L5:;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":512
* err = Pm_Poll(self.midi)
* if err < 0: raise Exception, Pm_GetErrorText(err)
* return err # <<<<<<<<<<<<<<
*
* def Read(self,length):
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_2 = PyInt_FromLong(__pyx_v_err); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 512; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__pyx_r = __pyx_t_2;
__pyx_t_2 = 0;
goto __pyx_L0;
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_2);
__Pyx_AddTraceback("pypm.Input.Poll");
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_FinishRefcountContext();
return __pyx_r;
}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":514
* return err
*
* def Read(self,length): # <<<<<<<<<<<<<<
* """
* Read(length): returns up to midi events stored in
*/
static PyObject *__pyx_pf_4pypm_5Input_Read(PyObject *__pyx_v_self, PyObject *__pyx_v_length); /*proto*/
static char __pyx_doc_4pypm_5Input_Read[] = "\nRead(length): returns up to midi events stored in\nthe buffer and returns them as a list:\n[[[status,data1,data2,data3],timestamp],\n [[status,data1,data2,data3],timestamp],...]\nexample: Read(50) returns all the events in the buffer,\n up to 50 events.\n ";
static PyObject *__pyx_pf_4pypm_5Input_Read(PyObject *__pyx_v_self, PyObject *__pyx_v_length) {
PmEvent __pyx_v_buffer[1024];
PyObject *__pyx_v_x;
PyObject *__pyx_v_NumEvents;
PyObject *__pyx_v_loop;
PyObject *__pyx_r = NULL;
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
int __pyx_t_3;
long __pyx_t_4;
PmError __pyx_t_5;
Py_ssize_t __pyx_t_6;
Py_ssize_t __pyx_t_7;
PyObject *__pyx_t_8 = NULL;
PyObject *__pyx_t_9 = NULL;
PyObject *__pyx_t_10 = NULL;
PyObject *__pyx_t_11 = NULL;
__Pyx_SetupRefcountContext("Read");
__pyx_v_x = Py_None; __Pyx_INCREF(Py_None);
__pyx_v_NumEvents = Py_None; __Pyx_INCREF(Py_None);
__pyx_v_loop = Py_None; __Pyx_INCREF(Py_None);
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":525
* cdef PmEvent buffer[1024]
*
* self._check_open() # <<<<<<<<<<<<<<
*
* x = []
*/
__pyx_t_1 = PyObject_GetAttr(__pyx_v_self, __pyx_kp__check_open); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_2 = PyObject_Call(__pyx_t_1, ((PyObject *)__pyx_empty_tuple), NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 525; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":527
* self._check_open()
*
* x = [] # <<<<<<<<<<<<<<
*
* if length > 1024: raise IndexError, 'maximum buffer length is 1024'
*/
__pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 527; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(((PyObject *)__pyx_t_2));
__Pyx_DECREF(__pyx_v_x);
__pyx_v_x = ((PyObject *)__pyx_t_2);
__pyx_t_2 = 0;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":529
* x = []
*
* if length > 1024: raise IndexError, 'maximum buffer length is 1024' # <<<<<<<<<<<<<<
* if length < 1: raise IndexError, 'minimum buffer length is 1'
* NumEvents = Pm_Read(self.midi,buffer,length)
*/
__pyx_t_2 = PyObject_RichCompare(__pyx_v_length, __pyx_int_1024, Py_GT); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
if (__pyx_t_3) {
__Pyx_Raise(__pyx_builtin_IndexError, __pyx_kp_23, 0);
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L5;
}
__pyx_L5:;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":530
*
* if length > 1024: raise IndexError, 'maximum buffer length is 1024'
* if length < 1: raise IndexError, 'minimum buffer length is 1' # <<<<<<<<<<<<<<
* NumEvents = Pm_Read(self.midi,buffer,length)
* if NumEvents < 0: raise Exception, Pm_GetErrorText(NumEvents)
*/
__pyx_t_2 = PyObject_RichCompare(__pyx_v_length, __pyx_int_1, Py_LT); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
if (__pyx_t_3) {
__Pyx_Raise(__pyx_builtin_IndexError, __pyx_kp_24, 0);
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 530; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L6;
}
__pyx_L6:;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":531
* if length > 1024: raise IndexError, 'maximum buffer length is 1024'
* if length < 1: raise IndexError, 'minimum buffer length is 1'
* NumEvents = Pm_Read(self.midi,buffer,length) # <<<<<<<<<<<<<<
* if NumEvents < 0: raise Exception, Pm_GetErrorText(NumEvents)
* x=[]
*/
__pyx_t_4 = __Pyx_PyInt_AsLong(__pyx_v_length); if (unlikely((__pyx_t_4 == (long)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_2 = PyInt_FromLong(Pm_Read(((struct __pyx_obj_4pypm_Input *)__pyx_v_self)->midi, __pyx_v_buffer, __pyx_t_4)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(__pyx_v_NumEvents);
__pyx_v_NumEvents = __pyx_t_2;
__pyx_t_2 = 0;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":532
* if length < 1: raise IndexError, 'minimum buffer length is 1'
* NumEvents = Pm_Read(self.midi,buffer,length)
* if NumEvents < 0: raise Exception, Pm_GetErrorText(NumEvents) # <<<<<<<<<<<<<<
* x=[]
* if NumEvents >= 1:
*/
__pyx_t_2 = PyObject_RichCompare(__pyx_v_NumEvents, __pyx_int_0, Py_LT); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 532; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 532; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
if (__pyx_t_3) {
__pyx_t_5 = ((PmError)PyInt_AsLong(__pyx_v_NumEvents)); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 532; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_2 = __Pyx_PyBytes_FromString(Pm_GetErrorText(__pyx_t_5)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 532; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_Raise(__pyx_builtin_Exception, __pyx_t_2, 0);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 532; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L7;
}
__pyx_L7:;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":533
* NumEvents = Pm_Read(self.midi,buffer,length)
* if NumEvents < 0: raise Exception, Pm_GetErrorText(NumEvents)
* x=[] # <<<<<<<<<<<<<<
* if NumEvents >= 1:
* for loop in range(NumEvents):
*/
__pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 533; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(((PyObject *)__pyx_t_2));
__Pyx_DECREF(__pyx_v_x);
__pyx_v_x = ((PyObject *)__pyx_t_2);
__pyx_t_2 = 0;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":534
* if NumEvents < 0: raise Exception, Pm_GetErrorText(NumEvents)
* x=[]
* if NumEvents >= 1: # <<<<<<<<<<<<<<
* for loop in range(NumEvents):
* x.append([[buffer[loop].message & 0xff, (buffer[loop].message >> 8) & 0xFF, (buffer[loop].message >> 16) & 0xFF, (buffer[loop].message >> 24) & 0xFF], buffer[loop].timestamp])
*/
__pyx_t_2 = PyObject_RichCompare(__pyx_v_NumEvents, __pyx_int_1, Py_GE); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 534; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 534; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
if (__pyx_t_3) {
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":535
* x=[]
* if NumEvents >= 1:
* for loop in range(NumEvents): # <<<<<<<<<<<<<<
* x.append([[buffer[loop].message & 0xff, (buffer[loop].message >> 8) & 0xFF, (buffer[loop].message >> 16) & 0xFF, (buffer[loop].message >> 24) & 0xFF], buffer[loop].timestamp])
* return x
*/
__pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 535; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(((PyObject *)__pyx_t_2));
__Pyx_INCREF(__pyx_v_NumEvents);
PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_NumEvents);
__Pyx_GIVEREF(__pyx_v_NumEvents);
__pyx_t_1 = PyObject_Call(__pyx_builtin_range, ((PyObject *)__pyx_t_2), NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 535; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(((PyObject *)__pyx_t_2)); __pyx_t_2 = 0;
if (PyList_CheckExact(__pyx_t_1) || PyTuple_CheckExact(__pyx_t_1)) {
__pyx_t_6 = 0; __pyx_t_2 = __pyx_t_1; __Pyx_INCREF(__pyx_t_2);
} else {
__pyx_t_6 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 535; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
}
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
for (;;) {
if (likely(PyList_CheckExact(__pyx_t_2))) {
if (__pyx_t_6 >= PyList_GET_SIZE(__pyx_t_2)) break;
__pyx_t_1 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_6); __Pyx_INCREF(__pyx_t_1); __pyx_t_6++;
} else if (likely(PyTuple_CheckExact(__pyx_t_2))) {
if (__pyx_t_6 >= PyTuple_GET_SIZE(__pyx_t_2)) break;
__pyx_t_1 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_6); __Pyx_INCREF(__pyx_t_1); __pyx_t_6++;
} else {
__pyx_t_1 = PyIter_Next(__pyx_t_2);
if (!__pyx_t_1) {
if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 535; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
break;
}
__Pyx_GOTREF(__pyx_t_1);
}
__Pyx_DECREF(__pyx_v_loop);
__pyx_v_loop = __pyx_t_1;
__pyx_t_1 = 0;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":536
* if NumEvents >= 1:
* for loop in range(NumEvents):
* x.append([[buffer[loop].message & 0xff, (buffer[loop].message >> 8) & 0xFF, (buffer[loop].message >> 16) & 0xFF, (buffer[loop].message >> 24) & 0xFF], buffer[loop].timestamp]) # <<<<<<<<<<<<<<
* return x
*/
__pyx_t_7 = __Pyx_PyIndex_AsSsize_t(__pyx_v_loop); if (unlikely((__pyx_t_7 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_1 = PyInt_FromLong(((__pyx_v_buffer[__pyx_t_7]).message & 0xff)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_7 = __Pyx_PyIndex_AsSsize_t(__pyx_v_loop); if (unlikely((__pyx_t_7 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_8 = PyInt_FromLong((((__pyx_v_buffer[__pyx_t_7]).message >> 8) & 0xFF)); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__pyx_t_7 = __Pyx_PyIndex_AsSsize_t(__pyx_v_loop); if (unlikely((__pyx_t_7 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_9 = PyInt_FromLong((((__pyx_v_buffer[__pyx_t_7]).message >> 16) & 0xFF)); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__pyx_t_7 = __Pyx_PyIndex_AsSsize_t(__pyx_v_loop); if (unlikely((__pyx_t_7 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_10 = PyInt_FromLong((((__pyx_v_buffer[__pyx_t_7]).message >> 24) & 0xFF)); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_10);
__pyx_t_11 = PyList_New(4); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(((PyObject *)__pyx_t_11));
PyList_SET_ITEM(__pyx_t_11, 0, __pyx_t_1);
__Pyx_GIVEREF(__pyx_t_1);
PyList_SET_ITEM(__pyx_t_11, 1, __pyx_t_8);
__Pyx_GIVEREF(__pyx_t_8);
PyList_SET_ITEM(__pyx_t_11, 2, __pyx_t_9);
__Pyx_GIVEREF(__pyx_t_9);
PyList_SET_ITEM(__pyx_t_11, 3, __pyx_t_10);
__Pyx_GIVEREF(__pyx_t_10);
__pyx_t_1 = 0;
__pyx_t_8 = 0;
__pyx_t_9 = 0;
__pyx_t_10 = 0;
__pyx_t_7 = __Pyx_PyIndex_AsSsize_t(__pyx_v_loop); if (unlikely((__pyx_t_7 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_10 = PyInt_FromLong((__pyx_v_buffer[__pyx_t_7]).timestamp); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_10);
__pyx_t_9 = PyList_New(2); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(((PyObject *)__pyx_t_9));
PyList_SET_ITEM(__pyx_t_9, 0, ((PyObject *)__pyx_t_11));
__Pyx_GIVEREF(((PyObject *)__pyx_t_11));
PyList_SET_ITEM(__pyx_t_9, 1, __pyx_t_10);
__Pyx_GIVEREF(__pyx_t_10);
__pyx_t_11 = 0;
__pyx_t_10 = 0;
__pyx_t_10 = __Pyx_PyObject_Append(__pyx_v_x, ((PyObject *)__pyx_t_9)); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_10);
__Pyx_DECREF(((PyObject *)__pyx_t_9)); __pyx_t_9 = 0;
__Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0;
}
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
goto __pyx_L8;
}
__pyx_L8:;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":537
* for loop in range(NumEvents):
* x.append([[buffer[loop].message & 0xff, (buffer[loop].message >> 8) & 0xFF, (buffer[loop].message >> 16) & 0xFF, (buffer[loop].message >> 24) & 0xFF], buffer[loop].timestamp])
* return x # <<<<<<<<<<<<<<
*/
__Pyx_XDECREF(__pyx_r);
__Pyx_INCREF(__pyx_v_x);
__pyx_r = __pyx_v_x;
goto __pyx_L0;
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_2);
__Pyx_XDECREF(__pyx_t_8);
__Pyx_XDECREF(__pyx_t_9);
__Pyx_XDECREF(__pyx_t_10);
__Pyx_XDECREF(__pyx_t_11);
__Pyx_AddTraceback("pypm.Input.Read");
__pyx_r = NULL;
__pyx_L0:;
__Pyx_DECREF(__pyx_v_x);
__Pyx_DECREF(__pyx_v_NumEvents);
__Pyx_DECREF(__pyx_v_loop);
__Pyx_XGIVEREF(__pyx_r);
__Pyx_FinishRefcountContext();
return __pyx_r;
}
static PyObject *__pyx_tp_new_4pypm_Output(PyTypeObject *t, PyObject *a, PyObject *k) {
PyObject *o = (*t->tp_alloc)(t, 0);
if (!o) return 0;
return o;
}
static void __pyx_tp_dealloc_4pypm_Output(PyObject *o) {
{
PyObject *etype, *eval, *etb;
PyErr_Fetch(&etype, &eval, &etb);
++Py_REFCNT(o);
__pyx_pf_4pypm_6Output___dealloc__(o);
if (PyErr_Occurred()) PyErr_WriteUnraisable(o);
--Py_REFCNT(o);
PyErr_Restore(etype, eval, etb);
}
(*Py_TYPE(o)->tp_free)(o);
}
static struct PyMethodDef __pyx_methods_4pypm_Output[] = {
{__Pyx_NAMESTR("_check_open"), (PyCFunction)__pyx_pf_4pypm_6Output__check_open, METH_NOARGS, __Pyx_DOCSTR(__pyx_doc_4pypm_6Output__check_open)},
{__Pyx_NAMESTR("Close"), (PyCFunction)__pyx_pf_4pypm_6Output_Close, METH_NOARGS, __Pyx_DOCSTR(__pyx_doc_4pypm_6Output_Close)},
{__Pyx_NAMESTR("Abort"), (PyCFunction)__pyx_pf_4pypm_6Output_Abort, METH_NOARGS, __Pyx_DOCSTR(__pyx_doc_4pypm_6Output_Abort)},
{__Pyx_NAMESTR("Write"), (PyCFunction)__pyx_pf_4pypm_6Output_Write, METH_O, __Pyx_DOCSTR(__pyx_doc_4pypm_6Output_Write)},
{__Pyx_NAMESTR("WriteShort"), (PyCFunction)__pyx_pf_4pypm_6Output_WriteShort, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_4pypm_6Output_WriteShort)},
{__Pyx_NAMESTR("WriteSysEx"), (PyCFunction)__pyx_pf_4pypm_6Output_WriteSysEx, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_4pypm_6Output_WriteSysEx)},
{0, 0, 0, 0}
};
static PyNumberMethods __pyx_tp_as_number_Output = {
0, /*nb_add*/
0, /*nb_subtract*/
0, /*nb_multiply*/
#if PY_MAJOR_VERSION < 3
0, /*nb_divide*/
#endif
0, /*nb_remainder*/
0, /*nb_divmod*/
0, /*nb_power*/
0, /*nb_negative*/
0, /*nb_positive*/
0, /*nb_absolute*/
0, /*nb_nonzero*/
0, /*nb_invert*/
0, /*nb_lshift*/
0, /*nb_rshift*/
0, /*nb_and*/
0, /*nb_xor*/
0, /*nb_or*/
#if PY_MAJOR_VERSION < 3
0, /*nb_coerce*/
#endif
0, /*nb_int*/
#if PY_MAJOR_VERSION >= 3
0, /*reserved*/
#else
0, /*nb_long*/
#endif
0, /*nb_float*/
#if PY_MAJOR_VERSION < 3
0, /*nb_oct*/
#endif
#if PY_MAJOR_VERSION < 3
0, /*nb_hex*/
#endif
0, /*nb_inplace_add*/
0, /*nb_inplace_subtract*/
0, /*nb_inplace_multiply*/
#if PY_MAJOR_VERSION < 3
0, /*nb_inplace_divide*/
#endif
0, /*nb_inplace_remainder*/
0, /*nb_inplace_power*/
0, /*nb_inplace_lshift*/
0, /*nb_inplace_rshift*/
0, /*nb_inplace_and*/
0, /*nb_inplace_xor*/
0, /*nb_inplace_or*/
0, /*nb_floor_divide*/
0, /*nb_true_divide*/
0, /*nb_inplace_floor_divide*/
0, /*nb_inplace_true_divide*/
#if (PY_MAJOR_VERSION >= 3) || (Py_TPFLAGS_DEFAULT & Py_TPFLAGS_HAVE_INDEX)
0, /*nb_index*/
#endif
};
static PySequenceMethods __pyx_tp_as_sequence_Output = {
0, /*sq_length*/
0, /*sq_concat*/
0, /*sq_repeat*/
0, /*sq_item*/
0, /*sq_slice*/
0, /*sq_ass_item*/
0, /*sq_ass_slice*/
0, /*sq_contains*/
0, /*sq_inplace_concat*/
0, /*sq_inplace_repeat*/
};
static PyMappingMethods __pyx_tp_as_mapping_Output = {
0, /*mp_length*/
0, /*mp_subscript*/
0, /*mp_ass_subscript*/
};
static PyBufferProcs __pyx_tp_as_buffer_Output = {
#if PY_MAJOR_VERSION < 3
0, /*bf_getreadbuffer*/
#endif
#if PY_MAJOR_VERSION < 3
0, /*bf_getwritebuffer*/
#endif
#if PY_MAJOR_VERSION < 3
0, /*bf_getsegcount*/
#endif
#if PY_MAJOR_VERSION < 3
0, /*bf_getcharbuffer*/
#endif
#if PY_VERSION_HEX >= 0x02060000
0, /*bf_getbuffer*/
#endif
#if PY_VERSION_HEX >= 0x02060000
0, /*bf_releasebuffer*/
#endif
};
PyTypeObject __pyx_type_4pypm_Output = {
PyVarObject_HEAD_INIT(0, 0)
__Pyx_NAMESTR("pypm.Output"), /*tp_name*/
sizeof(struct __pyx_obj_4pypm_Output), /*tp_basicsize*/
0, /*tp_itemsize*/
__pyx_tp_dealloc_4pypm_Output, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
&__pyx_tp_as_number_Output, /*tp_as_number*/
&__pyx_tp_as_sequence_Output, /*tp_as_sequence*/
&__pyx_tp_as_mapping_Output, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
&__pyx_tp_as_buffer_Output, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_NEWBUFFER, /*tp_flags*/
__Pyx_DOCSTR("\nclass Output:\n define an output MIDI stream. Takes the form:\n x = pypm.Output(MidiOutputDevice, latency)\n latency is in ms.\n If latency = 0 then timestamps for output are ignored.\n "), /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
__pyx_methods_4pypm_Output, /*tp_methods*/
0, /*tp_members*/
0, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
0, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictoffset*/
__pyx_pf_4pypm_6Output___init__, /*tp_init*/
0, /*tp_alloc*/
__pyx_tp_new_4pypm_Output, /*tp_new*/
0, /*tp_free*/
0, /*tp_is_gc*/
0, /*tp_bases*/
0, /*tp_mro*/
0, /*tp_cache*/
0, /*tp_subclasses*/
0, /*tp_weaklist*/
};
static PyObject *__pyx_tp_new_4pypm_Input(PyTypeObject *t, PyObject *a, PyObject *k) {
PyObject *o = (*t->tp_alloc)(t, 0);
if (!o) return 0;
return o;
}
static void __pyx_tp_dealloc_4pypm_Input(PyObject *o) {
{
PyObject *etype, *eval, *etb;
PyErr_Fetch(&etype, &eval, &etb);
++Py_REFCNT(o);
__pyx_pf_4pypm_5Input___dealloc__(o);
if (PyErr_Occurred()) PyErr_WriteUnraisable(o);
--Py_REFCNT(o);
PyErr_Restore(etype, eval, etb);
}
(*Py_TYPE(o)->tp_free)(o);
}
static struct PyMethodDef __pyx_methods_4pypm_Input[] = {
{__Pyx_NAMESTR("_check_open"), (PyCFunction)__pyx_pf_4pypm_5Input__check_open, METH_NOARGS, __Pyx_DOCSTR(__pyx_doc_4pypm_5Input__check_open)},
{__Pyx_NAMESTR("Close"), (PyCFunction)__pyx_pf_4pypm_5Input_Close, METH_NOARGS, __Pyx_DOCSTR(__pyx_doc_4pypm_5Input_Close)},
{__Pyx_NAMESTR("SetFilter"), (PyCFunction)__pyx_pf_4pypm_5Input_SetFilter, METH_O, __Pyx_DOCSTR(__pyx_doc_4pypm_5Input_SetFilter)},
{__Pyx_NAMESTR("SetChannelMask"), (PyCFunction)__pyx_pf_4pypm_5Input_SetChannelMask, METH_O, __Pyx_DOCSTR(__pyx_doc_4pypm_5Input_SetChannelMask)},
{__Pyx_NAMESTR("Poll"), (PyCFunction)__pyx_pf_4pypm_5Input_Poll, METH_NOARGS, __Pyx_DOCSTR(__pyx_doc_4pypm_5Input_Poll)},
{__Pyx_NAMESTR("Read"), (PyCFunction)__pyx_pf_4pypm_5Input_Read, METH_O, __Pyx_DOCSTR(__pyx_doc_4pypm_5Input_Read)},
{0, 0, 0, 0}
};
static PyNumberMethods __pyx_tp_as_number_Input = {
0, /*nb_add*/
0, /*nb_subtract*/
0, /*nb_multiply*/
#if PY_MAJOR_VERSION < 3
0, /*nb_divide*/
#endif
0, /*nb_remainder*/
0, /*nb_divmod*/
0, /*nb_power*/
0, /*nb_negative*/
0, /*nb_positive*/
0, /*nb_absolute*/
0, /*nb_nonzero*/
0, /*nb_invert*/
0, /*nb_lshift*/
0, /*nb_rshift*/
0, /*nb_and*/
0, /*nb_xor*/
0, /*nb_or*/
#if PY_MAJOR_VERSION < 3
0, /*nb_coerce*/
#endif
0, /*nb_int*/
#if PY_MAJOR_VERSION >= 3
0, /*reserved*/
#else
0, /*nb_long*/
#endif
0, /*nb_float*/
#if PY_MAJOR_VERSION < 3
0, /*nb_oct*/
#endif
#if PY_MAJOR_VERSION < 3
0, /*nb_hex*/
#endif
0, /*nb_inplace_add*/
0, /*nb_inplace_subtract*/
0, /*nb_inplace_multiply*/
#if PY_MAJOR_VERSION < 3
0, /*nb_inplace_divide*/
#endif
0, /*nb_inplace_remainder*/
0, /*nb_inplace_power*/
0, /*nb_inplace_lshift*/
0, /*nb_inplace_rshift*/
0, /*nb_inplace_and*/
0, /*nb_inplace_xor*/
0, /*nb_inplace_or*/
0, /*nb_floor_divide*/
0, /*nb_true_divide*/
0, /*nb_inplace_floor_divide*/
0, /*nb_inplace_true_divide*/
#if (PY_MAJOR_VERSION >= 3) || (Py_TPFLAGS_DEFAULT & Py_TPFLAGS_HAVE_INDEX)
0, /*nb_index*/
#endif
};
static PySequenceMethods __pyx_tp_as_sequence_Input = {
0, /*sq_length*/
0, /*sq_concat*/
0, /*sq_repeat*/
0, /*sq_item*/
0, /*sq_slice*/
0, /*sq_ass_item*/
0, /*sq_ass_slice*/
0, /*sq_contains*/
0, /*sq_inplace_concat*/
0, /*sq_inplace_repeat*/
};
static PyMappingMethods __pyx_tp_as_mapping_Input = {
0, /*mp_length*/
0, /*mp_subscript*/
0, /*mp_ass_subscript*/
};
static PyBufferProcs __pyx_tp_as_buffer_Input = {
#if PY_MAJOR_VERSION < 3
0, /*bf_getreadbuffer*/
#endif
#if PY_MAJOR_VERSION < 3
0, /*bf_getwritebuffer*/
#endif
#if PY_MAJOR_VERSION < 3
0, /*bf_getsegcount*/
#endif
#if PY_MAJOR_VERSION < 3
0, /*bf_getcharbuffer*/
#endif
#if PY_VERSION_HEX >= 0x02060000
0, /*bf_getbuffer*/
#endif
#if PY_VERSION_HEX >= 0x02060000
0, /*bf_releasebuffer*/
#endif
};
PyTypeObject __pyx_type_4pypm_Input = {
PyVarObject_HEAD_INIT(0, 0)
__Pyx_NAMESTR("pypm.Input"), /*tp_name*/
sizeof(struct __pyx_obj_4pypm_Input), /*tp_basicsize*/
0, /*tp_itemsize*/
__pyx_tp_dealloc_4pypm_Input, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
&__pyx_tp_as_number_Input, /*tp_as_number*/
&__pyx_tp_as_sequence_Input, /*tp_as_sequence*/
&__pyx_tp_as_mapping_Input, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
&__pyx_tp_as_buffer_Input, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_NEWBUFFER, /*tp_flags*/
__Pyx_DOCSTR("\nclass Input:\n define an input MIDI stream. Takes the form:\n x = pypm.Input(MidiInputDevice)\n "), /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
__pyx_methods_4pypm_Input, /*tp_methods*/
0, /*tp_members*/
0, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
0, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictoffset*/
__pyx_pf_4pypm_5Input___init__, /*tp_init*/
0, /*tp_alloc*/
__pyx_tp_new_4pypm_Input, /*tp_new*/
0, /*tp_free*/
0, /*tp_is_gc*/
0, /*tp_bases*/
0, /*tp_mro*/
0, /*tp_cache*/
0, /*tp_subclasses*/
0, /*tp_weaklist*/
};
static struct PyMethodDef __pyx_methods[] = {
{__Pyx_NAMESTR("Initialize"), (PyCFunction)__pyx_pf_4pypm_Initialize, METH_NOARGS, __Pyx_DOCSTR(__pyx_doc_4pypm_Initialize)},
{__Pyx_NAMESTR("Terminate"), (PyCFunction)__pyx_pf_4pypm_Terminate, METH_NOARGS, __Pyx_DOCSTR(__pyx_doc_4pypm_Terminate)},
{__Pyx_NAMESTR("GetDefaultInputDeviceID"), (PyCFunction)__pyx_pf_4pypm_GetDefaultInputDeviceID, METH_NOARGS, __Pyx_DOCSTR(0)},
{__Pyx_NAMESTR("GetDefaultOutputDeviceID"), (PyCFunction)__pyx_pf_4pypm_GetDefaultOutputDeviceID, METH_NOARGS, __Pyx_DOCSTR(0)},
{__Pyx_NAMESTR("CountDevices"), (PyCFunction)__pyx_pf_4pypm_CountDevices, METH_NOARGS, __Pyx_DOCSTR(0)},
{__Pyx_NAMESTR("GetDeviceInfo"), (PyCFunction)__pyx_pf_4pypm_GetDeviceInfo, METH_O, __Pyx_DOCSTR(__pyx_doc_4pypm_GetDeviceInfo)},
{__Pyx_NAMESTR("Time"), (PyCFunction)__pyx_pf_4pypm_Time, METH_NOARGS, __Pyx_DOCSTR(__pyx_doc_4pypm_Time)},
{__Pyx_NAMESTR("GetErrorText"), (PyCFunction)__pyx_pf_4pypm_GetErrorText, METH_O, __Pyx_DOCSTR(__pyx_doc_4pypm_GetErrorText)},
{__Pyx_NAMESTR("Channel"), (PyCFunction)__pyx_pf_4pypm_Channel, METH_O, __Pyx_DOCSTR(__pyx_doc_4pypm_Channel)},
{0, 0, 0, 0}
};
static void __pyx_init_filenames(void); /*proto*/
#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef __pyx_moduledef = {
PyModuleDef_HEAD_INIT,
__Pyx_NAMESTR("pypm"),
0, /* m_doc */
-1, /* m_size */
__pyx_methods /* m_methods */,
NULL, /* m_reload */
NULL, /* m_traverse */
NULL, /* m_clear */
NULL /* m_free */
};
#endif
static __Pyx_StringTabEntry __pyx_string_tab[] = {
{&__pyx_kp___main__, __pyx_k___main__, sizeof(__pyx_k___main__), 1, 1, 1},
{&__pyx_kp___init__, __pyx_k___init__, sizeof(__pyx_k___init__), 1, 1, 1},
{&__pyx_kp___dealloc__, __pyx_k___dealloc__, sizeof(__pyx_k___dealloc__), 1, 1, 1},
{&__pyx_kp__check_open, __pyx_k__check_open, sizeof(__pyx_k__check_open), 1, 1, 1},
{&__pyx_kp_Close, __pyx_k_Close, sizeof(__pyx_k_Close), 1, 1, 1},
{&__pyx_kp_Abort, __pyx_k_Abort, sizeof(__pyx_k_Abort), 1, 1, 1},
{&__pyx_kp_Write, __pyx_k_Write, sizeof(__pyx_k_Write), 1, 1, 1},
{&__pyx_kp_WriteShort, __pyx_k_WriteShort, sizeof(__pyx_k_WriteShort), 1, 1, 1},
{&__pyx_kp_WriteSysEx, __pyx_k_WriteSysEx, sizeof(__pyx_k_WriteSysEx), 1, 1, 1},
{&__pyx_kp_SetFilter, __pyx_k_SetFilter, sizeof(__pyx_k_SetFilter), 1, 1, 1},
{&__pyx_kp_SetChannelMask, __pyx_k_SetChannelMask, sizeof(__pyx_k_SetChannelMask), 1, 1, 1},
{&__pyx_kp_Poll, __pyx_k_Poll, sizeof(__pyx_k_Poll), 1, 1, 1},
{&__pyx_kp_Read, __pyx_k_Read, sizeof(__pyx_k_Read), 1, 1, 1},
{&__pyx_kp_i, __pyx_k_i, sizeof(__pyx_k_i), 1, 1, 1},
{&__pyx_kp_err, __pyx_k_err, sizeof(__pyx_k_err), 1, 1, 1},
{&__pyx_kp_chan, __pyx_k_chan, sizeof(__pyx_k_chan), 1, 1, 1},
{&__pyx_kp_OutputDevice, __pyx_k_OutputDevice, sizeof(__pyx_k_OutputDevice), 1, 1, 1},
{&__pyx_kp_latency, __pyx_k_latency, sizeof(__pyx_k_latency), 1, 1, 1},
{&__pyx_kp_data, __pyx_k_data, sizeof(__pyx_k_data), 1, 1, 1},
{&__pyx_kp_status, __pyx_k_status, sizeof(__pyx_k_status), 1, 1, 1},
{&__pyx_kp_1, __pyx_k_1, sizeof(__pyx_k_1), 1, 1, 1},
{&__pyx_kp_2, __pyx_k_2, sizeof(__pyx_k_2), 1, 1, 1},
{&__pyx_kp_when, __pyx_k_when, sizeof(__pyx_k_when), 1, 1, 1},
{&__pyx_kp_msg, __pyx_k_msg, sizeof(__pyx_k_msg), 1, 1, 1},
{&__pyx_kp_InputDevice, __pyx_k_InputDevice, sizeof(__pyx_k_InputDevice), 1, 1, 1},
{&__pyx_kp_buffersize, __pyx_k_buffersize, sizeof(__pyx_k_buffersize), 1, 1, 1},
{&__pyx_kp_filters, __pyx_k_filters, sizeof(__pyx_k_filters), 1, 1, 1},
{&__pyx_kp_mask, __pyx_k_mask, sizeof(__pyx_k_mask), 1, 1, 1},
{&__pyx_kp_length, __pyx_k_length, sizeof(__pyx_k_length), 1, 1, 1},
{&__pyx_kp___version__, __pyx_k___version__, sizeof(__pyx_k___version__), 1, 1, 1},
{&__pyx_kp_array, __pyx_k_array, sizeof(__pyx_k_array), 1, 1, 1},
{&__pyx_kp_FILT_ACTIVE, __pyx_k_FILT_ACTIVE, sizeof(__pyx_k_FILT_ACTIVE), 1, 1, 1},
{&__pyx_kp_FILT_SYSEX, __pyx_k_FILT_SYSEX, sizeof(__pyx_k_FILT_SYSEX), 1, 1, 1},
{&__pyx_kp_FILT_CLOCK, __pyx_k_FILT_CLOCK, sizeof(__pyx_k_FILT_CLOCK), 1, 1, 1},
{&__pyx_kp_FILT_PLAY, __pyx_k_FILT_PLAY, sizeof(__pyx_k_FILT_PLAY), 1, 1, 1},
{&__pyx_kp_4, __pyx_k_4, sizeof(__pyx_k_4), 1, 1, 1},
{&__pyx_kp_FILT_TICK, __pyx_k_FILT_TICK, sizeof(__pyx_k_FILT_TICK), 1, 1, 1},
{&__pyx_kp_FILT_FD, __pyx_k_FILT_FD, sizeof(__pyx_k_FILT_FD), 1, 1, 1},
{&__pyx_kp_FILT_UNDEFINED, __pyx_k_FILT_UNDEFINED, sizeof(__pyx_k_FILT_UNDEFINED), 1, 1, 1},
{&__pyx_kp_FILT_RESET, __pyx_k_FILT_RESET, sizeof(__pyx_k_FILT_RESET), 1, 1, 1},
{&__pyx_kp_FILT_REALTIME, __pyx_k_FILT_REALTIME, sizeof(__pyx_k_FILT_REALTIME), 1, 1, 1},
{&__pyx_kp_FILT_NOTE, __pyx_k_FILT_NOTE, sizeof(__pyx_k_FILT_NOTE), 1, 1, 1},
{&__pyx_kp_5, __pyx_k_5, sizeof(__pyx_k_5), 1, 1, 1},
{&__pyx_kp_6, __pyx_k_6, sizeof(__pyx_k_6), 1, 1, 1},
{&__pyx_kp_FILT_AFTERTOUCH, __pyx_k_FILT_AFTERTOUCH, sizeof(__pyx_k_FILT_AFTERTOUCH), 1, 1, 1},
{&__pyx_kp_FILT_PROGRAM, __pyx_k_FILT_PROGRAM, sizeof(__pyx_k_FILT_PROGRAM), 1, 1, 1},
{&__pyx_kp_FILT_CONTROL, __pyx_k_FILT_CONTROL, sizeof(__pyx_k_FILT_CONTROL), 1, 1, 1},
{&__pyx_kp_FILT_PITCHBEND, __pyx_k_FILT_PITCHBEND, sizeof(__pyx_k_FILT_PITCHBEND), 1, 1, 1},
{&__pyx_kp_FILT_MTC, __pyx_k_FILT_MTC, sizeof(__pyx_k_FILT_MTC), 1, 1, 1},
{&__pyx_kp_FILT_SONG_POSITION, __pyx_k_FILT_SONG_POSITION, sizeof(__pyx_k_FILT_SONG_POSITION), 1, 1, 1},
{&__pyx_kp_FILT_SONG_SELECT, __pyx_k_FILT_SONG_SELECT, sizeof(__pyx_k_FILT_SONG_SELECT), 1, 1, 1},
{&__pyx_kp_FILT_TUNE, __pyx_k_FILT_TUNE, sizeof(__pyx_k_FILT_TUNE), 1, 1, 1},
{&__pyx_kp_FALSE, __pyx_k_FALSE, sizeof(__pyx_k_FALSE), 1, 1, 1},
{&__pyx_kp_TRUE, __pyx_k_TRUE, sizeof(__pyx_k_TRUE), 1, 1, 1},
{&__pyx_kp_Exception, __pyx_k_Exception, sizeof(__pyx_k_Exception), 1, 1, 1},
{&__pyx_kp_IndexError, __pyx_k_IndexError, sizeof(__pyx_k_IndexError), 1, 1, 1},
{&__pyx_kp_range, __pyx_k_range, sizeof(__pyx_k_range), 1, 1, 1},
{&__pyx_kp_19, __pyx_k_19, sizeof(__pyx_k_19), 0, 1, 0},
{&__pyx_kp_tostring, __pyx_k_tostring, sizeof(__pyx_k_tostring), 1, 1, 1},
{&__pyx_kp_append, __pyx_k_append, sizeof(__pyx_k_append), 1, 1, 1},
{&__pyx_kp_3, __pyx_k_3, sizeof(__pyx_k_3), 0, 0, 0},
{&__pyx_kp_7, __pyx_k_7, sizeof(__pyx_k_7), 0, 0, 0},
{&__pyx_kp_8, __pyx_k_8, sizeof(__pyx_k_8), 0, 0, 0},
{&__pyx_kp_9, __pyx_k_9, sizeof(__pyx_k_9), 0, 0, 0},
{&__pyx_kp_10, __pyx_k_10, sizeof(__pyx_k_10), 0, 0, 0},
{&__pyx_kp_11, __pyx_k_11, sizeof(__pyx_k_11), 0, 0, 0},
{&__pyx_kp_12, __pyx_k_12, sizeof(__pyx_k_12), 0, 0, 0},
{&__pyx_kp_13, __pyx_k_13, sizeof(__pyx_k_13), 0, 0, 0},
{&__pyx_kp_14, __pyx_k_14, sizeof(__pyx_k_14), 0, 0, 0},
{&__pyx_kp_15, __pyx_k_15, sizeof(__pyx_k_15), 0, 0, 0},
{&__pyx_kp_16, __pyx_k_16, sizeof(__pyx_k_16), 0, 0, 0},
{&__pyx_kp_17, __pyx_k_17, sizeof(__pyx_k_17), 0, 0, 0},
{&__pyx_kp_18, __pyx_k_18, sizeof(__pyx_k_18), 0, 0, 0},
{&__pyx_kp_20, __pyx_k_20, sizeof(__pyx_k_20), 0, 0, 0},
{&__pyx_kp_21, __pyx_k_21, sizeof(__pyx_k_21), 0, 0, 0},
{&__pyx_kp_22, __pyx_k_22, sizeof(__pyx_k_22), 0, 0, 0},
{&__pyx_kp_23, __pyx_k_23, sizeof(__pyx_k_23), 0, 0, 0},
{&__pyx_kp_24, __pyx_k_24, sizeof(__pyx_k_24), 0, 0, 0},
{0, 0, 0, 0, 0, 0}
};
static int __Pyx_InitCachedBuiltins(void) {
__pyx_builtin_Exception = __Pyx_GetName(__pyx_b, __pyx_kp_Exception); if (!__pyx_builtin_Exception) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_builtin_IndexError = __Pyx_GetName(__pyx_b, __pyx_kp_IndexError); if (!__pyx_builtin_IndexError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 318; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_builtin_range = __Pyx_GetName(__pyx_b, __pyx_kp_range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 320; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
return 0;
__pyx_L1_error:;
return -1;
}
static int __Pyx_InitGlobals(void) {
__pyx_int_0x1 = PyInt_FromLong(0x1); if (unlikely(!__pyx_int_0x1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__pyx_int_0x2 = PyInt_FromLong(0x2); if (unlikely(!__pyx_int_0x2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__pyx_int_0x4 = PyInt_FromLong(0x4); if (unlikely(!__pyx_int_0x4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__pyx_int_0x8 = PyInt_FromLong(0x8); if (unlikely(!__pyx_int_0x8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__pyx_int_0x10 = PyInt_FromLong(0x10); if (unlikely(!__pyx_int_0x10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__pyx_int_0x20 = PyInt_FromLong(0x20); if (unlikely(!__pyx_int_0x20)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__pyx_int_0x30 = PyInt_FromLong(0x30); if (unlikely(!__pyx_int_0x30)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__pyx_int_0x40 = PyInt_FromLong(0x40); if (unlikely(!__pyx_int_0x40)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__pyx_int_0x7F = PyInt_FromLong(0x7F); if (unlikely(!__pyx_int_0x7F)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__pyx_int_0x80 = PyInt_FromLong(0x80); if (unlikely(!__pyx_int_0x80)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__pyx_int_0x100 = PyInt_FromLong(0x100); if (unlikely(!__pyx_int_0x100)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__pyx_int_0x200 = PyInt_FromLong(0x200); if (unlikely(!__pyx_int_0x200)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__pyx_int_0x300 = PyInt_FromLong(0x300); if (unlikely(!__pyx_int_0x300)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__pyx_int_0x400 = PyInt_FromLong(0x400); if (unlikely(!__pyx_int_0x400)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__pyx_int_0x800 = PyInt_FromLong(0x800); if (unlikely(!__pyx_int_0x800)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__pyx_int_0x1000 = PyInt_FromLong(0x1000); if (unlikely(!__pyx_int_0x1000)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__pyx_int_0x2000 = PyInt_FromLong(0x2000); if (unlikely(!__pyx_int_0x2000)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__pyx_int_0x4000 = PyInt_FromLong(0x4000); if (unlikely(!__pyx_int_0x4000)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__pyx_int_0x8000 = PyInt_FromLong(0x8000); if (unlikely(!__pyx_int_0x8000)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__pyx_int_0x10000 = PyInt_FromLong(0x10000); if (unlikely(!__pyx_int_0x10000)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__pyx_int_4096 = PyInt_FromLong(4096); if (unlikely(!__pyx_int_4096)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__pyx_int_0xFF = PyInt_FromLong(0xFF); if (unlikely(!__pyx_int_0xFF)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__pyx_int_16 = PyInt_FromLong(16); if (unlikely(!__pyx_int_16)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__pyx_int_0xFF0000 = PyInt_FromLong(0xFF0000); if (unlikely(!__pyx_int_0xFF0000)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__pyx_int_8 = PyInt_FromLong(8); if (unlikely(!__pyx_int_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__pyx_int_0xFF00 = PyInt_FromLong(0xFF00); if (unlikely(!__pyx_int_0xFF00)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__pyx_int_1024 = PyInt_FromLong(1024); if (unlikely(!__pyx_int_1024)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
return 0;
__pyx_L1_error:;
return -1;
}
#if PY_MAJOR_VERSION < 3
PyMODINIT_FUNC initpypm(void); /*proto*/
PyMODINIT_FUNC initpypm(void)
#else
PyMODINIT_FUNC PyInit_pypm(void); /*proto*/
PyMODINIT_FUNC PyInit_pypm(void)
#endif
{
PyObject *__pyx_1 = 0;
#ifdef CYTHON_REFNANNY
void* __pyx_refchk = NULL;
__Pyx_Refnanny = __Pyx_ImportRefcountAPI("refnanny");
if (!__Pyx_Refnanny) {
PyErr_Clear();
__Pyx_Refnanny = __Pyx_ImportRefcountAPI("Cython.Runtime.refnanny");
if (!__Pyx_Refnanny)
Py_FatalError("failed to import refnanny module");
}
__pyx_refchk = __Pyx_Refnanny->NewContext("PyMODINIT_FUNC PyInit_pypm(void)", __LINE__, __FILE__);
#endif
__pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/*--- Library function declarations ---*/
__pyx_init_filenames();
/*--- Threads initialization code ---*/
#if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS
#ifdef WITH_THREAD /* Python build with threading support? */
PyEval_InitThreads();
#endif
#endif
/*--- Initialize various global constants etc. ---*/
if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/*--- Module creation code ---*/
#if PY_MAJOR_VERSION < 3
__pyx_m = Py_InitModule4(__Pyx_NAMESTR("pypm"), __pyx_methods, 0, 0, PYTHON_API_VERSION);
#else
__pyx_m = PyModule_Create(&__pyx_moduledef);
#endif
if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
#if PY_MAJOR_VERSION < 3
Py_INCREF(__pyx_m);
#endif
__pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME));
if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
if (__pyx_module_is_main_pypm) {
if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_kp___main__) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
}
/*--- Builtin init code ---*/
if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_skip_dispatch = 0;
/*--- Global init code ---*/
/*--- Function export code ---*/
/*--- Type init code ---*/
if (PyType_Ready(&__pyx_type_4pypm_Output) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
if (__Pyx_SetAttrString(__pyx_m, "Output", (PyObject *)&__pyx_type_4pypm_Output) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 201; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_ptype_4pypm_Output = &__pyx_type_4pypm_Output;
if (PyType_Ready(&__pyx_type_4pypm_Input) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 394; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
if (__Pyx_SetAttrString(__pyx_m, "Input", (PyObject *)&__pyx_type_4pypm_Input) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 394; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_ptype_4pypm_Input = &__pyx_type_4pypm_Input;
/*--- Type import code ---*/
/*--- Function import code ---*/
/*--- Execution code ---*/
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":7
* # harrison@media.mit.edu
* # written in Pyrex
* __version__="0.05" # <<<<<<<<<<<<<<
*
* import array
*/
if (PyObject_SetAttr(__pyx_m, __pyx_kp___version__, __pyx_kp_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":9
* __version__="0.05"
*
* import array # <<<<<<<<<<<<<<
*
* # CHANGES:
*/
__pyx_1 = __Pyx_Import(__pyx_kp_array, 0); if (unlikely(!__pyx_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_1);
if (PyObject_SetAttr(__pyx_m, __pyx_kp_array, __pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_1); __pyx_1 = 0;
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":108
* PtTimestamp Pt_Time()
*
* FILT_ACTIVE=0x1 # <<<<<<<<<<<<<<
* FILT_SYSEX=0x2
* FILT_CLOCK=0x4
*/
if (PyObject_SetAttr(__pyx_m, __pyx_kp_FILT_ACTIVE, __pyx_int_0x1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 108; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":109
*
* FILT_ACTIVE=0x1
* FILT_SYSEX=0x2 # <<<<<<<<<<<<<<
* FILT_CLOCK=0x4
* FILT_PLAY=0x8
*/
if (PyObject_SetAttr(__pyx_m, __pyx_kp_FILT_SYSEX, __pyx_int_0x2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 109; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":110
* FILT_ACTIVE=0x1
* FILT_SYSEX=0x2
* FILT_CLOCK=0x4 # <<<<<<<<<<<<<<
* FILT_PLAY=0x8
* FILT_F9=0x10
*/
if (PyObject_SetAttr(__pyx_m, __pyx_kp_FILT_CLOCK, __pyx_int_0x4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 110; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":111
* FILT_SYSEX=0x2
* FILT_CLOCK=0x4
* FILT_PLAY=0x8 # <<<<<<<<<<<<<<
* FILT_F9=0x10
* FILT_TICK=0x10
*/
if (PyObject_SetAttr(__pyx_m, __pyx_kp_FILT_PLAY, __pyx_int_0x8) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 111; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":112
* FILT_CLOCK=0x4
* FILT_PLAY=0x8
* FILT_F9=0x10 # <<<<<<<<<<<<<<
* FILT_TICK=0x10
* FILT_FD=0x20
*/
if (PyObject_SetAttr(__pyx_m, __pyx_kp_4, __pyx_int_0x10) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 112; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":113
* FILT_PLAY=0x8
* FILT_F9=0x10
* FILT_TICK=0x10 # <<<<<<<<<<<<<<
* FILT_FD=0x20
* FILT_UNDEFINED=0x30
*/
if (PyObject_SetAttr(__pyx_m, __pyx_kp_FILT_TICK, __pyx_int_0x10) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":114
* FILT_F9=0x10
* FILT_TICK=0x10
* FILT_FD=0x20 # <<<<<<<<<<<<<<
* FILT_UNDEFINED=0x30
* FILT_RESET=0x40
*/
if (PyObject_SetAttr(__pyx_m, __pyx_kp_FILT_FD, __pyx_int_0x20) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":115
* FILT_TICK=0x10
* FILT_FD=0x20
* FILT_UNDEFINED=0x30 # <<<<<<<<<<<<<<
* FILT_RESET=0x40
* FILT_REALTIME=0x7F
*/
if (PyObject_SetAttr(__pyx_m, __pyx_kp_FILT_UNDEFINED, __pyx_int_0x30) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 115; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":116
* FILT_FD=0x20
* FILT_UNDEFINED=0x30
* FILT_RESET=0x40 # <<<<<<<<<<<<<<
* FILT_REALTIME=0x7F
* FILT_NOTE=0x80
*/
if (PyObject_SetAttr(__pyx_m, __pyx_kp_FILT_RESET, __pyx_int_0x40) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":117
* FILT_UNDEFINED=0x30
* FILT_RESET=0x40
* FILT_REALTIME=0x7F # <<<<<<<<<<<<<<
* FILT_NOTE=0x80
* FILT_CHANNEL_AFTERTOUCH=0x100
*/
if (PyObject_SetAttr(__pyx_m, __pyx_kp_FILT_REALTIME, __pyx_int_0x7F) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 117; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":118
* FILT_RESET=0x40
* FILT_REALTIME=0x7F
* FILT_NOTE=0x80 # <<<<<<<<<<<<<<
* FILT_CHANNEL_AFTERTOUCH=0x100
* FILT_POLY_AFTERTOUCH=0x200
*/
if (PyObject_SetAttr(__pyx_m, __pyx_kp_FILT_NOTE, __pyx_int_0x80) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 118; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":119
* FILT_REALTIME=0x7F
* FILT_NOTE=0x80
* FILT_CHANNEL_AFTERTOUCH=0x100 # <<<<<<<<<<<<<<
* FILT_POLY_AFTERTOUCH=0x200
* FILT_AFTERTOUCH=0x300
*/
if (PyObject_SetAttr(__pyx_m, __pyx_kp_5, __pyx_int_0x100) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 119; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":120
* FILT_NOTE=0x80
* FILT_CHANNEL_AFTERTOUCH=0x100
* FILT_POLY_AFTERTOUCH=0x200 # <<<<<<<<<<<<<<
* FILT_AFTERTOUCH=0x300
* FILT_PROGRAM=0x400
*/
if (PyObject_SetAttr(__pyx_m, __pyx_kp_6, __pyx_int_0x200) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":121
* FILT_CHANNEL_AFTERTOUCH=0x100
* FILT_POLY_AFTERTOUCH=0x200
* FILT_AFTERTOUCH=0x300 # <<<<<<<<<<<<<<
* FILT_PROGRAM=0x400
* FILT_CONTROL=0x800
*/
if (PyObject_SetAttr(__pyx_m, __pyx_kp_FILT_AFTERTOUCH, __pyx_int_0x300) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 121; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":122
* FILT_POLY_AFTERTOUCH=0x200
* FILT_AFTERTOUCH=0x300
* FILT_PROGRAM=0x400 # <<<<<<<<<<<<<<
* FILT_CONTROL=0x800
* FILT_PITCHBEND=0x1000
*/
if (PyObject_SetAttr(__pyx_m, __pyx_kp_FILT_PROGRAM, __pyx_int_0x400) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 122; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":123
* FILT_AFTERTOUCH=0x300
* FILT_PROGRAM=0x400
* FILT_CONTROL=0x800 # <<<<<<<<<<<<<<
* FILT_PITCHBEND=0x1000
* FILT_MTC=0x2000
*/
if (PyObject_SetAttr(__pyx_m, __pyx_kp_FILT_CONTROL, __pyx_int_0x800) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":124
* FILT_PROGRAM=0x400
* FILT_CONTROL=0x800
* FILT_PITCHBEND=0x1000 # <<<<<<<<<<<<<<
* FILT_MTC=0x2000
* FILT_SONG_POSITION=0x4000
*/
if (PyObject_SetAttr(__pyx_m, __pyx_kp_FILT_PITCHBEND, __pyx_int_0x1000) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":125
* FILT_CONTROL=0x800
* FILT_PITCHBEND=0x1000
* FILT_MTC=0x2000 # <<<<<<<<<<<<<<
* FILT_SONG_POSITION=0x4000
* FILT_SONG_SELECT=0x8000
*/
if (PyObject_SetAttr(__pyx_m, __pyx_kp_FILT_MTC, __pyx_int_0x2000) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 125; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":126
* FILT_PITCHBEND=0x1000
* FILT_MTC=0x2000
* FILT_SONG_POSITION=0x4000 # <<<<<<<<<<<<<<
* FILT_SONG_SELECT=0x8000
* FILT_TUNE=0x10000
*/
if (PyObject_SetAttr(__pyx_m, __pyx_kp_FILT_SONG_POSITION, __pyx_int_0x4000) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 126; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":127
* FILT_MTC=0x2000
* FILT_SONG_POSITION=0x4000
* FILT_SONG_SELECT=0x8000 # <<<<<<<<<<<<<<
* FILT_TUNE=0x10000
* FALSE=0
*/
if (PyObject_SetAttr(__pyx_m, __pyx_kp_FILT_SONG_SELECT, __pyx_int_0x8000) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":128
* FILT_SONG_POSITION=0x4000
* FILT_SONG_SELECT=0x8000
* FILT_TUNE=0x10000 # <<<<<<<<<<<<<<
* FALSE=0
* TRUE=1
*/
if (PyObject_SetAttr(__pyx_m, __pyx_kp_FILT_TUNE, __pyx_int_0x10000) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 128; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":129
* FILT_SONG_SELECT=0x8000
* FILT_TUNE=0x10000
* FALSE=0 # <<<<<<<<<<<<<<
* TRUE=1
*
*/
if (PyObject_SetAttr(__pyx_m, __pyx_kp_FALSE, __pyx_int_0) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":130
* FILT_TUNE=0x10000
* FALSE=0
* TRUE=1 # <<<<<<<<<<<<<<
*
* def Initialize():
*/
if (PyObject_SetAttr(__pyx_m, __pyx_kp_TRUE, __pyx_int_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "/home/rene/dev/pygame/pygame/trunk/src/pypm.pyx":514
* return err
*
* def Read(self,length): # <<<<<<<<<<<<<<
* """
* Read(length): returns up to midi events stored in
*/
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_1);
__Pyx_AddTraceback("pypm");
Py_DECREF(__pyx_m); __pyx_m = 0;
__pyx_L0:;
__Pyx_FinishRefcountContext();
#if PY_MAJOR_VERSION < 3
return;
#else
return __pyx_m;
#endif
}
static const char *__pyx_filenames[] = {
"pypm.pyx",
};
/* Runtime support code */
static void __pyx_init_filenames(void) {
__pyx_f = __pyx_filenames;
}
static void __Pyx_RaiseDoubleKeywordsError(
const char* func_name,
PyObject* kw_name)
{
PyErr_Format(PyExc_TypeError,
#if PY_MAJOR_VERSION >= 3
"%s() got multiple values for keyword argument '%U'", func_name, kw_name);
#else
"%s() got multiple values for keyword argument '%s'", func_name,
PyString_AS_STRING(kw_name));
#endif
}
static void __Pyx_RaiseArgtupleInvalid(
const char* func_name,
int exact,
Py_ssize_t num_min,
Py_ssize_t num_max,
Py_ssize_t num_found)
{
Py_ssize_t num_expected;
const char *number, *more_or_less;
if (num_found < num_min) {
num_expected = num_min;
more_or_less = "at least";
} else {
num_expected = num_max;
more_or_less = "at most";
}
if (exact) {
more_or_less = "exactly";
}
number = (num_expected == 1) ? "" : "s";
PyErr_Format(PyExc_TypeError,
#if PY_VERSION_HEX < 0x02050000
"%s() takes %s %d positional argument%s (%d given)",
#else
"%s() takes %s %zd positional argument%s (%zd given)",
#endif
func_name, more_or_less, num_expected, number, num_found);
}
static int __Pyx_ParseOptionalKeywords(
PyObject *kwds,
PyObject **argnames[],
PyObject *kwds2,
PyObject *values[],
Py_ssize_t num_pos_args,
const char* function_name)
{
PyObject *key = 0, *value = 0;
Py_ssize_t pos = 0;
PyObject*** name;
PyObject*** first_kw_arg = argnames + num_pos_args;
while (PyDict_Next(kwds, &pos, &key, &value)) {
name = first_kw_arg;
while (*name && (**name != key)) name++;
if (*name) {
values[name-argnames] = value;
} else {
#if PY_MAJOR_VERSION < 3
if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) {
#else
if (unlikely(!PyUnicode_CheckExact(key)) && unlikely(!PyUnicode_Check(key))) {
#endif
goto invalid_keyword_type;
} else {
for (name = first_kw_arg; *name; name++) {
#if PY_MAJOR_VERSION >= 3
if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) &&
PyUnicode_Compare(**name, key) == 0) break;
#else
if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) &&
_PyString_Eq(**name, key)) break;
#endif
}
if (*name) {
values[name-argnames] = value;
} else {
/* unexpected keyword found */
for (name=argnames; name != first_kw_arg; name++) {
if (**name == key) goto arg_passed_twice;
#if PY_MAJOR_VERSION >= 3
if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) &&
PyUnicode_Compare(**name, key) == 0) goto arg_passed_twice;
#else
if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) &&
_PyString_Eq(**name, key)) goto arg_passed_twice;
#endif
}
if (kwds2) {
if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad;
} else {
goto invalid_keyword;
}
}
}
}
}
return 0;
arg_passed_twice:
__Pyx_RaiseDoubleKeywordsError(function_name, **name);
goto bad;
invalid_keyword_type:
PyErr_Format(PyExc_TypeError,
"%s() keywords must be strings", function_name);
goto bad;
invalid_keyword:
PyErr_Format(PyExc_TypeError,
#if PY_MAJOR_VERSION < 3
"%s() got an unexpected keyword argument '%s'",
function_name, PyString_AsString(key));
#else
"%s() got an unexpected keyword argument '%U'",
function_name, key);
#endif
bad:
return -1;
}
static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list) {
PyObject *__import__ = 0;
PyObject *empty_list = 0;
PyObject *module = 0;
PyObject *global_dict = 0;
PyObject *empty_dict = 0;
PyObject *list;
__import__ = __Pyx_GetAttrString(__pyx_b, "__import__");
if (!__import__)
goto bad;
if (from_list)
list = from_list;
else {
empty_list = PyList_New(0);
if (!empty_list)
goto bad;
list = empty_list;
}
global_dict = PyModule_GetDict(__pyx_m);
if (!global_dict)
goto bad;
empty_dict = PyDict_New();
if (!empty_dict)
goto bad;
module = PyObject_CallFunctionObjArgs(__import__,
name, global_dict, empty_dict, list, NULL);
bad:
Py_XDECREF(empty_list);
Py_XDECREF(__import__);
Py_XDECREF(empty_dict);
return module;
}
#if PY_MAJOR_VERSION < 3
static PyObject *__Pyx_GetStdout(void) {
PyObject *f = PySys_GetObject((char *)"stdout");
if (!f) {
PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
}
return f;
}
static int __Pyx_Print(PyObject *arg_tuple, int newline) {
PyObject *f;
PyObject* v;
int i;
if (!(f = __Pyx_GetStdout()))
return -1;
for (i=0; i < PyTuple_GET_SIZE(arg_tuple); i++) {
if (PyFile_SoftSpace(f, 1)) {
if (PyFile_WriteString(" ", f) < 0)
return -1;
}
v = PyTuple_GET_ITEM(arg_tuple, i);
if (PyFile_WriteObject(v, f, Py_PRINT_RAW) < 0)
return -1;
if (PyString_Check(v)) {
char *s = PyString_AsString(v);
Py_ssize_t len = PyString_Size(v);
if (len > 0 &&
isspace(Py_CHARMASK(s[len-1])) &&
s[len-1] != ' ')
PyFile_SoftSpace(f, 0);
}
}
if (newline) {
if (PyFile_WriteString("\n", f) < 0)
return -1;
PyFile_SoftSpace(f, 0);
}
return 0;
}
#else /* Python 3 has a print function */
static int __Pyx_Print(PyObject *arg_tuple, int newline) {
PyObject* kwargs = 0;
PyObject* result = 0;
PyObject* end_string;
if (!__pyx_print) {
__pyx_print = __Pyx_GetAttrString(__pyx_b, "print");
if (!__pyx_print)
return -1;
}
if (!newline) {
if (!__pyx_print_kwargs) {
__pyx_print_kwargs = PyDict_New();
if (!__pyx_print_kwargs)
return -1;
end_string = PyUnicode_FromStringAndSize(" ", 1);
if (!end_string)
return -1;
if (PyDict_SetItemString(__pyx_print_kwargs, "end", end_string) < 0) {
Py_DECREF(end_string);
return -1;
}
Py_DECREF(end_string);
}
kwargs = __pyx_print_kwargs;
}
result = PyObject_Call(__pyx_print, arg_tuple, kwargs);
if (!result)
return -1;
Py_DECREF(result);
return 0;
}
#endif
#if PY_MAJOR_VERSION < 3
static int __Pyx_PrintOne(PyObject *o) {
PyObject *f;
if (!(f = __Pyx_GetStdout()))
return -1;
if (PyFile_SoftSpace(f, 0)) {
if (PyFile_WriteString(" ", f) < 0)
return -1;
}
if (PyFile_WriteObject(o, f, Py_PRINT_RAW) < 0)
return -1;
if (PyFile_WriteString("\n", f) < 0)
return -1;
return 0;
/* the line below is just to avoid compiler
* compiler warnings about unused functions */
return __Pyx_Print(NULL, 0);
}
#else /* Python 3 has a print function */
static int __Pyx_PrintOne(PyObject *o) {
int res;
PyObject* arg_tuple = PyTuple_New(1);
if (unlikely(!arg_tuple))
return -1;
Py_INCREF(o);
PyTuple_SET_ITEM(arg_tuple, 0, o);
res = __Pyx_Print(arg_tuple, 1);
Py_DECREF(arg_tuple);
return res;
}
#endif
static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) {
PyObject *result;
result = PyObject_GetAttr(dict, name);
if (!result)
PyErr_SetObject(PyExc_NameError, name);
return result;
}
static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb) {
Py_XINCREF(type);
Py_XINCREF(value);
Py_XINCREF(tb);
/* First, check the traceback argument, replacing None with NULL. */
if (tb == Py_None) {
Py_DECREF(tb);
tb = 0;
}
else if (tb != NULL && !PyTraceBack_Check(tb)) {
PyErr_SetString(PyExc_TypeError,
"raise: arg 3 must be a traceback or None");
goto raise_error;
}
/* Next, replace a missing value with None */
if (value == NULL) {
value = Py_None;
Py_INCREF(value);
}
#if PY_VERSION_HEX < 0x02050000
if (!PyClass_Check(type))
#else
if (!PyType_Check(type))
#endif
{
/* Raising an instance. The value should be a dummy. */
if (value != Py_None) {
PyErr_SetString(PyExc_TypeError,
"instance exception may not have a separate value");
goto raise_error;
}
/* Normalize to raise , */
Py_DECREF(value);
value = type;
#if PY_VERSION_HEX < 0x02050000
if (PyInstance_Check(type)) {
type = (PyObject*) ((PyInstanceObject*)type)->in_class;
Py_INCREF(type);
}
else {
type = 0;
PyErr_SetString(PyExc_TypeError,
"raise: exception must be an old-style class or instance");
goto raise_error;
}
#else
type = (PyObject*) Py_TYPE(type);
Py_INCREF(type);
if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) {
PyErr_SetString(PyExc_TypeError,
"raise: exception class must be a subclass of BaseException");
goto raise_error;
}
#endif
}
__Pyx_ErrRestore(type, value, tb);
return;
raise_error:
Py_XDECREF(value);
Py_XDECREF(type);
Py_XDECREF(tb);
return;
}
static INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) {
PyObject *tmp_type, *tmp_value, *tmp_tb;
PyThreadState *tstate = PyThreadState_GET();
#if PY_MAJOR_VERSION >= 3
/* Note: this is a temporary work-around to prevent crashes in Python 3.0 */
if ((tstate->exc_type != NULL) & (tstate->exc_type != Py_None)) {
tmp_type = tstate->exc_type;
tmp_value = tstate->exc_value;
tmp_tb = tstate->exc_traceback;
PyErr_NormalizeException(&type, &value, &tb);
PyErr_NormalizeException(&tmp_type, &tmp_value, &tmp_tb);
tstate->exc_type = 0;
tstate->exc_value = 0;
tstate->exc_traceback = 0;
PyException_SetContext(value, tmp_value);
Py_DECREF(tmp_type);
Py_XDECREF(tmp_tb);
}
#endif
tmp_type = tstate->curexc_type;
tmp_value = tstate->curexc_value;
tmp_tb = tstate->curexc_traceback;
tstate->curexc_type = type;
tstate->curexc_value = value;
tstate->curexc_traceback = tb;
Py_XDECREF(tmp_type);
Py_XDECREF(tmp_value);
Py_XDECREF(tmp_tb);
}
static INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) {
PyThreadState *tstate = PyThreadState_GET();
*type = tstate->curexc_type;
*value = tstate->curexc_value;
*tb = tstate->curexc_traceback;
tstate->curexc_type = 0;
tstate->curexc_value = 0;
tstate->curexc_traceback = 0;
}
static INLINE int __Pyx_StrEq(const char *s1, const char *s2) {
while (*s1 != '\0' && *s1 == *s2) { s1++; s2++; }
return *s1 == *s2;
}
static INLINE unsigned char __Pyx_PyInt_AsUnsignedChar(PyObject* x) {
if (sizeof(unsigned char) < sizeof(long)) {
long val = __Pyx_PyInt_AsLong(x);
if (unlikely(val != (long)(unsigned char)val)) {
if (unlikely(val == -1 && PyErr_Occurred()))
return (unsigned char)-1;
if (unlikely(val < 0)) {
PyErr_SetString(PyExc_OverflowError,
"can't convert negative value to unsigned char");
return (unsigned char)-1;
}
PyErr_SetString(PyExc_OverflowError,
"value too large to convert to unsigned char");
return (unsigned char)-1;
}
return (unsigned char)val;
}
return (unsigned char)__Pyx_PyInt_AsUnsignedLong(x);
}
static INLINE unsigned short __Pyx_PyInt_AsUnsignedShort(PyObject* x) {
if (sizeof(unsigned short) < sizeof(long)) {
long val = __Pyx_PyInt_AsLong(x);
if (unlikely(val != (long)(unsigned short)val)) {
if (unlikely(val == -1 && PyErr_Occurred()))
return (unsigned short)-1;
if (unlikely(val < 0)) {
PyErr_SetString(PyExc_OverflowError,
"can't convert negative value to unsigned short");
return (unsigned short)-1;
}
PyErr_SetString(PyExc_OverflowError,
"value too large to convert to unsigned short");
return (unsigned short)-1;
}
return (unsigned short)val;
}
return (unsigned short)__Pyx_PyInt_AsUnsignedLong(x);
}
static INLINE unsigned int __Pyx_PyInt_AsUnsignedInt(PyObject* x) {
if (sizeof(unsigned int) < sizeof(long)) {
long val = __Pyx_PyInt_AsLong(x);
if (unlikely(val != (long)(unsigned int)val)) {
if (unlikely(val == -1 && PyErr_Occurred()))
return (unsigned int)-1;
if (unlikely(val < 0)) {
PyErr_SetString(PyExc_OverflowError,
"can't convert negative value to unsigned int");
return (unsigned int)-1;
}
PyErr_SetString(PyExc_OverflowError,
"value too large to convert to unsigned int");
return (unsigned int)-1;
}
return (unsigned int)val;
}
return (unsigned int)__Pyx_PyInt_AsUnsignedLong(x);
}
static INLINE char __Pyx_PyInt_AsChar(PyObject* x) {
if (sizeof(char) < sizeof(long)) {
long val = __Pyx_PyInt_AsLong(x);
if (unlikely(val != (long)(char)val)) {
if (unlikely(val == -1 && PyErr_Occurred()))
return (char)-1;
PyErr_SetString(PyExc_OverflowError,
"value too large to convert to char");
return (char)-1;
}
return (char)val;
}
return (char)__Pyx_PyInt_AsLong(x);
}
static INLINE short __Pyx_PyInt_AsShort(PyObject* x) {
if (sizeof(short) < sizeof(long)) {
long val = __Pyx_PyInt_AsLong(x);
if (unlikely(val != (long)(short)val)) {
if (unlikely(val == -1 && PyErr_Occurred()))
return (short)-1;
PyErr_SetString(PyExc_OverflowError,
"value too large to convert to short");
return (short)-1;
}
return (short)val;
}
return (short)__Pyx_PyInt_AsLong(x);
}
static INLINE int __Pyx_PyInt_AsInt(PyObject* x) {
if (sizeof(int) < sizeof(long)) {
long val = __Pyx_PyInt_AsLong(x);
if (unlikely(val != (long)(int)val)) {
if (unlikely(val == -1 && PyErr_Occurred()))
return (int)-1;
PyErr_SetString(PyExc_OverflowError,
"value too large to convert to int");
return (int)-1;
}
return (int)val;
}
return (int)__Pyx_PyInt_AsLong(x);
}
static INLINE signed char __Pyx_PyInt_AsSignedChar(PyObject* x) {
if (sizeof(signed char) < sizeof(long)) {
long val = __Pyx_PyInt_AsLong(x);
if (unlikely(val != (long)(signed char)val)) {
if (unlikely(val == -1 && PyErr_Occurred()))
return (signed char)-1;
PyErr_SetString(PyExc_OverflowError,
"value too large to convert to signed char");
return (signed char)-1;
}
return (signed char)val;
}
return (signed char)__Pyx_PyInt_AsSignedLong(x);
}
static INLINE signed short __Pyx_PyInt_AsSignedShort(PyObject* x) {
if (sizeof(signed short) < sizeof(long)) {
long val = __Pyx_PyInt_AsLong(x);
if (unlikely(val != (long)(signed short)val)) {
if (unlikely(val == -1 && PyErr_Occurred()))
return (signed short)-1;
PyErr_SetString(PyExc_OverflowError,
"value too large to convert to signed short");
return (signed short)-1;
}
return (signed short)val;
}
return (signed short)__Pyx_PyInt_AsSignedLong(x);
}
static INLINE signed int __Pyx_PyInt_AsSignedInt(PyObject* x) {
if (sizeof(signed int) < sizeof(long)) {
long val = __Pyx_PyInt_AsLong(x);
if (unlikely(val != (long)(signed int)val)) {
if (unlikely(val == -1 && PyErr_Occurred()))
return (signed int)-1;
PyErr_SetString(PyExc_OverflowError,
"value too large to convert to signed int");
return (signed int)-1;
}
return (signed int)val;
}
return (signed int)__Pyx_PyInt_AsSignedLong(x);
}
static INLINE unsigned long __Pyx_PyInt_AsUnsignedLong(PyObject* x) {
#if PY_VERSION_HEX < 0x03000000
if (likely(PyInt_CheckExact(x) || PyInt_Check(x))) {
long val = PyInt_AS_LONG(x);
if (unlikely(val < 0)) {
PyErr_SetString(PyExc_OverflowError,
"can't convert negative value to unsigned long");
return (unsigned long)-1;
}
return (unsigned long)val;
} else
#endif
if (likely(PyLong_CheckExact(x) || PyLong_Check(x))) {
if (unlikely(Py_SIZE(x) < 0)) {
PyErr_SetString(PyExc_OverflowError,
"can't convert negative value to unsigned long");
return (unsigned long)-1;
}
return PyLong_AsUnsignedLong(x);
} else {
unsigned long val;
PyObject *tmp = __Pyx_PyNumber_Int(x);
if (!tmp) return (unsigned long)-1;
val = __Pyx_PyInt_AsUnsignedLong(tmp);
Py_DECREF(tmp);
return val;
}
}
static INLINE unsigned PY_LONG_LONG __Pyx_PyInt_AsUnsignedLongLong(PyObject* x) {
#if PY_VERSION_HEX < 0x03000000
if (likely(PyInt_CheckExact(x) || PyInt_Check(x))) {
long val = PyInt_AS_LONG(x);
if (unlikely(val < 0)) {
PyErr_SetString(PyExc_OverflowError,
"can't convert negative value to unsigned PY_LONG_LONG");
return (unsigned PY_LONG_LONG)-1;
}
return (unsigned PY_LONG_LONG)val;
} else
#endif
if (likely(PyLong_CheckExact(x) || PyLong_Check(x))) {
if (unlikely(Py_SIZE(x) < 0)) {
PyErr_SetString(PyExc_OverflowError,
"can't convert negative value to unsigned PY_LONG_LONG");
return (unsigned PY_LONG_LONG)-1;
}
return PyLong_AsUnsignedLongLong(x);
} else {
unsigned PY_LONG_LONG val;
PyObject *tmp = __Pyx_PyNumber_Int(x);
if (!tmp) return (unsigned PY_LONG_LONG)-1;
val = __Pyx_PyInt_AsUnsignedLongLong(tmp);
Py_DECREF(tmp);
return val;
}
}
static INLINE long __Pyx_PyInt_AsLong(PyObject* x) {
#if PY_VERSION_HEX < 0x03000000
if (likely(PyInt_CheckExact(x) || PyInt_Check(x))) {
long val = PyInt_AS_LONG(x);
return (long)val;
} else
#endif
if (likely(PyLong_CheckExact(x) || PyLong_Check(x))) {
return PyLong_AsLong(x);
} else {
long val;
PyObject *tmp = __Pyx_PyNumber_Int(x);
if (!tmp) return (long)-1;
val = __Pyx_PyInt_AsLong(tmp);
Py_DECREF(tmp);
return val;
}
}
static INLINE PY_LONG_LONG __Pyx_PyInt_AsLongLong(PyObject* x) {
#if PY_VERSION_HEX < 0x03000000
if (likely(PyInt_CheckExact(x) || PyInt_Check(x))) {
long val = PyInt_AS_LONG(x);
return (PY_LONG_LONG)val;
} else
#endif
if (likely(PyLong_CheckExact(x) || PyLong_Check(x))) {
return PyLong_AsLongLong(x);
} else {
PY_LONG_LONG val;
PyObject *tmp = __Pyx_PyNumber_Int(x);
if (!tmp) return (PY_LONG_LONG)-1;
val = __Pyx_PyInt_AsLongLong(tmp);
Py_DECREF(tmp);
return val;
}
}
static INLINE signed long __Pyx_PyInt_AsSignedLong(PyObject* x) {
#if PY_VERSION_HEX < 0x03000000
if (likely(PyInt_CheckExact(x) || PyInt_Check(x))) {
long val = PyInt_AS_LONG(x);
return (signed long)val;
} else
#endif
if (likely(PyLong_CheckExact(x) || PyLong_Check(x))) {
return PyLong_AsLong(x);
} else {
signed long val;
PyObject *tmp = __Pyx_PyNumber_Int(x);
if (!tmp) return (signed long)-1;
val = __Pyx_PyInt_AsSignedLong(tmp);
Py_DECREF(tmp);
return val;
}
}
static INLINE signed PY_LONG_LONG __Pyx_PyInt_AsSignedLongLong(PyObject* x) {
#if PY_VERSION_HEX < 0x03000000
if (likely(PyInt_CheckExact(x) || PyInt_Check(x))) {
long val = PyInt_AS_LONG(x);
return (signed PY_LONG_LONG)val;
} else
#endif
if (likely(PyLong_CheckExact(x) || PyLong_Check(x))) {
return PyLong_AsLongLong(x);
} else {
signed PY_LONG_LONG val;
PyObject *tmp = __Pyx_PyNumber_Int(x);
if (!tmp) return (signed PY_LONG_LONG)-1;
val = __Pyx_PyInt_AsSignedLongLong(tmp);
Py_DECREF(tmp);
return val;
}
}
#include "compile.h"
#include "frameobject.h"
#include "traceback.h"
static void __Pyx_AddTraceback(const char *funcname) {
PyObject *py_srcfile = 0;
PyObject *py_funcname = 0;
PyObject *py_globals = 0;
PyObject *empty_string = 0;
PyCodeObject *py_code = 0;
PyFrameObject *py_frame = 0;
#if PY_MAJOR_VERSION < 3
py_srcfile = PyString_FromString(__pyx_filename);
#else
py_srcfile = PyUnicode_FromString(__pyx_filename);
#endif
if (!py_srcfile) goto bad;
if (__pyx_clineno) {
#if PY_MAJOR_VERSION < 3
py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno);
#else
py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno);
#endif
}
else {
#if PY_MAJOR_VERSION < 3
py_funcname = PyString_FromString(funcname);
#else
py_funcname = PyUnicode_FromString(funcname);
#endif
}
if (!py_funcname) goto bad;
py_globals = PyModule_GetDict(__pyx_m);
if (!py_globals) goto bad;
#if PY_MAJOR_VERSION < 3
empty_string = PyString_FromStringAndSize("", 0);
#else
empty_string = PyBytes_FromStringAndSize("", 0);
#endif
if (!empty_string) goto bad;
py_code = PyCode_New(
0, /*int argcount,*/
#if PY_MAJOR_VERSION >= 3
0, /*int kwonlyargcount,*/
#endif
0, /*int nlocals,*/
0, /*int stacksize,*/
0, /*int flags,*/
empty_string, /*PyObject *code,*/
__pyx_empty_tuple, /*PyObject *consts,*/
__pyx_empty_tuple, /*PyObject *names,*/
__pyx_empty_tuple, /*PyObject *varnames,*/
__pyx_empty_tuple, /*PyObject *freevars,*/
__pyx_empty_tuple, /*PyObject *cellvars,*/
py_srcfile, /*PyObject *filename,*/
py_funcname, /*PyObject *name,*/
__pyx_lineno, /*int firstlineno,*/
empty_string /*PyObject *lnotab*/
);
if (!py_code) goto bad;
py_frame = PyFrame_New(
PyThreadState_GET(), /*PyThreadState *tstate,*/
py_code, /*PyCodeObject *code,*/
py_globals, /*PyObject *globals,*/
0 /*PyObject *locals*/
);
if (!py_frame) goto bad;
py_frame->f_lineno = __pyx_lineno;
PyTraceBack_Here(py_frame);
bad:
Py_XDECREF(py_srcfile);
Py_XDECREF(py_funcname);
Py_XDECREF(empty_string);
Py_XDECREF(py_code);
Py_XDECREF(py_frame);
}
static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) {
while (t->p) {
#if PY_MAJOR_VERSION < 3
if (t->is_unicode && (!t->is_identifier)) {
*t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL);
} else if (t->intern) {
*t->p = PyString_InternFromString(t->s);
} else {
*t->p = PyString_FromStringAndSize(t->s, t->n - 1);
}
#else /* Python 3+ has unicode identifiers */
if (t->is_identifier || (t->is_unicode && t->intern)) {
*t->p = PyUnicode_InternFromString(t->s);
} else if (t->is_unicode) {
*t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1);
} else {
*t->p = PyBytes_FromStringAndSize(t->s, t->n - 1);
}
#endif
if (!*t->p)
return -1;
++t;
}
return 0;
}
/* Type Conversion Functions */
static INLINE int __Pyx_PyObject_IsTrue(PyObject* x) {
if (x == Py_True) return 1;
else if ((x == Py_False) | (x == Py_None)) return 0;
else return PyObject_IsTrue(x);
}
static INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) {
PyNumberMethods *m;
const char *name = NULL;
PyObject *res = NULL;
#if PY_VERSION_HEX < 0x03000000
if (PyInt_Check(x) || PyLong_Check(x))
#else
if (PyLong_Check(x))
#endif
return Py_INCREF(x), x;
m = Py_TYPE(x)->tp_as_number;
#if PY_VERSION_HEX < 0x03000000
if (m && m->nb_int) {
name = "int";
res = PyNumber_Int(x);
}
else if (m && m->nb_long) {
name = "long";
res = PyNumber_Long(x);
}
#else
if (m && m->nb_int) {
name = "int";
res = PyNumber_Long(x);
}
#endif
if (res) {
#if PY_VERSION_HEX < 0x03000000
if (!PyInt_Check(res) && !PyLong_Check(res)) {
#else
if (!PyLong_Check(res)) {
#endif
PyErr_Format(PyExc_TypeError,
"__%s__ returned non-%s (type %.200s)",
name, name, Py_TYPE(res)->tp_name);
Py_DECREF(res);
return NULL;
}
}
else if (!PyErr_Occurred()) {
PyErr_SetString(PyExc_TypeError,
"an integer is required");
}
return res;
}
static INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) {
Py_ssize_t ival;
PyObject* x = PyNumber_Index(b);
if (!x) return -1;
ival = PyInt_AsSsize_t(x);
Py_DECREF(x);
return ival;
}
static INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) {
#if PY_VERSION_HEX < 0x02050000
if (ival <= LONG_MAX)
return PyInt_FromLong((long)ival);
else {
unsigned char *bytes = (unsigned char *) &ival;
int one = 1; int little = (int)*(unsigned char*)&one;
return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0);
}
#else
return PyInt_FromSize_t(ival);
#endif
}
static INLINE size_t __Pyx_PyInt_AsSize_t(PyObject* x) {
unsigned PY_LONG_LONG val = __Pyx_PyInt_AsUnsignedLongLong(x);
if (unlikely(val == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())) {
return (size_t)-1;
} else if (unlikely(val != (unsigned PY_LONG_LONG)(size_t)val)) {
PyErr_SetString(PyExc_OverflowError,
"value too large to convert to size_t");
return (size_t)-1;
}
return (size_t)val;
}
pygame-1.9.1release/src/pygamedocs.h 0000644 0001750 0001750 00000356222 11216627051 017351 0 ustar vincent vincent /* Auto generated file: with makeref.py . Docs go in src/ *.doc . */
#define DOC_PYGAME "the top level pygame package"
#define DOC_PYGAMEINIT "pygame.init(): return (numpass, numfail)\ninitialize all imported pygame modules"
#define DOC_PYGAMEQUIT "pygame.quit(): return None\nuninitialize all pygame modules"
#define DOC_PYGAMEERROR "raise pygame.error, message\nstandard pygame exception"
#define DOC_PYGAMEGETERROR "pygame.get_error(): return errorstr\nget the current error message"
#define DOC_PYGAMESETERROR "pygame.set_error(error_msg): return None\nset the current error message"
#define DOC_PYGAMEGETSDLVERSION "pygame.get_sdl_version(): return major, minor, patch\nget the version number of SDL"
#define DOC_PYGAMEGETSDLBYTEORDER "pygame.get_sdl_byteorder(): return int\nget the byte order of SDL"
#define DOC_PYGAMEREGISTERQUIT "register_quit(callable): return None\nregister a function to be called when pygame quits"
#define DOC_PYGAMEVERSION "module pygame.version\nsmall module containing version information"
#define DOC_PYGAMEVERSIONVER "pygame.version.ver = '1.2'\nversion number as a string"
#define DOC_PYGAMEVERSIONVERNUM "pygame.version.vernum = (1, 5, 3)\ntupled integers of the version"
#define DOC_PYGAMECAMERA "pygame module for camera use"
#define DOC_PYGAMECAMERACOLORSPACE "pygame.camera.colorspace(Surface, format, DestSurface = None): return Surface\nSurface colorspace conversion"
#define DOC_PYGAMECAMERALISTCAMERAS "pygame.camera.list_cameras(): return [cameras]\nreturns a list of available cameras"
#define DOC_PYGAMECAMERACAMERA "pygame.camera.Camera(device, (width, height), format): return Camera\nload a camera"
#define DOC_CAMERASTART "Camera.start(): return None\nopens, initializes, and starts capturing"
#define DOC_CAMERASTOP "Camera.stop(): return None\nstops, uninitializes, and closes the camera"
#define DOC_CAMERAGETCONTROLS "Camera.get_controls(): return (hflip = bool, vflip = bool, brightness)\ngets current values of user controls"
#define DOC_CAMERASETCONTROLS "Camera.set_controls(hflip = bool, vflip = bool, brightness): return (hflip = bool, vflip = bool, brightness)\nchanges camera settings if supported by the camera"
#define DOC_CAMERAGETSIZE "Camera.get_size(): return (width, height)\nreturns the dimensions of the images being recorded"
#define DOC_CAMERAQUERYIMAGE "Camera.query_image(): return bool\nchecks if a frame is ready"
#define DOC_CAMERAGETIMAGE "Camera.get_image(Surface = None): return Surface\ncaptures an image as a Surface"
#define DOC_CAMERAGETRAW "Camera.get_raw(): return string\nreturns an unmodified image as a string"
#define DOC_PYGAMECDROM "pygame module for audio cdrom control"
#define DOC_PYGAMECDROMINIT "pygame.cdrom.init(): return None\ninitialize the cdrom module"
#define DOC_PYGAMECDROMQUIT "pygame.cdrom.quit(): return None\nuninitialize the cdrom module"
#define DOC_PYGAMECDROMGETINIT "pygame.cdrom.get_init(): return bool\ntrue if the cdrom module is initialized"
#define DOC_PYGAMECDROMGETCOUNT "pygame.cdrom.get_count(): return count\nnumber of cd drives on the system"
#define DOC_PYGAMECDROMCD "pygame.cdrom.CD(id): return CD\nclass to manage a cdrom drive"
#define DOC_CDINIT "CD.init(): return None\ninitialize a cdrom drive for use"
#define DOC_CDQUIT "CD.quit(): return None\nuninitialize a cdrom drive for use"
#define DOC_CDGETINIT "CD.get_init(): return bool\ntrue if this cd device initialized"
#define DOC_CDPLAY "CD.play(track, start=None, end=None): return None\nstart playing audio"
#define DOC_CDSTOP "CD.stop(): return None\nstop audio playback"
#define DOC_CDPAUSE "CD.pause(): return None\ntemporarily stop audio playback"
#define DOC_CDRESUME "CD.resume(): return None\nunpause audio playback"
#define DOC_CDEJECT "CD.eject(): return None\neject or open the cdrom drive"
#define DOC_CDGETID "CD.get_id(): return id\nthe index of the cdrom drive"
#define DOC_CDGETNAME "CD.get_name(): return name\nthe system name of the cdrom drive"
#define DOC_CDGETBUSY "CD.get_busy(): return bool\ntrue if the drive is playing audio"
#define DOC_CDGETPAUSED "CD.get_paused(): return bool\ntrue if the drive is paused"
#define DOC_CDGETCURRENT "CD.get_current(): return track, seconds\nthe current audio playback position"
#define DOC_CDGETEMPTY "CD.get_empty(): return bool\nFalse if a cdrom is in the drive"
#define DOC_CDGETNUMTRACKS "CD.get_numtracks(): return count\nthe number of tracks on the cdrom"
#define DOC_CDGETTRACKAUDIO "CD.get_track_audio(track): return bool\ntrue if the cdrom track has audio data"
#define DOC_CDGETALL "CD.get_all(): return [(audio, start, end, lenth), ...]\nget all track information"
#define DOC_CDGETTRACKSTART "CD.get_track_start(track): return seconds\nstart time of a cdrom track"
#define DOC_CDGETTRACKLENGTH "CD.get_track_length(track): return seconds\nlength of a cdrom track"
#define DOC_PYGAMECOLOR "pygame.Color(name): Return Color\npygame.Color(r, g, b, a): Return Color\npygame.Color(rgbvalue): Return Color\npygame object for color representations"
#define DOC_COLORR "Color.r: Return int\nGets or sets the red value of the Color."
#define DOC_COLORG "Color.g: Return int\nGets or sets the green value of the Color."
#define DOC_COLORB "Color.b: Return int\nGets or sets the blue value of the Color."
#define DOC_COLORA "Color.a: Return int\nGets or sets the alpha value of the Color."
#define DOC_COLORCMY "Color.cmy: Return tuple\nGets or sets the CMY representation of the Color."
#define DOC_COLORHSVA "Color.hsva: Return tuple\nGets or sets the HSVA representation of the Color."
#define DOC_COLORHSLA "Color.hsla: Return tuple\nGets or sets the HSLA representation of the Color."
#define DOC_COLORI1I2I3 "Color.i1i2i3: Return tuple\nGets or sets the I1I2I3 representation of the Color."
#define DOC_COLORNORMALIZE "Color.normalize(): Return tuple\nReturns the normalized RGBA values of the Color."
#define DOC_COLORCORRECTGAMMA "Color.correct_gamma (gamma): Return Color\nApplies a certain gamma value to the Color."
#define DOC_COLORSETLENGTH "Color.set_length(len)\nSet the number of elements in the Color to 1,2,3, or 4."
#define DOC_PYGAMECURSORS "pygame module for cursor resources"
#define DOC_PYGAMECURSORSCOMPILE "pygame.cursor.compile(strings, black='X', white='.', xor='o'): return data, mask\ncreate binary cursor data from simple strings"
#define DOC_PYGAMECURSORSLOADXBM "pygame.cursors.load_xbm(cursorfile): return cursor_args\npygame.cursors.load_xbm(cursorfile, maskfile): return cursor_args\nload cursor data from an xbm file"
#define DOC_PYGAMEDISPLAY "pygame module to control the display window and screen"
#define DOC_PYGAMEDISPLAYINIT "pygame.display.init(): return None\ninitialize the display module"
#define DOC_PYGAMEDISPLAYQUIT "pygame.display.quit(): return None\nuninitialize the display module"
#define DOC_PYGAMEDISPLAYGETINIT "pygame.display.get_init(): return bool\ntrue if the display module is initialized"
#define DOC_PYGAMEDISPLAYSETMODE "pygame.display.set_mode(resolution=(0,0), flags=0, depth=0): return Surface\ninitialize a window or screen for display"
#define DOC_PYGAMEDISPLAYGETSURFACE "pygame.display.get_surface(): return Surface\nget a reference to the currently set display surface"
#define DOC_PYGAMEDISPLAYFLIP "pygame.display.flip(): return None\nupdate the full display Surface to the screen"
#define DOC_PYGAMEDISPLAYUPDATE "pygame.display.update(rectangle=None): return None\npygame.display.update(rectangle_list): return None\nupdate portions of the screen for software displays"
#define DOC_PYGAMEDISPLAYGETDRIVER "pygame.display.get_driver(): return name\nget the name of the pygame display backend"
#define DOC_PYGAMEDISPLAYINFO "pygame.display.Info(): return VideoInfo\nCreate a video display information object"
#define DOC_PYGAMEDISPLAYGETWMINFO "pygame.display.get_wm_info(): return dict\nGet information about the current windowing system"
#define DOC_PYGAMEDISPLAYLISTMODES "pygame.display.list_modes(depth=0, flags=pygame.FULLSCREEN): return list\nget list of available fullscreen modes"
#define DOC_PYGAMEDISPLAYMODEOK "pygame.display.mode_ok(size, flags=0, depth=0): return depth\npick the best color depth for a display mode"
#define DOC_PYGAMEDISPLAYGLGETATTRIBUTE "pygame.display.gl_get_attribute(flag): return value\nget the value for an opengl flag for the current display"
#define DOC_PYGAMEDISPLAYGLSETATTRIBUTE "pygame.display.gl_set_attribute(flag, value): return None\nrequest an opengl display attribute for the display mode"
#define DOC_PYGAMEDISPLAYGETACTIVE "pygame.display.get_active(): return bool\ntrue when the display is active on the display"
#define DOC_PYGAMEDISPLAYICONIFY "pygame.display.iconify(): return bool\niconify the display surface"
#define DOC_PYGAMEDISPLAYTOGGLEFULLSCREEN "pygame.display.toggle_fullscreen(): return bool\nswitch between fullscreen and windowed displays"
#define DOC_PYGAMEDISPLAYSETGAMMA "pygame.display.set_gamma(red, green=None, blue=None): return bool\nchange the hardware gamma ramps"
#define DOC_PYGAMEDISPLAYSETGAMMARAMP "change the hardware gamma ramps with a custom lookup\npygame.display.set_gamma_ramp(red, green, blue): return bool\nset_gamma_ramp(red, green, blue): return bool"
#define DOC_PYGAMEDISPLAYSETICON "pygame.display.set_icon(Surface): return None\nchange the system image for the display window"
#define DOC_PYGAMEDISPLAYSETCAPTION "pygame.display.set_caption(title, icontitle=None): return None\nset the current window caption"
#define DOC_PYGAMEDISPLAYGETCAPTION "pygame.display.get_caption(): return (title, icontitle)\nget the current window caption"
#define DOC_PYGAMEDISPLAYSETPALETTE "pygame.display.set_palette(palette=None): return None\nset the display color palette for indexed displays"
#define DOC_PYGAMEDRAW "pygame module for drawing shapes"
#define DOC_PYGAMEDRAWRECT "pygame.draw.rect(Surface, color, Rect, width=0): return Rect\ndraw a rectangle shape"
#define DOC_PYGAMEDRAWPOLYGON "pygame.draw.polygon(Surface, color, pointlist, width=0): return Rect\ndraw a shape with any number of sides"
#define DOC_PYGAMEDRAWCIRCLE "pygame.draw.circle(Surface, color, pos, radius, width=0): return Rect\ndraw a circle around a point"
#define DOC_PYGAMEDRAWELLIPSE "pygame.draw.ellipse(Surface, color, Rect, width=0): return Rect\ndraw a round shape inside a rectangle"
#define DOC_PYGAMEDRAWARC "pygame.draw.arc(Surface, color, Rect, start_angle, stop_angle, width=1): return Rect\ndraw a partial section of an ellipse"
#define DOC_PYGAMEDRAWLINE "pygame.draw.line(Surface, color, start_pos, end_pos, width=1): return Rect\ndraw a straight line segment"
#define DOC_PYGAMEDRAWLINES "pygame.draw.lines(Surface, color, closed, pointlist, width=1): return Rect\ndraw multiple contiguous line segments"
#define DOC_PYGAMEDRAWAALINE "pygame.draw.aaline(Surface, color, startpos, endpos, blend=1): return Rect\ndraw fine antialiased lines"
#define DOC_PYGAMEDRAWAALINES "pygame.draw.aalines(Surface, color, closed, pointlist, blend=1): return Rect"
#define DOC_PYGAMEEVENT "pygame module for interacting with events and queues"
#define DOC_PYGAMEEVENTPUMP "pygame.event.pump(): return None\ninternally process pygame event handlers"
#define DOC_PYGAMEEVENTGET "pygame.event.get(): return Eventlist\npygame.event.get(type): return Eventlist\npygame.event.get(typelist): return Eventlist\nget events from the queue"
#define DOC_PYGAMEEVENTPOLL "pygame.event.poll(): return Event\nget a single event from the queue"
#define DOC_PYGAMEEVENTWAIT "pygame.event.wait(): return Event\nwait for a single event from the queue"
#define DOC_PYGAMEEVENTPEEK "pygame.event.peek(type): return bool\npygame.event.peek(typelist): return bool\ntest if event types are waiting on the queue"
#define DOC_PYGAMEEVENTCLEAR "pygame.event.clear(): return None\npygame.event.clear(type): return None\npygame.event.clear(typelist): return None\nremove all events from the queue"
#define DOC_PYGAMEEVENTEVENTNAME "pygame.event.event_name(type): return string\nget the string name from and event id"
#define DOC_PYGAMEEVENTSETBLOCKED "pygame.event.set_blocked(type): return None\npygame.event.set_blocked(typelist): return None\npygame.event.set_blocked(None): return None\ncontrol which events are allowed on the queue"
#define DOC_PYGAMEEVENTSETALLOWED "pygame.event.set_allowed(type): return None\npygame.event.set_allowed(typelist): return None\npygame.event.set_allowed(None): return None\ncontrol which events are allowed on the queue"
#define DOC_PYGAMEEVENTGETBLOCKED "pygame.event.get_blocked(type): return bool\ntest if a type of event is blocked from the queue"
#define DOC_PYGAMEEVENTSETGRAB "pygame.event.set_grab(bool): return None\ncontrol the sharing of input devices with other applications"
#define DOC_PYGAMEEVENTGETGRAB "pygame.event.get_grab(): return bool\ntest if the program is sharing input devices"
#define DOC_PYGAMEEVENTPOST "pygame.event.post(Event): return None\nplace a new event on the queue"
#define DOC_PYGAMEEVENTEVENT "pygame.event.Event(type, dict): return Event\npygame.event.Event(type, **attributes): return Event\ncreate a new event object"
#define DOC_PYGAMEEXAMPLES "module of example programs"
#define DOC_PYGAMEEXAMPLESALIENSMAIN "pygame.aliens.main(): return None\nplay the full aliens example"
#define DOC_PYGAMEEXAMPLESOLDALIENMAIN "pygame.examples.oldalien.main(): return None\nplay the original aliens example"
#define DOC_PYGAMEEXAMPLESSTARSMAIN "pygame.examples.stars.main(): return None\nrun a simple starfield example"
#define DOC_PYGAMEEXAMPLESCHIMPMAIN "pygame.examples.chimp.main(): return None\nhit the moving chimp"
#define DOC_PYGAMEEXAMPLESMOVEITMAIN "pygame.examples.moveit.main(): return None\ndisplay animated objects on the screen"
#define DOC_PYGAMEEXAMPLESFONTYMAIN "pygame.examples.fonty.main(): return None\nrun a font rendering example"
#define DOC_PYGAMEEXAMPLESVGRADEMAIN "pygame.examples.vgrade.main(): return None\ndisplay a vertical gradient"
#define DOC_PYGAMEEXAMPLESEVENTLISTMAIN "pygame.examples.eventlist.main(): return None\ndisplay pygame events"
#define DOC_PYGAMEEXAMPLESARRAYDEMOMAIN "pygame.examples.arraydemo.main(arraytype=None): return None\nshow various surfarray effects"
#define DOC_PYGAMEEXAMPLESSOUNDMAIN "pygame.examples.sound.main(file_path=None): return None\nload and play a sound"
#define DOC_PYGAMEEXAMPLESSOUNDARRAYDEMOSMAIN "pygame.examples.sound_array_demos.main(arraytype=None): return None\nplay various sndarray effects"
#define DOC_PYGAMEEXAMPLESLIQUIDMAIN "pygame.examples.liquid.main(): return None\ndisplay an animated liquid effect"
#define DOC_PYGAMEEXAMPLESGLCUBEMAIN "pygame.examples.glcube.main(): return None\ndisplay an animated 3D cube using OpenGL"
#define DOC_PYGAMEEXAMPLESSCRAPCLIPBOARDMAIN "pygame.examples.scrap_clipboard.main(): return None\naccess the clipboard"
#define DOC_PYGAMEEXAMPLESMASKMAIN "pygame.examples.mask.main(*args): return None\ndisplay multiple images bounce off each other using collision detection"
#define DOC_PYGAMEEXAMPLESTESTSPRITEMAIN "pygame.examples.testsprite.main(update_rects = True, use_static = False, use_FastRenderGroup = False, screen_dims = [640, 480], use_alpha = False, flags = 0): return None\nshow lots of sprites moving around"
#define DOC_PYGAMEEXAMPLESHEADLESSNOWINDOWSNEEDEDMAIN "pygame.examples.headless_no_windows_needed.main(fin, fout, w, h): return None\nwrite an image file that is smoothscaled copy of an input file"
#define DOC_PYGAMEEXAMPLESFASTEVENTSMAIN "pygame.examples.fastevents.main(): return None\nstress test the fastevents module"
#define DOC_PYGAMEEXAMPLESOVERLAYMAIN "pygame.examples.overlay.main(fname): return None\nplay a .pgm video using overlays"
#define DOC_PYGAMEEXAMPLESBLENDFILLMAIN "pygame.examples.blend_fill.main(): return None\ndemonstrate the various surface.fill method blend options"
#define DOC_PYGAMEEXAMPLESCURSORSMAIN "pygame.examples.cursors.main(): return None\ndisplay two different custom cursors"
#define DOC_PYGAMEEXAMPLESPIXELARRAYMAIN "pygame.examples.pixelarray.main(): return None\ndisplay various pixelarray generated effects"
#define DOC_PYGAMEEXAMPLESSCALETESTMAIN "pygame.examples.scaletest.main(imagefile, convert_alpha=False, run_speed_test=True): return None\ninteractively scale an image using smoothscale"
#define DOC_PYGAMEEXAMPLESMIDIMAIN "pygame.examples.midi.main(mode='output', device_id=None): return None\nrun a midi example"
#define DOC_PYGAMEEXAMPLESSCROLLMAIN "pygame.examples.scroll.main(image_file=None): return None\nrun a Surface.scroll example that shows a magnified image"
#define DOC_PYGAMEEXAMPLESMOVIEPLAYERMAIN "pygame.examples.moveplayer.main(filepath): return None\nplay an MPEG movie"
#define DOC_PYGAMEFONT "pygame module for loading and rendering fonts"
#define DOC_PYGAMEFONTINIT "pygame.font.init(): return None\ninitialize the font module"
#define DOC_PYGAMEFONTQUIT "pygame.font.quit(): return None\nuninitialize the font module"
#define DOC_PYGAMEFONTGETINIT "pygame.font.get_init(): return bool\ntrue if the font module is initialized"
#define DOC_PYGAMEFONTGETDEFAULTFONT "pygame.font.get_default_font(): return string\nget the filename of the default font"
#define DOC_PYGAMEFONTGETFONTS "pygame.font.get_fonts(): return list of strings\nget all available fonts"
#define DOC_PYGAMEFONTMATCHFONT "pygame.font.match_font(name, bold=False, italic=False): return path\nfind a specific font on the system"
#define DOC_PYGAMEFONTSYSFONT "pygame.font.SysFont(name, size, bold=False, italic=False): return Font\ncreate a Font object from the system fonts"
#define DOC_PYGAMEFONTFONT "pygame.font.Font(filename, size): return Font\npygame.font.Font(object, size): return Font\ncreate a new Font object from a file"
#define DOC_FONTRENDER "Font.render(text, antialias, color, background=None): return Surface\ndraw text on a new Surface"
#define DOC_FONTSIZE "Font.size(text): return (width, height)\ndetermine the amount of space needed to render text"
#define DOC_FONTSETUNDERLINE "Font.set_underline(bool): return None\ncontrol if text is rendered with an underline"
#define DOC_FONTGETUNDERLINE "Font.get_underline(): return bool\ncheck if text will be rendered with an underline"
#define DOC_FONTSETBOLD "Font.set_bold(bool): return None\nenable fake rendering of bold text"
#define DOC_FONTGETBOLD "Font.get_bold(): return bool\ncheck if text will be rendered bold"
#define DOC_FONTSETITALIC "Font.set_bold(bool): return None\nenable fake rendering of italic text"
#define DOC_FONTMETRICS "Font.metrics(text): return list\nGets the metrics for each character in the pased string."
#define DOC_FONTGETITALIC "Font.get_italic(): return bool\ncheck if the text will be rendered italic"
#define DOC_FONTGETLINESIZE "Font.get_linesize(): return int\nget the line space of the font text"
#define DOC_FONTGETHEIGHT "Font.get_height(): return int\nget the height of the font"
#define DOC_FONTGETASCENT "Font.get_ascent(): return int\nget the ascent of the font"
#define DOC_FONTGETDESCENT "Font.get_descent(): return int\nget the descent of the font"
#define DOC_PYGAMEGFXDRAW "pygame module for drawing shapes"
#define DOC_PYGAMEGFXDRAWPIXEL "pygame.gfxdraw.pixel(surface, x, y, color): return None\nplace a pixel"
#define DOC_PYGAMEGFXDRAWHLINE "pygame.gfxdraw.hline(surface, x1, x2, y, color): return None\ndraw a horizontal line"
#define DOC_PYGAMEGFXDRAWVLINE "pgyame.gfxdraw.vline(surface, x, y1, y2, color): return None\ndraw a vertical line"
#define DOC_PYGAMEGFXDRAWRECTANGLE "pgyame.gfxdraw.rectangle(surface, rect, color): return None\ndraw a rectangle"
#define DOC_PYGAMEGFXDRAWBOX "pgyame.gfxdraw.box(surface, rect, color): return None\ndraw a box"
#define DOC_PYGAMEGFXDRAWLINE "pgyame.gfxdraw.line(surface, x1, y1, x2, y2, color): return None\ndraw a line"
#define DOC_PYGAMEGFXDRAWCIRCLE "pgyame.gfxdraw.circle(surface, x, y, r, color): return None\ndraw a circle"
#define DOC_PYGAMEGFXDRAWARC "pgyame.gfxdraw.arc(surface, x, y, r, start, end, color): return None\ndraw an arc"
#define DOC_PYGAMEGFXDRAWAACIRCLE "pgyame.gfxdraw.aacircle(surface, x, y, r, color): return None\ndraw an anti-aliased circle"
#define DOC_PYGAMEGFXDRAWFILLEDCIRCLE "pgyame.gfxdraw.filled_circle(surface, x, y, r, color): return None\ndraw a filled circle"
#define DOC_PYGAMEGFXDRAWELLIPSE "pgyame.gfxdraw.ellipse(surface, x, y, rx, ry, color): return None\ndraw an ellipse"
#define DOC_PYGAMEGFXDRAWAAELLIPSE "pgyame.gfxdraw.aaellipse(surface, x, y, rx, ry, color): return None\ndraw an anti-aliased ellipse"
#define DOC_PYGAMEGFXDRAWFILLEDELLIPSE "pgyame.gfxdraw.filled_ellipse(surface, x, y, rx, ry, color): return None\ndraw a filled ellipse"
#define DOC_PYGAMEGFXDRAWPIE "pgyame.gfxdraw.pie(surface, x, y, r, start, end, color): return None\ndraw a pie"
#define DOC_PYGAMEGFXDRAWTRIGON "pgyame.gfxdraw.trigon(surface, x1, y1, x2, y2, x3, y3, color): return None\ndraw a triangle"
#define DOC_PYGAMEGFXDRAWAATRIGON "pgyame.gfxdraw.aatrigon(surface, x1, y1, x2, y2, x3, y3, color): return None\ndraw an anti-aliased triangle"
#define DOC_PYGAMEGFXDRAWFILLEDTRIGON "pgyame.gfxdraw.filled_trigon(surface, x1, y1, x3, y2, x3, y3, color): return None\ndraw a filled trigon"
#define DOC_PYGAMEGFXDRAWPOLYGON "pgyame.gfxdraw.polygon(surface, points, color): return None\ndraw a polygon"
#define DOC_PYGAMEGFXDRAWAAPOLYGON "pgyame.gfxdraw.aapolygon(surface, points, color): return None\ndraw an anti-aliased polygon"
#define DOC_PYGAMEGFXDRAWFILLEDPOLYGON "pgyame.gfxdraw.filled_polygon(surface, points, color): return None\ndraw a filled polygon"
#define DOC_PYGAMEGFXDRAWTEXTUREDPOLYGON "pgyame.gfxdraw.textured_polygon(surface, points, texture, tx, ty): return None\ndraw a textured polygon"
#define DOC_PYGAMEGFXDRAWBEZIER "pgyame.gfxdraw.bezier(surface, points, steps, color): return None\ndraw a bezier curve"
#define DOC_PYGAMEIMAGE "pygame module for image transfer"
#define DOC_PYGAMEIMAGELOAD "pygame.image.load(filename): return Surface\npygame.image.load(fileobj, namehint=""): return Surface\nload new image from a file"
#define DOC_PYGAMEIMAGESAVE "pygame.image.save(Surface, filename): return None\nsave an image to disk"
#define DOC_PYGAMEIMAGEGETEXTENDED "pygame.image.get_extended(): return bool\ntest if extended image formats can be loaded"
#define DOC_PYGAMEIMAGETOSTRING "pygame.image.tostring(Surface, format, flipped=False): return string\ntransfer image to string buffer"
#define DOC_PYGAMEIMAGEFROMSTRING "pygame.image.fromstring(string, size, format, flipped=False): return Surface\ncreate new Surface from a string buffer"
#define DOC_PYGAMEIMAGEFROMBUFFER "pygame.image.frombuffer(string, size, format): return Surface\ncreate a new Surface that shares data inside a string buffer"
#define DOC_PYGAMEJOYSTICK "pygame module for interacting with joystick devices"
#define DOC_PYGAMEJOYSTICKINIT "pygame.joystick.init(): return None\ninitialize the joystick module"
#define DOC_PYGAMEJOYSTICKQUIT "pygame.joystick.quit(): return None\nuninitialize the joystick module"
#define DOC_PYGAMEJOYSTICKGETINIT "pygame.joystick.get_init(): return bool\ntrue if the joystick module is initialized"
#define DOC_PYGAMEJOYSTICKGETCOUNT "pygame.joystick.get_count(): return count\nnumber of joysticks on the system"
#define DOC_PYGAMEJOYSTICKJOYSTICK "pygame.joystick.Joystick(id): return Joystick\ncreate a new Joystick object"
#define DOC_JOYSTICKINIT "Joystick.init(): return None\ninitialize the Joystick"
#define DOC_JOYSTICKQUIT "Joystick.quit(): return None\nuninitialize the Joystick"
#define DOC_JOYSTICKGETINIT "Joystick.get_init(): return bool\ncheck if the Joystick is initialized"
#define DOC_JOYSTICKGETID "Joystick.get_id(): return int\nget the Joystick ID"
#define DOC_JOYSTICKGETNAME "Joystick.get_name(): return string\nget the Joystick system name"
#define DOC_JOYSTICKGETNUMAXES "Joystick.get_numaxes(): return int\nget the number of axes on a Joystick"
#define DOC_JOYSTICKGETAXIS "Joystick.get_axis(axis_number): return float\nget the current position of an axis"
#define DOC_JOYSTICKGETNUMBALLS "Joystick.get_numballs(): return int\nget the number of trackballs on a Joystick"
#define DOC_JOYSTICKGETBALL "Joystick.get_ball(ball_number): return x, y\nget the relative position of a trackball"
#define DOC_JOYSTICKGETNUMBUTTONS "Joystick.get_numbuttons(): return int\nget the number of buttons on a Joystick"
#define DOC_JOYSTICKGETBUTTON "Joystick.get_button(button): return bool\nget the current button state"
#define DOC_JOYSTICKGETNUMHATS "Joystick.get_numhats(): return int\nget the number of hat controls on a Joystick"
#define DOC_JOYSTICKGETHAT "Joystick.get_hat(hat_number): return x, y\nget the position of a joystick hat"
#define DOC_PYGAMEKEY "pygame module to work with the keyboard"
#define DOC_PYGAMEKEYGETFOCUSED "pygame.key.get_focused(): return bool\ntrue if the display is receiving keyboard input from the system"
#define DOC_PYGAMEKEYGETPRESSED "pygame.key.get_pressed(): return bools\nget the state of all keyboard buttons"
#define DOC_PYGAMEKEYGETMODS "pygame.key.get_mods(): return int\ndetermine which modifier keys are being held"
#define DOC_PYGAMEKEYSETMODS "pygame.key.set_mods(int): return None\ntemporarily set which modifier keys are pressed"
#define DOC_PYGAMEKEYSETREPEAT "pygame.key.set_repeat(): return None\npygame.key.set_repeat(delay, interval): return None\ncontrol how held keys are repeated"
#define DOC_PYGAMEKEYGETREPEAT "pygame.key.get_repeat(): return (delay, interval)\nsee how held keys are repeated"
#define DOC_PYGAMEKEYNAME "pygame.key.name(key): return string\nget the name of a key identifier"
#define DOC_PYGAMELOCALS "pygame constants"
#define DOC_PYGAMEMASK "pygame module for image masks."
#define DOC_PYGAMEMASKFROMSURFACE "pygame.mask.from_surface(Surface, threshold = 127) -> Mask\nReturns a Mask from the given surface."
#define DOC_PYGAMEMASKFROMTHRESHOLD "pygame.mask.from_surface(Surface, color, threshold = (0,0,0,255), othersurface = None, palette_colors = 1) -> Mask\nCreates a mask by thresholding Surfaces"
#define DOC_PYGAMEMASKMASK "pygame.Mask((width, height)): return Mask\npygame object for representing 2d bitmasks"
#define DOC_MASKGETSIZE "Mask.get_size() -> width,height\nReturns the size of the mask."
#define DOC_MASKGETAT "Mask.get_at((x,y)) -> int\nReturns nonzero if the bit at (x,y) is set."
#define DOC_MASKSETAT "Mask.set_at((x,y),value)\nSets the position in the mask given by x and y."
#define DOC_MASKOVERLAP "Mask.overlap(othermask, offset) -> x,y\nReturns the point of intersection if the masks overlap with the given offset - or None if it does not overlap."
#define DOC_MASKOVERLAPAREA "Mask.overlap_area(othermask, offset) -> numpixels\nReturns the number of overlapping 'pixels'."
#define DOC_MASKOVERLAPMASK "Mask.overlap_mask(othermask, offset) -> Mask\nReturns a mask of the overlapping pixels"
#define DOC_MASKFILL "Mask.fill()\nSets all bits to 1"
#define DOC_MASKCLEAR "Mask.clear()\nSets all bits to 0"
#define DOC_MASKINVERT "Mask.invert()\nFlips the bits in a Mask"
#define DOC_MASKSCALE "Mask.scale((x, y)) -> Mask\nResizes a mask"
#define DOC_MASKDRAW "Mask.draw(othermask, offset)\nDraws a mask onto another"
#define DOC_MASKERASE "Mask.erase(othermask, offset)\nErases a mask from another"
#define DOC_MASKCOUNT "Mask.count() -> pixels\nReturns the number of set pixels"
#define DOC_MASKCENTROID "Mask.centroid() -> (x, y)\nReturns the centroid of the pixels in a Mask"
#define DOC_MASKANGLE "Mask.angle() -> theta\nReturns the orientation of the pixels"
#define DOC_MASKOUTLINE "Mask.outline(every = 1) -> [(x,y), (x,y) ...]\nlist of points outlining an object"
#define DOC_MASKCONVOLVE "Mask.convolve(othermask, outputmask = None, offset = (0,0)) -> Mask\nReturn the convolution of self with another mask."
#define DOC_MASKCONNECTEDCOMPONENT "Mask.connected_component((x,y) = None) -> Mask\nReturns a mask of a connected region of pixels."
#define DOC_MASKCONNECTEDCOMPONENTS "Mask.connected_components(min = 0) -> [Masks]\nReturns a list of masks of connected regions of pixels."
#define DOC_MASKGETBOUNDINGRECTS "Mask.get_bounding_rects() -> Rects\nReturns a list of bounding rects of regions of set pixels."
#define DOC_PYGAMEMIDI "pygame module for interacting with midi input and output."
#define DOC_PYGAMEMIDIINPUT "Input(device_id)\nInput(device_id, buffer_size)\nInput is used to get midi input from midi devices."
#define DOC_INPUTCLOSE "Input.close(): return None\n closes a midi stream, flushing any pending buffers."
#define DOC_INPUTPOLL "Input.poll(): return Bool\nreturns true if there's data, or false if not."
#define DOC_INPUTREAD "Input.read(num_events): return midi_event_list\nreads num_events midi events from the buffer."
#define DOC_PYGAMEMIDIMIDIEXCEPTION "MidiException(errno)\nexception that pygame.midi functions and classes can raise"
#define DOC_PYGAMEMIDIOUTPUT "Output(device_id)\nOutput(device_id, latency = 0)\nOutput(device_id, buffer_size = 4096)\nOutput(device_id, latency, buffer_size)\nOutput is used to send midi to an output device"
#define DOC_OUTPUTABORT "Output.abort(): return None\n terminates outgoing messages immediately"
#define DOC_OUTPUTCLOSE "Output.close(): return None\n closes a midi stream, flushing any pending buffers."
#define DOC_OUTPUTNOTEOFF "Output.note_off(note, velocity=None, channel = 0)\nturns a midi note off. Note must be on."
#define DOC_OUTPUTNOTEON "Output.note_on(note, velocity=None, channel = 0)\nturns a midi note on. Note must be off."
#define DOC_OUTPUTSETINSTRUMENT "Output.set_instrument(instrument_id, channel = 0)\nselect an instrument, with a value between 0 and 127"
#define DOC_OUTPUTWRITE "Output.write(data)\nwrites a list of midi data to the Output"
#define DOC_OUTPUTWRITESHORT "Output.write_short(status)\nOutput.write_short(status, data1 = 0, data2 = 0)\nwrite_short(status <, data1><, data2>)"
#define DOC_OUTPUTWRITESYSEX "Output.write_sys_ex(when, msg)\nwrites a timestamped system-exclusive midi message."
#define DOC_PYGAMEMIDIGETCOUNT "pygame.midi.get_count(): return num_devices\ngets the number of devices."
#define DOC_PYGAMEMIDIGETDEFAULTINPUTID "pygame.midi.get_default_input_id(): return default_id\ngets default input device number"
#define DOC_PYGAMEMIDIGETDEFAULTOUTPUTID "pygame.midi.get_default_output_id(): return default_id\ngets default output device number"
#define DOC_PYGAMEMIDIGETDEVICEINFO "pygame.midi.get_device_info(an_id): return (interf, name, input, output, opened)\n returns information about a midi device"
#define DOC_PYGAMEMIDIINIT "pygame.midi.init(): return None\ninitialize the midi module"
#define DOC_PYGAMEMIDIMIDIS2EVENTS "pygame.midi.midis2events(midis, device_id): return [Event, ...]\nconverts midi events to pygame events"
#define DOC_PYGAMEMIDIQUIT "pygame.midi.quit(): return None\nuninitialize the midi module"
#define DOC_PYGAMEMIDITIME "pygame.midi.time(): return time\nreturns the current time in ms of the PortMidi timer"
#define DOC_PYGAMEMIXER "pygame module for loading and playing sounds"
#define DOC_PYGAMEMIXERINIT "pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096): return None\ninitialize the mixer module"
#define DOC_PYGAMEMIXERPREINIT "pygame.mixer.pre_init(frequency=22050, size=-16, channels=2, buffersize=4096): return None\npreset the mixer init arguments"
#define DOC_PYGAMEMIXERQUIT "pygame.mixer.quit(): return None\nuninitialize the mixer"
#define DOC_PYGAMEMIXERGETINIT "pygame.mixer.get_init(): return (frequency, format, channels)\ntest if the mixer is initialized"
#define DOC_PYGAMEMIXERSTOP "pygame.mixer.stop(): return None\nstop playback of all sound channels"
#define DOC_PYGAMEMIXERPAUSE "pygame.mixer.pause(): return None\ntemporarily stop playback of all sound channels"
#define DOC_PYGAMEMIXERUNPAUSE "pygame.mixer.unpause(): return None\nresume paused playback of sound channels"
#define DOC_PYGAMEMIXERFADEOUT "pygame.mixer.fadeout(time): return None\nfade out the volume on all sounds before stopping"
#define DOC_PYGAMEMIXERSETNUMCHANNELS "pygame.mixer.set_num_channels(count): return None\nset the total number of playback channels"
#define DOC_PYGAMEMIXERGETNUMCHANNELS "get the total number of playback channels"
#define DOC_PYGAMEMIXERSETRESERVED "pygame.mixer.set_reserved(count): return None\nreserve channels from being automatically used"
#define DOC_PYGAMEMIXERFINDCHANNEL "pygame.mixer.find_channel(force=False): return Channel\nfind an unused channel"
#define DOC_PYGAMEMIXERGETBUSY "pygame.mixer.get_busy(): return bool\ntest if any sound is being mixed"
#define DOC_PYGAMEMIXERSOUND "pygame.mixer.Sound(filename): return Sound\npygame.mixer.Sound(buffer): return Sound\npygame.mixer.Sound(object): return Sound\nCreate a new Sound object from a file"
#define DOC_SOUNDPLAY "Sound.play(loops=0, maxtime=0, fade_ms=0): return Channel\nbegin sound playback"
#define DOC_SOUNDSTOP "Sound.stop(): return None\nstop sound playback"
#define DOC_SOUNDFADEOUT "Sound.fadeout(time): return None\nstop sound playback after fading out"
#define DOC_SOUNDSETVOLUME "Sound.set_volume(value): return None\nset the playback volume for this Sound"
#define DOC_SOUNDGETVOLUME "Sound.get_volume(): return value\nget the playback volume"
#define DOC_SOUNDGETNUMCHANNELS "Sound.get_num_channels(): return count\ncount how many times this Sound is playing"
#define DOC_SOUNDGETLENGTH "Sound.get_length(): return seconds\nget the length of the Sound"
#define DOC_SOUNDGETBUFFER "Sound.get_buffer(): return BufferProxy\nacquires a buffer object for the sameples of the Sound."
#define DOC_PYGAMEMIXERCHANNEL "pygame.mixer.Channel(id): return Channel\nCreate a Channel object for controlling playback"
#define DOC_CHANNELPLAY "Channel.play(Sound, loops=0, maxtime=0, fade_ms=0): return None\nplay a Sound on a specific Channel"
#define DOC_CHANNELSTOP "Channel.stop(): return None\nstop playback on a Channel"
#define DOC_CHANNELPAUSE "Channel.pause(): return None\ntemporarily stop playback of a channel"
#define DOC_CHANNELUNPAUSE "Channel.unpause(): return None\nresume pause playback of a channel"
#define DOC_CHANNELFADEOUT "Channel.fadeout(time): return None\nstop playback after fading channel out"
#define DOC_CHANNELSETVOLUME "Channel.set_volume(value): return None\nChannel.set_volume(left, right): return None\nset the volume of a playing channel"
#define DOC_CHANNELGETVOLUME "Channel.get_volume(): return value\nget the volume of the playing channel"
#define DOC_CHANNELGETBUSY "Channel.get_busy(): return bool\ncheck if the channel is active"
#define DOC_CHANNELGETSOUND "Channel.get_sound(): return Sound\nget the currently playing Sound"
#define DOC_CHANNELQUEUE "Channel.queue(Sound): return None\nqueue a Sound object to follow the current"
#define DOC_CHANNELGETQUEUE "Channel.get_queue(): return Sound\nreturn any Sound that is queued"
#define DOC_CHANNELSETENDEVENT "Channel.set_endevent(): return None\nChannel.set_endevent(type): return None\nhave the channel send an event when playback stops"
#define DOC_CHANNELGETENDEVENT "Channel.get_endevent(): return type\nget the event a channel sends when playback stops"
#define DOC_PYGAMEMOUSE "pygame module to work with the mouse"
#define DOC_PYGAMEMOUSEGETPRESSED "pygame.moouse.get_pressed(): return (button1, button2, button3)\nget the state of the mouse buttons"
#define DOC_PYGAMEMOUSEGETPOS "pygame.mouse.get_pos(): return (x, y)\nget the mouse cursor position"
#define DOC_PYGAMEMOUSEGETREL "pygame.mouse.get_rel(): return (x, y)\nget the amount of mouse movement"
#define DOC_PYGAMEMOUSESETPOS "pygame.mouse.set_pos([x, y]): return None\nset the mouse cursor position"
#define DOC_PYGAMEMOUSESETVISIBLE "pygame.mouse.set_visible(bool): return bool\nhide or show the mouse cursor"
#define DOC_PYGAMEMOUSEGETFOCUSED "pygame.mouse.get_focused(): return bool\ncheck if the display is receiving mouse input"
#define DOC_PYGAMEMOUSESETCURSOR "pygame.mouse.set_cursor(size, hotspot, xormasks, andmasks): return None\nset the image for the system mouse cursor"
#define DOC_PYGAMEMOUSEGETCURSOR "pygame.mouse.get_cursor(): return (size, hotspot, xormasks, andmasks)\nget the image for the system mouse cursor"
#define DOC_PYGAMEMOVIE "pygame module for playback of mpeg video"
#define DOC_PYGAMEMOVIEMOVIE "pygame.movie.Movie(filename): return Movie\npygame.movie.Movie(object): return Movie\nload an mpeg movie file"
#define DOC_MOVIEPLAY "Movie.play(loops=0): return None\nstart playback of a movie"
#define DOC_MOVIESTOP "Movie.stop(): return None\nstop movie playback"
#define DOC_MOVIEPAUSE "Movie.pause(): return None\ntemporarily stop and resume playback"
#define DOC_MOVIESKIP "Movie.skip(seconds): return None\nadvance the movie playback position"
#define DOC_MOVIEREWIND "Movie.rewind(): return None\nrestart the movie playback"
#define DOC_MOVIERENDERFRAME "Movie.render_frame(frame_number): return frame_number\nset the current video frame"
#define DOC_MOVIEGETFRAME "Movie.get_frame(): return frame_number\nget the current video frame"
#define DOC_MOVIEGETTIME "Movie.get_time(): return seconds\nget the current vide playback time"
#define DOC_MOVIEGETBUSY "Movie.get_busy(): return bool\ncheck if the movie is currently playing"
#define DOC_MOVIEGETLENGTH "Movie.get_length(): return seconds\nthe total length of the movie in seconds"
#define DOC_MOVIEGETSIZE "Movie.get_size(): return (width, height)\nget the resolution of the video"
#define DOC_MOVIEHASVIDEO "Movie.get_video(): return bool\ncheck if the movie file contains video"
#define DOC_MOVIEHASAUDIO "Movie.get_audio(): return bool\ncheck if the movie file contains audio"
#define DOC_MOVIESETVOLUME "Movie.set_volume(value): return None\nset the audio playback volume"
#define DOC_MOVIESETDISPLAY "Movie.set_display(Surface, rect=None): return None\nset the video target Surface"
#define DOC_PYGAMEMIXERMUSIC "pygame module for controlling streamed audio"
#define DOC_PYGAMEMIXERMUSICLOAD "pygame.mixer.music.load(filename): return None\npygame.mixer.music.load(object): return None\nLoad a music file for playback"
#define DOC_PYGAMEMIXERMUSICPLAY "pygame.mixer.music.play(loops=0, start=0.0): return None\nStart the playback of the music stream"
#define DOC_PYGAMEMIXERMUSICREWIND "pygame.mixer.music.rewind(): return None\nrestart music"
#define DOC_PYGAMEMIXERMUSICSTOP "pygame.mixer.music.stop(): return None\nstop the music playback"
#define DOC_PYGAMEMIXERMUSICPAUSE "pygame.mixer.music.pause(): return None\ntemporarily stop music playback"
#define DOC_PYGAMEMIXERMUSICUNPAUSE "pygame.mixer.music.unpause(): return None\nresume paused music"
#define DOC_PYGAMEMIXERMUSICFADEOUT "pygame.mixer.music.fadeout(time): return None\nstop music playback after fading out"
#define DOC_PYGAMEMIXERMUSICSETVOLUME "pygame.mixer.music.set_volume(value): return None\nset the music volume"
#define DOC_PYGAMEMIXERMUSICGETVOLUME "pygame.mixer.music.get_volume(): return value\nget the music volume"
#define DOC_PYGAMEMIXERMUSICGETBUSY "pygame.mixer.music.get_busy(): return bool\ncheck if the music stream is playing"
#define DOC_PYGAMEMIXERMUSICGETPOS "pygame.mixer.music.get_pos(): return time\nget the music play time"
#define DOC_PYGAMEMIXERMUSICQUEUE "pygame.mixer.music.queue(filename): return None\nqueue a music file to follow the current"
#define DOC_PYGAMEMIXERMUSICSETENDEVENT "pygame.mixer.music.set_endevent(): return None\npygame.mixer.music.set_endevent(type): return None\nhave the music send an event when playback stops"
#define DOC_PYGAMEMIXERMUSICGETENDEVENT "pygame.mixer.music.get_endevent(): return type\nget the event a channel sends when playback stops"
#define DOC_PYGAMEOVERLAY "pygame.Overlay(format, (width, height)): return Overlay\npygame object for video overlay graphics"
#define DOC_OVERLAYDISPLAY "Overlay.display((y, u, v)): return None\nOverlay.display(): return None\nset the overlay pixel data"
#define DOC_OVERLAYSETLOCATION "Overlay.set_location(rect): return None\ncontrol where the overlay is displayed"
#define DOC_OVERLAYGETHARDWARE "Overlay.get_hardware(rect): return int\ntest if the Overlay is hardware accelerated"
#define DOC_PYGAMEPIXELARRAY "pygame.PixelArray(Surface): return PixelArray\npygame object for direct pixel access of surfaces"
#define DOC_PIXELARRAYSURFACE "PixelArray.surface: Return Surface\nGets the Surface the PixelArray uses."
#define DOC_PIXELARRAYMAKESURFACE "PixelArray.make_surface (): Return Surface\nCreates a new Surface from the current PixelArray."
#define DOC_PIXELARRAYREPLACE "PixelArray.replace (color, repcolor, distance=0, weights=(0.299, 0.587, 0.114)): Return None\nReplaces the passed color in the PixelArray with another one."
#define DOC_PIXELARRAYEXTRACT "PixelArray.extract (color, distance=0, weights=(0.299, 0.587, 0.114)): Return PixelArray\nExtracts the passed color from the PixelArray."
#define DOC_PIXELARRAYCOMPARE "PixelArray.compare (array, distance=0, weights=(0.299, 0.587, 0.114)): Return PixelArray\nCompares the PixelArray with another one."
#define DOC_PYGAMERECT "pygame.Rect(left, top, width, height): return Rect\npygame.Rect((left, top), (width, height)): return Rect\npygame.Rect(object): return Rect\npygame object for storing rectangular coordinates"
#define DOC_RECTCOPY "Rect.copy(): return Rect\ncopy the rectangle"
#define DOC_RECTMOVE "Rect.move(x, y): return Rect\nmoves the rectangle"
#define DOC_RECTMOVEIP "Rect.move_ip(x, y): return None\nmoves the rectangle, in place"
#define DOC_RECTINFLATE "Rect.inflate(x, y): return Rect\ngrow or shrink the rectangle size"
#define DOC_RECTINFLATEIP "Rect.inflate_ip(x, y): return None\ngrow or shrink the rectangle size, in place"
#define DOC_RECTCLAMP "Rect.clamp(Rect): return Rect\nmoves the rectangle inside another"
#define DOC_RECTCLAMPIP "Rect.clamp_ip(Rect): return None\nmoves the rectangle inside another, in place"
#define DOC_RECTCLIP "Rect.clip(Rect): return Rect\ncrops a rectangle inside another"
#define DOC_RECTUNION "Rect.union(Rect): return Rect\njoins two rectangles into one"
#define DOC_RECTUNIONIP "Rect.union_ip(Rect): return None\njoins two rectangles into one, in place"
#define DOC_RECTUNIONALL "Rect.unionall(Rect_sequence): return Rect\nthe union of many rectangles"
#define DOC_RECTUNIONALLIP "Rect.unionall_ip(Rect_sequence): return None\nthe union of many rectangles, in place"
#define DOC_RECTFIT "Rect.fit(Rect): return Rect\nresize and move a rectangle with aspect ratio"
#define DOC_RECTNORMALIZE "Rect.normalize(): return None\ncorrect negative sizes"
#define DOC_RECTCONTAINS "Rect.contains(Rect): return bool\ntest if one rectangle is inside another"
#define DOC_RECTCOLLIDEPOINT "Rect.collidepoint(x, y): return bool\nRect.collidepoint((x,y)): return bool\ntest if a point is inside a rectangle"
#define DOC_RECTCOLLIDERECT "Rect.colliderect(Rect): return bool\ntest if two rectangles overlap"
#define DOC_RECTCOLLIDELIST "Rect.collidelist(list): return index\ntest if one rectangle in a list intersects"
#define DOC_RECTCOLLIDELISTALL "Rect.collidelistall(list): return indices\ntest if all rectangles in a list intersect"
#define DOC_RECTCOLLIDEDICT "Rect.collidedict(dict): return (key, value)\ntest if one rectangle in a dictionary intersects"
#define DOC_RECTCOLLIDEDICTALL "Rect.collidedictall(dict): return [(key, value), ...]\ntest if all rectangles in a dictionary intersect"
#define DOC_PYGAMESCRAP "pygame module for clipboard support."
#define DOC_PYGAMESCRAPINIT "scrap.init () -> None\nInitializes the scrap module."
#define DOC_PYGAMESCRAPGET "scrap.get (type) -> string\nGets the data for the specified type from the clipboard."
#define DOC_PYGAMESCRAPGETTYPES "scrap.get_types () -> list\nGets a list of the available clipboard types."
#define DOC_PYGAMESCRAPPUT "scrap.put(type, data) -> None\nPlaces data into the clipboard."
#define DOC_PYGAMESCRAPCONTAINS "scrap.contains (type) -> bool\nChecks, whether a certain type is available in the clipboard."
#define DOC_PYGAMESCRAPLOST "scrap.lost() -> bool\nChecks whether the clipboard is currently owned by the application."
#define DOC_PYGAMESCRAPSETMODE "scrap.set_mode(mode) -> None\nSets the clipboard access mode."
#define DOC_PYGAMESNDARRAY "pygame module for accessing sound sample data"
#define DOC_PYGAMESNDARRAYARRAY "pygame.sndarray.array(Sound): return array\ncopy Sound samples into an array"
#define DOC_PYGAMESNDARRAYSAMPLES "pygame.sndarray.samples(Sound): return array\nreference Sound samples into an array"
#define DOC_PYGAMESNDARRAYMAKESOUND "pygame.sndarray.make_sound(array): return Sound\nconvert an array into a Sound object"
#define DOC_PYGAMESNDARRAYUSEARRAYTYPE "pygame.sndarray.use_arraytype (arraytype): return None\nSets the array system to be used for sound arrays"
#define DOC_PYGAMESNDARRAYGETARRAYTYPE "pygame.sndarray.get_arraytype (): return str\nGets the currently active array type."
#define DOC_PYGAMESNDARRAYGETARRAYTYPES "pygame.sndarray.get_arraytypes (): return tuple\nGets the array system types currently supported."
#define DOC_PYGAMESPRITE "pygame module with basic game object classes"
#define DOC_PYGAMESPRITESPRITE "pygame.sprite.Sprite(*groups): return Sprite\nsimple base class for visible game objects"
#define DOC_SPRITEUPDATE "Sprite.update(*args):\nmethod to control sprite behavior"
#define DOC_SPRITEADD "Sprite.add(*groups): return None\nadd the sprite to groups"
#define DOC_SPRITEREMOVE "Sprite.remove(*groups): return None\nremove the sprite from groups"
#define DOC_SPRITEKILL "Sprite.kill(): return None\nremove the Sprite from all Groups"
#define DOC_SPRITEALIVE "Sprite.alive(): return bool\ndoes the sprite belong to any groups"
#define DOC_SPRITEGROUPS "Sprite.groups(): return group_list\nlist of Groups that contain this Sprite"
#define DOC_PYGAMESPRITEDIRTYSPRITE "pygame.sprite.DirtySprite(*groups): return DirtySprite\na more featureful subclass of Sprite with more attributes"
#define DOC_ ""
#define DOC_PYGAMESPRITEGROUP "pygame.sprite.Group(*sprites): return Group\ncontainer class for many Sprites"
#define DOC_GROUPSPRITES "Group.sprites(): return sprite_list\nlist of the Sprites this Group contains"
#define DOC_GROUPCOPY "Group.copy(): return Group\nduplicate the Group"
#define DOC_GROUPADD "Group.add(*sprites): return None\nadd Sprites to this Group"
#define DOC_GROUPREMOVE "Group.remove(*sprites): return None\nremove Sprites from the Group"
#define DOC_GROUPHAS "Group.has(*sprites): return None\ntest if a Group contains Sprites"
#define DOC_GROUPUPDATE "Group.update(*args): return None\ncall the update method on contained Sprites"
#define DOC_GROUPDRAW "Group.draw(Surface): return None\nblit the Sprite images"
#define DOC_GROUPCLEAR "Group.clear(Surface_dest, background): return None\ndraw a background over the Sprites"
#define DOC_GROUPEMPTY "Group.empty(): return None\nremove all Sprites"
#define DOC_PYGAMESPRITERENDERUPDATES "pygame.sprite.RenderUpdates(*sprites): return RenderUpdates\nGroup class that tracks dirty updates"
#define DOC_RENDERUPDATESDRAW "RenderUpdates.draw(surface): return Rect_list\nblit the Sprite images and track changed areas"
#define DOC_PYGAMESPRITEORDEREDUPDATES "pygame.sprite.OrderedUpdates(*spites): return OrderedUpdates\nRenderUpdates class that draws Sprites in order of addition"
#define DOC_PYGAMESPRITELAYEREDUPDATES "pygame.sprite.LayeredUpdates(*spites, **kwargs): return LayeredUpdates\nLayeredUpdates Group handles layers, that draws like OrderedUpdates."
#define DOC_LAYEREDUPDATESADD "LayeredUpdates.add(*sprites, **kwargs): return None\nadd a sprite or sequence of sprites to a group"
#define DOC_LAYEREDUPDATESSPRITES "LayeredUpdates.sprites(): return sprites\nreturns a ordered list of sprites (first back, last top)."
#define DOC_LAYEREDUPDATESDRAW "LayeredUpdates.draw(surface): return Rect_list\ndraw all sprites in the right order onto the passed surface."
#define DOC_LAYEREDUPDATESGETSPRITESAT "LayeredUpdates.get_sprites_at(pos): return colliding_sprites\nreturns a list with all sprites at that position."
#define DOC_LAYEREDUPDATESGETSPRITE "LayeredUpdates.get_sprite(idx): return sprite\nreturns the sprite at the index idx from the groups sprites"
#define DOC_LAYEREDUPDATESREMOVESPRITESOFLAYER "LayeredUpdates.remove_sprites_of_layer(layer_nr): return sprites\nremoves all sprites from a layer and returns them as a list."
#define DOC_LAYEREDUPDATESLAYERS "LayeredUpdates.layers(): return layers\nreturns a list of layers defined (unique), sorted from botton up."
#define DOC_LAYEREDUPDATESCHANGELAYER "LayeredUpdates.change_layer(sprite, new_layer): return None\nchanges the layer of the sprite"
#define DOC_LAYEREDUPDATESGETLAYEROFSPRITE "LayeredUpdates.get_layer_of_sprite(sprite): return layer\nreturns the layer that sprite is currently in."
#define DOC_LAYEREDUPDATESGETTOPLAYER "LayeredUpdates.get_top_layer(): return layer\nreturns the top layer"
#define DOC_LAYEREDUPDATESGETBOTTOMLAYER "LayeredUpdates.get_bottom_layer(): return layer\nreturns the bottom layer"
#define DOC_LAYEREDUPDATESMOVETOFRONT "LayeredUpdates.move_to_front(sprite): return None\nbrings the sprite to front layer"
#define DOC_LAYEREDUPDATESMOVETOBACK "LayeredUpdates.move_to_back(sprite): return None\nmoves the sprite to the bottom layer"
#define DOC_LAYEREDUPDATESGETTOPSPRITE "LayeredUpdates.get_top_sprite(): return Sprite\nreturns the topmost sprite"
#define DOC_LAYEREDUPDATESGETSPRITESFROMLAYER "LayeredUpdates.get_sprites_from_layer(layer): return sprites\nreturns all sprites from a layer, ordered by how they where added"
#define DOC_LAYEREDUPDATESSWITCHLAYER "LayeredUpdates.switch_layer(layer1_nr, layer2_nr): return None\nswitches the sprites from layer1 to layer2"
#define DOC_PYGAMESPRITELAYEREDDIRTY "pygame.sprite.LayeredDirty(*spites, **kwargs): return LayeredDirty\nLayeredDirty Group is for DirtySprites. Subclasses LayeredUpdates."
#define DOC_LAYEREDDIRTYDRAW "LayeredDirty.draw(surface, bgd=None): return Rect_list\ndraw all sprites in the right order onto the passed surface."
#define DOC_LAYEREDDIRTYCLEAR "LayeredDirty.clear(surface, bgd): return None\nused to set background"
#define DOC_LAYEREDDIRTYREPAINTRECT "LayeredDirty.repaint_rect(screen_rect): return None\nrepaints the given area"
#define DOC_LAYEREDDIRTYSETCLIP "LayeredDirty.set_clip(screen_rect=None): return None\nclip the area where to draw. Just pass None (default) to reset the clip"
#define DOC_LAYEREDDIRTYGETCLIP "LayeredDirty.get_clip(): return Rect\nclip the area where to draw. Just pass None (default) to reset the clip"
#define DOC_LAYEREDDIRTYCHANGELAYER "change_layer(sprite, new_layer): return None\nchanges the layer of the sprite"
#define DOC_LAYEREDDIRTYSETTIMINGTRESHOLD "set_timing_treshold(time_ms): return None\nsets the treshold in milliseconds"
#define DOC_PYGAMESPRITEGROUPSINGLE "pygame.sprite.GroupSingle(sprite=None): return GroupSingle\nGroup container that holds a single Sprite"
#define DOC_PYGAMESPRITESPRITECOLLIDE "pygame.sprite.spritecollide(sprite, group, dokill, collided = None): return Sprite_list\nfind Sprites in a Group that intersect another Sprite"
#define DOC_PYGAMESPRITECOLLIDERECT "pygame.sprite.collide_rect(left, right): return bool\ncollision detection between two sprites, using rects."
#define DOC_PYGAMESPRITECOLLIDERECTRATIO "pygame.sprite.collide_rect_ratio(ratio): return collided_callable\ncollision detection between two sprites, using rects scaled to a ratio."
#define DOC_PYGAMESPRITECOLLIDECIRCLE "pygame.sprite.collide_circle(left, right): return bool\ncollision detection between two sprites, using circles."
#define DOC_PYGAMESPRITECOLLIDECIRCLERATIO "pygame.sprite.collide_circle_ratio(ratio): return collided_callable\ncollision detection between two sprites, using circles scaled to a ratio."
#define DOC_PYGAMESPRITECOLLIDEMASK "pygame.sprite.collide_mask(SpriteLeft, SpriteRight): return bool\ncollision detection between two sprites, using masks."
#define DOC_PYGAMESPRITEGROUPCOLLIDE "pygame.sprite.groupcollide(group1, group2, dokill1, dokill2): return Sprite_dict\nfind all Sprites that collide between two Groups"
#define DOC_PYGAMESPRITESPRITECOLLIDEANY "pygame.sprite.spritecollideany(sprite, group): return bool\nsimple test if a Sprite intersects anything in a Group"
#define DOC_ ""
#define DOC_PYGAMESURFACE "pygame.Surface((width, height), flags=0, depth=0, masks=None): return Surface\npygame.Surface((width, height), flags=0, Surface): return Surface\npygame object for representing images"
#define DOC_SURFACEBLIT "Surface.blit(source, dest, area=None, special_flags = 0): return Rect\ndraw one image onto another"
#define DOC_SURFACECONVERT "Surface.convert(Surface): return Surface\nSurface.convert(depth, flags=0): return Surface\nSurface.convert(masks, flags=0): return Surface\nSurface.convert(): return Surface\nchange the pixel format of an image"
#define DOC_SURFACECONVERTALPHA "Surface.convert_alpha(Surface): return Surface\nSurface.convert_alpha(): return Surface\nchange the pixel format of an image including per pixel alphas"
#define DOC_SURFACECOPY "Surface.copy(): return Surface\ncreate a new copy of a Surface"
#define DOC_SURFACEFILL "Surface.fill(color, rect=None, special_flags=0): return Rect\nfill Surface with a solid color"
#define DOC_SURFACESCROLL "Surface.scroll(dx=0, dy=0): return None\nShift the surface image in place"
#define DOC_SURFACESETCOLORKEY "Surface.set_colorkey(Color, flags=0): return None\nSurface.set_colorkey(None): return None\nSet the transparent colorkey"
#define DOC_SURFACEGETCOLORKEY "Surface.get_colorkey(): return RGB or None\nGet the current transparent colorkey"
#define DOC_SURFACESETALPHA "Surface.set_alpha(value, flags=0): return None\nSurface.set_alpha(None): return None\nset the alpha value for the full Surface image"
#define DOC_SURFACEGETALPHA "Surface.get_alpha(): return int_value or None\nget the current Surface transparency value"
#define DOC_SURFACELOCK "Surface.lock(): return None\nlock the Surface memory for pixel access"
#define DOC_SURFACEUNLOCK "Surface.unlock(): return None\nunlock the Surface memory from pixel access"
#define DOC_SURFACEMUSTLOCK "Surface.mustlock(): return bool\ntest if the Surface requires locking"
#define DOC_SURFACEGETLOCKED "Surface.get_locked(): return bool\ntest if the Surface is current locked"
#define DOC_SURFACEGETLOCKS "Surface.get_locks(): return tuple\nGets the locks for the Surface"
#define DOC_SURFACEGETAT "Surface.get_at((x, y)): return Color\nget the color value at a single pixel"
#define DOC_SURFACESETAT "Surface.set_at((x, y), Color): return None\nset the color value for a single pixel"
#define DOC_SURFACEGETPALETTE "Surface.get_palette(): return [RGB, RGB, RGB, ...]\nget the color index palette for an 8bit Surface"
#define DOC_SURFACEGETPALETTEAT "Surface.get_palette_at(index): return RGB\nget the color for a single entry in a palette"
#define DOC_SURFACESETPALETTE "Surface.set_palette([RGB, RGB, RGB, ...]): return None\nset the color palette for an 8bit Surface"
#define DOC_SURFACESETPALETTEAT "Surface.set_at(index, RGB): return None\nset the color for a single index in an 8bit Surface palette"
#define DOC_SURFACEMAPRGB "Surface.map_rgb(Color): return mapped_int\nconvert a color into a mapped color value"
#define DOC_SURFACEUNMAPRGB "Surface.map_rgb(mapped_int): return Color\nconvert a mapped integer color value into a Color"
#define DOC_SURFACESETCLIP "Surface.set_clip(rect): return None\nSurface.set_clip(None): return None\nset the current clipping area of the Surface"
#define DOC_SURFACEGETCLIP "Surface.get_clip(): return Rect\nget the current clipping area of the Surface"
#define DOC_SURFACESUBSURFACE "Surface.subsurface(Rect): return Surface\ncreate a new surface that references its parent"
#define DOC_SURFACEGETPARENT "Surface.get_parent(): return Surface\nfind the parent of a subsurface"
#define DOC_SURFACEGETABSPARENT "Surface.get_abs_parent(): return Surface\nfind the top level parent of a subsurface"
#define DOC_SURFACEGETOFFSET "Surface.get_offset(): return (x, y)\nfind the position of a child subsurface inside a parent"
#define DOC_SURFACEGETABSOFFSET "Surface.get_abs_offset(): return (x, y)\nfind the absolute position of a child subsurface inside its top level parent"
#define DOC_SURFACEGETSIZE "Surface.get_size(): return (width, height)\nget the dimensions of the Surface"
#define DOC_SURFACEGETWIDTH "Surface.get_width(): return width\nget the width of the Surface"
#define DOC_SURFACEGETHEIGHT "Surface.get_height(): return height\nget the height of the Surface"
#define DOC_SURFACEGETRECT "Surface.get_rect(**kwargs): return Rect\nget the rectangular area of the Surface"
#define DOC_SURFACEGETBITSIZE "Surface.get_bitsize(): return int\nget the bit depth of the Surface pixel format"
#define DOC_SURFACEGETBYTESIZE "Surface.get_bytesize(): return int\nget the bytes used per Surface pixel"
#define DOC_SURFACEGETFLAGS "Surface.get_flags(): return int\nget the additional flags used for the Surface"
#define DOC_SURFACEGETPITCH "Surface.get_pitch(): return int\nget the number of bytes used per Surface row"
#define DOC_SURFACEGETMASKS "Surface.get_masks(): return (R, G, B, A)\nthe bitmasks needed to convert between a color and a mapped integer"
#define DOC_SURFACESETMASKS "Surface.set_masks((r,g,b,a)): return None\nset the bitmasks needed to convert between a color and a mapped integer"
#define DOC_SURFACEGETSHIFTS "Surface.get_shifts(): return (R, G, B, A)\nthe bit shifts needed to convert between a color and a mapped integer"
#define DOC_SURFACESETSHIFTS "Surface.get_shifts((r,g,b,a)): return None\nsets the bit shifts needed to convert between a color and a mapped integer"
#define DOC_SURFACEGETLOSSES "Surface.get_losses(): return (R, G, B, A)\nthe significant bits used to convert between a color and a mapped integer"
#define DOC_SURFACEGETBOUNDINGRECT "Surface.get_bounding_rect(min_alpha = 1): return Rect\nfind the smallest rect containing data"
#define DOC_SURFACEGETBUFFER "Surface.get_buffer(): return BufferProxy\nacquires a buffer object for the pixels of the Surface."
#define DOC_PYGAMESURFARRAY "pygame module for accessing surface pixel data using array interfaces"
#define DOC_PYGAMESURFARRAYARRAY2D "pygame.surfarray.array2d(Surface): return array\nCopy pixels into a 2d array"
#define DOC_PYGAMESURFARRAYPIXELS2D "pygame.surfarray.pixels2d(Surface): return array\nReference pixels into a 2d array"
#define DOC_PYGAMESURFARRAYARRAY3D "pygame.surfarray.array3d(Surface): return array\nCopy pixels into a 3d array"
#define DOC_PYGAMESURFARRAYPIXELS3D "pygame.surfarray.pixels3d(Surface): return array\nReference pixels into a 3d array"
#define DOC_PYGAMESURFARRAYARRAYALPHA "pygame.surfarray.array_alpha(Surface): return array\nCopy pixel alphas into a 2d array"
#define DOC_PYGAMESURFARRAYPIXELSALPHA "pygame.surfarray.pixels_alpha(Surface): return array\nReference pixel alphas into a 2d array"
#define DOC_PYGAMESURFARRAYARRAYCOLORKEY "pygame.surfarray.array_colorkey(Surface): return array\nCopy the colorkey values into a 2d array"
#define DOC_PYGAMESURFARRAYMAKESURFACE "pygame.surfarray.make_surface(array): return Surface\nCopy an array to a new surface"
#define DOC_PYGAMESURFARRAYBLITARRAY "pygame.surfarray.blit_array(Surface, array): return None\nBlit directly from a array values"
#define DOC_PYGAMESURFARRAYMAPARRAY "pygame.surfarray.map_array(Surface, array3d): return array2d\nMap a 3d array into a 2d array"
#define DOC_PYGAMESURFARRAYUSEARRAYTYPE "pygame.surfarray.use_arraytype (arraytype): return None\nSets the array system to be used for surface arrays"
#define DOC_PYGAMESURFARRAYGETARRAYTYPE "pygame.surfarray.get_arraytype (): return str\nGets the currently active array type."
#define DOC_PYGAMESURFARRAYGETARRAYTYPES "pygame.surfarray.get_arraytypes (): return tuple\nGets the array system types currently supported."
#define DOC_PYGAMETESTS "Pygame unit test suite package"
#define DOC_PYGAMETESTSRUN "pygame.tests.run(*args, **kwds): return tuple\nRun the Pygame unit test suite"
#define DOC_PYGAMETIME "pygame module for monitoring time"
#define DOC_PYGAMETIMEGETTICKS "pygame.time.get_ticks(): return milliseconds\nget the time in milliseconds"
#define DOC_PYGAMETIMEWAIT "pygame.time.wait(milliseconds): return time\npause the program for an amount of time"
#define DOC_PYGAMETIMEDELAY "pygame.time.delay(milliseconds): return time\npause the program for an amount of time"
#define DOC_PYGAMETIMESETTIMER "pygame.time.set_timer(eventid, milliseconds): return None\nrepeatedly create an event on the event queue"
#define DOC_PYGAMETIMECLOCK "pygame.time.Clock(): return Clock\ncreate an object to help track time"
#define DOC_CLOCKTICK "Clock.tick(framerate=0): return milliseconds\ncontrol timer events\nupdate the clock"
#define DOC_CLOCKTICKBUSYLOOP "Clock.tick_busy_loop(framerate=0): return milliseconds\ncontrol timer events\nupdate the clock"
#define DOC_CLOCKGETTIME "Clock.get_time(): return milliseconds\ntime used in the previous tick"
#define DOC_CLOCKGETRAWTIME "Clock.get_rawtime(): return milliseconds\nactual time used in the previous tick"
#define DOC_CLOCKGETFPS "Clock.get_fps(): return float\ncompute the clock framerate"
#define DOC_PYGAMETRANSFORM "pygame module to transform surfaces"
#define DOC_PYGAMETRANSFORMFLIP "pygame.transform.flip(Surface, xbool, ybool): return Surface\nflip vertically and horizontally"
#define DOC_PYGAMETRANSFORMSCALE "pygame.transform.scale(Surface, (width, height), DestSurface = None): return Surface\nresize to new resolution"
#define DOC_PYGAMETRANSFORMROTATE "pygame.transform.rotate(Surface, angle): return Surface\nrotate an image"
#define DOC_PYGAMETRANSFORMROTOZOOM "pygame.transform.rotozoom(Surface, angle, scale): return Surface\nfiltered scale and rotation"
#define DOC_PYGAMETRANSFORMSCALE2X "pygame.transform.scale2x(Surface, DestSurface = None): Surface\nspecialized image doubler"
#define DOC_PYGAMETRANSFORMSMOOTHSCALE "pygame.transform.smoothscale(Surface, (width, height), DestSurface = None): return Surface\nscale a surface to an arbitrary size smoothly"
#define DOC_PYGAMETRANSFORMGETSMOOTHSCALEBACKEND "pygame.transform.get_smoothscale_backend(): return String\nreturn smoothscale filter version in use: 'GENERIC', 'MMX', or 'SSE'"
#define DOC_PYGAMETRANSFORMSETSMOOTHSCALEBACKEND "pygame.transform.get_smoothscale_backend(type): return None\nset smoothscale filter version to one of: 'GENERIC', 'MMX', or 'SSE'"
#define DOC_PYGAMETRANSFORMCHOP "pygame.transform.chop(Surface, rect): return Surface\ngets a copy of an image with an interior area removed"
#define DOC_PYGAMETRANSFORMLAPLACIAN "pygame.transform.laplacian(Surface, DestSurface = None): return Surface\nfind edges in a surface"
#define DOC_PYGAMETRANSFORMAVERAGESURFACES "pygame.transform.average_surfaces(Surfaces, DestSurface = None, palette_colors = 1): return Surface\nfind the average surface from many surfaces."
#define DOC_PYGAMETRANSFORMAVERAGECOLOR "pygame.transform.average_color(Surface, Rect = None): return Color\nfinds the average color of a surface"
#define DOC_PYGAMETRANSFORMTHRESHOLD "pygame.transform.threshold(DestSurface, Surface, color, threshold = (0,0,0,0), diff_color = (0,0,0,0), change_return = 1, Surface = None, inverse = False): return num_threshold_pixels\nfinds which, and how many pixels in a surface are within a threshold of a color."
/* Docs in a comments... slightly easier to read. */
/*
pygame
the top level pygame package
pygame.init
pygame.init(): return (numpass, numfail)
initialize all imported pygame modules
pygame.quit
pygame.quit(): return None
uninitialize all pygame modules
pygame.error
raise pygame.error, message
standard pygame exception
pygame.get_error
pygame.get_error(): return errorstr
get the current error message
pygame.set_error
pygame.set_error(error_msg): return None
set the current error message
pygame.get_sdl_version
pygame.get_sdl_version(): return major, minor, patch
get the version number of SDL
pygame.get_sdl_byteorder
pygame.get_sdl_byteorder(): return int
get the byte order of SDL
pygame.register_quit
register_quit(callable): return None
register a function to be called when pygame quits
pygame.version
module pygame.version
small module containing version information
pygame.version.ver
pygame.version.ver = '1.2'
version number as a string
pygame.version.vernum
pygame.version.vernum = (1, 5, 3)
tupled integers of the version
pygame.camera
pygame module for camera use
pygame.camera.colorspace
pygame.camera.colorspace(Surface, format, DestSurface = None): return Surface
Surface colorspace conversion
pygame.camera.list_cameras
pygame.camera.list_cameras(): return [cameras]
returns a list of available cameras
pygame.camera.Camera
pygame.camera.Camera(device, (width, height), format): return Camera
load a camera
Camera.start
Camera.start(): return None
opens, initializes, and starts capturing
Camera.stop
Camera.stop(): return None
stops, uninitializes, and closes the camera
Camera.get_controls
Camera.get_controls(): return (hflip = bool, vflip = bool, brightness)
gets current values of user controls
Camera.set_controls
Camera.set_controls(hflip = bool, vflip = bool, brightness): return (hflip = bool, vflip = bool, brightness)
changes camera settings if supported by the camera
Camera.get_size
Camera.get_size(): return (width, height)
returns the dimensions of the images being recorded
Camera.query_image
Camera.query_image(): return bool
checks if a frame is ready
Camera.get_image
Camera.get_image(Surface = None): return Surface
captures an image as a Surface
Camera.get_raw
Camera.get_raw(): return string
returns an unmodified image as a string
pygame.cdrom
pygame module for audio cdrom control
pygame.cdrom.init
pygame.cdrom.init(): return None
initialize the cdrom module
pygame.cdrom.quit
pygame.cdrom.quit(): return None
uninitialize the cdrom module
pygame.cdrom.get_init
pygame.cdrom.get_init(): return bool
true if the cdrom module is initialized
pygame.cdrom.get_count
pygame.cdrom.get_count(): return count
number of cd drives on the system
pygame.cdrom.CD
pygame.cdrom.CD(id): return CD
class to manage a cdrom drive
CD.init
CD.init(): return None
initialize a cdrom drive for use
CD.quit
CD.quit(): return None
uninitialize a cdrom drive for use
CD.get_init
CD.get_init(): return bool
true if this cd device initialized
CD.play
CD.play(track, start=None, end=None): return None
start playing audio
CD.stop
CD.stop(): return None
stop audio playback
CD.pause
CD.pause(): return None
temporarily stop audio playback
CD.resume
CD.resume(): return None
unpause audio playback
CD.eject
CD.eject(): return None
eject or open the cdrom drive
CD.get_id
CD.get_id(): return id
the index of the cdrom drive
CD.get_name
CD.get_name(): return name
the system name of the cdrom drive
CD.get_busy
CD.get_busy(): return bool
true if the drive is playing audio
CD.get_paused
CD.get_paused(): return bool
true if the drive is paused
CD.get_current
CD.get_current(): return track, seconds
the current audio playback position
CD.get_empty
CD.get_empty(): return bool
False if a cdrom is in the drive
CD.get_numtracks
CD.get_numtracks(): return count
the number of tracks on the cdrom
CD.get_track_audio
CD.get_track_audio(track): return bool
true if the cdrom track has audio data
CD.get_all
CD.get_all(): return [(audio, start, end, lenth), ...]
get all track information
CD.get_track_start
CD.get_track_start(track): return seconds
start time of a cdrom track
CD.get_track_length
CD.get_track_length(track): return seconds
length of a cdrom track
pygame.Color
pygame.Color(name): Return Color
pygame.Color(r, g, b, a): Return Color
pygame.Color(rgbvalue): Return Color
pygame object for color representations
Color.r
Color.r: Return int
Gets or sets the red value of the Color.
Color.g
Color.g: Return int
Gets or sets the green value of the Color.
Color.b
Color.b: Return int
Gets or sets the blue value of the Color.
Color.a
Color.a: Return int
Gets or sets the alpha value of the Color.
Color.cmy
Color.cmy: Return tuple
Gets or sets the CMY representation of the Color.
Color.hsva
Color.hsva: Return tuple
Gets or sets the HSVA representation of the Color.
Color.hsla
Color.hsla: Return tuple
Gets or sets the HSLA representation of the Color.
Color.i1i2i3
Color.i1i2i3: Return tuple
Gets or sets the I1I2I3 representation of the Color.
Color.normalize
Color.normalize(): Return tuple
Returns the normalized RGBA values of the Color.
Color.correct_gamma
Color.correct_gamma (gamma): Return Color
Applies a certain gamma value to the Color.
Color.set_length
Color.set_length(len)
Set the number of elements in the Color to 1,2,3, or 4.
pygame.cursors
pygame module for cursor resources
pygame.cursors.compile
pygame.cursor.compile(strings, black='X', white='.', xor='o'): return data, mask
create binary cursor data from simple strings
pygame.cursors.load_xbm
pygame.cursors.load_xbm(cursorfile): return cursor_args
pygame.cursors.load_xbm(cursorfile, maskfile): return cursor_args
load cursor data from an xbm file
pygame.display
pygame module to control the display window and screen
pygame.display.init
pygame.display.init(): return None
initialize the display module
pygame.display.quit
pygame.display.quit(): return None
uninitialize the display module
pygame.display.get_init
pygame.display.get_init(): return bool
true if the display module is initialized
pygame.display.set_mode
pygame.display.set_mode(resolution=(0,0), flags=0, depth=0): return Surface
initialize a window or screen for display
pygame.display.get_surface
pygame.display.get_surface(): return Surface
get a reference to the currently set display surface
pygame.display.flip
pygame.display.flip(): return None
update the full display Surface to the screen
pygame.display.update
pygame.display.update(rectangle=None): return None
pygame.display.update(rectangle_list): return None
update portions of the screen for software displays
pygame.display.get_driver
pygame.display.get_driver(): return name
get the name of the pygame display backend
pygame.display.Info
pygame.display.Info(): return VideoInfo
Create a video display information object
pygame.display.get_wm_info
pygame.display.get_wm_info(): return dict
Get information about the current windowing system
pygame.display.list_modes
pygame.display.list_modes(depth=0, flags=pygame.FULLSCREEN): return list
get list of available fullscreen modes
pygame.display.mode_ok
pygame.display.mode_ok(size, flags=0, depth=0): return depth
pick the best color depth for a display mode
pygame.display.gl_get_attribute
pygame.display.gl_get_attribute(flag): return value
get the value for an opengl flag for the current display
pygame.display.gl_set_attribute
pygame.display.gl_set_attribute(flag, value): return None
request an opengl display attribute for the display mode
pygame.display.get_active
pygame.display.get_active(): return bool
true when the display is active on the display
pygame.display.iconify
pygame.display.iconify(): return bool
iconify the display surface
pygame.display.toggle_fullscreen
pygame.display.toggle_fullscreen(): return bool
switch between fullscreen and windowed displays
pygame.display.set_gamma
pygame.display.set_gamma(red, green=None, blue=None): return bool
change the hardware gamma ramps
pygame.display.set_gamma_ramp
change the hardware gamma ramps with a custom lookup
pygame.display.set_gamma_ramp(red, green, blue): return bool
set_gamma_ramp(red, green, blue): return bool
pygame.display.set_icon
pygame.display.set_icon(Surface): return None
change the system image for the display window
pygame.display.set_caption
pygame.display.set_caption(title, icontitle=None): return None
set the current window caption
pygame.display.get_caption
pygame.display.get_caption(): return (title, icontitle)
get the current window caption
pygame.display.set_palette
pygame.display.set_palette(palette=None): return None
set the display color palette for indexed displays
pygame.draw
pygame module for drawing shapes
pygame.draw.rect
pygame.draw.rect(Surface, color, Rect, width=0): return Rect
draw a rectangle shape
pygame.draw.polygon
pygame.draw.polygon(Surface, color, pointlist, width=0): return Rect
draw a shape with any number of sides
pygame.draw.circle
pygame.draw.circle(Surface, color, pos, radius, width=0): return Rect
draw a circle around a point
pygame.draw.ellipse
pygame.draw.ellipse(Surface, color, Rect, width=0): return Rect
draw a round shape inside a rectangle
pygame.draw.arc
pygame.draw.arc(Surface, color, Rect, start_angle, stop_angle, width=1): return Rect
draw a partial section of an ellipse
pygame.draw.line
pygame.draw.line(Surface, color, start_pos, end_pos, width=1): return Rect
draw a straight line segment
pygame.draw.lines
pygame.draw.lines(Surface, color, closed, pointlist, width=1): return Rect
draw multiple contiguous line segments
pygame.draw.aaline
pygame.draw.aaline(Surface, color, startpos, endpos, blend=1): return Rect
draw fine antialiased lines
pygame.draw.aalines
pygame.draw.aalines(Surface, color, closed, pointlist, blend=1): return Rect
pygame.event
pygame module for interacting with events and queues
pygame.event.pump
pygame.event.pump(): return None
internally process pygame event handlers
pygame.event.get
pygame.event.get(): return Eventlist
pygame.event.get(type): return Eventlist
pygame.event.get(typelist): return Eventlist
get events from the queue
pygame.event.poll
pygame.event.poll(): return Event
get a single event from the queue
pygame.event.wait
pygame.event.wait(): return Event
wait for a single event from the queue
pygame.event.peek
pygame.event.peek(type): return bool
pygame.event.peek(typelist): return bool
test if event types are waiting on the queue
pygame.event.clear
pygame.event.clear(): return None
pygame.event.clear(type): return None
pygame.event.clear(typelist): return None
remove all events from the queue
pygame.event.event_name
pygame.event.event_name(type): return string
get the string name from and event id
pygame.event.set_blocked
pygame.event.set_blocked(type): return None
pygame.event.set_blocked(typelist): return None
pygame.event.set_blocked(None): return None
control which events are allowed on the queue
pygame.event.set_allowed
pygame.event.set_allowed(type): return None
pygame.event.set_allowed(typelist): return None
pygame.event.set_allowed(None): return None
control which events are allowed on the queue
pygame.event.get_blocked
pygame.event.get_blocked(type): return bool
test if a type of event is blocked from the queue
pygame.event.set_grab
pygame.event.set_grab(bool): return None
control the sharing of input devices with other applications
pygame.event.get_grab
pygame.event.get_grab(): return bool
test if the program is sharing input devices
pygame.event.post
pygame.event.post(Event): return None
place a new event on the queue
pygame.event.Event
pygame.event.Event(type, dict): return Event
pygame.event.Event(type, **attributes): return Event
create a new event object
pygame.examples
module of example programs
pygame.examples.aliens.main
pygame.aliens.main(): return None
play the full aliens example
pygame.examples.oldalien.main
pygame.examples.oldalien.main(): return None
play the original aliens example
pygame.examples.stars.main
pygame.examples.stars.main(): return None
run a simple starfield example
pygame.examples.chimp.main
pygame.examples.chimp.main(): return None
hit the moving chimp
pygame.examples.moveit.main
pygame.examples.moveit.main(): return None
display animated objects on the screen
pygame.examples.fonty.main
pygame.examples.fonty.main(): return None
run a font rendering example
pygame.examples.vgrade.main
pygame.examples.vgrade.main(): return None
display a vertical gradient
pygame.examples.eventlist.main
pygame.examples.eventlist.main(): return None
display pygame events
pygame.examples.arraydemo.main
pygame.examples.arraydemo.main(arraytype=None): return None
show various surfarray effects
pygame.examples.sound.main
pygame.examples.sound.main(file_path=None): return None
load and play a sound
pygame.examples.sound_array_demos.main
pygame.examples.sound_array_demos.main(arraytype=None): return None
play various sndarray effects
pygame.examples.liquid.main
pygame.examples.liquid.main(): return None
display an animated liquid effect
pygame.examples.glcube.main
pygame.examples.glcube.main(): return None
display an animated 3D cube using OpenGL
pygame.examples.scrap_clipboard.main
pygame.examples.scrap_clipboard.main(): return None
access the clipboard
pygame.examples.mask.main
pygame.examples.mask.main(*args): return None
display multiple images bounce off each other using collision detection
pygame.examples.testsprite.main
pygame.examples.testsprite.main(update_rects = True, use_static = False, use_FastRenderGroup = False, screen_dims = [640, 480], use_alpha = False, flags = 0): return None
show lots of sprites moving around
pygame.examples.headless_no_windows_needed.main
pygame.examples.headless_no_windows_needed.main(fin, fout, w, h): return None
write an image file that is smoothscaled copy of an input file
pygame.examples.fastevents.main
pygame.examples.fastevents.main(): return None
stress test the fastevents module
pygame.examples.overlay.main
pygame.examples.overlay.main(fname): return None
play a .pgm video using overlays
pygame.examples.blend_fill.main
pygame.examples.blend_fill.main(): return None
demonstrate the various surface.fill method blend options
pygame.examples.cursors.main
pygame.examples.cursors.main(): return None
display two different custom cursors
pygame.examples.pixelarray.main
pygame.examples.pixelarray.main(): return None
display various pixelarray generated effects
pygame.examples.scaletest.main
pygame.examples.scaletest.main(imagefile, convert_alpha=False, run_speed_test=True): return None
interactively scale an image using smoothscale
pygame.examples.midi.main
pygame.examples.midi.main(mode='output', device_id=None): return None
run a midi example
pygame.examples.scroll.main
pygame.examples.scroll.main(image_file=None): return None
run a Surface.scroll example that shows a magnified image
pygame.examples.movieplayer.main
pygame.examples.moveplayer.main(filepath): return None
play an MPEG movie
pygame.font
pygame module for loading and rendering fonts
pygame.font.init
pygame.font.init(): return None
initialize the font module
pygame.font.quit
pygame.font.quit(): return None
uninitialize the font module
pygame.font.get_init
pygame.font.get_init(): return bool
true if the font module is initialized
pygame.font.get_default_font
pygame.font.get_default_font(): return string
get the filename of the default font
pygame.font.get_fonts
pygame.font.get_fonts(): return list of strings
get all available fonts
pygame.font.match_font
pygame.font.match_font(name, bold=False, italic=False): return path
find a specific font on the system
pygame.font.SysFont
pygame.font.SysFont(name, size, bold=False, italic=False): return Font
create a Font object from the system fonts
pygame.font.Font
pygame.font.Font(filename, size): return Font
pygame.font.Font(object, size): return Font
create a new Font object from a file
Font.render
Font.render(text, antialias, color, background=None): return Surface
draw text on a new Surface
Font.size
Font.size(text): return (width, height)
determine the amount of space needed to render text
Font.set_underline
Font.set_underline(bool): return None
control if text is rendered with an underline
Font.get_underline
Font.get_underline(): return bool
check if text will be rendered with an underline
Font.set_bold
Font.set_bold(bool): return None
enable fake rendering of bold text
Font.get_bold
Font.get_bold(): return bool
check if text will be rendered bold
Font.set_italic
Font.set_bold(bool): return None
enable fake rendering of italic text
Font.metrics
Font.metrics(text): return list
Gets the metrics for each character in the pased string.
Font.get_italic
Font.get_italic(): return bool
check if the text will be rendered italic
Font.get_linesize
Font.get_linesize(): return int
get the line space of the font text
Font.get_height
Font.get_height(): return int
get the height of the font
Font.get_ascent
Font.get_ascent(): return int
get the ascent of the font
Font.get_descent
Font.get_descent(): return int
get the descent of the font
pygame.gfxdraw
pygame module for drawing shapes
pygame.gfxdraw.pixel
pygame.gfxdraw.pixel(surface, x, y, color): return None
place a pixel
pygame.gfxdraw.hline
pygame.gfxdraw.hline(surface, x1, x2, y, color): return None
draw a horizontal line
pygame.gfxdraw.vline
pgyame.gfxdraw.vline(surface, x, y1, y2, color): return None
draw a vertical line
pygame.gfxdraw.rectangle
pgyame.gfxdraw.rectangle(surface, rect, color): return None
draw a rectangle
pygame.gfxdraw.box
pgyame.gfxdraw.box(surface, rect, color): return None
draw a box
pygame.gfxdraw.line
pgyame.gfxdraw.line(surface, x1, y1, x2, y2, color): return None
draw a line
pygame.gfxdraw.circle
pgyame.gfxdraw.circle(surface, x, y, r, color): return None
draw a circle
pygame.gfxdraw.arc
pgyame.gfxdraw.arc(surface, x, y, r, start, end, color): return None
draw an arc
pygame.gfxdraw.aacircle
pgyame.gfxdraw.aacircle(surface, x, y, r, color): return None
draw an anti-aliased circle
pygame.gfxdraw.filled_circle
pgyame.gfxdraw.filled_circle(surface, x, y, r, color): return None
draw a filled circle
pygame.gfxdraw.ellipse
pgyame.gfxdraw.ellipse(surface, x, y, rx, ry, color): return None
draw an ellipse
pygame.gfxdraw.aaellipse
pgyame.gfxdraw.aaellipse(surface, x, y, rx, ry, color): return None
draw an anti-aliased ellipse
pygame.gfxdraw.filled_ellipse
pgyame.gfxdraw.filled_ellipse(surface, x, y, rx, ry, color): return None
draw a filled ellipse
pygame.gfxdraw.pie
pgyame.gfxdraw.pie(surface, x, y, r, start, end, color): return None
draw a pie
pygame.gfxdraw.trigon
pgyame.gfxdraw.trigon(surface, x1, y1, x2, y2, x3, y3, color): return None
draw a triangle
pygame.gfxdraw.aatrigon
pgyame.gfxdraw.aatrigon(surface, x1, y1, x2, y2, x3, y3, color): return None
draw an anti-aliased triangle
pygame.gfxdraw.filled_trigon
pgyame.gfxdraw.filled_trigon(surface, x1, y1, x3, y2, x3, y3, color): return None
draw a filled trigon
pygame.gfxdraw.polygon
pgyame.gfxdraw.polygon(surface, points, color): return None
draw a polygon
pygame.gfxdraw.aapolygon
pgyame.gfxdraw.aapolygon(surface, points, color): return None
draw an anti-aliased polygon
pygame.gfxdraw.filled_polygon
pgyame.gfxdraw.filled_polygon(surface, points, color): return None
draw a filled polygon
pygame.gfxdraw.textured_polygon
pgyame.gfxdraw.textured_polygon(surface, points, texture, tx, ty): return None
draw a textured polygon
pygame.gfxdraw.bezier
pgyame.gfxdraw.bezier(surface, points, steps, color): return None
draw a bezier curve
pygame.image
pygame module for image transfer
pygame.image.load
pygame.image.load(filename): return Surface
pygame.image.load(fileobj, namehint=""): return Surface
load new image from a file
pygame.image.save
pygame.image.save(Surface, filename): return None
save an image to disk
pygame.image.get_extended
pygame.image.get_extended(): return bool
test if extended image formats can be loaded
pygame.image.tostring
pygame.image.tostring(Surface, format, flipped=False): return string
transfer image to string buffer
pygame.image.fromstring
pygame.image.fromstring(string, size, format, flipped=False): return Surface
create new Surface from a string buffer
pygame.image.frombuffer
pygame.image.frombuffer(string, size, format): return Surface
create a new Surface that shares data inside a string buffer
pygame.joystick
pygame module for interacting with joystick devices
pygame.joystick.init
pygame.joystick.init(): return None
initialize the joystick module
pygame.joystick.quit
pygame.joystick.quit(): return None
uninitialize the joystick module
pygame.joystick.get_init
pygame.joystick.get_init(): return bool
true if the joystick module is initialized
pygame.joystick.get_count
pygame.joystick.get_count(): return count
number of joysticks on the system
pygame.joystick.Joystick
pygame.joystick.Joystick(id): return Joystick
create a new Joystick object
Joystick.init
Joystick.init(): return None
initialize the Joystick
Joystick.quit
Joystick.quit(): return None
uninitialize the Joystick
Joystick.get_init
Joystick.get_init(): return bool
check if the Joystick is initialized
Joystick.get_id
Joystick.get_id(): return int
get the Joystick ID
Joystick.get_name
Joystick.get_name(): return string
get the Joystick system name
Joystick.get_numaxes
Joystick.get_numaxes(): return int
get the number of axes on a Joystick
Joystick.get_axis
Joystick.get_axis(axis_number): return float
get the current position of an axis
Joystick.get_numballs
Joystick.get_numballs(): return int
get the number of trackballs on a Joystick
Joystick.get_ball
Joystick.get_ball(ball_number): return x, y
get the relative position of a trackball
Joystick.get_numbuttons
Joystick.get_numbuttons(): return int
get the number of buttons on a Joystick
Joystick.get_button
Joystick.get_button(button): return bool
get the current button state
Joystick.get_numhats
Joystick.get_numhats(): return int
get the number of hat controls on a Joystick
Joystick.get_hat
Joystick.get_hat(hat_number): return x, y
get the position of a joystick hat
pygame.key
pygame module to work with the keyboard
pygame.key.get_focused
pygame.key.get_focused(): return bool
true if the display is receiving keyboard input from the system
pygame.key.get_pressed
pygame.key.get_pressed(): return bools
get the state of all keyboard buttons
pygame.key.get_mods
pygame.key.get_mods(): return int
determine which modifier keys are being held
pygame.key.set_mods
pygame.key.set_mods(int): return None
temporarily set which modifier keys are pressed
pygame.key.set_repeat
pygame.key.set_repeat(): return None
pygame.key.set_repeat(delay, interval): return None
control how held keys are repeated
pygame.key.get_repeat
pygame.key.get_repeat(): return (delay, interval)
see how held keys are repeated
pygame.key.name
pygame.key.name(key): return string
get the name of a key identifier
pygame.locals
pygame constants
pygame.mask
pygame module for image masks.
pygame.mask.from_surface
pygame.mask.from_surface(Surface, threshold = 127) -> Mask
Returns a Mask from the given surface.
pygame.mask.from_threshold
pygame.mask.from_surface(Surface, color, threshold = (0,0,0,255), othersurface = None, palette_colors = 1) -> Mask
Creates a mask by thresholding Surfaces
pygame.mask.Mask
pygame.Mask((width, height)): return Mask
pygame object for representing 2d bitmasks
Mask.get_size
Mask.get_size() -> width,height
Returns the size of the mask.
Mask.get_at
Mask.get_at((x,y)) -> int
Returns nonzero if the bit at (x,y) is set.
Mask.set_at
Mask.set_at((x,y),value)
Sets the position in the mask given by x and y.
Mask.overlap
Mask.overlap(othermask, offset) -> x,y
Returns the point of intersection if the masks overlap with the given offset - or None if it does not overlap.
Mask.overlap_area
Mask.overlap_area(othermask, offset) -> numpixels
Returns the number of overlapping 'pixels'.
Mask.overlap_mask
Mask.overlap_mask(othermask, offset) -> Mask
Returns a mask of the overlapping pixels
Mask.fill
Mask.fill()
Sets all bits to 1
Mask.clear
Mask.clear()
Sets all bits to 0
Mask.invert
Mask.invert()
Flips the bits in a Mask
Mask.scale
Mask.scale((x, y)) -> Mask
Resizes a mask
Mask.draw
Mask.draw(othermask, offset)
Draws a mask onto another
Mask.erase
Mask.erase(othermask, offset)
Erases a mask from another
Mask.count
Mask.count() -> pixels
Returns the number of set pixels
Mask.centroid
Mask.centroid() -> (x, y)
Returns the centroid of the pixels in a Mask
Mask.angle
Mask.angle() -> theta
Returns the orientation of the pixels
Mask.outline
Mask.outline(every = 1) -> [(x,y), (x,y) ...]
list of points outlining an object
Mask.convolve
Mask.convolve(othermask, outputmask = None, offset = (0,0)) -> Mask
Return the convolution of self with another mask.
Mask.connected_component
Mask.connected_component((x,y) = None) -> Mask
Returns a mask of a connected region of pixels.
Mask.connected_components
Mask.connected_components(min = 0) -> [Masks]
Returns a list of masks of connected regions of pixels.
Mask.get_bounding_rects
Mask.get_bounding_rects() -> Rects
Returns a list of bounding rects of regions of set pixels.
pygame.midi
pygame module for interacting with midi input and output.
pygame.midi.Input
Input(device_id)
Input(device_id, buffer_size)
Input is used to get midi input from midi devices.
Input.close
Input.close(): return None
closes a midi stream, flushing any pending buffers.
Input.poll
Input.poll(): return Bool
returns true if there's data, or false if not.
Input.read
Input.read(num_events): return midi_event_list
reads num_events midi events from the buffer.
pygame.midi.MidiException
MidiException(errno)
exception that pygame.midi functions and classes can raise
pygame.midi.Output
Output(device_id)
Output(device_id, latency = 0)
Output(device_id, buffer_size = 4096)
Output(device_id, latency, buffer_size)
Output is used to send midi to an output device
Output.abort
Output.abort(): return None
terminates outgoing messages immediately
Output.close
Output.close(): return None
closes a midi stream, flushing any pending buffers.
Output.note_off
Output.note_off(note, velocity=None, channel = 0)
turns a midi note off. Note must be on.
Output.note_on
Output.note_on(note, velocity=None, channel = 0)
turns a midi note on. Note must be off.
Output.set_instrument
Output.set_instrument(instrument_id, channel = 0)
select an instrument, with a value between 0 and 127
Output.write
Output.write(data)
writes a list of midi data to the Output
Output.write_short
Output.write_short(status)
Output.write_short(status, data1 = 0, data2 = 0)
write_short(status <, data1><, data2>)
Output.write_sys_ex
Output.write_sys_ex(when, msg)
writes a timestamped system-exclusive midi message.
pygame.midi.get_count
pygame.midi.get_count(): return num_devices
gets the number of devices.
pygame.midi.get_default_input_id
pygame.midi.get_default_input_id(): return default_id
gets default input device number
pygame.midi.get_default_output_id
pygame.midi.get_default_output_id(): return default_id
gets default output device number
pygame.midi.get_device_info
pygame.midi.get_device_info(an_id): return (interf, name, input, output, opened)
returns information about a midi device
pygame.midi.init
pygame.midi.init(): return None
initialize the midi module
pygame.midi.midis2events
pygame.midi.midis2events(midis, device_id): return [Event, ...]
converts midi events to pygame events
pygame.midi.quit
pygame.midi.quit(): return None
uninitialize the midi module
pygame.midi.time
pygame.midi.time(): return time
returns the current time in ms of the PortMidi timer
pygame.mixer
pygame module for loading and playing sounds
pygame.mixer.init
pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096): return None
initialize the mixer module
pygame.mixer.pre_init
pygame.mixer.pre_init(frequency=22050, size=-16, channels=2, buffersize=4096): return None
preset the mixer init arguments
pygame.mixer.quit
pygame.mixer.quit(): return None
uninitialize the mixer
pygame.mixer.get_init
pygame.mixer.get_init(): return (frequency, format, channels)
test if the mixer is initialized
pygame.mixer.stop
pygame.mixer.stop(): return None
stop playback of all sound channels
pygame.mixer.pause
pygame.mixer.pause(): return None
temporarily stop playback of all sound channels
pygame.mixer.unpause
pygame.mixer.unpause(): return None
resume paused playback of sound channels
pygame.mixer.fadeout
pygame.mixer.fadeout(time): return None
fade out the volume on all sounds before stopping
pygame.mixer.set_num_channels
pygame.mixer.set_num_channels(count): return None
set the total number of playback channels
pygame.mixer.get_num_channels
get the total number of playback channels
pygame.mixer.set_reserved
pygame.mixer.set_reserved(count): return None
reserve channels from being automatically used
pygame.mixer.find_channel
pygame.mixer.find_channel(force=False): return Channel
find an unused channel
pygame.mixer.get_busy
pygame.mixer.get_busy(): return bool
test if any sound is being mixed
pygame.mixer.Sound
pygame.mixer.Sound(filename): return Sound
pygame.mixer.Sound(buffer): return Sound
pygame.mixer.Sound(object): return Sound
Create a new Sound object from a file
Sound.play
Sound.play(loops=0, maxtime=0, fade_ms=0): return Channel
begin sound playback
Sound.stop
Sound.stop(): return None
stop sound playback
Sound.fadeout
Sound.fadeout(time): return None
stop sound playback after fading out
Sound.set_volume
Sound.set_volume(value): return None
set the playback volume for this Sound
Sound.get_volume
Sound.get_volume(): return value
get the playback volume
Sound.get_num_channels
Sound.get_num_channels(): return count
count how many times this Sound is playing
Sound.get_length
Sound.get_length(): return seconds
get the length of the Sound
Sound.get_buffer
Sound.get_buffer(): return BufferProxy
acquires a buffer object for the sameples of the Sound.
pygame.mixer.Channel
pygame.mixer.Channel(id): return Channel
Create a Channel object for controlling playback
Channel.play
Channel.play(Sound, loops=0, maxtime=0, fade_ms=0): return None
play a Sound on a specific Channel
Channel.stop
Channel.stop(): return None
stop playback on a Channel
Channel.pause
Channel.pause(): return None
temporarily stop playback of a channel
Channel.unpause
Channel.unpause(): return None
resume pause playback of a channel
Channel.fadeout
Channel.fadeout(time): return None
stop playback after fading channel out
Channel.set_volume
Channel.set_volume(value): return None
Channel.set_volume(left, right): return None
set the volume of a playing channel
Channel.get_volume
Channel.get_volume(): return value
get the volume of the playing channel
Channel.get_busy
Channel.get_busy(): return bool
check if the channel is active
Channel.get_sound
Channel.get_sound(): return Sound
get the currently playing Sound
Channel.queue
Channel.queue(Sound): return None
queue a Sound object to follow the current
Channel.get_queue
Channel.get_queue(): return Sound
return any Sound that is queued
Channel.set_endevent
Channel.set_endevent(): return None
Channel.set_endevent(type): return None
have the channel send an event when playback stops
Channel.get_endevent
Channel.get_endevent(): return type
get the event a channel sends when playback stops
pygame.mouse
pygame module to work with the mouse
pygame.mouse.get_pressed
pygame.moouse.get_pressed(): return (button1, button2, button3)
get the state of the mouse buttons
pygame.mouse.get_pos
pygame.mouse.get_pos(): return (x, y)
get the mouse cursor position
pygame.mouse.get_rel
pygame.mouse.get_rel(): return (x, y)
get the amount of mouse movement
pygame.mouse.set_pos
pygame.mouse.set_pos([x, y]): return None
set the mouse cursor position
pygame.mouse.set_visible
pygame.mouse.set_visible(bool): return bool
hide or show the mouse cursor
pygame.mouse.get_focused
pygame.mouse.get_focused(): return bool
check if the display is receiving mouse input
pygame.mouse.set_cursor
pygame.mouse.set_cursor(size, hotspot, xormasks, andmasks): return None
set the image for the system mouse cursor
pygame.mouse.get_cursor
pygame.mouse.get_cursor(): return (size, hotspot, xormasks, andmasks)
get the image for the system mouse cursor
pygame.movie
pygame module for playback of mpeg video
pygame.movie.Movie
pygame.movie.Movie(filename): return Movie
pygame.movie.Movie(object): return Movie
load an mpeg movie file
Movie.play
Movie.play(loops=0): return None
start playback of a movie
Movie.stop
Movie.stop(): return None
stop movie playback
Movie.pause
Movie.pause(): return None
temporarily stop and resume playback
Movie.skip
Movie.skip(seconds): return None
advance the movie playback position
Movie.rewind
Movie.rewind(): return None
restart the movie playback
Movie.render_frame
Movie.render_frame(frame_number): return frame_number
set the current video frame
Movie.get_frame
Movie.get_frame(): return frame_number
get the current video frame
Movie.get_time
Movie.get_time(): return seconds
get the current vide playback time
Movie.get_busy
Movie.get_busy(): return bool
check if the movie is currently playing
Movie.get_length
Movie.get_length(): return seconds
the total length of the movie in seconds
Movie.get_size
Movie.get_size(): return (width, height)
get the resolution of the video
Movie.has_video
Movie.get_video(): return bool
check if the movie file contains video
Movie.has_audio
Movie.get_audio(): return bool
check if the movie file contains audio
Movie.set_volume
Movie.set_volume(value): return None
set the audio playback volume
Movie.set_display
Movie.set_display(Surface, rect=None): return None
set the video target Surface
pygame.mixer.music
pygame module for controlling streamed audio
pygame.mixer.music.load
pygame.mixer.music.load(filename): return None
pygame.mixer.music.load(object): return None
Load a music file for playback
pygame.mixer.music.play
pygame.mixer.music.play(loops=0, start=0.0): return None
Start the playback of the music stream
pygame.mixer.music.rewind
pygame.mixer.music.rewind(): return None
restart music
pygame.mixer.music.stop
pygame.mixer.music.stop(): return None
stop the music playback
pygame.mixer.music.pause
pygame.mixer.music.pause(): return None
temporarily stop music playback
pygame.mixer.music.unpause
pygame.mixer.music.unpause(): return None
resume paused music
pygame.mixer.music.fadeout
pygame.mixer.music.fadeout(time): return None
stop music playback after fading out
pygame.mixer.music.set_volume
pygame.mixer.music.set_volume(value): return None
set the music volume
pygame.mixer.music.get_volume
pygame.mixer.music.get_volume(): return value
get the music volume
pygame.mixer.music.get_busy
pygame.mixer.music.get_busy(): return bool
check if the music stream is playing
pygame.mixer.music.get_pos
pygame.mixer.music.get_pos(): return time
get the music play time
pygame.mixer.music.queue
pygame.mixer.music.queue(filename): return None
queue a music file to follow the current
pygame.mixer.music.set_endevent
pygame.mixer.music.set_endevent(): return None
pygame.mixer.music.set_endevent(type): return None
have the music send an event when playback stops
pygame.mixer.music.get_endevent
pygame.mixer.music.get_endevent(): return type
get the event a channel sends when playback stops
pygame.Overlay
pygame.Overlay(format, (width, height)): return Overlay
pygame object for video overlay graphics
Overlay.display
Overlay.display((y, u, v)): return None
Overlay.display(): return None
set the overlay pixel data
Overlay.set_location
Overlay.set_location(rect): return None
control where the overlay is displayed
Overlay.get_hardware
Overlay.get_hardware(rect): return int
test if the Overlay is hardware accelerated
pygame.PixelArray
pygame.PixelArray(Surface): return PixelArray
pygame object for direct pixel access of surfaces
PixelArray.surface
PixelArray.surface: Return Surface
Gets the Surface the PixelArray uses.
PixelArray.make_surface
PixelArray.make_surface (): Return Surface
Creates a new Surface from the current PixelArray.
PixelArray.replace
PixelArray.replace (color, repcolor, distance=0, weights=(0.299, 0.587, 0.114)): Return None
Replaces the passed color in the PixelArray with another one.
PixelArray.extract
PixelArray.extract (color, distance=0, weights=(0.299, 0.587, 0.114)): Return PixelArray
Extracts the passed color from the PixelArray.
PixelArray.compare
PixelArray.compare (array, distance=0, weights=(0.299, 0.587, 0.114)): Return PixelArray
Compares the PixelArray with another one.
pygame.Rect
pygame.Rect(left, top, width, height): return Rect
pygame.Rect((left, top), (width, height)): return Rect
pygame.Rect(object): return Rect
pygame object for storing rectangular coordinates
Rect.copy
Rect.copy(): return Rect
copy the rectangle
Rect.move
Rect.move(x, y): return Rect
moves the rectangle
Rect.move_ip
Rect.move_ip(x, y): return None
moves the rectangle, in place
Rect.inflate
Rect.inflate(x, y): return Rect
grow or shrink the rectangle size
Rect.inflate_ip
Rect.inflate_ip(x, y): return None
grow or shrink the rectangle size, in place
Rect.clamp
Rect.clamp(Rect): return Rect
moves the rectangle inside another
Rect.clamp_ip
Rect.clamp_ip(Rect): return None
moves the rectangle inside another, in place
Rect.clip
Rect.clip(Rect): return Rect
crops a rectangle inside another
Rect.union
Rect.union(Rect): return Rect
joins two rectangles into one
Rect.union_ip
Rect.union_ip(Rect): return None
joins two rectangles into one, in place
Rect.unionall
Rect.unionall(Rect_sequence): return Rect
the union of many rectangles
Rect.unionall_ip
Rect.unionall_ip(Rect_sequence): return None
the union of many rectangles, in place
Rect.fit
Rect.fit(Rect): return Rect
resize and move a rectangle with aspect ratio
Rect.normalize
Rect.normalize(): return None
correct negative sizes
Rect.contains
Rect.contains(Rect): return bool
test if one rectangle is inside another
Rect.collidepoint
Rect.collidepoint(x, y): return bool
Rect.collidepoint((x,y)): return bool
test if a point is inside a rectangle
Rect.colliderect
Rect.colliderect(Rect): return bool
test if two rectangles overlap
Rect.collidelist
Rect.collidelist(list): return index
test if one rectangle in a list intersects
Rect.collidelistall
Rect.collidelistall(list): return indices
test if all rectangles in a list intersect
Rect.collidedict
Rect.collidedict(dict): return (key, value)
test if one rectangle in a dictionary intersects
Rect.collidedictall
Rect.collidedictall(dict): return [(key, value), ...]
test if all rectangles in a dictionary intersect
pygame.scrap
pygame module for clipboard support.
pygame.scrap.init
scrap.init () -> None
Initializes the scrap module.
pygame.scrap.get
scrap.get (type) -> string
Gets the data for the specified type from the clipboard.
pygame.scrap.get_types
scrap.get_types () -> list
Gets a list of the available clipboard types.
pygame.scrap.put
scrap.put(type, data) -> None
Places data into the clipboard.
pygame.scrap.contains
scrap.contains (type) -> bool
Checks, whether a certain type is available in the clipboard.
pygame.scrap.lost
scrap.lost() -> bool
Checks whether the clipboard is currently owned by the application.
pygame.scrap.set_mode
scrap.set_mode(mode) -> None
Sets the clipboard access mode.
pygame.sndarray
pygame module for accessing sound sample data
pygame.sndarray.array
pygame.sndarray.array(Sound): return array
copy Sound samples into an array
pygame.sndarray.samples
pygame.sndarray.samples(Sound): return array
reference Sound samples into an array
pygame.sndarray.make_sound
pygame.sndarray.make_sound(array): return Sound
convert an array into a Sound object
pygame.sndarray.use_arraytype
pygame.sndarray.use_arraytype (arraytype): return None
Sets the array system to be used for sound arrays
pygame.sndarray.get_arraytype
pygame.sndarray.get_arraytype (): return str
Gets the currently active array type.
pygame.sndarray.get_arraytypes
pygame.sndarray.get_arraytypes (): return tuple
Gets the array system types currently supported.
pygame.sprite
pygame module with basic game object classes
pygame.sprite.Sprite
pygame.sprite.Sprite(*groups): return Sprite
simple base class for visible game objects
Sprite.update
Sprite.update(*args):
method to control sprite behavior
Sprite.add
Sprite.add(*groups): return None
add the sprite to groups
Sprite.remove
Sprite.remove(*groups): return None
remove the sprite from groups
Sprite.kill
Sprite.kill(): return None
remove the Sprite from all Groups
Sprite.alive
Sprite.alive(): return bool
does the sprite belong to any groups
Sprite.groups
Sprite.groups(): return group_list
list of Groups that contain this Sprite
pygame.sprite.DirtySprite
pygame.sprite.DirtySprite(*groups): return DirtySprite
a more featureful subclass of Sprite with more attributes
pygame.sprite.Group
pygame.sprite.Group(*sprites): return Group
container class for many Sprites
Group.sprites
Group.sprites(): return sprite_list
list of the Sprites this Group contains
Group.copy
Group.copy(): return Group
duplicate the Group
Group.add
Group.add(*sprites): return None
add Sprites to this Group
Group.remove
Group.remove(*sprites): return None
remove Sprites from the Group
Group.has
Group.has(*sprites): return None
test if a Group contains Sprites
Group.update
Group.update(*args): return None
call the update method on contained Sprites
Group.draw
Group.draw(Surface): return None
blit the Sprite images
Group.clear
Group.clear(Surface_dest, background): return None
draw a background over the Sprites
Group.empty
Group.empty(): return None
remove all Sprites
pygame.sprite.RenderUpdates
pygame.sprite.RenderUpdates(*sprites): return RenderUpdates
Group class that tracks dirty updates
RenderUpdates.draw
RenderUpdates.draw(surface): return Rect_list
blit the Sprite images and track changed areas
pygame.sprite.OrderedUpdates
pygame.sprite.OrderedUpdates(*spites): return OrderedUpdates
RenderUpdates class that draws Sprites in order of addition
pygame.sprite.LayeredUpdates
pygame.sprite.LayeredUpdates(*spites, **kwargs): return LayeredUpdates
LayeredUpdates Group handles layers, that draws like OrderedUpdates.
LayeredUpdates.add
LayeredUpdates.add(*sprites, **kwargs): return None
add a sprite or sequence of sprites to a group
LayeredUpdates.sprites
LayeredUpdates.sprites(): return sprites
returns a ordered list of sprites (first back, last top).
LayeredUpdates.draw
LayeredUpdates.draw(surface): return Rect_list
draw all sprites in the right order onto the passed surface.
LayeredUpdates.get_sprites_at
LayeredUpdates.get_sprites_at(pos): return colliding_sprites
returns a list with all sprites at that position.
LayeredUpdates.get_sprite
LayeredUpdates.get_sprite(idx): return sprite
returns the sprite at the index idx from the groups sprites
LayeredUpdates.remove_sprites_of_layer
LayeredUpdates.remove_sprites_of_layer(layer_nr): return sprites
removes all sprites from a layer and returns them as a list.
LayeredUpdates.layers
LayeredUpdates.layers(): return layers
returns a list of layers defined (unique), sorted from botton up.
LayeredUpdates.change_layer
LayeredUpdates.change_layer(sprite, new_layer): return None
changes the layer of the sprite
LayeredUpdates.get_layer_of_sprite
LayeredUpdates.get_layer_of_sprite(sprite): return layer
returns the layer that sprite is currently in.
LayeredUpdates.get_top_layer
LayeredUpdates.get_top_layer(): return layer
returns the top layer
LayeredUpdates.get_bottom_layer
LayeredUpdates.get_bottom_layer(): return layer
returns the bottom layer
LayeredUpdates.move_to_front
LayeredUpdates.move_to_front(sprite): return None
brings the sprite to front layer
LayeredUpdates.move_to_back
LayeredUpdates.move_to_back(sprite): return None
moves the sprite to the bottom layer
LayeredUpdates.get_top_sprite
LayeredUpdates.get_top_sprite(): return Sprite
returns the topmost sprite
LayeredUpdates.get_sprites_from_layer
LayeredUpdates.get_sprites_from_layer(layer): return sprites
returns all sprites from a layer, ordered by how they where added
LayeredUpdates.switch_layer
LayeredUpdates.switch_layer(layer1_nr, layer2_nr): return None
switches the sprites from layer1 to layer2
pygame.sprite.LayeredDirty
pygame.sprite.LayeredDirty(*spites, **kwargs): return LayeredDirty
LayeredDirty Group is for DirtySprites. Subclasses LayeredUpdates.
LayeredDirty.draw
LayeredDirty.draw(surface, bgd=None): return Rect_list
draw all sprites in the right order onto the passed surface.
LayeredDirty.clear
LayeredDirty.clear(surface, bgd): return None
used to set background
LayeredDirty.repaint_rect
LayeredDirty.repaint_rect(screen_rect): return None
repaints the given area
LayeredDirty.set_clip
LayeredDirty.set_clip(screen_rect=None): return None
clip the area where to draw. Just pass None (default) to reset the clip
LayeredDirty.get_clip
LayeredDirty.get_clip(): return Rect
clip the area where to draw. Just pass None (default) to reset the clip
LayeredDirty.change_layer
change_layer(sprite, new_layer): return None
changes the layer of the sprite
LayeredDirty.set_timing_treshold
set_timing_treshold(time_ms): return None
sets the treshold in milliseconds
pygame.sprite.GroupSingle
pygame.sprite.GroupSingle(sprite=None): return GroupSingle
Group container that holds a single Sprite
pygame.sprite.spritecollide
pygame.sprite.spritecollide(sprite, group, dokill, collided = None): return Sprite_list
find Sprites in a Group that intersect another Sprite
pygame.sprite.collide_rect
pygame.sprite.collide_rect(left, right): return bool
collision detection between two sprites, using rects.
pygame.sprite.collide_rect_ratio
pygame.sprite.collide_rect_ratio(ratio): return collided_callable
collision detection between two sprites, using rects scaled to a ratio.
pygame.sprite.collide_circle
pygame.sprite.collide_circle(left, right): return bool
collision detection between two sprites, using circles.
pygame.sprite.collide_circle_ratio
pygame.sprite.collide_circle_ratio(ratio): return collided_callable
collision detection between two sprites, using circles scaled to a ratio.
pygame.sprite.collide_mask
pygame.sprite.collide_mask(SpriteLeft, SpriteRight): return bool
collision detection between two sprites, using masks.
pygame.sprite.groupcollide
pygame.sprite.groupcollide(group1, group2, dokill1, dokill2): return Sprite_dict
find all Sprites that collide between two Groups
pygame.sprite.spritecollideany
pygame.sprite.spritecollideany(sprite, group): return bool
simple test if a Sprite intersects anything in a Group
pygame.Surface
pygame.Surface((width, height), flags=0, depth=0, masks=None): return Surface
pygame.Surface((width, height), flags=0, Surface): return Surface
pygame object for representing images
Surface.blit
Surface.blit(source, dest, area=None, special_flags = 0): return Rect
draw one image onto another
Surface.convert
Surface.convert(Surface): return Surface
Surface.convert(depth, flags=0): return Surface
Surface.convert(masks, flags=0): return Surface
Surface.convert(): return Surface
change the pixel format of an image
Surface.convert_alpha
Surface.convert_alpha(Surface): return Surface
Surface.convert_alpha(): return Surface
change the pixel format of an image including per pixel alphas
Surface.copy
Surface.copy(): return Surface
create a new copy of a Surface
Surface.fill
Surface.fill(color, rect=None, special_flags=0): return Rect
fill Surface with a solid color
Surface.scroll
Surface.scroll(dx=0, dy=0): return None
Shift the surface image in place
Surface.set_colorkey
Surface.set_colorkey(Color, flags=0): return None
Surface.set_colorkey(None): return None
Set the transparent colorkey
Surface.get_colorkey
Surface.get_colorkey(): return RGB or None
Get the current transparent colorkey
Surface.set_alpha
Surface.set_alpha(value, flags=0): return None
Surface.set_alpha(None): return None
set the alpha value for the full Surface image
Surface.get_alpha
Surface.get_alpha(): return int_value or None
get the current Surface transparency value
Surface.lock
Surface.lock(): return None
lock the Surface memory for pixel access
Surface.unlock
Surface.unlock(): return None
unlock the Surface memory from pixel access
Surface.mustlock
Surface.mustlock(): return bool
test if the Surface requires locking
Surface.get_locked
Surface.get_locked(): return bool
test if the Surface is current locked
Surface.get_locks
Surface.get_locks(): return tuple
Gets the locks for the Surface
Surface.get_at
Surface.get_at((x, y)): return Color
get the color value at a single pixel
Surface.set_at
Surface.set_at((x, y), Color): return None
set the color value for a single pixel
Surface.get_palette
Surface.get_palette(): return [RGB, RGB, RGB, ...]
get the color index palette for an 8bit Surface
Surface.get_palette_at
Surface.get_palette_at(index): return RGB
get the color for a single entry in a palette
Surface.set_palette
Surface.set_palette([RGB, RGB, RGB, ...]): return None
set the color palette for an 8bit Surface
Surface.set_palette_at
Surface.set_at(index, RGB): return None
set the color for a single index in an 8bit Surface palette
Surface.map_rgb
Surface.map_rgb(Color): return mapped_int
convert a color into a mapped color value
Surface.unmap_rgb
Surface.map_rgb(mapped_int): return Color
convert a mapped integer color value into a Color
Surface.set_clip
Surface.set_clip(rect): return None
Surface.set_clip(None): return None
set the current clipping area of the Surface
Surface.get_clip
Surface.get_clip(): return Rect
get the current clipping area of the Surface
Surface.subsurface
Surface.subsurface(Rect): return Surface
create a new surface that references its parent
Surface.get_parent
Surface.get_parent(): return Surface
find the parent of a subsurface
Surface.get_abs_parent
Surface.get_abs_parent(): return Surface
find the top level parent of a subsurface
Surface.get_offset
Surface.get_offset(): return (x, y)
find the position of a child subsurface inside a parent
Surface.get_abs_offset
Surface.get_abs_offset(): return (x, y)
find the absolute position of a child subsurface inside its top level parent
Surface.get_size
Surface.get_size(): return (width, height)
get the dimensions of the Surface
Surface.get_width
Surface.get_width(): return width
get the width of the Surface
Surface.get_height
Surface.get_height(): return height
get the height of the Surface
Surface.get_rect
Surface.get_rect(**kwargs): return Rect
get the rectangular area of the Surface
Surface.get_bitsize
Surface.get_bitsize(): return int
get the bit depth of the Surface pixel format
Surface.get_bytesize
Surface.get_bytesize(): return int
get the bytes used per Surface pixel
Surface.get_flags
Surface.get_flags(): return int
get the additional flags used for the Surface
Surface.get_pitch
Surface.get_pitch(): return int
get the number of bytes used per Surface row
Surface.get_masks
Surface.get_masks(): return (R, G, B, A)
the bitmasks needed to convert between a color and a mapped integer
Surface.set_masks
Surface.set_masks((r,g,b,a)): return None
set the bitmasks needed to convert between a color and a mapped integer
Surface.get_shifts
Surface.get_shifts(): return (R, G, B, A)
the bit shifts needed to convert between a color and a mapped integer
Surface.set_shifts
Surface.get_shifts((r,g,b,a)): return None
sets the bit shifts needed to convert between a color and a mapped integer
Surface.get_losses
Surface.get_losses(): return (R, G, B, A)
the significant bits used to convert between a color and a mapped integer
Surface.get_bounding_rect
Surface.get_bounding_rect(min_alpha = 1): return Rect
find the smallest rect containing data
Surface.get_buffer
Surface.get_buffer(): return BufferProxy
acquires a buffer object for the pixels of the Surface.
pygame.surfarray
pygame module for accessing surface pixel data using array interfaces
pygame.surfarray.array2d
pygame.surfarray.array2d(Surface): return array
Copy pixels into a 2d array
pygame.surfarray.pixels2d
pygame.surfarray.pixels2d(Surface): return array
Reference pixels into a 2d array
pygame.surfarray.array3d
pygame.surfarray.array3d(Surface): return array
Copy pixels into a 3d array
pygame.surfarray.pixels3d
pygame.surfarray.pixels3d(Surface): return array
Reference pixels into a 3d array
pygame.surfarray.array_alpha
pygame.surfarray.array_alpha(Surface): return array
Copy pixel alphas into a 2d array
pygame.surfarray.pixels_alpha
pygame.surfarray.pixels_alpha(Surface): return array
Reference pixel alphas into a 2d array
pygame.surfarray.array_colorkey
pygame.surfarray.array_colorkey(Surface): return array
Copy the colorkey values into a 2d array
pygame.surfarray.make_surface
pygame.surfarray.make_surface(array): return Surface
Copy an array to a new surface
pygame.surfarray.blit_array
pygame.surfarray.blit_array(Surface, array): return None
Blit directly from a array values
pygame.surfarray.map_array
pygame.surfarray.map_array(Surface, array3d): return array2d
Map a 3d array into a 2d array
pygame.surfarray.use_arraytype
pygame.surfarray.use_arraytype (arraytype): return None
Sets the array system to be used for surface arrays
pygame.surfarray.get_arraytype
pygame.surfarray.get_arraytype (): return str
Gets the currently active array type.
pygame.surfarray.get_arraytypes
pygame.surfarray.get_arraytypes (): return tuple
Gets the array system types currently supported.
pygame.tests
Pygame unit test suite package
pygame.tests.run
pygame.tests.run(*args, **kwds): return tuple
Run the Pygame unit test suite
pygame.time
pygame module for monitoring time
pygame.time.get_ticks
pygame.time.get_ticks(): return milliseconds
get the time in milliseconds
pygame.time.wait
pygame.time.wait(milliseconds): return time
pause the program for an amount of time
pygame.time.delay
pygame.time.delay(milliseconds): return time
pause the program for an amount of time
pygame.time.set_timer
pygame.time.set_timer(eventid, milliseconds): return None
repeatedly create an event on the event queue
pygame.time.Clock
pygame.time.Clock(): return Clock
create an object to help track time
Clock.tick
Clock.tick(framerate=0): return milliseconds
control timer events
update the clock
Clock.tick_busy_loop
Clock.tick_busy_loop(framerate=0): return milliseconds
control timer events
update the clock
Clock.get_time
Clock.get_time(): return milliseconds
time used in the previous tick
Clock.get_rawtime
Clock.get_rawtime(): return milliseconds
actual time used in the previous tick
Clock.get_fps
Clock.get_fps(): return float
compute the clock framerate
pygame.transform
pygame module to transform surfaces
pygame.transform.flip
pygame.transform.flip(Surface, xbool, ybool): return Surface
flip vertically and horizontally
pygame.transform.scale
pygame.transform.scale(Surface, (width, height), DestSurface = None): return Surface
resize to new resolution
pygame.transform.rotate
pygame.transform.rotate(Surface, angle): return Surface
rotate an image
pygame.transform.rotozoom
pygame.transform.rotozoom(Surface, angle, scale): return Surface
filtered scale and rotation
pygame.transform.scale2x
pygame.transform.scale2x(Surface, DestSurface = None): Surface
specialized image doubler
pygame.transform.smoothscale
pygame.transform.smoothscale(Surface, (width, height), DestSurface = None): return Surface
scale a surface to an arbitrary size smoothly
pygame.transform.get_smoothscale_backend
pygame.transform.get_smoothscale_backend(): return String
return smoothscale filter version in use: 'GENERIC', 'MMX', or 'SSE'
pygame.transform.set_smoothscale_backend
pygame.transform.get_smoothscale_backend(type): return None
set smoothscale filter version to one of: 'GENERIC', 'MMX', or 'SSE'
pygame.transform.chop
pygame.transform.chop(Surface, rect): return Surface
gets a copy of an image with an interior area removed
pygame.transform.laplacian
pygame.transform.laplacian(Surface, DestSurface = None): return Surface
find edges in a surface
pygame.transform.average_surfaces
pygame.transform.average_surfaces(Surfaces, DestSurface = None, palette_colors = 1): return Surface
find the average surface from many surfaces.
pygame.transform.average_color
pygame.transform.average_color(Surface, Rect = None): return Color
finds the average color of a surface
pygame.transform.threshold
pygame.transform.threshold(DestSurface, Surface, color, threshold = (0,0,0,0), diff_color = (0,0,0,0), change_return = 1, Surface = None, inverse = False): return num_threshold_pixels
finds which, and how many pixels in a surface are within a threshold of a color.
*/
pygame-1.9.1release/src/pygame.h 0000644 0001750 0001750 00000101370 11224420716 016466 0 ustar vincent vincent /*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
#ifndef PYGAME_H
#define PYGAME_H
/** This header file includes all the definitions for the
** base pygame extensions. This header only requires
** SDL and Python includes. The reason for functions
** prototyped with #define's is to allow for maximum
** python portability. It also uses python as the
** runtime linker, which allows for late binding. For more
** information on this style of development, read the Python
** docs on this subject.
** http://www.python.org/doc/current/ext/using-cobjects.html
**
** If using this to build your own derived extensions,
** you'll see that the functions available here are mainly
** used to help convert between python objects and SDL objects.
** Since this library doesn't add a lot of functionality to
** the SDL libarary, it doesn't need to offer a lot either.
**
** When initializing your extension module, you must manually
** import the modules you want to use. (this is the part about
** using python as the runtime linker). Each module has its
** own import_xxx() routine. You need to perform this import
** after you have initialized your own module, and before
** you call any routines from that module. Since every module
** in pygame does this, there are plenty of examples.
**
** The base module does include some useful conversion routines
** that you are free to use in your own extension.
**
** When making changes, it is very important to keep the
** FIRSTSLOT and NUMSLOT constants up to date for each
** section. Also be sure not to overlap any of the slots.
** When you do make a mistake with this, it will result
** is a dereferenced NULL pointer that is easier to diagnose
** than it could be :]
**/
#if defined(HAVE_SNPRINTF) /* defined in python.h (pyerrors.h) and SDL.h (SDL_config.h) */
#undef HAVE_SNPRINTF /* remove GCC redefine warning */
#endif
// This must be before all else
#if defined(__SYMBIAN32__) && defined( OPENC )
#include
#if defined(__WINS__)
void* _alloca(size_t size);
# define alloca _alloca
#endif
#endif
#include
// No signal()
#if defined(__SYMBIAN32__) && defined(HAVE_SIGNAL_H)
#undef HAVE_SIGNAL_H
#endif
#if defined(HAVE_SNPRINTF)
#undef HAVE_SNPRINTF
#endif
#ifdef MS_WIN32 /*Python gives us MS_WIN32, SDL needs just WIN32*/
#ifndef WIN32
#define WIN32
#endif
#endif
/// Prefix when initializing module
#define MODPREFIX ""
/// Prefix when importing module
#define IMPPREFIX "pygame."
#ifdef __SYMBIAN32__
#undef MODPREFIX
#undef IMPPREFIX
// On Symbian there is no pygame package. The extensions are built-in or in sys\bin.
#define MODPREFIX "pygame_"
#define IMPPREFIX "pygame_"
#endif
#include
/* macros used throughout the source */
#define RAISE(x,y) (PyErr_SetString((x), (y)), (PyObject*)NULL)
#if PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION == 3
# define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None
# define Py_RETURN_TRUE return Py_INCREF(Py_True), Py_True
# define Py_RETURN_FALSE return Py_INCREF(Py_False), Py_False
#endif
/* Py_ssize_t availability. */
#if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN)
typedef int Py_ssize_t;
#define PY_SSIZE_T_MAX INT_MAX
#define PY_SSIZE_T_MIN INT_MIN
typedef inquiry lenfunc;
typedef intargfunc ssizeargfunc;
typedef intobjargproc ssizeobjargproc;
typedef intintargfunc ssizessizeargfunc;
typedef intintobjargproc ssizessizeobjargproc;
typedef getreadbufferproc readbufferproc;
typedef getwritebufferproc writebufferproc;
typedef getsegcountproc segcountproc;
typedef getcharbufferproc charbufferproc;
#endif
#define PyType_Init(x) (((x).ob_type) = &PyType_Type)
#define PYGAMEAPI_LOCAL_ENTRY "_PYGAME_C_API"
#ifndef MIN
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#endif
#ifndef MAX
#define MAX(a,b) ( (a) > (b) ? (a) : (b))
#endif
#ifndef ABS
#define ABS(a) (((a) < 0) ? -(a) : (a))
#endif
/* test sdl initializations */
#define VIDEO_INIT_CHECK() \
if(!SDL_WasInit(SDL_INIT_VIDEO)) \
return RAISE(PyExc_SDLError, "video system not initialized")
#define CDROM_INIT_CHECK() \
if(!SDL_WasInit(SDL_INIT_CDROM)) \
return RAISE(PyExc_SDLError, "cdrom system not initialized")
#define JOYSTICK_INIT_CHECK() \
if(!SDL_WasInit(SDL_INIT_JOYSTICK)) \
return RAISE(PyExc_SDLError, "joystick system not initialized")
/* BASE */
#define PYGAMEAPI_BASE_FIRSTSLOT 0
#define PYGAMEAPI_BASE_NUMSLOTS 13
#ifndef PYGAMEAPI_BASE_INTERNAL
#define PyExc_SDLError ((PyObject*)PyGAME_C_API[PYGAMEAPI_BASE_FIRSTSLOT])
#define PyGame_RegisterQuit \
(*(void(*)(void(*)(void)))PyGAME_C_API[PYGAMEAPI_BASE_FIRSTSLOT + 1])
#define IntFromObj \
(*(int(*)(PyObject*, int*))PyGAME_C_API[PYGAMEAPI_BASE_FIRSTSLOT + 2])
#define IntFromObjIndex \
(*(int(*)(PyObject*, int, int*))PyGAME_C_API[PYGAMEAPI_BASE_FIRSTSLOT + 3])
#define TwoIntsFromObj \
(*(int(*)(PyObject*, int*, int*))PyGAME_C_API[PYGAMEAPI_BASE_FIRSTSLOT + 4])
#define FloatFromObj \
(*(int(*)(PyObject*, float*))PyGAME_C_API[PYGAMEAPI_BASE_FIRSTSLOT + 5])
#define FloatFromObjIndex \
(*(float(*)(PyObject*, int, float*)) \
PyGAME_C_API[PYGAMEAPI_BASE_FIRSTSLOT + 6])
#define TwoFloatsFromObj \
(*(int(*)(PyObject*, float*, float*)) \
PyGAME_C_API[PYGAMEAPI_BASE_FIRSTSLOT + 7])
#define UintFromObj \
(*(int(*)(PyObject*, Uint32*))PyGAME_C_API[PYGAMEAPI_BASE_FIRSTSLOT + 8])
#define UintFromObjIndex \
(*(int(*)(PyObject*, int, Uint32*)) \
PyGAME_C_API[PYGAMEAPI_BASE_FIRSTSLOT + 9])
#define PyGame_Video_AutoQuit \
(*(void(*)(void))PyGAME_C_API[PYGAMEAPI_BASE_FIRSTSLOT + 10])
#define PyGame_Video_AutoInit \
(*(int(*)(void))PyGAME_C_API[PYGAMEAPI_BASE_FIRSTSLOT + 11])
#define RGBAFromObj \
(*(int(*)(PyObject*, Uint8*))PyGAME_C_API[PYGAMEAPI_BASE_FIRSTSLOT + 12])
#define import_pygame_base() { \
PyObject *_module = PyImport_ImportModule(IMPPREFIX "base"); \
if (_module != NULL) { \
PyObject *_dict = PyModule_GetDict(_module); \
PyObject *_c_api = PyDict_GetItemString(_dict, \
PYGAMEAPI_LOCAL_ENTRY); \
if(PyCObject_Check(_c_api)) { \
int i; void** localptr = (void**)PyCObject_AsVoidPtr(_c_api); \
for(i = 0; i < PYGAMEAPI_BASE_NUMSLOTS; ++i) \
PyGAME_C_API[i + PYGAMEAPI_BASE_FIRSTSLOT] = localptr[i]; \
} \
Py_DECREF(_module); \
} \
}
#endif
/* RECT */
#define PYGAMEAPI_RECT_FIRSTSLOT \
(PYGAMEAPI_BASE_FIRSTSLOT + PYGAMEAPI_BASE_NUMSLOTS)
#define PYGAMEAPI_RECT_NUMSLOTS 4
typedef struct {
int x, y;
int w, h;
}GAME_Rect;
typedef struct {
PyObject_HEAD
GAME_Rect r;
PyObject *weakreflist;
} PyRectObject;
#define PyRect_AsRect(x) (((PyRectObject*)x)->r)
#ifndef PYGAMEAPI_RECT_INTERNAL
#define PyRect_Check(x) \
((x)->ob_type == (PyTypeObject*)PyGAME_C_API[PYGAMEAPI_RECT_FIRSTSLOT + 0])
#define PyRect_Type (*(PyTypeObject*)PyGAME_C_API[PYGAMEAPI_RECT_FIRSTSLOT + 0])
#define PyRect_New \
(*(PyObject*(*)(SDL_Rect*))PyGAME_C_API[PYGAMEAPI_RECT_FIRSTSLOT + 1])
#define PyRect_New4 \
(*(PyObject*(*)(int,int,int,int))PyGAME_C_API[PYGAMEAPI_RECT_FIRSTSLOT + 2])
#define GameRect_FromObject \
(*(GAME_Rect*(*)(PyObject*, GAME_Rect*)) \
PyGAME_C_API[PYGAMEAPI_RECT_FIRSTSLOT + 3])
#define import_pygame_rect() { \
PyObject *_module = PyImport_ImportModule(IMPPREFIX "rect"); \
if (_module != NULL) { \
PyObject *_dict = PyModule_GetDict(_module); \
PyObject *_c_api = PyDict_GetItemString(_dict, \
PYGAMEAPI_LOCAL_ENTRY); \
if(PyCObject_Check(_c_api)) { \
int i; void** localptr = (void**)PyCObject_AsVoidPtr(_c_api); \
for(i = 0; i < PYGAMEAPI_RECT_NUMSLOTS; ++i) \
PyGAME_C_API[i + PYGAMEAPI_RECT_FIRSTSLOT] = localptr[i]; \
} \
Py_DECREF(_module); \
} \
}
#endif
/* CDROM */
#define PYGAMEAPI_CDROM_FIRSTSLOT \
(PYGAMEAPI_RECT_FIRSTSLOT + PYGAMEAPI_RECT_NUMSLOTS)
#define PYGAMEAPI_CDROM_NUMSLOTS 2
typedef struct {
PyObject_HEAD
int id;
} PyCDObject;
#define PyCD_AsID(x) (((PyCDObject*)x)->id)
#ifndef PYGAMEAPI_CDROM_INTERNAL
#define PyCD_Check(x) \
((x)->ob_type == (PyTypeObject*)PyGAME_C_API[PYGAMEAPI_CDROM_FIRSTSLOT + 0])
#define PyCD_Type (*(PyTypeObject*)PyGAME_C_API[PYGAMEAPI_CDROM_FIRSTSLOT + 0])
#define PyCD_New \
(*(PyObject*(*)(int))PyGAME_C_API[PYGAMEAPI_CDROM_FIRSTSLOT + 1])
#define import_pygame_cd() { \
PyObject *_module = PyImport_ImportModule(IMPPREFIX "cdrom"); \
if (_module != NULL) { \
PyObject *_dict = PyModule_GetDict(_module); \
PyObject *_c_api = PyDict_GetItemString(_dict, \
PYGAMEAPI_LOCAL_ENTRY); \
if(PyCObject_Check(_c_api)) { \
int i; void** localptr = (void**)PyCObject_AsVoidPtr(_c_api); \
for(i = 0; i < PYGAMEAPI_CDROM_NUMSLOTS; ++i) \
PyGAME_C_API[i + PYGAMEAPI_CDROM_FIRSTSLOT] = localptr[i]; \
} \
Py_DECREF(_module); \
} \
}
#endif
/* JOYSTICK */
#define PYGAMEAPI_JOYSTICK_FIRSTSLOT \
(PYGAMEAPI_CDROM_FIRSTSLOT + PYGAMEAPI_CDROM_NUMSLOTS)
#define PYGAMEAPI_JOYSTICK_NUMSLOTS 2
typedef struct {
PyObject_HEAD
int id;
} PyJoystickObject;
#define PyJoystick_AsID(x) (((PyJoystickObject*)x)->id)
#ifndef PYGAMEAPI_JOYSTICK_INTERNAL
#define PyJoystick_Check(x) \
((x)->ob_type == (PyTypeObject*) \
PyGAME_C_API[PYGAMEAPI_JOYSTICK_FIRSTSLOT + 0])
#define PyJoystick_Type \
(*(PyTypeObject*)PyGAME_C_API[PYGAMEAPI_JOYSTICK_FIRSTSLOT + 0])
#define PyJoystick_New \
(*(PyObject*(*)(int))PyGAME_C_API[PYGAMEAPI_JOYSTICK_FIRSTSLOT + 1])
#define import_pygame_joystick() { \
PyObject *_module = PyImport_ImportModule(IMPPREFIX "joystick"); \
if (_module != NULL) { \
PyObject *_dict = PyModule_GetDict(_module); \
PyObject *_c_api = PyDict_GetItemString(_dict, \
PYGAMEAPI_LOCAL_ENTRY); \
if(PyCObject_Check(_c_api)) { \
int i; void** localptr = (void**)PyCObject_AsVoidPtr(_c_api); \
for(i = 0; i < PYGAMEAPI_JOYSTICK_NUMSLOTS; ++i) \
PyGAME_C_API[i + PYGAMEAPI_JOYSTICK_FIRSTSLOT] = \
localptr[i]; \
} \
Py_DECREF(_module); \
} \
}
#endif
/* DISPLAY */
#define PYGAMEAPI_DISPLAY_FIRSTSLOT \
(PYGAMEAPI_JOYSTICK_FIRSTSLOT + PYGAMEAPI_JOYSTICK_NUMSLOTS)
#define PYGAMEAPI_DISPLAY_NUMSLOTS 2
typedef struct {
PyObject_HEAD
SDL_VideoInfo info;
} PyVidInfoObject;
#define PyVidInfo_AsVidInfo(x) (((PyVidInfoObject*)x)->info)
#ifndef PYGAMEAPI_DISPLAY_INTERNAL
#define PyVidInfo_Check(x) \
((x)->ob_type == (PyTypeObject*) \
PyGAME_C_API[PYGAMEAPI_DISPLAY_FIRSTSLOT + 0])
#define PyVidInfo_Type \
(*(PyTypeObject*)PyGAME_C_API[PYGAMEAPI_DISPLAY_FIRSTSLOT + 0])
#define PyVidInfo_New \
(*(PyObject*(*)(SDL_VideoInfo*)) \
PyGAME_C_API[PYGAMEAPI_DISPLAY_FIRSTSLOT + 1])
#define import_pygame_display() { \
PyObject *_module = PyImport_ImportModule(IMPPREFIX "display"); \
if (_module != NULL) { \
PyObject *_dict = PyModule_GetDict(_module); \
PyObject *_c_api = PyDict_GetItemString(_dict, \
PYGAMEAPI_LOCAL_ENTRY); \
if(PyCObject_Check(_c_api)) { \
int i; void** localptr = (void**)PyCObject_AsVoidPtr(_c_api); \
for(i = 0; i < PYGAMEAPI_DISPLAY_NUMSLOTS; ++i) \
PyGAME_C_API[i + PYGAMEAPI_DISPLAY_FIRSTSLOT] = \
localptr[i]; \
} \
Py_DECREF(_module); \
} \
}
#endif
/* SURFACE */
#define PYGAMEAPI_SURFACE_FIRSTSLOT \
(PYGAMEAPI_DISPLAY_FIRSTSLOT + PYGAMEAPI_DISPLAY_NUMSLOTS)
#define PYGAMEAPI_SURFACE_NUMSLOTS 3
typedef struct {
PyObject_HEAD
SDL_Surface* surf;
struct SubSurface_Data* subsurface; /*ptr to subsurface data (if a
* subsurface)*/
PyObject *weakreflist;
PyObject *locklist;
PyObject *dependency;
} PySurfaceObject;
#define PySurface_AsSurface(x) (((PySurfaceObject*)x)->surf)
#ifndef PYGAMEAPI_SURFACE_INTERNAL
#define PySurface_Check(x) \
((x)->ob_type == (PyTypeObject*) \
PyGAME_C_API[PYGAMEAPI_SURFACE_FIRSTSLOT + 0])
#define PySurface_Type \
(*(PyTypeObject*)PyGAME_C_API[PYGAMEAPI_SURFACE_FIRSTSLOT + 0])
#define PySurface_New \
(*(PyObject*(*)(SDL_Surface*)) \
PyGAME_C_API[PYGAMEAPI_SURFACE_FIRSTSLOT + 1])
#define PySurface_Blit \
(*(int(*)(PyObject*,PyObject*,SDL_Rect*,SDL_Rect*,int)) \
PyGAME_C_API[PYGAMEAPI_SURFACE_FIRSTSLOT + 2])
#define import_pygame_surface() do { \
PyObject *_module = PyImport_ImportModule(IMPPREFIX "surface"); \
if (_module != NULL) { \
PyObject *_dict = PyModule_GetDict(_module); \
PyObject *_c_api = PyDict_GetItemString(_dict, \
PYGAMEAPI_LOCAL_ENTRY); \
if(PyCObject_Check(_c_api)) { \
int i; void** localptr = (void**)PyCObject_AsVoidPtr(_c_api); \
for(i = 0; i < PYGAMEAPI_SURFACE_NUMSLOTS; ++i) \
PyGAME_C_API[i + PYGAMEAPI_SURFACE_FIRSTSLOT] = \
localptr[i]; \
} \
Py_DECREF(_module); \
} \
else \
{ \
break; \
} \
_module = PyImport_ImportModule(IMPPREFIX "surflock"); \
if (_module != NULL) { \
PyObject *_dict = PyModule_GetDict(_module); \
PyObject *_c_api = PyDict_GetItemString(_dict, \
PYGAMEAPI_LOCAL_ENTRY); \
if(PyCObject_Check(_c_api)) { \
int i; void** localptr = (void**)PyCObject_AsVoidPtr(_c_api); \
for(i = 0; i < PYGAMEAPI_SURFLOCK_NUMSLOTS; ++i) \
PyGAME_C_API[i + PYGAMEAPI_SURFLOCK_FIRSTSLOT] = \
localptr[i]; \
} \
Py_DECREF(_module); \
} \
} while (0)
#endif
/* SURFLOCK */ /*auto import/init by surface*/
#define PYGAMEAPI_SURFLOCK_FIRSTSLOT \
(PYGAMEAPI_SURFACE_FIRSTSLOT + PYGAMEAPI_SURFACE_NUMSLOTS)
#define PYGAMEAPI_SURFLOCK_NUMSLOTS 8
struct SubSurface_Data
{
PyObject* owner;
int pixeloffset;
int offsetx, offsety;
};
typedef struct
{
PyObject_HEAD
PyObject *surface;
PyObject *lockobj;
PyObject *weakrefs;
} PyLifetimeLock;
#ifndef PYGAMEAPI_SURFLOCK_INTERNAL
#define PyLifetimeLock_Check(x) \
((x)->ob_type == (PyTypeObject*) \
PyGAME_C_API[PYGAMEAPI_SURFLOCK_FIRSTSLOT + 0])
#define PySurface_Prep(x) \
if(((PySurfaceObject*)x)->subsurface) \
(*(*(void(*)(PyObject*)) \
PyGAME_C_API[PYGAMEAPI_SURFLOCK_FIRSTSLOT + 1]))(x)
#define PySurface_Unprep(x) \
if(((PySurfaceObject*)x)->subsurface) \
(*(*(void(*)(PyObject*)) \
PyGAME_C_API[PYGAMEAPI_SURFLOCK_FIRSTSLOT + 2]))(x)
#define PySurface_Lock \
(*(int(*)(PyObject*))PyGAME_C_API[PYGAMEAPI_SURFLOCK_FIRSTSLOT + 3])
#define PySurface_Unlock \
(*(int(*)(PyObject*))PyGAME_C_API[PYGAMEAPI_SURFLOCK_FIRSTSLOT + 4])
#define PySurface_LockBy \
(*(int(*)(PyObject*,PyObject*)) \
PyGAME_C_API[PYGAMEAPI_SURFLOCK_FIRSTSLOT + 5])
#define PySurface_UnlockBy \
(*(int(*)(PyObject*,PyObject*)) \
PyGAME_C_API[PYGAMEAPI_SURFLOCK_FIRSTSLOT + 6])
#define PySurface_LockLifetime \
(*(PyObject*(*)(PyObject*,PyObject*)) \
PyGAME_C_API[PYGAMEAPI_SURFLOCK_FIRSTSLOT + 7])
#endif
/* EVENT */
#define PYGAMEAPI_EVENT_FIRSTSLOT \
(PYGAMEAPI_SURFLOCK_FIRSTSLOT + PYGAMEAPI_SURFLOCK_NUMSLOTS)
#define PYGAMEAPI_EVENT_NUMSLOTS 4
typedef struct {
PyObject_HEAD
int type;
PyObject* dict;
} PyEventObject;
#ifndef PYGAMEAPI_EVENT_INTERNAL
#define PyEvent_Check(x) \
((x)->ob_type == (PyTypeObject*)PyGAME_C_API[PYGAMEAPI_EVENT_FIRSTSLOT + 0])
#define PyEvent_Type \
(*(PyTypeObject*)PyGAME_C_API[PYGAMEAPI_EVENT_FIRSTSLOT + 0])
#define PyEvent_New \
(*(PyObject*(*)(SDL_Event*))PyGAME_C_API[PYGAMEAPI_EVENT_FIRSTSLOT + 1])
#define PyEvent_New2 \
(*(PyObject*(*)(int, PyObject*))PyGAME_C_API[PYGAMEAPI_EVENT_FIRSTSLOT + 2])
#define PyEvent_FillUserEvent \
(*(int (*)(PyEventObject*, SDL_Event*)) \
PyGAME_C_API[PYGAMEAPI_EVENT_FIRSTSLOT + 3])
#define import_pygame_event() { \
PyObject *_module = PyImport_ImportModule(IMPPREFIX "event"); \
if (_module != NULL) { \
PyObject *_dict = PyModule_GetDict(_module); \
PyObject *_c_api = PyDict_GetItemString(_dict, \
PYGAMEAPI_LOCAL_ENTRY); \
if(PyCObject_Check(_c_api)) { \
int i; void** localptr = (void**)PyCObject_AsVoidPtr(_c_api); \
for(i = 0; i < PYGAMEAPI_EVENT_NUMSLOTS; ++i) \
PyGAME_C_API[i + PYGAMEAPI_EVENT_FIRSTSLOT] = localptr[i]; \
} \
Py_DECREF(_module); \
} \
}
#endif
/* RWOBJECT */
/*the rwobject are only needed for C side work, not accessable from python*/
#define PYGAMEAPI_RWOBJECT_FIRSTSLOT \
(PYGAMEAPI_EVENT_FIRSTSLOT + PYGAMEAPI_EVENT_NUMSLOTS)
#define PYGAMEAPI_RWOBJECT_NUMSLOTS 4
#ifndef PYGAMEAPI_RWOBJECT_INTERNAL
#define RWopsFromPython \
(*(SDL_RWops*(*)(PyObject*))PyGAME_C_API[PYGAMEAPI_RWOBJECT_FIRSTSLOT + 0])
#define RWopsCheckPython \
(*(int(*)(SDL_RWops*))PyGAME_C_API[PYGAMEAPI_RWOBJECT_FIRSTSLOT + 1])
#define RWopsFromPythonThreaded \
(*(SDL_RWops*(*)(PyObject*))PyGAME_C_API[PYGAMEAPI_RWOBJECT_FIRSTSLOT + 2])
#define RWopsCheckPythonThreaded \
(*(int(*)(SDL_RWops*))PyGAME_C_API[PYGAMEAPI_RWOBJECT_FIRSTSLOT + 3])
#define import_pygame_rwobject() { \
PyObject *_module = PyImport_ImportModule(IMPPREFIX "rwobject"); \
if (_module != NULL) { \
PyObject *_dict = PyModule_GetDict(_module); \
PyObject *_c_api = PyDict_GetItemString(_dict, \
PYGAMEAPI_LOCAL_ENTRY); \
if(PyCObject_Check(_c_api)) { \
int i; void** localptr = (void**)PyCObject_AsVoidPtr(_c_api); \
for(i = 0; i < PYGAMEAPI_RWOBJECT_NUMSLOTS; ++i) \
PyGAME_C_API[i + PYGAMEAPI_RWOBJECT_FIRSTSLOT] = \
localptr[i]; \
} \
Py_DECREF(_module); \
} \
}
#endif
/* BufferProxy */
typedef struct
{
PyObject_HEAD
PyObject *dict; /* dict for subclassing */
PyObject *weakrefs; /* Weakrefs for subclassing */
void *buffer; /* Pointer to the buffer of the parent object. */
Py_ssize_t length; /* Length of the buffer. */
PyObject *parent; /* Parent object associated with this object. */
PyObject *lock; /* Lock object for the surface. */
} PyBufferProxy;
#define PYGAMEAPI_BUFFERPROXY_FIRSTSLOT \
(PYGAMEAPI_RWOBJECT_FIRSTSLOT + PYGAMEAPI_RWOBJECT_NUMSLOTS)
#define PYGAMEAPI_BUFFERPROXY_NUMSLOTS 2
#ifndef PYGAMEAPI_BUFFERPROXY_INTERNAL
#define PyBufferProxy_Check(x) \
((x)->ob_type == (PyTypeObject*) \
PyGAME_C_API[PYGAMEAPI_BUFFERPROXY_FIRSTSLOT + 0])
#define PyBufferProxy_New \
(*(PyObject*(*)(PyObject*, void*, Py_ssize_t, PyObject*)) \
PyGAME_C_API[PYGAMEAPI_BUFFERPROXY_FIRSTSLOT + 1])
#define import_pygame_bufferproxy() \
{ \
PyObject *_module = PyImport_ImportModule (IMPPREFIX "bufferproxy");\
if (_module != NULL) \
{ \
PyObject *_dict = PyModule_GetDict (_module); \
PyObject *_c_api = PyDict_GetItemString \
(_dict, PYGAMEAPI_LOCAL_ENTRY); \
if (PyCObject_Check (_c_api)) \
{ \
int i; \
void** localptr = (void**) PyCObject_AsVoidPtr (_c_api); \
for (i = 0; i < PYGAMEAPI_BUFFERPROXY_NUMSLOTS; ++i) \
PyGAME_C_API[i + PYGAMEAPI_BUFFERPROXY_FIRSTSLOT] = \
localptr[i]; \
} \
Py_DECREF (_module); \
} \
}
#endif /* PYGAMEAPI_BUFFERPROXY_INTERNAL */
/* PixelArray */
#define PYGAMEAPI_PIXELARRAY_FIRSTSLOT \
(PYGAMEAPI_BUFFERPROXY_FIRSTSLOT + PYGAMEAPI_BUFFERPROXY_NUMSLOTS)
#define PYGAMEAPI_PIXELARRAY_NUMSLOTS 2
#ifndef PYGAMEAPI_PIXELARRAY_INTERNAL
#define PyPixelArray_Check(x) \
((x)->ob_type == (PyTypeObject*) \
PyGAME_C_API[PYGAMEAPI_PIXELARRAY_FIRSTSLOT + 0])
#define PyPixelArray_New \
(*(PyObject*(*)) PyGAME_C_API[PYGAMEAPI_PIXELARRAY_FIRSTSLOT + 1])
#define import_pygame_pixelarray() \
{ \
PyObject *_module = PyImport_ImportModule (IMPPREFIX "pixelarray"); \
if (_module != NULL) \
{ \
PyObject *_dict = PyModule_GetDict (_module); \
PyObject *_c_api = PyDict_GetItemString \
(_dict, PYGAMEAPI_LOCAL_ENTRY); \
if (PyCObject_Check (_c_api)) \
{ \
int i; \
void** localptr = (void**) PyCObject_AsVoidPtr (_c_api); \
for (i = 0; i < PYGAMEAPI_PIXELARRAY_NUMSLOTS; ++i) \
PyGAME_C_API[i + PYGAMEAPI_PIXELARRAY_FIRSTSLOT] = \
localptr[i]; \
} \
Py_DECREF (_module); \
} \
}
#endif /* PYGAMEAPI_PIXELARRAY_INTERNAL */
/* Color */
#define PYGAMEAPI_COLOR_FIRSTSLOT \
(PYGAMEAPI_PIXELARRAY_FIRSTSLOT + PYGAMEAPI_PIXELARRAY_NUMSLOTS)
#define PYGAMEAPI_COLOR_NUMSLOTS 4
#ifndef PYGAMEAPI_COLOR_INTERNAL
#define PyColor_Check(x) \
((x)->ob_type == (PyTypeObject*) \
PyGAME_C_API[PYGAMEAPI_COLOR_FIRSTSLOT + 0])
#define PyColor_New \
(*(PyObject *(*)(Uint8*)) PyGAME_C_API[PYGAMEAPI_COLOR_FIRSTSLOT + 1])
#define PyColor_NewLength \
(*(PyObject *(*)(Uint8*, Uint8)) PyGAME_C_API[PYGAMEAPI_COLOR_FIRSTSLOT + 3])
#define RGBAFromColorObj \
(*(int(*)(PyObject*, Uint8*)) PyGAME_C_API[PYGAMEAPI_COLOR_FIRSTSLOT + 2])
#define import_pygame_color() \
{ \
PyObject *_module = PyImport_ImportModule (IMPPREFIX "color"); \
if (_module != NULL) \
{ \
PyObject *_dict = PyModule_GetDict (_module); \
PyObject *_c_api = PyDict_GetItemString \
(_dict, PYGAMEAPI_LOCAL_ENTRY); \
if (PyCObject_Check (_c_api)) \
{ \
int i; \
void** localptr = (void**) PyCObject_AsVoidPtr (_c_api); \
for (i = 0; i < PYGAMEAPI_COLOR_NUMSLOTS; ++i) \
PyGAME_C_API[i + PYGAMEAPI_COLOR_FIRSTSLOT] = \
localptr[i]; \
} \
Py_DECREF (_module); \
} \
}
#endif /* PYGAMEAPI_COLOR_INTERNAL */
#ifndef NO_PYGAME_C_API
#define PYGAMEAPI_TOTALSLOTS \
(PYGAMEAPI_COLOR_FIRSTSLOT + PYGAMEAPI_COLOR_NUMSLOTS)
static void* PyGAME_C_API[PYGAMEAPI_TOTALSLOTS] = { NULL };
#endif
/*last platform compiler stuff*/
#if defined(macintosh) && defined(__MWERKS__) || defined(__SYMBIAN32__)
#define PYGAME_EXPORT __declspec(export)
#else
#define PYGAME_EXPORT
#endif
#if defined(__SYMBIAN32__) && PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION == 2
// These are missing from Python 2.2
#ifndef Py_RETURN_NONE
#define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None
#define Py_RETURN_TRUE return Py_INCREF(Py_True), Py_True
#define Py_RETURN_FALSE return Py_INCREF(Py_False), Py_False
#ifndef intrptr_t
#define intptr_t int
// No PySlice_GetIndicesEx on Py 2.2
#define PySlice_GetIndicesEx(a,b,c,d,e,f) PySlice_GetIndices(a,b,c,d,e)
#define PyBool_FromLong(x) Py_BuildValue("b", x)
#endif
// _symport_free and malloc are not exported in python.dll
// See http://discussion.forum.nokia.com/forum/showthread.php?t=57874
#undef PyObject_NEW
#define PyObject_NEW PyObject_New
#undef PyMem_MALLOC
#define PyMem_MALLOC PyMem_Malloc
#undef PyObject_DEL
#define PyObject_DEL PyObject_Del
#endif // intptr_t
#endif // __SYMBIAN32__ Python 2.2.2
#endif /* PYGAME_H */
pygame-1.9.1release/src/pygame.doc 0000644 0001750 0001750 00000010754 11176715722 017023 0 ustar vincent vincent pygame
the top level pygame package
The pygame package represents the top-level package for others to use. Pygame
itself is broken into many submodules, but this does not affect programs that
use Pygame.
As a convenience, most of the top-level variables in pygame have been placed
inside a module named 'pygame.locals'. This is meant to be used with
'from pygame.locals import *', in addition to 'import pygame'.
When you 'import pygame' all available pygame submodules are automatically
imported. Be aware that some of the pygame modules are considered "optional",
and may not be available. In that case, Pygame will provide a placeholder object
instead of the module, which can be used to test for availability.
init
initialize all imported pygame modules
pygame.init(): return (numpass, numfail)
Initialize all imported Pygame modules. No exceptions will be raised if a
module fails, but the total number if successful and failed inits will be
returned as a tuple. You can always initialize individual modules manually,
but pygame.init is a convenient way to get everything started. The init()
functions for individual modules will raise exceptions when they fail.
You may want to initalise the different modules seperately to speed up
your program or to not use things your game does not.
It is safe to call this init() more than once: repeated calls will have no effect.
This is true even if you have pygame.quit() all the modules.
quit
uninitialize all pygame modules
pygame.quit(): return None
Uninitialize all pygame modules that have previously been initialized. When
the Python interpreter shuts down, this method is called regardless, so your
program should not need it, except when it wants to terminate its pygame
resources and continue. It is safe to call this function more than once:
repeated calls have no effect.
Note, that pygame.quit will not exit your program. Consider letting your
program end in the same way a normal python program will end.
error
standard pygame exception
raise pygame.error, message
This exception is raised whenever a pygame or SDL operation fails. You can
catch any anticipated problems and deal with the error. The exception is
always raised with a descriptive message about the problem.
Derived from the RuntimeError exception, which can also be used to catch these
raised errors.
get_error
get the current error message
pygame.get_error(): return errorstr
SDL maintains an internal error message. This message will usually be given to
you when pygame.error is raised. You will rarely need to call this function.
set_error
set the current error message
pygame.set_error(error_msg): return None
SDL maintains an internal error message. This message will usually be given to
you when pygame.error is raised. You will rarely need to call this function.
get_sdl_version
get the version number of SDL
pygame.get_sdl_version(): return major, minor, patch
Returns the three version numbers of the SDL library. This version is
built at compile time. It can be used to detect which features may not
be available through Pygame.
get_sdl_version is new in pygame 1.7.0
get_sdl_byteorder
get the byte order of SDL
pygame.get_sdl_byteorder(): return int
Returns the byte order of the SDL library. It returns LIL_ENDIAN for
little endian byte order and BIG_ENDIAN for big endian byte order.
get_sdl_byteorder is new in pygame 1.8
register_quit
register a function to be called when pygame quits
register_quit(callable): return None
When pygame.quit is called, all registered quit functions are called. Pygame
modules do this automatically when they are initializing. This function is
not be needed for regular pygame users.
version
small module containing version information
module pygame.version
This module is automatically imported into the pygame package and offers a
few variables to check with version of pygame has been imported.
ver
version number as a string
pygame.version.ver = '1.2'
This is the version represented as a string. It can contain a micro release
number as well, e.g., '1.5.2'
vernum
tupled integers of the version
pygame.version.vernum = (1, 5, 3)
This variable for the version can easily be compared with other version
numbers of the same format. An example of checking Pygame version numbers
would look like this:
if pygame.version.vernum < (1, 5):
print 'Warning, older version of Pygame (%s)' % pygame.version.ver
disable_advanced_features = True
pygame-1.9.1release/src/pixelarray_methods.c 0000644 0001750 0001750 00000111440 11207055754 021110 0 ustar vincent vincent /*
pygame - Python Game Library
Copyright (C) 2007-2008 Marcus von Appen
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* Simple weighted euclidian distance, which tries to get near to the
* human eye reception using the weights.
* It receives RGB values in the range 0-255 and returns a distance
* value between 0.0 and 1.0.
*/
#define COLOR_DIFF_RGB(wr,wg,wb,r1,g1,b1,r2,g2,b2) \
(sqrt (wr * (r1 - r2) * (r1 - r2) + \
wg * (g1 - g2) * (g1 - g2) + \
wb * (b1 - b2) * (b1 - b2)) / 255.0)
#define WR_NTSC 0.299
#define WG_NTSC 0.587
#define WB_NTSC 0.114
/**
* Tries to retrieve a valid color for a Surface.
*/
static int
_get_color_from_object (PyObject *val, SDL_PixelFormat *format, Uint32 *color)
{
Uint8 rgba[4];
if (!val)
return 0;
if (PyInt_Check (val))
{
long intval = PyInt_AsLong (val);
if (intval == -1 && PyErr_Occurred ())
{
PyErr_SetString (PyExc_ValueError, "invalid color argument");
return 0;
}
*color = (Uint32) intval;
return 1;
}
else if (PyLong_Check (val))
{
unsigned long longval = PyLong_AsUnsignedLong (val);
if (PyErr_Occurred ())
{
PyErr_SetString(PyExc_ValueError, "invalid color argument");
return 0;
}
*color = (Uint32) longval;
return 1;
}
else if (RGBAFromColorObj (val, rgba))
{
*color = (Uint32) SDL_MapRGBA
(format, rgba[0], rgba[1], rgba[2], rgba[3]);
return 1;
}
else
PyErr_SetString (PyExc_ValueError, "invalid color argument");
return 0;
}
/**
* Retrieves a single pixel located at index from the surface pixel
* array.
*/
static PyObject*
_get_single_pixel (Uint8 *pixels, int bpp, Uint32 _index, Uint32 row)
{
Uint32 pixel;
switch (bpp)
{
case 1:
pixel = (Uint32)*((Uint8 *) pixels + row + _index);
break;
case 2:
pixel = (Uint32)*((Uint16 *) (pixels + row) + _index);
break;
case 3:
{
Uint8 *px = ((Uint8 *) (pixels + row) + _index * 3);
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
pixel = (px[0]) + (px[1] << 8) + (px[2] << 16);
#else
pixel = (px[2]) + (px[1] << 8) + (px[0] << 16);
#endif
break;
}
default: /* 4 bpp */
pixel = *((Uint32 *) (pixels + row) + _index);
break;
}
return PyInt_FromLong ((long)pixel);
}
/**
* Sets a single pixel located at index from the surface pixel array.
*/
static void
_set_single_pixel (Uint8 *pixels, int bpp, Uint32 _index, Uint32 row,
SDL_PixelFormat *format, Uint32 color)
{
switch (bpp)
{
case 1:
*((Uint8 *) pixels + row + _index) = (Uint8) color;
break;
case 2:
*((Uint16 *) (pixels + row) + _index) = (Uint16) color;
break;
case 3:
#if (SDL_BYTEORDER == SDL_LIL_ENDIAN)
*((Uint8 *) (pixels + row) + _index * 3 + (format->Rshift >> 3)) =
(Uint8) (color >> 16);
*((Uint8 *) (pixels + row) + _index * 3 + (format->Gshift >> 3)) =
(Uint8) (color >> 8);
*((Uint8 *) (pixels + row) + _index * 3 + (format->Bshift >> 3)) =
(Uint8) color;
#else
*((Uint8 *) (pixels + row) + _index * 3 + 2 - (format->Rshift >> 3)) =
(Uint8) (color >> 16);
*((Uint8 *) (pixels + row) + _index * 3 + 2 - (format->Gshift >> 3)) =
(Uint8) (color >> 8);
*((Uint8 *) (pixels + row) + _index * 3 + 2 - (format->Bshift >> 3)) =
(Uint8) color;
#endif
break;
default: /* 4 bpp */
*((Uint32 *) (pixels + row) + _index) = color;
break;
}
}
/**
* Creates a new surface using the currently applied dimensions, step
* size, etc.
*/
static PyObject*
_make_surface(PyPixelArray *array)
{
PyObject *newsf;
SDL_Surface *tmpsf;
SDL_Surface *newsurf;
Uint8 *pixels;
Uint8 *origpixels;
SDL_Surface *surface;
int bpp;
Uint32 x = 0;
Uint32 y = 0;
Uint32 vx = 0;
Uint32 vy = 0;
Uint32 posx = 0;
Uint32 posy = 0;
Uint32 absxstep;
Uint32 absystep;
surface = PySurface_AsSurface (array->surface);
bpp = surface->format->BytesPerPixel;
/* Create the second surface. */
tmpsf = SDL_CreateRGBSurface (surface->flags,
(int) (array->xlen / ABS (array->xstep)),
(int) (array->ylen / ABS (array->ystep)), bpp, surface->format->Rmask,
surface->format->Gmask, surface->format->Bmask, surface->format->Amask);
if (!tmpsf)
return RAISE (PyExc_SDLError, SDL_GetError ());
/* Guarantee an identical format. */
newsurf = SDL_ConvertSurface (tmpsf, surface->format, surface->flags);
if (!newsurf)
{
SDL_FreeSurface (tmpsf);
return RAISE (PyExc_SDLError, SDL_GetError ());
}
SDL_FreeSurface (tmpsf);
newsf = PySurface_New (newsurf);
if (!newsf)
{
SDL_FreeSurface (newsurf);
return NULL;
}
/* Acquire a temporary lock. */
if (SDL_MUSTLOCK (newsurf) == 0)
SDL_LockSurface (newsurf);
pixels = (Uint8 *) newsurf->pixels;
origpixels = (Uint8 *) surface->pixels;
absxstep = ABS (array->xstep);
absystep = ABS (array->ystep);
y = array->ystart;
Py_BEGIN_ALLOW_THREADS;
/* Single value assignment. */
switch (bpp)
{
case 1:
while (posy < array->ylen)
{
vx = 0;
x = array->xstart;
posx = 0;
while (posx < array->xlen)
{
*((Uint8 *) pixels + vy * newsurf->pitch + vx) =
(Uint8)*((Uint8 *) origpixels + y * array->padding + x);
vx++;
x += array->xstep;
posx += absxstep;
}
vy++;
y += array->ystep;
posy += absystep;
}
break;
case 2:
while (posy < array->ylen)
{
vx = 0;
x = array->xstart;
posx = 0;
while (posx < array->xlen)
{
*((Uint16 *) (pixels + vy * newsurf->pitch) + vx) =
(Uint16)*((Uint16 *) (origpixels + y * array->padding) + x);
vx++;
x += array->xstep;
posx += absxstep;
}
vy++;
y += array->ystep;
posy += absystep;
}
break;
case 3:
{
Uint8 *px;
Uint8 *vpx;
SDL_PixelFormat *format = newsurf->format;
SDL_PixelFormat *vformat = surface->format;
while (posy < array->ylen)
{
vx = 0;
x = array->xstart;
posx = 0;
while (posx < array->xlen)
{
px = ((Uint8 *) (pixels + vy * newsurf->pitch) + vx * 3);
vpx = ((Uint8 *) (origpixels + y * array->padding) + x * 3);
#if (SDL_BYTEORDER == SDL_LIL_ENDIAN)
*(px + (format->Rshift >> 3)) =
*(vpx + (vformat->Rshift >> 3));
*(px + (format->Gshift >> 3)) =
*(vpx + (vformat->Gshift >> 3));
*(px + (format->Bshift >> 3)) =
*(vpx + (vformat->Bshift >> 3));
#else
*(px + 2 - (format->Rshift >> 3)) =
*(vpx + 2 - (vformat->Rshift >> 3));
*(px + 2 - (format->Gshift >> 3)) =
*(vpx + 2 - (vformat->Gshift >> 3));
*(px + 2 - (format->Bshift >> 3)) =
*(vpx + 2 - (vformat->Bshift >> 3));
#endif
vx++;
x += array->xstep;
posx += absxstep;
}
vy++;
y += array->ystep;
posy += absystep;
}
break;
}
default:
while (posy < array->ylen)
{
vx = 0;
x = array->xstart;
posx = 0;
while (posx < array->xlen)
{
*((Uint32 *) (pixels + vy * newsurf->pitch) + vx) =
(Uint32)*((Uint32 *) (origpixels + y * array->padding) + x);
vx++;
x += array->xstep;
posx += absxstep;
}
vy++;
y += array->ystep;
posy += absystep;
}
break;
}
Py_END_ALLOW_THREADS;
if (SDL_MUSTLOCK (newsurf) == 0)
SDL_UnlockSurface (newsurf);
return newsf;
}
static int
_get_weights (PyObject *weights, float *wr, float *wg, float *wb)
{
int success = 1;
float rgb[3] = { 0 };
if (!weights)
{
*wr = WR_NTSC;
*wg = WG_NTSC;
*wb = WB_NTSC;
return 1;
}
if (!PySequence_Check (weights))
{
PyErr_SetString (PyExc_TypeError, "weights must be a sequence");
success = 0;
}
else if (PySequence_Size (weights) < 3)
{
PyErr_SetString (PyExc_TypeError,
"weights must contain at least 3 values");
success = 0;
}
else
{
PyObject *item;
int i;
for (i = 0; i < 3; i++)
{
item = PySequence_GetItem (weights, i);
if (PyNumber_Check (item))
{
PyObject *num = NULL;
if ((num = PyNumber_Float (item)) != NULL)
{
rgb[i] = (float) PyFloat_AsDouble (num);
Py_DECREF (num);
}
else if ((num = PyNumber_Int (item)) != NULL)
{
rgb[i] = (float) PyInt_AsLong (num);
if (rgb[i] == -1 && PyErr_Occurred ())
success = 0;
Py_DECREF (num);
}
else if ((num = PyNumber_Long (item)) != NULL)
{
rgb[i] = (float) PyLong_AsLong (num);
if (PyErr_Occurred () &&
PyErr_ExceptionMatches (PyExc_OverflowError))
success = 0;
Py_DECREF (num);
}
}
else
{
PyErr_SetString (PyExc_TypeError, "invalid weights");
success = 0;
}
Py_XDECREF (item);
if (!success)
break;
}
}
if (success)
{
float sum = 0;
*wr = rgb[0];
*wg = rgb[1];
*wb = rgb[2];
if ((*wr < 0 || *wg < 0 || *wb < 0) ||
(*wr == 0 && *wg == 0 && *wb == 0))
{
PyErr_SetString (PyExc_ValueError,
"weights must be positive and greater than 0");
return 0;
}
/* Build the average weight values. */
sum = *wr + *wg + *wb;
*wr = *wr / sum;
*wg = *wg / sum;
*wb = *wb / sum;
return success;
}
return 0;
}
static PyObject*
_replace_color (PyPixelArray *array, PyObject *args, PyObject *kwds)
{
PyObject *weights = NULL;
PyObject *delcolor = NULL;
PyObject *replcolor = NULL;
Uint32 dcolor;
Uint32 rcolor;
Uint8 r1, g1, b1, r2, g2, b2, a2;
SDL_Surface *surface;
float distance = 0;
float wr, wg, wb;
Uint32 x = 0;
Uint32 y = 0;
Uint32 posx = 0;
Uint32 posy = 0;
Sint32 absxstep;
Sint32 absystep;
Uint8 *pixels;
static char *keys[] = { "color", "repcolor", "distance", "weights", NULL };
if (!PyArg_ParseTupleAndKeywords (args, kwds, "OO|fO", keys, &delcolor,
&replcolor, &distance, &weights))
return NULL;
if (distance < 0 || distance > 1)
return RAISE (PyExc_ValueError,
"distance must be in the range from 0.0 to 1.0");
surface = PySurface_AsSurface (array->surface);
if (!_get_color_from_object (delcolor, surface->format, &dcolor) ||
!_get_color_from_object (replcolor, surface->format, &rcolor))
return NULL;
if (!_get_weights (weights, &wr, &wg, &wb))
return NULL;
surface = PySurface_AsSurface (array->surface);
pixels = surface->pixels;
absxstep = ABS (array->xstep);
absystep = ABS (array->ystep);
y = array->ystart;
if (distance)
SDL_GetRGB (dcolor, surface->format, &r1, &g1, &b1);
Py_BEGIN_ALLOW_THREADS;
switch (surface->format->BytesPerPixel)
{
case 1:
{
Uint8 *pixel;
while (posy < array->ylen)
{
x = array->xstart;
posx = 0;
while (posx < array->xlen)
{
pixel = ((Uint8 *) pixels + y * surface->pitch + x);
if (distance)
{
GET_PIXELVALS_1 (r2, g2, b2, a2, pixel, surface->format);
if (COLOR_DIFF_RGB (wr, wg, wb, r1, g1, b1, r2, g2, b2) <=
distance)
*pixel = (Uint8) rcolor;
}
else if (*pixel == dcolor)
*pixel = (Uint8) rcolor;
x += array->xstep;
posx += absxstep;
}
y += array->ystep;
posy += absystep;
}
break;
}
case 2:
{
Uint16 *pixel;
int ppa = (surface->flags & SDL_SRCALPHA &&
surface->format->Amask);
while (posy < array->ylen)
{
x = array->xstart;
posx = 0;
while (posx < array->xlen)
{
pixel = ((Uint16 *) (pixels + y * surface->pitch) + x);
if (distance)
{
GET_PIXELVALS (r2, g2, b2, a2, (Uint32) *pixel,
surface->format, ppa);
if (COLOR_DIFF_RGB (wr, wg, wb, r1, g1, b1, r2, g2, b2) <=
distance)
*pixel = (Uint16) rcolor;
}
else if (*pixel == dcolor)
*pixel = (Uint16) rcolor;
x += array->xstep;
posx += absxstep;
}
y += array->ystep;
posy += absystep;
}
break;
}
case 3:
{
Uint8 *px;
Uint32 pxcolor;
SDL_PixelFormat *format = surface->format;
int ppa = (surface->flags & SDL_SRCALPHA && format->Amask);
while (posy < array->ylen)
{
x = array->xstart;
posx = 0;
while (posx < array->xlen)
{
px = ((Uint8 *) (pixels + y * surface->pitch) + x * 3);
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
pxcolor = (px[0]) + (px[1] << 8) + (px[2] << 16);
if (distance)
{
GET_PIXELVALS (r2, g2, b2, a2, pxcolor, format, ppa);
if (COLOR_DIFF_RGB (wr, wg, wb, r1, g1, b1, r2, g2, b2) <=
distance)
{
*(px + (format->Rshift >> 3)) = (Uint8) (rcolor >> 16);
*(px + (format->Gshift >> 3)) = (Uint8) (rcolor >> 8);
*(px + (format->Bshift >> 3)) = (Uint8) rcolor;
}
}
else if (pxcolor == dcolor)
{
*(px + (format->Rshift >> 3)) = (Uint8) (rcolor >> 16);
*(px + (format->Gshift >> 3)) = (Uint8) (rcolor >> 8);
*(px + (format->Bshift >> 3)) = (Uint8) rcolor;
}
#else
pxcolor = (px[2]) + (px[1] << 8) + (px[0] << 16);
if (distance)
{
GET_PIXELVALS (r2, g2, b2, a2, pxcolor, format, ppa);
if (COLOR_DIFF_RGB (wr, wg, wb, r1, g1, b1, r2, g2, b2) <=
distance)
{
*(px + 2 - (format->Rshift >> 3)) =
(Uint8) (rcolor >> 16);
*(px + 2 - (format->Gshift >> 3)) =
(Uint8) (rcolor >> 8);
*(px + 2 - (format->Bshift >> 3)) = (Uint8) rcolor;
}
}
else if (pxcolor == dcolor)
{
*(px + 2 - (format->Rshift >> 3)) = (Uint8) (rcolor >> 16);
*(px + 2 - (format->Gshift >> 3)) = (Uint8) (rcolor >> 8);
*(px + 2 - (format->Bshift >> 3)) = (Uint8) rcolor;
}
#endif
x += array->xstep;
posx += absxstep;
}
y += array->ystep;
posy += absystep;
}
break;
}
default:
{
Uint32 *pixel;
int ppa = (surface->flags & SDL_SRCALPHA &&
surface->format->Amask);
while (posy < array->ylen)
{
x = array->xstart;
posx = 0;
while (posx < array->xlen)
{
pixel = ((Uint32 *) (pixels + y * surface->pitch) + x);
if (distance)
{
GET_PIXELVALS (r2, g2, b2, a2, *pixel,
surface->format, ppa);
if (COLOR_DIFF_RGB (wr, wg, wb, r1, g1, b1, r2, g2, b2) <=
distance)
*pixel = rcolor;
}
else if (*pixel == dcolor)
*pixel = rcolor;
x += array->xstep;
posx += absxstep;
}
y += array->ystep;
posy += absystep;
}
break;
}
}
Py_END_ALLOW_THREADS;
Py_RETURN_NONE;
}
static PyObject*
_extract_color (PyPixelArray *array, PyObject *args, PyObject *kwds)
{
PyObject *weights = NULL;
PyObject *sf = NULL;
PyObject *excolor = NULL;
PyPixelArray *newarray = NULL;
Uint32 color;
Uint32 white;
Uint32 black;
SDL_Surface *surface;
float distance = 0;
float wr, wg, wb;
Uint8 r1, g1, b1, r2, g2, b2, a2;
Uint32 x = 0;
Uint32 y = 0;
Uint32 posx = 0;
Uint32 posy = 0;
Sint32 absxstep;
Sint32 absystep;
Uint8 *pixels;
static char *keys[] = { "color", "distance", "weights", NULL };
if (!PyArg_ParseTupleAndKeywords (args, kwds, "O|fO", keys, &excolor,
&distance, &weights))
return NULL;
if (distance < 0 || distance > 1)
return RAISE (PyExc_ValueError,
"distance must be in the range from 0.0 to 1.0");
if (!_get_weights (weights, &wr, &wg, &wb))
return NULL;
surface = PySurface_AsSurface (array->surface);
if (!_get_color_from_object (excolor, surface->format, &color))
return NULL;
/* Create the b/w mask surface. */
sf = _make_surface (array);
if (!sf)
return NULL;
newarray = (PyPixelArray *) PyPixelArray_New (sf);
if (!newarray)
{
Py_DECREF (sf);
return NULL;
}
surface = PySurface_AsSurface (newarray->surface);
black = SDL_MapRGBA (surface->format, 0, 0, 0, 255);
white = SDL_MapRGBA (surface->format, 255, 255, 255, 255);
if (distance)
SDL_GetRGB (color, surface->format, &r1, &g1, &b1);
pixels = surface->pixels;
absxstep = ABS (newarray->xstep);
absystep = ABS (newarray->ystep);
y = newarray->ystart;
Py_BEGIN_ALLOW_THREADS;
switch (surface->format->BytesPerPixel)
{
case 1:
{
Uint8 *pixel;
while (posy < newarray->ylen)
{
x = newarray->xstart;
posx = 0;
while (posx < newarray->xlen)
{
pixel = ((Uint8 *) pixels + y * surface->pitch + x);
if (distance)
{
GET_PIXELVALS_1 (r2, g2, b2, a2, pixel, surface->format);
if (COLOR_DIFF_RGB (wr, wg, wb, r1, g1, b1, r2, g2, b2) <=
distance)
*pixel = (Uint8) white;
else
*pixel = (Uint8) black;
}
else
*pixel = (*pixel == color) ? (Uint8) white : (Uint8) black;
x += newarray->xstep;
posx += absxstep;
}
y += newarray->ystep;
posy += absystep;
}
break;
}
case 2:
{
Uint16 *pixel;
int ppa = (surface->flags & SDL_SRCALPHA &&
surface->format->Amask);
while (posy < newarray->ylen)
{
x = newarray->xstart;
posx = 0;
while (posx < newarray->xlen)
{
pixel = ((Uint16 *) (pixels + y * surface->pitch) + x);
if (distance)
{
GET_PIXELVALS (r2, g2, b2, a2, (Uint32) *pixel,
surface->format, ppa);
if (COLOR_DIFF_RGB (wr, wg, wb, r1, g1, b1, r2, g2, b2) <=
distance)
*pixel = (Uint16) white;
else
*pixel = (Uint16) black;
}
else
*pixel = (*pixel == color) ? (Uint16) white :
(Uint16) black;
x += newarray->xstep;
posx += absxstep;
}
y += newarray->ystep;
posy += absystep;
}
break;
}
case 3:
{
Uint8 *px;
Uint32 pxcolor;
SDL_PixelFormat *format = surface->format;
int ppa = (surface->flags & SDL_SRCALPHA && format->Amask);
while (posy < newarray->ylen)
{
x = newarray->xstart;
posx = 0;
while (posx < newarray->xlen)
{
px = ((Uint8 *) (pixels + y * surface->pitch) + x * 3);
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
pxcolor = (px[0]) + (px[1] << 8) + (px[2] << 16);
if (distance)
{
GET_PIXELVALS (r2, g2, b2, a2, pxcolor, format, ppa);
if (COLOR_DIFF_RGB (wr, wg, wb, r1, g1, b1, r2, g2, b2) <=
distance)
{
*(px + (format->Rshift >> 3)) = (Uint8) (white >> 16);
*(px + (format->Gshift >> 3)) = (Uint8) (white >> 8);
*(px + (format->Bshift >> 3)) = (Uint8) white;
}
else
{
*(px + (format->Rshift >> 3)) = (Uint8) (black >> 16);
*(px + (format->Gshift >> 3)) = (Uint8) (black >> 8);
*(px + (format->Bshift >> 3)) = (Uint8) black;
}
}
else if (pxcolor == color)
{
*(px + (format->Rshift >> 3)) = (Uint8) (white >> 16);
*(px + (format->Gshift >> 3)) = (Uint8) (white >> 8);
*(px + (format->Bshift >> 3)) = (Uint8) white;
}
else
{
*(px + (format->Rshift >> 3)) = (Uint8) (black >> 16);
*(px + (format->Gshift >> 3)) = (Uint8) (black >> 8);
*(px + (format->Bshift >> 3)) = (Uint8) black;
}
#else
pxcolor = (px[2]) + (px[1] << 8) + (px[0] << 16);
if (distance)
{
GET_PIXELVALS (r2, g2, b2, a2, pxcolor, format, ppa);
if (COLOR_DIFF_RGB (wr, wg, wb, r1, g1, b1, r2, g2, b2) <=
distance)
{
*(px + 2 - (format->Rshift >> 3)) =
(Uint8) (white >> 16);
*(px + 2 - (format->Gshift >> 3)) =
(Uint8) (white >> 8);
*(px + 2 - (format->Bshift >> 3)) = (Uint8) white;
}
else
{
*(px + 2 - (format->Rshift >> 3)) =
(Uint8) (black >> 16);
*(px + 2 - (format->Gshift >> 3)) =
(Uint8) (black >> 8);
*(px + 2 - (format->Bshift >> 3)) = (Uint8) black;
}
}
else if (pxcolor == color)
{
*(px + 2 - (format->Rshift >> 3)) = (Uint8) (white >> 16);
*(px + 2 - (format->Gshift >> 3)) = (Uint8) (white >> 8);
*(px + 2 - (format->Bshift >> 3)) = (Uint8) white;
}
else
{
*(px + 2 - (format->Rshift >> 3)) = (Uint8) (black >> 16);
*(px + 2 - (format->Gshift >> 3)) = (Uint8) (black >> 8);
*(px + 2 - (format->Bshift >> 3)) = (Uint8) black;
}
#endif
x += newarray->xstep;
posx += absxstep;
}
y += newarray->ystep;
posy += absystep;
}
break;
}
default:
{
Uint32 *pixel;
int ppa = (surface->flags & SDL_SRCALPHA &&
surface->format->Amask);
while (posy < newarray->ylen)
{
x = newarray->xstart;
posx = 0;
while (posx < newarray->xlen)
{
pixel = ((Uint32 *) (pixels + y * surface->pitch) + x);
if (distance)
{
GET_PIXELVALS (r2, g2, b2, a2, *pixel,
surface->format, ppa);
if (COLOR_DIFF_RGB (wr, wg, wb, r1, g1, b1, r2, g2, b2) <=
distance)
*pixel = white;
else
*pixel = black;
}
else
*pixel = (*pixel == color) ? white : black;
x += newarray->xstep;
posx += absxstep;
}
y += newarray->ystep;
posy += absystep;
}
break;
}
}
Py_END_ALLOW_THREADS;
return (PyObject *) newarray;
}
static PyObject*
_compare (PyPixelArray *array, PyObject *args, PyObject *kwds)
{
PyPixelArray *array2 = NULL;
PyPixelArray *newarray = NULL;
PyObject *weights = NULL;
PyObject *sf = NULL;
SDL_Surface *surface1 = NULL;
SDL_Surface *surface2 = NULL;
Uint32 black;
Uint32 white;
float distance = 0;
Uint8 r1, g1, b1, a1, r2, g2, b2, a2;
float wr, wg, wb;
Uint32 x = 0;
Uint32 y = 0;
Uint32 vx = 0;
Uint32 vy = 0;
Uint32 posx = 0;
Uint32 posy = 0;
Sint32 absxstep;
Sint32 absystep;
Uint8 *pixels1;
Uint8 *pixels2;
static char *keys[] = { "array", "distance", "weights", NULL };
if (!PyArg_ParseTupleAndKeywords (args, kwds, "O|fO", keys, &newarray,
&distance, &weights))
return NULL;
if (!PyPixelArray_Check (newarray))
return RAISE (PyExc_TypeError, "invalid array type");
array2 = (PyPixelArray *) newarray;
newarray = NULL;
if (distance < 0 || distance > 1)
return RAISE (PyExc_ValueError,
"distance must be in the range from 0.0 to 1.0");
if (!_get_weights (weights, &wr, &wg, &wb))
return NULL;
if (array->ylen / ABS (array->ystep) != array2->ylen / ABS (array2->ystep)
|| array->xlen / ABS (array->xstep) != array2->xlen / ABS (array2->xstep))
{
/* Bounds do not match. */
PyErr_SetString (PyExc_ValueError, "array sizes do not match");
return NULL;
}
surface1 = PySurface_AsSurface (array->surface);
surface2 = PySurface_AsSurface (array2->surface);
if (surface2->format->BytesPerPixel != surface1->format->BytesPerPixel)
return RAISE (PyExc_ValueError, "bit depths do not match");
/* Create the b/w mask surface. */
sf = _make_surface (array);
if (!sf)
return NULL;
newarray = (PyPixelArray *) PyPixelArray_New (sf);
if (!newarray)
{
Py_DECREF (sf);
return NULL;
}
surface1 = PySurface_AsSurface (newarray->surface);
black = SDL_MapRGBA (surface1->format, 0, 0, 0, 255);
white = SDL_MapRGBA (surface1->format, 255, 255, 255, 255);
pixels1 = surface1->pixels;
pixels2 = surface2->pixels;
absxstep = ABS (array2->xstep);
absystep = ABS (array2->ystep);
y = array2->ystart;
Py_BEGIN_ALLOW_THREADS;
switch (surface1->format->BytesPerPixel)
{
case 1:
{
Uint8 *pixel1, *pixel2;
while (posy < newarray->ylen)
{
vx = array2->xstart;
x = newarray->xstart;
posx = 0;
while (posx < newarray->xlen)
{
pixel1 = ((Uint8 *) pixels1 + y * surface1->pitch + x);
pixel2 = ((Uint8 *) pixels2 + vy * surface2->pitch + vx);
if (distance)
{
GET_PIXELVALS_1 (r1, g1, b1, a1, pixel1, surface1->format);
GET_PIXELVALS_1 (r2, g2, b2, a2, pixel2, surface2->format);
if (COLOR_DIFF_RGB (wr, wg, wb, r1, g1, b1, r2, g2, b2) >
distance)
*pixel1 = (Uint8) white;
else
*pixel1 = (Uint8) black;
}
else
*pixel1 = (*pixel1 == *pixel2) ? (Uint8) white :
(Uint8) black;
vx += array2->xstep;
x += newarray->xstep;
posx += absxstep;
}
vy += array2->ystep;
y += newarray->ystep;
posy += absystep;
}
break;
}
case 2:
{
Uint16 *pixel1, *pixel2;
int ppa = (surface1->flags & SDL_SRCALPHA &&
surface1->format->Amask);
while (posy < newarray->ylen)
{
vx = array2->xstart;
x = array->xstart;
posx = 0;
while (posx < newarray->xlen)
{
pixel1 = ((Uint16 *) (pixels1 + y * surface1->pitch) + x);
pixel2 = ((Uint16 *) (pixels2 + vy * surface2->pitch) + vx);
if (distance)
{
GET_PIXELVALS (r1, g1, b1, a1, (Uint32) *pixel1,
surface1->format, ppa);
GET_PIXELVALS (r2, g2, b2, a2, (Uint32) *pixel2,
surface1->format, ppa);
if (COLOR_DIFF_RGB (wr, wg, wb, r1, g1, b1, r2, g2, b2) >
distance)
*pixel1 = (Uint16) white;
else
*pixel1 = (Uint16) black;
}
else
*pixel1 = (*pixel1 == *pixel2) ? (Uint16) white :
(Uint16) black;
vx += array2->xstep;
x += newarray->xstep;
posx += absxstep;
}
vy += array2->ystep;
y += newarray->ystep;
posy += absystep;
}
break;
}
case 3:
{
Uint8 *px1, *px2;
Uint32 pxcolor1, pxcolor2;
SDL_PixelFormat *format = surface1->format;
int ppa1 = (surface1->flags & SDL_SRCALPHA &&
surface1->format->Amask);
int ppa2 = (surface2->flags & SDL_SRCALPHA &&
surface2->format->Amask);
while (posy < newarray->ylen)
{
vx = array2->xstart;
x = newarray->xstart;
posx = 0;
while (posx < newarray->xlen)
{
px1 = ((Uint8 *) (pixels1 + y * surface1->pitch) + x * 3);
px2 = ((Uint8 *) (pixels2 + vy * surface2->pitch) + vx * 3);
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
pxcolor1 = (px1[0]) + (px1[1] << 8) + (px1[2] << 16);
pxcolor2 = (px2[0]) + (px2[1] << 8) + (px2[2] << 16);
if (distance)
{
GET_PIXELVALS (r1, g1, b1, a1, pxcolor1,
surface1->format, ppa1);
GET_PIXELVALS (r2, g2, b2, a2, pxcolor2,
surface2->format, ppa2);
if (COLOR_DIFF_RGB (wr, wg, wb, r1, g1, b1, r2, g2, b2) >
distance)
{
*(px1 + (format->Rshift >> 3)) = (Uint8) (white >> 16);
*(px1 + (format->Gshift >> 3)) = (Uint8) (white >> 8);
*(px1 + (format->Bshift >> 3)) = (Uint8) white;
}
else
{
*(px1 + (format->Rshift >> 3)) = (Uint8) (black >> 16);
*(px1 + (format->Gshift >> 3)) = (Uint8) (black >> 8);
*(px1 + (format->Bshift >> 3)) = (Uint8) black;
}
}
else if (pxcolor1 != pxcolor2)
{
*(px1 + (format->Rshift >> 3)) = (Uint8) (white >> 16);
*(px1 + (format->Gshift >> 3)) = (Uint8) (white >> 8);
*(px1 + (format->Bshift >> 3)) = (Uint8) white;
}
else
{
*(px1 + (format->Rshift >> 3)) = (Uint8) (black >> 16);
*(px1 + (format->Gshift >> 3)) = (Uint8) (black >> 8);
*(px1 + (format->Bshift >> 3)) = (Uint8) black;
}
#else
pxcolor1 = (px1[2]) + (px1[1] << 8) + (px1[0] << 16);
pxcolor2 = (px2[2]) + (px2[1] << 8) + (px2[0] << 16);
if (distance)
{
GET_PIXELVALS (r1, g1, b1, a1, pxcolor1,
surface1->format, ppa1);
GET_PIXELVALS (r2, g2, b2, a2, pxcolor2,
surface2->format, ppa2);
if (COLOR_DIFF_RGB (wr, wg, wb, r1, g1, b1, r2, g2, b2) >
distance)
{
*(px1 + 2 - (format->Rshift >> 3)) =
(Uint8) (white >> 16);
*(px1 + 2 - (format->Gshift >> 3)) =
(Uint8) (white >> 8);
*(px1 + 2 - (format->Bshift >> 3)) = (Uint8) white;
}
else
{
*(px1 + 2 - (format->Rshift >> 3)) =
(Uint8) (black >> 16);
*(px1 + 2 - (format->Gshift >> 3)) =
(Uint8) (black >> 8);
*(px1 + 2 - (format->Bshift >> 3)) = (Uint8) black;
}
}
else if (pxcolor1 != pxcolor2)
{
*(px1 + 2 - (format->Rshift >> 3)) = (Uint8) (white >> 16);
*(px1 + 2 - (format->Gshift >> 3)) = (Uint8) (white >> 8);
*(px1 + 2 - (format->Bshift >> 3)) = (Uint8) white;
}
else
{
*(px1 + 2 - (format->Rshift >> 3)) = (Uint8) (black >> 16);
*(px1 + 2 - (format->Gshift >> 3)) = (Uint8) (black >> 8);
*(px1 + 2 - (format->Bshift >> 3)) = (Uint8) black;
}
#endif
vx += array2->xstep;
x += newarray->xstep;
posx += absxstep;
}
vy += array2->ystep;
y += newarray->ystep;
posy += absystep;
}
break;
}
default:
{
Uint32 *pixel1, *pixel2;
int ppa1 = (surface1->flags & SDL_SRCALPHA &&
surface1->format->Amask);
int ppa2 = (surface2->flags & SDL_SRCALPHA &&
surface2->format->Amask);
while (posy < newarray->ylen)
{
vx = array2->xstart;
x = newarray->xstart;
posx = 0;
while (posx < newarray->xlen)
{
pixel1 = ((Uint32 *) (pixels1 + y * surface1->pitch) + x);
pixel2 = ((Uint32 *) (pixels2 + vy * surface2->pitch) + vx);
if (distance)
{
GET_PIXELVALS (r1, g1, b1, a1, *pixel1,
surface1->format, ppa1);
GET_PIXELVALS (r2, g2, b2, a2, *pixel2,
surface2->format, ppa2);
if (COLOR_DIFF_RGB (wr, wg, wb, r1, g1, b1, r2, g2, b2) >
distance)
*pixel1 = white;
else
*pixel1 = black;
}
else
*pixel1 = (*pixel1 == *pixel2) ? white : black;
vx += array2->xstep;
x += newarray->xstep;
posx += absxstep;
}
vy += array2->ystep;
y += newarray->ystep;
posy += absystep;
}
break;
}
}
Py_END_ALLOW_THREADS;
return (PyObject *) newarray;
}
pygame-1.9.1release/src/pixelarray.doc 0000644 0001750 0001750 00000012644 11001455412 017701 0 ustar vincent vincent pygame.PixelArray
pygame object for direct pixel access of surfaces
pygame.PixelArray(Surface): return PixelArray
The PixelArray wraps up a Surface and provides a direct 2D array access
to its pixels using the surface its rows as first and its columns as
second axis. It supports slicing, row and pixel manipluation, slicing
and slice assignments while inplace operations such as addition,
subtraction, multiplication, division and so forth are not allowed.
While it is possible to assign both, integer color values and RGB(A)
color tuples, the PixelArray will only use integers for the color
representation. Thus, checking for certain colors has to be done using
the Surface.map_rgb() method of the surface, the PixelArray was created
for.
pxarray = pygame.PixelArray (surface)
# Check, if the first pixel at the topleft corner is blue
if pxarray[0][0] == surface.map_rgb ((0, 0, 255)):
...
Pixels can be manipulated using integer values or color tuples.
pxarray[x][y] = 0xFF00FF
pxarray[x][y] = (255, 0, 255)
If you operate on a slice, you also can use arbitrary sequences or other
PixelArray objects to modify the pixels. They have to match the size of
the PixelArray however.
pxarray[a:b] = 0xFF00FF # set all pixels to 0xFF00FF
pxarray[a:b] = (0xFF00FF, 0xAACCEE, ... ) # first pixel = 0xFF00FF,
# second pixel = 0xAACCEE, ...
pxarray[a:b] = ((255, 0, 255), (170, 204, 238), ...) # same as above
pxarray[a:b] = ((255, 0, 255), 0xAACCEE, ...) # same as above
pxarray[a:b] = otherarray[x:y] # slice sizes must match
Note, that something like
pxarray[2:4][3:5] = ...
will not cause a rectangular manipulation. Instead it will be first
sliced to a two-column array, which then shall be sliced by columns once
more, which will fail due an IndexError. This is caused by the slicing
mechanisms in python and an absolutely correct behaviour.
Create a single columned slice first, which you can manipulate then:
pxarray[2][3:5] = ...
pxarray[3][3:5] = ...
If you want to make a rectangular manipulation or create a view of a
part of the PixelArray, you also can use the subscript abilities. You
can easily create different view by creating 'subarrays' using the
subscripts.
# Create some new PixelArray objects providing a different view
# of the original array/surface.
newarray = pxarray[2:4,3:5]
otherarray = pxarray[::2,::2]
Subscripts also can be used to do fast rectangular pixel manipulations
instead of iterating over the x or y axis as above.
pxarray[::2,:] = (0, 0, 0) # Make each second column black.
During its lifetime, the PixelArray locks the surface, thus you
explicitly have to delete it once its not used anymore and the surface
should perform operations in the same scope.
New in pygame 1.8. Subscript support is new in pygame 1.8.1.
surface
Gets the Surface the PixelArray uses.
PixelArray.surface: Return Surface
The Surface, the PixelArray was created for.
make_surface
Creates a new Surface from the current PixelArray.
PixelArray.make_surface (): Return Surface
Creates a new Surface from the current PixelArray. Depending on the
current PixelArray the size, pixel order etc. will be different from the
original Surface.
# Create a new surface flipped around the vertical axis.
sf = pxarray[:,::-1].make_surface ()
New in pygame 1.8.1.
replace
Replaces the passed color in the PixelArray with another one.
PixelArray.replace (color, repcolor, distance=0, weights=(0.299, 0.587, 0.114)): Return None
Replaces the pixels with the passed color in the PixelArray by changing
them them to the passed replacement color.
It uses a simple weighted euclidian distance formula to calculate the
distance between the colors. The distance space ranges from 0.0 to 1.0
and is used as threshold for the color detection. This causes the
replacement to take pixels with a similar, but not exactly identical
color, into account as well.
This is an in place operation that directly affects the pixels of the
PixelArray.
New in pygame 1.8.1.
extract
Extracts the passed color from the PixelArray.
PixelArray.extract (color, distance=0, weights=(0.299, 0.587, 0.114)): Return PixelArray
Extracts the passed color by changing all matching pixels to white,
while non-matching pixels are changed to black. This returns a new
PixelArray with the black/white color mask.
It uses a simple weighted euclidian distance formula to calculate the
distance between the colors. The distance space ranges from 0.0 to
1.0 and is used as threshold for the color detection. This causes the
extraction to take pixels with a similar, but not exactly identical
color, into account as well.
New in pygame 1.8.1.
compare
Compares the PixelArray with another one.
PixelArray.compare (array, distance=0, weights=(0.299, 0.587, 0.114)): Return PixelArray
Compares the contents of the PixelArray with those from the passed PixelArray.
It returns a new PixelArray with a black/white color mask that indicates the
differences (white) of both arrays. Both PixelArray objects must have indentical
bit depths and dimensions.
It uses a simple weighted euclidian distance formula to calculate the
distance between the colors. The distance space ranges from 0.0 to
1.0 and is used as threshold for the color detection. This causes the
comparision to mark pixels with a similar, but not exactly identical
color, as black.
New in pygame 1.8.1.
pygame-1.9.1release/src/pixelarray.c 0000644 0001750 0001750 00000170501 11216024112 017350 0 ustar vincent vincent /*
pygame - Python Game Library
Copyright (C) 2007-2008 Marcus von Appen
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#define PYGAMEAPI_PIXELARRAY_INTERNAL
#include "pygame.h"
#include "pgcompat.h"
#include "pygamedocs.h"
#include "surface.h"
#if PY_VERSION_HEX < 0x02050000
#define PyIndex_Check(op) 0
#endif
typedef struct
{
PyObject_HEAD
PyObject *dict; /* dict for subclassing */
PyObject *weakrefs; /* Weakrefs for subclassing */
PyObject *surface; /* Surface associated with the array. */
PyObject *lock; /* Lock object for the surface. */
Uint32 xstart; /* X offset for subarrays */
Uint32 ystart; /* Y offset for subarrays */
Uint32 xlen; /* X segment length. */
Uint32 ylen; /* Y segment length. */
Sint32 xstep; /* X offset step width. */
Sint32 ystep; /* Y offset step width. */
Uint32 padding; /* Padding to get to the next x offset. */
PyObject *parent; /* Parent pixel array */
} PyPixelArray;
static PyPixelArray* _pxarray_new_internal (PyTypeObject *type,
PyObject *surface, Uint32 xstart, Uint32 ystart, Uint32 xlen, Uint32 ylen,
Sint32 xstep, Sint32 ystep, Uint32 padding, PyObject *parent);
static PyObject* _pxarray_new (PyTypeObject *type, PyObject *args,
PyObject *kwds);
static void _pxarray_dealloc (PyPixelArray *self);
static PyObject* _pxarray_get_dict (PyPixelArray *self, void *closure);
static PyObject* _pxarray_get_surface (PyPixelArray *self, void *closure);
static PyObject* _pxarray_repr (PyPixelArray *array);
static PyObject* _array_slice_internal (PyPixelArray *array, Sint32 _start,
Sint32 _end, Sint32 _step);
/* Sequence methods */
static Py_ssize_t _pxarray_length (PyPixelArray *array);
static PyObject* _pxarray_item (PyPixelArray *array, Py_ssize_t _index);
#if !PY3
static PyObject* _pxarray_slice (PyPixelArray *array, Py_ssize_t low,
Py_ssize_t high);
#endif
static int _array_assign_array (PyPixelArray *array, Py_ssize_t low,
Py_ssize_t high, PyPixelArray *val);
static int _array_assign_sequence (PyPixelArray *array, Py_ssize_t low,
Py_ssize_t high, PyObject *val);
static int _array_assign_slice (PyPixelArray *array, Py_ssize_t low,
Py_ssize_t high, Uint32 color);
static int _pxarray_ass_item (PyPixelArray *array, Py_ssize_t _index,
PyObject *value);
static int _pxarray_ass_slice (PyPixelArray *array, Py_ssize_t low,
Py_ssize_t high, PyObject *value);
static int _pxarray_contains (PyPixelArray *array, PyObject *value);
static PyObject* _pxarray_iter (PyPixelArray *array);
/* Mapping methods */
static int _get_subslice (PyObject *op, Py_ssize_t length, Py_ssize_t *start,
Py_ssize_t *stop, Py_ssize_t *step);
static PyObject* _pxarray_subscript (PyPixelArray *array, PyObject *op);
static int _pxarray_ass_subscript (PyPixelArray *array, PyObject* op,
PyObject* value);
/* C API interfaces */
static PyObject* PyPixelArray_New (PyObject *surfobj);
/* Incomplete forward declaration so we can use it in the methods included
* below.
*/
static PyTypeObject PyPixelArray_Type;
#define PyPixelArray_Check(o) \
(Py_TYPE (o) == (PyTypeObject *) &PyPixelArray_Type)
#define SURFACE_EQUALS(x,y) \
(((PyPixelArray *)x)->surface == ((PyPixelArray *)y)->surface)
#include "pixelarray_methods.c"
/**
* Methods, which are bound to the PyPixelArray type.
*/
static PyMethodDef _pxarray_methods[] =
{
{ "compare", (PyCFunction) _compare, METH_VARARGS | METH_KEYWORDS,
DOC_PIXELARRAYCOMPARE },
{ "extract", (PyCFunction) _extract_color, METH_VARARGS | METH_KEYWORDS,
DOC_PIXELARRAYEXTRACT },
{ "make_surface", (PyCFunction) _make_surface, METH_VARARGS | METH_NOARGS,
DOC_PIXELARRAYMAKESURFACE },
{ "replace", (PyCFunction) _replace_color, METH_VARARGS | METH_KEYWORDS,
DOC_PIXELARRAYREPLACE },
{ NULL, NULL, 0, NULL }
};
#if PY3
static void
Text_ConcatAndDel (PyObject **string, PyObject *newpart)
{
PyObject *result = NULL;
if (*string != NULL && newpart != NULL) {
PyUnicode_Concat (*string, newpart);
Py_DECREF (*string);
Py_DECREF (newpart);
}
else {
Py_XDECREF (*string);
Py_XDECREF (newpart);
}
*string = result;
}
#else
#define Text_ConcatAndDel PyString_ConcatAndDel
#endif
/**
* Getters and setters for the PyPixelArray.
*/
static PyGetSetDef _pxarray_getsets[] =
{
{ "__dict__", (getter) _pxarray_get_dict, NULL, NULL, NULL },
{ "surface", (getter) _pxarray_get_surface, NULL, DOC_PIXELARRAYSURFACE,
NULL },
{ NULL, NULL, NULL, NULL, NULL }
};
/**
* Sequence interface support for the PyPixelArray.
* concat and repeat are not implemented due to the possible confusion
* of their behaviour (see lists numpy array).
*/
static PySequenceMethods _pxarray_sequence =
{
(lenfunc) _pxarray_length, /*sq_length*/
NULL, /*sq_concat*/
NULL, /*sq_repeat*/
(ssizeargfunc) _pxarray_item, /*sq_item*/
#if PY3
NULL,
#else
(ssizessizeargfunc) _pxarray_slice, /*sq_slice*/
#endif
(ssizeobjargproc) _pxarray_ass_item, /*sq_ass_item*/
#if PY3
NULL,
#else
(ssizessizeobjargproc) _pxarray_ass_slice, /*sq_ass_slice*/
#endif
(objobjproc) _pxarray_contains, /*sq_contains*/
NULL, /*sq_inplace_concat*/
NULL, /*sq_inplace_repeat*/
};
/**
* Mapping interface support for the PyPixelArray.
*/
static PyMappingMethods _pxarray_mapping =
{
(inquiry) _pxarray_length, /*mp_length*/
(binaryfunc) _pxarray_subscript, /*mp_subscript*/
(objobjargproc) _pxarray_ass_subscript, /*mp_ass_subscript*/
};
static PyTypeObject PyPixelArray_Type =
{
TYPE_HEAD (NULL, 0)
"pygame.PixelArray", /* tp_name */
sizeof (PyPixelArray), /* tp_basicsize */
0, /* tp_itemsize */
(destructor) _pxarray_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
(reprfunc) _pxarray_repr, /* tp_repr */
0, /* tp_as_number */
&_pxarray_sequence, /* tp_as_sequence */
&_pxarray_mapping, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS,
DOC_PYGAMEPIXELARRAY, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
offsetof (PyPixelArray, weakrefs), /* tp_weaklistoffset */
(getiterfunc) _pxarray_iter, /* tp_iter */
0, /* tp_iternext */
_pxarray_methods, /* tp_methods */
0, /* tp_members */
_pxarray_getsets, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
offsetof (PyPixelArray, dict), /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
_pxarray_new, /* tp_new */
#ifndef __SYMBIAN32__
0, /* tp_free */
0, /* tp_is_gc */
0, /* tp_bases */
0, /* tp_mro */
0, /* tp_cache */
0, /* tp_subclasses */
0, /* tp_weaklist */
0 /* tp_del */
#endif
};
static PyPixelArray*
_pxarray_new_internal (PyTypeObject *type, PyObject *surface,
Uint32 xstart, Uint32 ystart, Uint32 xlen, Uint32 ylen,
Sint32 xstep, Sint32 ystep, Uint32 padding, PyObject *parent)
{
PyPixelArray *self = (PyPixelArray *) type->tp_alloc (type, 0);
if (!self)
return NULL;
self->surface = (PyObject *) surface;
self->lock = NULL;
self->parent = NULL;
Py_INCREF (surface);
if (!parent)
{
/* Initial PixelArray */
if (surface)
{
self->lock = PySurface_LockLifetime (surface, (PyObject *) self);
if (!self->lock)
{
Py_DECREF (surface);
Py_TYPE (self)->tp_free ((PyObject *) self);
return NULL;
}
}
}
else
{
self->parent = parent;
Py_INCREF (parent);
self->lock = ((PyPixelArray *)parent)->lock;
Py_INCREF (self->lock);
}
self->weakrefs = NULL;
self->dict = NULL;
self->xstart = xstart;
self->ystart = ystart;
self->xlen = xlen;
self->ylen = ylen;
self->xstep = xstep;
self->ystep = ystep;
self->padding = padding;
return self;
}
/**
* Creates a new PyPixelArray.
*/
static PyObject*
_pxarray_new (PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PyObject *surfobj;
SDL_Surface* surface;
if (!PyArg_ParseTuple (args, "O!", &PySurface_Type, &surfobj))
return NULL;
surface = PySurface_AsSurface (surfobj);
if (surface->format->BytesPerPixel < 1 ||
surface->format->BytesPerPixel > 4)
return RAISE (PyExc_ValueError,
"unsupport bit depth for reference array");
return (PyObject *) _pxarray_new_internal
(type, surfobj, 0, 0, (Uint32) surface->w, (Uint32) surface->h, 1, 1,
surface->pitch, NULL);
}
/**
* Deallocates the PyPixelArray and its members.
*/
static void
_pxarray_dealloc (PyPixelArray *self)
{
if (self->weakrefs)
PyObject_ClearWeakRefs ((PyObject *) self);
Py_XDECREF (self->lock);
Py_XDECREF (self->parent);
Py_XDECREF (self->dict);
Py_DECREF (self->surface);
Py_TYPE (self)->tp_free ((PyObject *) self);
}
/**** Getter and setter access ****/
/**
* Getter for PixelArray.__dict__.
*/
static PyObject*
_pxarray_get_dict (PyPixelArray *self, void *closure)
{
if (!self->dict)
{
self->dict = PyDict_New ();
if (!self->dict)
return NULL;
}
Py_INCREF (self->dict);
return self->dict;
}
/**
* Getter for PixelArray.surface
*/
static PyObject*
_pxarray_get_surface (PyPixelArray *self, void *closure)
{
Py_XINCREF (self->surface);
return self->surface;
}
/**** Methods ****/
/**
* repr(PixelArray)
*/
static PyObject*
_pxarray_repr (PyPixelArray *array)
{
PyObject *string;
SDL_Surface *surface;
int bpp;
Uint8 *pixels;
Uint8 *px24;
Uint32 pixel;
Uint32 x = 0;
Uint32 y = 0;
Sint32 xlen = 0;
Sint32 absxstep;
Sint32 absystep;
Uint32 posx = 0;
Uint32 posy = 0;
surface = PySurface_AsSurface (array->surface);
bpp = surface->format->BytesPerPixel;
pixels = (Uint8 *) surface->pixels;
/*
printf ("::ARRAY: %d:%d:%d, %d:%d:%d %d\n",
array->xstart, array->xlen, array->xstep, array->ystart,
array->ylen, array->ystep, array->padding);
*/
string = Text_FromUTF8 ("PixelArray(");
absxstep = ABS (array->xstep);
absystep = ABS (array->ystep);
xlen = (Sint32) array->xlen - absxstep;
y = array->ystart;
switch (bpp)
{
case 1:
while (posy < array->ylen)
{
/* Construct the rows */
Text_ConcatAndDel (&string, Text_FromUTF8 ("\n ["));
if (string == NULL)
{
return NULL;
}
posx = 0;
x = array->xstart;
while (posx < (Uint32)xlen)
{
/* Construct the columns */
pixel = (Uint32) *((Uint8 *) pixels + x + y * array->padding);
Text_ConcatAndDel (&string,
Text_FromFormat ("%ld, ", (long)pixel));
if (string == NULL)
{
return NULL;
}
x += array->xstep;
posx += absxstep;
}
pixel = (Uint32) *((Uint8 *) pixels + x + y * array->padding);
Text_ConcatAndDel (&string,
Text_FromFormat ("%ld]", (long)pixel));
if (string == NULL)
{
return NULL;
}
y += array->ystep;
posy += absystep;
}
break;
case 2:
while (posy < array->ylen)
{
/* Construct the rows */
Text_ConcatAndDel (&string, Text_FromUTF8 ("\n ["));
if (string == NULL)
{
return NULL;
}
posx = 0;
x = array->xstart;
while (posx < (Uint32)xlen)
{
/* Construct the columns */
pixel = (Uint32)
*((Uint16 *) (pixels + y * array->padding) + x);
Text_ConcatAndDel (&string,
Text_FromFormat ("%ld, ", (long)pixel));
if (string == NULL)
{
return NULL;
}
x += array->xstep;
posx += absxstep;
}
pixel = (Uint32) *((Uint16 *) (pixels + y * array->padding) + x);
Text_ConcatAndDel (&string,
Text_FromFormat ("%ld]", (long)pixel));
if (string == NULL)
{
return NULL;
}
y += array->ystep;
posy += absystep;
}
break;
case 3:
while (posy < array->ylen)
{
/* Construct the rows */
Text_ConcatAndDel (&string, Text_FromUTF8 ("\n ["));
if (string == NULL)
{
return NULL;
}
posx = 0;
x = array->xstart;
while (posx < (Uint32)xlen)
{
/* Construct the columns */
px24 = ((Uint8 *) (pixels + y * array->padding) + x * 3);
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
pixel = (px24[0]) + (px24[1] << 8) + (px24[2] << 16);
#else
pixel = (px24[2]) + (px24[1] << 8) + (px24[0] << 16);
#endif
Text_ConcatAndDel (&string,
Text_FromFormat ("%ld, ", (long)pixel));
if (string == NULL)
{
return NULL;
}
x += array->xstep;
posx += absxstep;
}
px24 = ((Uint8 *) (pixels + y * array->padding) + x * 3);
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
pixel = (px24[0]) + (px24[1] << 8) + (px24[2] << 16);
#else
pixel = (px24[2]) + (px24[1] << 8) + (px24[0] << 16);
#endif
Text_ConcatAndDel (&string,
Text_FromFormat ("%ld]", (long)pixel));
if (string == NULL)
{
return NULL;
}
y += array->ystep;
posy += absystep;
}
break;
default: /* 4bpp */
while (posy < array->ylen)
{
/* Construct the rows */
Text_ConcatAndDel (&string, Text_FromUTF8 ("\n ["));
if (string == NULL)
{
return NULL;
}
posx = 0;
x = array->xstart;
while (posx < (Uint32)xlen)
{
/* Construct the columns */
pixel = *((Uint32 *) (pixels + y * array->padding) + x);
Text_ConcatAndDel (&string,
Text_FromFormat ("%ld, ", (long)pixel));
if (string == NULL)
{
return NULL;
}
x += array->xstep;
posx += absxstep;
}
pixel = *((Uint32 *) (pixels + y * array->padding) + x);
Text_ConcatAndDel (&string,
Text_FromFormat ("%ld]", (long)pixel));
if (string == NULL)
{
return NULL;
}
y += array->ystep;
posy += absystep;
}
break;
}
Text_ConcatAndDel (&string, Text_FromUTF8 ("\n)"));
return string;
}
/**
* Creates a 2D slice of the array.
*/
static PyObject*
_array_slice_internal (PyPixelArray *array, Sint32 _start, Sint32 _end,
Sint32 _step)
{
Uint32 xstart = 0;
Uint32 ystart = 0;
Uint32 xlen;
Uint32 ylen;
Sint32 xstep;
Sint32 ystep;
Uint32 padding;
if (_end == _start)
return RAISE (PyExc_IndexError, "array size must not be 0");
if (array->xlen == 1)
{
ystart = array->ystart + _start * array->ystep;
xstart = array->xstart;
xlen = array->xlen;
ylen = ABS (_end - _start);
ystep = _step;
xstep = array->xstep;
padding = array->padding;
/* Out of bounds? */
if (_start >= (Sint32) array->ylen && ystep > 0)
return RAISE (PyExc_IndexError, "array index out of range");
}
else
{
xstart = array->xstart + _start * array->xstep;
ystart = array->ystart;
xlen = ABS (_end - _start);
ylen = array->ylen;
xstep = _step;
ystep = array->ystep;
padding = array->padding;
/* Out of bounds? */
if (_start >= (Sint32) array->xlen && xstep > 0)
return RAISE (PyExc_IndexError, "array index out of range");
}
/*
printf ("VALS: %d:%d, %d:%d %d:%d %d\n",
xstart, ystart, xlen, xstep, ylen, ystep, padding);
*/
return (PyObject *) _pxarray_new_internal
(&PyPixelArray_Type, array->surface, xstart, ystart, xlen, ylen,
xstep, ystep, padding, (PyObject *) array);
}
/**** Sequence interfaces ****/
/**
* len (array)
*/
static Py_ssize_t
_pxarray_length (PyPixelArray *array)
{
if (array->xlen > 1)
return array->xlen / ABS (array->xstep);
return array->ylen / ABS (array->ystep);
}
/**
* array[x]
*/
static PyObject*
_pxarray_item (PyPixelArray *array, Py_ssize_t _index)
{
SDL_Surface *surface;
int bpp;
if (_index < 0)
return RAISE (PyExc_IndexError, "array index out of range");
surface = PySurface_AsSurface (array->surface);
bpp = surface->format->BytesPerPixel;
/* Access of a single column. */
if (array->xlen == 1)
{
if ((Uint32) _index >= array->ystart + array->ylen)
return RAISE (PyExc_IndexError, "array index out of range");
return _get_single_pixel ((Uint8 *) surface->pixels, bpp,
array->xstart, _index * array->padding * array->ystep);
}
if (array->ylen == 1)
{
if ((Uint32) _index >= array->xstart + array->xlen)
return RAISE (PyExc_IndexError, "array index out of range");
return _get_single_pixel ((Uint8 *) surface->pixels, bpp,
array->xstart + _index * array->xstep,
array->ystart * array->padding * array->ystep);
}
return _array_slice_internal (array, _index, _index + 1, 1);
}
#if !PY3
/**
* array[x:y]
*/
static PyObject*
_pxarray_slice (PyPixelArray *array, Py_ssize_t low, Py_ssize_t high)
{
if (low < 0)
low = 0;
else if (low > (Sint32) array->xlen)
low = array->xlen;
if (high < low)
high = low;
else if (high > (Sint32) array->xlen)
high = array->xlen;
if (low == high)
Py_RETURN_NONE;
return _array_slice_internal (array, low, high, 1);
}
#endif
static int
_array_assign_array (PyPixelArray *array, Py_ssize_t low, Py_ssize_t high,
PyPixelArray *val)
{
SDL_Surface *surface;
SDL_Surface *valsf = NULL;
Uint32 x = 0;
Uint32 y = 0;
Uint32 vx = 0;
Uint32 vy = 0;
int bpp;
int valbpp;
Uint8 *pixels;
Uint8 *valpixels;
int copied = 0;
Uint32 xstart = 0;
Uint32 ystart = 0;
Uint32 xlen;
Uint32 ylen;
Sint32 xstep;
Sint32 ystep;
Uint32 padding;
Uint32 posx = 0;
Uint32 posy = 0;
Sint32 absxstep;
Sint32 absystep;
/* Set the correct slice indices */
surface = PySurface_AsSurface (array->surface);
if (array->xlen == 1)
{
xstart = array->xstart;
ystart = array->ystart + low * array->ystep;
xlen = array->xlen;
ylen = ABS (high - low);
ystep = array->ystep;
xstep = array->xstep;
padding = array->padding;
}
else
{
xstart = array->xstart + low * array->xstep;
ystart = array->ystart;
xlen = ABS (high - low);
ylen = array->ylen;
xstep = array->xstep;
ystep = array->ystep;
padding = array->padding;
}
/*
printf ("ARRAY: %d:%d:%d, %d:%d:%d -- VAL: %d:%d:%d, %d:%d:%d\n",
xstart, xlen, xstep, ystart, ylen, ystep,
val->xstart, val->xlen, val->xstep,
val->ystart, val->ylen, val->ystep);
*/
if (val->ylen / ABS (val->ystep) != ylen / ABS (ystep) ||
val->xlen / ABS (val->xstep) != xlen / ABS (xstep))
{
/* Bounds do not match. */
PyErr_SetString (PyExc_ValueError, "array sizes do not match");
return -1;
}
valsf = PySurface_AsSurface (val->surface);
bpp = surface->format->BytesPerPixel;
valbpp = valsf->format->BytesPerPixel;
pixels = (Uint8 *) surface->pixels;
valpixels = valsf->pixels;
if (bpp != valbpp)
{
/* bpp do not match. We cannot guarantee that the padding and co
* would be set correctly. */
PyErr_SetString (PyExc_ValueError, "bit depths do not match");
return -1;
}
/* If we reassign the same array, we need to copy the pixels
* first. */
if (SURFACE_EQUALS (array, val))
{
/* We assign a different view or so. Copy the source buffer. */
valpixels = malloc ((size_t) (surface->pitch * surface->h));
if (!valpixels)
{
PyErr_SetString (PyExc_ValueError, "could not copy pixels");
return -1;
}
valpixels = memcpy (valpixels, pixels,
(size_t) (surface->pitch * surface->h));
copied = 1;
}
absxstep = ABS (xstep);
absystep = ABS (ystep);
y = ystart;
vy = val->ystart;
Py_BEGIN_ALLOW_THREADS;
/* Single value assignment. */
switch (bpp)
{
case 1:
while (posy < ylen)
{
vx = val->xstart;
posx = 0;
x = xstart;
while (posx < xlen)
{
*((Uint8 *) pixels + y * padding + x) =
(Uint8)*((Uint8 *) valpixels + vy * val->padding + vx);
vx += val->xstep;
x += xstep;
posx += absxstep;
}
vy += val->ystep;
y += ystep;
posy += absystep;
}
break;
case 2:
while (posy < ylen)
{
vx = val->xstart;
posx = 0;
x = xstart;
while (posx < xlen)
{
*((Uint16 *) (pixels + y * padding) + x) =
(Uint16)*((Uint16 *) (valpixels + vy * val->padding) + vx);
vx += val->xstep;
x += xstep;
posx += absxstep;
}
vy += val->ystep;
y += ystep;
posy += absystep;
}
break;
case 3:
{
Uint8 *px;
Uint8 *vpx;
SDL_PixelFormat *format = surface->format;
SDL_PixelFormat *vformat = valsf->format;
while (posy < ylen)
{
vx = val->xstart;
posx = 0;
x = xstart;
while (posx < xlen)
{
px = ((Uint8 *) (pixels + y * padding) + x * 3);
vpx = ((Uint8 *) (valpixels + vy * val->padding) + vx * 3);
#if (SDL_BYTEORDER == SDL_LIL_ENDIAN)
*(px + (format->Rshift >> 3)) =
*(vpx + (vformat->Rshift >> 3));
*(px + (format->Gshift >> 3)) =
*(vpx + (vformat->Gshift >> 3));
*(px + (format->Bshift >> 3)) =
*(vpx + (vformat->Bshift >> 3));
#else
*(px + 2 - (format->Rshift >> 3)) =
*(vpx + 2 - (vformat->Rshift >> 3));
*(px + 2 - (format->Gshift >> 3)) =
*(vpx + 2 - (vformat->Gshift >> 3));
*(px + 2 - (format->Bshift >> 3)) =
*(vpx + 2 - (vformat->Bshift >> 3));
#endif
vx += val->xstep;
x += xstep;
posx += absxstep;
}
vy += val->ystep;
y += ystep;
posy += absystep;
}
break;
}
default:
while (posy < ylen)
{
vx = val->xstart;
posx = 0;
x = xstart;
while (posx < xlen)
{
*((Uint32 *) (pixels + y * padding) + x) =
(Uint32)*((Uint32 *) (valpixels + vy * val->padding) + vx);
vx += val->xstep;
x += xstep;
posx += absxstep;
}
vy += val->ystep;
y += ystep;
posy += absystep;
}
break;
}
Py_END_ALLOW_THREADS;
if (copied)
{
free (valpixels);
}
return 0;
}
static int
_array_assign_sequence (PyPixelArray *array, Py_ssize_t low, Py_ssize_t high,
PyObject *val)
{
SDL_Surface *surface;
Uint32 x = 0;
Uint32 y = 0;
int bpp;
int gooverx = 0;
Uint8 *pixels;
Uint32 color = 0;
Uint32 *colorvals = NULL;
Uint32 *nextcolor = NULL;
Py_ssize_t offset = 0;
Py_ssize_t seqsize = PySequence_Size (val);
Uint32 xstart = 0;
Uint32 ystart = 0;
Uint32 xlen;
Uint32 ylen;
Sint32 xstep;
Sint32 ystep;
Uint32 padding;
Uint32 posx = 0;
Uint32 posy = 0;
Sint32 absxstep;
Sint32 absystep;
surface = PySurface_AsSurface (array->surface);
bpp = surface->format->BytesPerPixel;
pixels = (Uint8 *) surface->pixels;
/* Set the correct slice indices */
if (array->xlen == 1)
{
xstart = array->xstart;
ystart = array->ystart + low * array->ystep;
xlen = array->xlen;
ylen = ABS (high - low);
ystep = array->ystep;
xstep = array->xstep;
padding = array->padding;
}
else
{
xstart = array->xstart + low * array->xstep;
ystart = array->ystart;
xlen = ABS (high - low);
ylen = array->ylen;
xstep = array->xstep;
ystep = array->ystep;
padding = array->padding;
}
if ((Uint32)seqsize != ylen / ABS (ystep))
{
if ((Uint32)seqsize != xlen / ABS (xstep))
{
PyErr_SetString(PyExc_ValueError, "sequence size mismatch");
return -1;
}
gooverx = 1; /* We have to iterate over the x axis. */
}
if (seqsize == 1)
{
/* Single value assignment. */
_set_single_pixel (pixels, bpp, xstart, ystart + padding * ystep,
surface->format, color);
return 0;
}
/* Copy the values. */
colorvals = malloc (sizeof (Uint32) * seqsize);
if (!colorvals)
{
PyErr_SetString (PyExc_ValueError, "could not copy colors");
return -1;
}
for (offset = 0; offset < seqsize; offset++)
{
if (!_get_color_from_object (PySequence_Fast_GET_ITEM (val, offset),
surface->format, &color))
{
free (colorvals);
return -1;
}
colorvals[offset] = color;
}
absxstep = ABS (xstep);
absystep = ABS (ystep);
y = ystart;
nextcolor = colorvals;
Py_BEGIN_ALLOW_THREADS;
switch (bpp)
{
case 1:
if (gooverx)
{
while (posy < ylen)
{
posx = 0;
x = xstart;
nextcolor = colorvals;
while (posx < xlen)
{
color = *nextcolor++;
*((Uint8 *) pixels + y * padding + x) = (Uint8) color;
x += xstep;
posx += absxstep;
}
y += ystep;
posy += absystep;
}
}
else
{
while (posy < ylen)
{
posx = 0;
x = xstart;
color = *nextcolor++;
while (posx < xlen)
{
*((Uint8 *) pixels + y * padding + x) = (Uint8) color;
x += xstep;
posx += absxstep;
}
y += ystep;
posy += absystep;
}
}
break;
case 2:
if (gooverx)
{
while (posy < ylen)
{
posx = 0;
x = xstart;
nextcolor = colorvals;
while (posx < xlen)
{
color = *nextcolor++;
*((Uint16 *) (pixels + y * padding) + x) = (Uint16) color;
x += xstep;
posx += absxstep;
}
y += ystep;
posy += absystep;
}
}
else
{
while (posy < ylen)
{
posx = 0;
x = xstart;
color = *nextcolor++;
while (posx < xlen)
{
*((Uint16 *) (pixels + y * padding) + x) = (Uint16) color;
x += xstep;
posx += absxstep;
}
y += ystep;
posy += absystep;
}
}
break;
case 3:
{
Uint8 *px;
SDL_PixelFormat *format = surface->format;
if (gooverx)
{
while (posy < ylen)
{
posx = 0;
x = xstart;
nextcolor = colorvals;
while (posx < xlen)
{
color = *nextcolor++;
px = ((Uint8 *) (pixels + y * padding) + x * 3);
#if (SDL_BYTEORDER == SDL_LIL_ENDIAN)
*(px + (format->Rshift >> 3)) = (Uint8) (color >> 16);
*(px + (format->Gshift >> 3)) = (Uint8) (color >> 8);
*(px + (format->Bshift >> 3)) = (Uint8) color;
#else
*(px + 2 - (format->Rshift >> 3)) = (Uint8) (color >> 16);
*(px + 2 - (format->Gshift >> 3)) = (Uint8) (color >> 8);
*(px + 2 - (format->Bshift >> 3)) = (Uint8) color;
#endif
x += xstep;
posx += absxstep;
}
y += ystep;
posy += absystep;
}
}
else
{
while (posy < ylen)
{
posx = 0;
x = xstart;
color = *nextcolor++;
while (posx < xlen)
{
px = ((Uint8 *) (pixels + y * padding) + x * 3);
#if (SDL_BYTEORDER == SDL_LIL_ENDIAN)
*(px + (format->Rshift >> 3)) = (Uint8) (color >> 16);
*(px + (format->Gshift >> 3)) = (Uint8) (color >> 8);
*(px + (format->Bshift >> 3)) = (Uint8) color;
#else
*(px + 2 - (format->Rshift >> 3)) = (Uint8) (color >> 16);
*(px + 2 - (format->Gshift >> 3)) = (Uint8) (color >> 8);
*(px + 2 - (format->Bshift >> 3)) = (Uint8) color;
#endif
x += xstep;
posx += absxstep;
}
y += ystep;
posy += absystep;
}
}
break;
}
default:
if (gooverx)
{
while (posy < ylen)
{
posx = 0;
x = xstart;
nextcolor = colorvals;
while (posx < xlen)
{
color = *nextcolor++;
*((Uint32 *) (pixels + y * padding) + x) = color;
x += xstep;
posx += absxstep;
}
y += ystep;
posy += absystep;
}
}
else
{
while (posy < ylen)
{
posx = 0;
x = xstart;
color = *nextcolor++;
while (posx < xlen)
{
*((Uint32 *) (pixels + y * padding) + x) = color;
x += xstep;
posx += absxstep;
}
y += ystep;
posy += absystep;
}
}
break;
}
free (colorvals);
Py_END_ALLOW_THREADS;
return 0;
}
static int
_array_assign_slice (PyPixelArray *array, Py_ssize_t low, Py_ssize_t high,
Uint32 color)
{
SDL_Surface *surface;
Uint32 x = 0;
Uint32 y = 0;
int bpp;
Uint8 *pixels;
Uint32 xstart = 0;
Uint32 ystart = 0;
Uint32 xlen;
Uint32 ylen;
Sint32 xstep;
Sint32 ystep;
Uint32 padding;
Uint32 posx = 0;
Uint32 posy = 0;
Sint32 absxstep;
Sint32 absystep;
surface = PySurface_AsSurface (array->surface);
bpp = surface->format->BytesPerPixel;
pixels = (Uint8 *) surface->pixels;
/* Set the correct slice indices */
if (array->xlen == 1)
{
xstart = array->xstart;
ystart = array->ystart + low * array->ystep;
xlen = array->xlen;
ylen = ABS (high - low);
ystep = array->ystep;
xstep = array->xstep;
padding = array->padding;
}
else
{
xstart = array->xstart + low * array->xstep;
ystart = array->ystart;
xlen = ABS (high - low);
ylen = array->ylen;
xstep = array->xstep;
ystep = array->ystep;
padding = array->padding;
}
absxstep = ABS (xstep);
absystep = ABS (ystep);
y = ystart;
Py_BEGIN_ALLOW_THREADS;
/* Single value assignment. */
switch (bpp)
{
case 1:
while (posy < ylen)
{
posx = 0;
x = xstart;
while (posx < xlen)
{
*((Uint8 *) pixels + y * padding + x) = (Uint8) color;
x += xstep;
posx += absxstep;
}
y += ystep;
posy += absystep;
}
break;
case 2:
while (posy < ylen)
{
posx = 0;
x = xstart;
while (posx < xlen)
{
*((Uint16 *) (pixels + y * padding) + x) = (Uint16) color;
x += xstep;
posx += absxstep;
}
y += ystep;
posy += absystep;
}
break;
case 3:
{
Uint8 *px;
SDL_PixelFormat *format = surface->format;
while (posy < ylen)
{
posx = 0;
x = xstart;
while (posx < xlen)
{
px = ((Uint8 *) (pixels + y * padding) + x * 3);
#if (SDL_BYTEORDER == SDL_LIL_ENDIAN)
*(px + (format->Rshift >> 3)) = (Uint8) (color >> 16);
*(px + (format->Gshift >> 3)) = (Uint8) (color >> 8);
*(px + (format->Bshift >> 3)) = (Uint8) color;
#else
*(px + 2 - (format->Rshift >> 3)) = (Uint8) (color >> 16);
*(px + 2 - (format->Gshift >> 3)) = (Uint8) (color >> 8);
*(px + 2 - (format->Bshift >> 3)) = (Uint8) color;
#endif
x += xstep;
posx += absxstep;
}
y += ystep;
posy += absystep;
}
break;
}
default: /* 4 bpp */
while (posy < ylen)
{
posx = 0;
x = xstart;
while (posx < xlen)
{
*((Uint32 *) (pixels + y * padding) + x) = color;
x += xstep;
posx += absxstep;
}
y += ystep;
posy += absystep;
}
break;
}
Py_END_ALLOW_THREADS;
return 0;
}
/**
* array[x] = ...
*/
static int
_pxarray_ass_item (PyPixelArray *array, Py_ssize_t _index, PyObject *value)
{
SDL_Surface *surface;
Uint32 x = 0;
Uint32 y = 0;
int bpp;
Uint8 *pixels;
Uint32 color = 0;
Uint32 xstart = 0;
Uint32 ystart = 0;
Uint32 xlen;
Uint32 ylen;
Sint32 xstep;
Sint32 ystep;
Uint32 padding;
Uint32 posx = 0;
Uint32 posy = 0;
Sint32 absxstep;
Sint32 absystep;
surface = PySurface_AsSurface (array->surface);
bpp = surface->format->BytesPerPixel;
pixels = (Uint8 *) surface->pixels;
if (!_get_color_from_object (value, surface->format, &color))
{
if (PyPixelArray_Check (value))
{
PyErr_Clear (); /* _get_color_from_object */
return _array_assign_array (array, _index, _index + 1,
(PyPixelArray *) value);
}
else if (PySequence_Check (value))
{
PyErr_Clear (); /* _get_color_from_object */
return _array_assign_sequence (array, _index, _index + 1, value);
}
else /* Error already set by _get_color_from_object(). */
return -1;
}
/* Set the correct slice indices */
if (array->xlen == 1)
{
xstart = array->xstart;
ystart = array->ystart + _index * array->ystep;
xlen = array->xlen;
ylen = 1;
ystep = array->ystep;
xstep = array->xstep;
padding = array->padding;
}
else
{
xstart = array->xstart + _index * array->xstep;
ystart = array->ystart;
xlen = 1;
ylen = array->ylen;
xstep = array->xstep;
ystep = array->ystep;
padding = array->padding;
}
/*
printf ("ITEM: %d:%d, %d:%d %d:%d %d\n",
xstart, ystart, xlen, xstep, ylen, ystep, padding);
*/
absxstep = ABS (xstep);
absystep = ABS (ystep);
y = ystart;
Py_BEGIN_ALLOW_THREADS;
/* Single value assignment. */
switch (bpp)
{
case 1:
while (posy < ylen)
{
posx = 0;
x = xstart;
while (posx < xlen)
{
*((Uint8 *) pixels + y * padding + x) = (Uint8) color;
x += xstep;
posx += absxstep;
}
y += ystep;
posy += absystep;
}
break;
case 2:
while (posy < ylen)
{
posx = 0;
x = xstart;
while (posx < xlen)
{
*((Uint16 *) (pixels + y * padding) + x) = (Uint16) color;
x += xstep;
posx += absxstep;
}
y += ystep;
posy += absystep;
}
break;
case 3:
{
Uint8 *px;
SDL_PixelFormat *format = surface->format;
while (posy < ylen)
{
posx = 0;
x = xstart;
while (posx < xlen)
{
px = ((Uint8 *) (pixels + y * padding) + x * 3);
#if (SDL_BYTEORDER == SDL_LIL_ENDIAN)
*(px + (format->Rshift >> 3)) = (Uint8) (color >> 16);
*(px + (format->Gshift >> 3)) = (Uint8) (color >> 8);
*(px + (format->Bshift >> 3)) = (Uint8) color;
#else
*(px + 2 - (format->Rshift >> 3)) = (Uint8) (color >> 16);
*(px + 2 - (format->Gshift >> 3)) = (Uint8) (color >> 8);
*(px + 2 - (format->Bshift >> 3)) = (Uint8) color;
#endif
x += xstep;
posx += absxstep;
}
y += ystep;
posy += absystep;
}
break;
}
default: /* 4 bpp */
while (posy < ylen)
{
posx = 0;
x = xstart;
while (posx < xlen)
{
*((Uint32 *) (pixels + y * padding) + x) = color;
x += xstep;
posx += absxstep;
}
y += ystep;
posy += absystep;
}
break;
}
Py_END_ALLOW_THREADS;
return 0;
}
/**
* array[x:y] = ....
*/
static int
_pxarray_ass_slice (PyPixelArray *array, Py_ssize_t low, Py_ssize_t high,
PyObject *value)
{
SDL_Surface *surface;
Uint32 color;
if (array->xlen != 1)
{
if (low < 0)
low = 0;
else if (low > (Sint32) array->xlen)
low = array->xlen;
if (high < low)
high = low;
else if (high > (Sint32) array->xlen)
high = array->xlen;
}
else
{
if (low < 0)
low = 0;
else if (low > (Sint32) array->ylen)
low = array->ylen;
if (high < low)
high = low;
else if (high > (Sint32) array->ylen)
high = array->ylen;
}
surface = PySurface_AsSurface (array->surface);
/*
printf ("SLICE IS: %d:%d\n", low, high);
*/
if (PyPixelArray_Check (value))
{
return _array_assign_array (array, low, high, (PyPixelArray *) value);
}
else if (_get_color_from_object (value, surface->format, &color))
{
return _array_assign_slice (array, low, high, color);
}
else if (PySequence_Check (value))
{
PyErr_Clear (); /* In case _get_color_from_object set it */
return _array_assign_sequence (array, low, high, value);
}
return 0;
}
/**
* x in array
*/
static int
_pxarray_contains (PyPixelArray *array, PyObject *value)
{
SDL_Surface *surface;
Uint32 x = 0;
Uint32 y = 0;
Uint8 *pixels;
int bpp;
Uint32 color;
Uint32 posx = 0;
Uint32 posy = 0;
Sint32 absxstep;
Sint32 absystep;
int found = 0;
surface = PySurface_AsSurface (array->surface);
bpp = surface->format->BytesPerPixel;
pixels = (Uint8 *) surface->pixels;
if (!_get_color_from_object (value, surface->format, &color))
return -1;
absxstep = ABS (array->xstep);
absystep = ABS (array->ystep);
y = array->ystart;
Py_BEGIN_ALLOW_THREADS;
switch (bpp)
{
case 1:
while (posy < array->ylen && !found)
{
posx = 0;
x = array->xstart;
while (posx < array->xlen)
{
if (*((Uint8 *) pixels + y * array->padding + x)
== (Uint8) color)
{
found = 1;
break;
}
x += array->xstep;
posx += absxstep;
}
y += array->ystep;
posy += absystep;
}
break;
case 2:
while (posy < array->ylen && !found)
{
posx = 0;
x = array->xstart;
while (posx < array->xlen)
{
if (*((Uint16 *) (pixels + y * array->padding) + x)
== (Uint16) color)
{
found = 1;
break;
}
x += array->xstep;
posx += absxstep;
}
y += array->ystep;
posy += absystep;
}
break;
case 3:
{
Uint32 pxcolor;
Uint8 *pix;
while (posy < array->ylen && !found)
{
posx = 0;
x = array->xstart;
while (posx < array->xlen)
{
pix = ((Uint8 *) (pixels + y * array->padding) + x * 3);
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
pxcolor = (pix[0]) + (pix[1] << 8) + (pix[2] << 16);
#else
pxcolor = (pix[2]) + (pix[1] << 8) + (pix[0] << 16);
#endif
if (pxcolor == color)
{
found = 1;
break;
}
x += array->xstep;
posx += absxstep;
}
y += array->ystep;
posy += absystep;
}
break;
}
default: /* 4 bpp */
while (posy < array->ylen && !found)
{
posx = 0;
x = array->xstart;
while (posx < array->xlen)
{
if (*((Uint32 *) (pixels + y * array->padding) + x)
== color)
{
found = 1;
break;
}
x += array->xstep;
posx += absxstep;
}
y += array->ystep;
posy += absystep;
}
break;
}
Py_END_ALLOW_THREADS;
return found;
}
/**
* iter (arrray), for x in array
*/
static PyObject*
_pxarray_iter (PyPixelArray *array)
{
/*
printf ("Iter ARRAY: %d:%d:%d %d:%d:%d\n",
array->xstart, array->xlen, array->xstep,
array->ystart, array->ylen, array->ystep);
*/
return PySeqIter_New ((PyObject *) array);
}
/**** Mapping interfaces ****/
/**
* Internally used parser function for the 2D slices:
* array[x,y], array[:,:], ...
*/
static int
_get_subslice (PyObject *op, Py_ssize_t length, Py_ssize_t *start,
Py_ssize_t *stop, Py_ssize_t *step)
{
*start = -1;
*stop = -1;
*step = -1;
if (PySlice_Check (op))
{
Py_ssize_t slicelen;
/* Operator is a slice: array[x::, */
if (PySlice_GetIndicesEx ((PySliceObject *) op, length,
start, stop, step, &slicelen) < 0)
{
return 0;
}
}
else if (PyInt_Check (op))
{
/* Plain index: array[x, */
*start = PyInt_AsLong (op);
if (*start < 0)
*start += length;
if (*start >= length || *start < 0)
{
PyErr_SetString(PyExc_IndexError, "invalid index");
return 0;
}
*stop = (*start) + 1;
*step = 1;
}
else if (PyLong_Check (op))
{
long long val = -1;
/* Plain index: array[x, */
val = PyLong_AsLong (op);
if ((val < INT_MIN) || (val > INT_MAX))
{
PyErr_SetString(PyExc_ValueError,
"index too big for array access");
return 0;
}
*start = (int) val;
if (*start < 0)
*start += length;
if (*start >= length || *start < 0)
{
PyErr_SetString(PyExc_IndexError, "invalid index");
return 0;
}
*stop = (*start) + 1;
*step = 1;
}
return 1;
}
/**
* Slicing support for 1D and 2D access.
* array[x,y] is only supported for 2D arrays.
*/
static PyObject*
_pxarray_subscript (PyPixelArray *array, PyObject *op)
{
SDL_Surface *surface = PySurface_AsSurface (array->surface);
/* Note: order matters here.
* First check array[x,y], then array[x:y:z], then array[x]
* Otherwise it'll fail.
*/
if (PySequence_Check (op))
{
PyObject *obj;
Py_ssize_t size = PySequence_Size (op);
Py_ssize_t xstart, xstop, xstep;
Py_ssize_t ystart, ystop, ystep;
Py_ssize_t lenx, leny;
if (size == 0)
{
/* array[,], array[()] ... */
Py_INCREF (array);
return (PyObject *) array;
}
if (size > 2 || (size == 2 && array->xlen == 1))
return RAISE (PyExc_IndexError, "too many indices for the array");
lenx = (array->xlen > 1) ? array->xlen / ABS (array->xstep) : 0;
leny = array->ylen / ABS (array->ystep);
obj = PySequence_Fast_GET_ITEM (op, 0);
if (obj == Py_Ellipsis || obj == Py_None)
{
/* Operator is the ellipsis or None
* array[...,XXX], array[None,XXX]
*/
xstart = 0;
xstop = array->xlen;
xstep = array->xstep;
}
else if (!_get_subslice (obj, lenx, &xstart, &xstop, &xstep))
{
/* Error on retrieving the subslice. */
return NULL;
}
if (size == 2)
{
obj = PySequence_Fast_GET_ITEM (op, 1);
if (obj == Py_Ellipsis || obj == Py_None)
{
/* Operator is the ellipsis or None
* array[XXX,...], array[XXX,None]
*/
ystart = array->ystart;
ystop = array->ylen;
ystep = array->ystep;
}
else if (!_get_subslice (obj, leny, &ystart, &ystop, &ystep))
{
/* Error on retrieving the subslice. */
return NULL;
}
}
else
{
ystart = array->ystart;
ystop = array->ylen;
ystep = array->ystep;
}
/* Null value? */
if (xstart == xstop || ystart == ystop)
Py_RETURN_NONE;
/*
printf ("X: %d:%d:%d Y: %d:%d:%d\n", xstart, xstop, xstep,
ystart, ystop, ystep);
*/
/* Single value? */
if (ABS (xstop - xstart) == 1 && ABS (ystop - ystart) == 1)
{
return _get_single_pixel ((Uint8 *) surface->pixels,
surface->format->BytesPerPixel, array->xstart + xstart,
ystart * array->padding * array->ystep);
}
/*
printf ("NEW ARRAY: %d:%d:%d %d:%d:%d\n",
array->xstart + xstart, ABS (xstop - xstart), xstep,
array->ystart + ystart, ABS (ystop - ystart), ystep);
*/
return (PyObject *) _pxarray_new_internal (&PyPixelArray_Type,
array->surface,
(Uint32) array->xstart + xstart,
(Uint32) array->ystart + ystart,
(Uint32) ABS (xstop - xstart),
(Uint32) ABS (ystop - ystart),
(Sint32) xstep,
(Sint32) ystep,
(Uint32) array->padding, (PyObject *) array);
}
else if (PySlice_Check (op))
{
/* A slice */
Py_ssize_t slicelen;
Py_ssize_t step;
Py_ssize_t start;
Py_ssize_t stop;
int retval;
if (array->xlen > 1)
{
/* 2D array - slice along the x axis */
retval = PySlice_GetIndicesEx ((PySliceObject *) op,
(Py_ssize_t) (array->xlen / ABS (array->xstep)), &start, &stop,
&step, &slicelen);
}
else
{
/* 1D array - use the y axis. */
retval = PySlice_GetIndicesEx ((PySliceObject *) op,
(Py_ssize_t) (array->ylen / ABS (array->ystep)), &start, &stop,
&step, &slicelen);
}
if (retval < 0 || slicelen < 0)
return NULL;
if (slicelen == 0)
Py_RETURN_NONE;
/*
printf ("start: %d, stop: %d, step: %d, len: %d\n", start, stop,
step, slicelen);
*/
return (PyObject *) _array_slice_internal (array, start, stop, step);
}
else if (PyIndex_Check (op) || PyInt_Check (op) || PyLong_Check (op))
{
Py_ssize_t i;
#if PY_VERSION_HEX >= 0x02050000
PyObject *val = PyNumber_Index (op);
if (!val)
return NULL;
/* A simple index. */
i = PyNumber_AsSsize_t (val, PyExc_IndexError);
#else
if (PyInt_Check (op))
i = PyInt_AsLong (op);
else
i = PyLong_AsLong (op);
#endif
if (i == -1 && PyErr_Occurred ())
return NULL;
if (i < 0)
i += (array->xlen > 1) ? array->xlen / ABS (array->xstep) :
array->ylen / ABS (array->ystep);
return _pxarray_item (array, i);
}
return RAISE (PyExc_TypeError,
"index must be an integer, sequence or slice");
}
static int
_pxarray_ass_subscript (PyPixelArray *array, PyObject* op, PyObject* value)
{
/* TODO: by time we can make this faster by avoiding the creation of
* temporary subarrays.
*/
/* Note: order matters here.
* First check array[x,y], then array[x:y:z], then array[x]
* Otherwise it'll fail.
*/
if (PySequence_Check (op))
{
PyPixelArray *tmparray;
PyObject *obj;
Py_ssize_t size = PySequence_Size (op);
Py_ssize_t xstart, xstop, xstep;
Py_ssize_t ystart, ystop, ystep;
Py_ssize_t lenx, leny;
int retval;
if (size == 0)
{
/* array[,], array[()] ... */
if (array->xlen == 1)
return _pxarray_ass_slice (array, 0, (Py_ssize_t) array->ylen,
value);
else
return _pxarray_ass_slice (array, 0, (Py_ssize_t) array->xlen,
value);
}
if (size > 2 || (size == 2 && array->xlen == 1))
{
PyErr_SetString (PyExc_IndexError,
"too many indices for the array");
return -1;
}
lenx = (array->xlen > 1) ? array->xlen / ABS (array->xstep) : 0;
leny = array->ylen / ABS (array->ystep);
obj = PySequence_Fast_GET_ITEM (op, 0);
if (obj == Py_Ellipsis || obj == Py_None)
{
/* Operator is the ellipsis or None
* array[...,XXX], array[None,XXX]
*/
xstart = 0;
xstop = array->xlen;
xstep = array->xstep;
}
else if (!_get_subslice (obj, lenx, &xstart, &xstop, &xstep))
{
/* Error on retrieving the subslice. */
return -1;
}
if (size == 2)
{
obj = PySequence_Fast_GET_ITEM (op, 1);
if (obj == Py_Ellipsis || obj == Py_None)
{
/* Operator is the ellipsis or None
* array[XXX,...], array[XXX,None]
*/
ystart = array->ystart;
ystop = array->ylen;
ystep = array->ystep;
}
else if (!_get_subslice (obj, leny, &ystart, &ystop, &ystep))
{
/* Error on retrieving the subslice. */
return -1;
}
}
else
{
ystart = array->ystart;
ystop = array->ylen;
ystep = array->ystep;
}
/* Null value? Do nothing then. */
if (xstart == xstop || ystart == ystop)
return 0;
/* Single value? */
if (ABS (xstop - xstart) == 1 && ABS (ystop - ystart) == 1)
{
tmparray = _pxarray_new_internal (&PyPixelArray_Type,
array->surface,
(Uint32) array->xstart + xstart,
(Uint32) array->ystart + ystart,
1, 1, 1, 1, (Uint32) array->padding, (PyObject *) array);
if (!tmparray)
return -1;
retval = _pxarray_ass_item (tmparray, 0, value);
Py_DECREF (tmparray);
return retval;
}
tmparray =_pxarray_new_internal (&PyPixelArray_Type,
array->surface,
(Uint32) array->xstart + xstart, (Uint32) array->ystart + ystart,
(Uint32) ABS (xstop - xstart), (Uint32) ABS (ystop - ystart),
(Sint32) xstep, (Sint32) ystep,
(Uint32) array->padding, (PyObject *) array);
if (!tmparray)
return -1;
if (tmparray->xlen == 1)
retval = _pxarray_ass_slice (tmparray, 0,
(Py_ssize_t) tmparray->ylen, value);
else
retval = _pxarray_ass_slice (tmparray, 0,
(Py_ssize_t) tmparray->xlen, value);
Py_DECREF (tmparray);
return retval;
}
else if (PySlice_Check (op))
{
/* A slice */
PyPixelArray *tmparray;
Py_ssize_t slicelen;
Py_ssize_t step;
Py_ssize_t start;
Py_ssize_t stop;
int retval;
if (array->xlen > 1)
{
/* 2D array - slice along the x axis */
retval = PySlice_GetIndicesEx ((PySliceObject *) op,
(Py_ssize_t) (array->xlen / ABS (array->xstep)), &start, &stop,
&step, &slicelen);
}
else
{
/* 1D array - use the y axis. */
retval = PySlice_GetIndicesEx ((PySliceObject *) op,
(Py_ssize_t) (array->ylen / ABS (array->ystep)), &start, &stop,
&step, &slicelen);
}
if (retval < 0 || slicelen < 0)
return -1;
if (slicelen == 0)
return 0;
/*
printf ("start: %d, stop: %d, step: %d, len: %d\n", start, stop,
step, slicelen);
*/
tmparray = (PyPixelArray *) _array_slice_internal (array, start, stop,
step);
if (!tmparray)
return -1;
if (tmparray->xlen == 1)
retval = _pxarray_ass_slice (tmparray, 0,
(Py_ssize_t) tmparray->ylen, value);
else
retval = _pxarray_ass_slice (tmparray, 0,
(Py_ssize_t) tmparray->xlen, value);
Py_DECREF (tmparray);
return retval;
}
else if (PyIndex_Check (op) || PyInt_Check (op) || PyLong_Check (op))
{
Py_ssize_t i;
#if PY_VERSION_HEX >= 0x02050000
PyObject *val = PyNumber_Index (op);
if (!val)
return -1;
/* A simple index. */
i = PyNumber_AsSsize_t (val, PyExc_IndexError);
#else
if (PyInt_Check (op))
i = PyInt_AsLong (op);
else
i = PyLong_AsLong (op);
#endif
if (i == -1 && PyErr_Occurred ())
return -1;
if (i < 0)
i += (array->xlen > 1) ? array->xlen / ABS (array->xstep) :
array->ylen / ABS (array->ystep);
return _pxarray_ass_item (array, i, value);
}
PyErr_SetString (PyExc_TypeError,
"index must be an integer, sequence or slice");
return -1;
}
/**** C API interfaces ****/
static PyObject* PyPixelArray_New (PyObject *surfobj)
{
SDL_Surface *surface;
if (!PySurface_Check (surfobj))
return RAISE (PyExc_TypeError, "argument is no a Surface");
surface = PySurface_AsSurface (surfobj);
if (surface->format->BytesPerPixel < 1 ||
surface->format->BytesPerPixel > 4)
return RAISE (PyExc_ValueError,
"unsupported bit depth for reference array");
return (PyObject *) _pxarray_new_internal
(&PyPixelArray_Type, surfobj, 0, 0,
(Uint32) surface->w, (Uint32) surface->h, 1, 1,
(Uint32) surface->pitch, NULL);
}
MODINIT_DEFINE (pixelarray)
{
PyObject *module;
PyObject *dict;
PyObject *apiobj;
int ecode;
static void* c_api[PYGAMEAPI_PIXELARRAY_NUMSLOTS];
#if PY3
static struct PyModuleDef _module = {
PyModuleDef_HEAD_INIT,
"pixelarray",
NULL,
-1,
NULL,
NULL, NULL, NULL, NULL
};
#endif
/* imported needed apis; Do this first so if there is an error
the module is not loaded.
*/
import_pygame_base ();
if (PyErr_Occurred ()) {
MODINIT_ERROR;
}
import_pygame_color();
if (PyErr_Occurred ()) {
MODINIT_ERROR;
}
import_pygame_surface ();
if (PyErr_Occurred ()) {
MODINIT_ERROR;
}
/* type preparation */
if (PyType_Ready (&PyPixelArray_Type) < 0)
{
MODINIT_ERROR;
}
/* create the module */
#if PY3
module = PyModule_Create (&_module);
#else
module = Py_InitModule3 (MODPREFIX "pixelarray", NULL, NULL);
#endif
if (module == NULL)
{
MODINIT_ERROR;
}
Py_INCREF (&PyPixelArray_Type);
if (PyModule_AddObject (module, "PixelArray",
(PyObject *) &PyPixelArray_Type) == -1)
{
Py_DECREF ((PyObject *) &PyPixelArray_Type);
DECREF_MOD (module);
MODINIT_ERROR;
}
PyPixelArray_Type.tp_getattro = PyObject_GenericGetAttr;
dict = PyModule_GetDict (module);
c_api[0] = &PyPixelArray_Type;
c_api[1] = PyPixelArray_New;
apiobj = PyCObject_FromVoidPtr (c_api, NULL);
if (apiobj == NULL)
{
DECREF_MOD (module);
MODINIT_ERROR;
}
ecode = PyDict_SetItemString (dict, PYGAMEAPI_LOCAL_ENTRY, apiobj);
Py_DECREF (apiobj);
if (ecode == -1)
{
DECREF_MOD (module);
MODINIT_ERROR;
}
MODINIT_RETURN (module);
}
pygame-1.9.1release/src/pgopengl.h 0000644 0001750 0001750 00000000613 11024515251 017012 0 ustar vincent vincent #if !defined(PGOPENGL_H)
#define PGOPENGL_H
/** This header includes definitions of Opengl functions as pointer types for
** use with the SDL function SDL_GL_GetProcAddress.
**/
#if defined(_WIN32)
#define GL_APIENTRY __stdcall
#else
#define GL_APIENTRY
#endif
typedef void (GL_APIENTRY *GL_glReadPixels_Func)(int, int, int, int, unsigned int, unsigned int, void*);
#endif
pygame-1.9.1release/src/pgcompat.h 0000644 0001750 0001750 00000007504 11176715722 017034 0 ustar vincent vincent /* Python 2.x/3.x compitibility tools
*/
#if !defined(PGCOMPAT_H)
#define PGCOMPAT_H
#if PY_MAJOR_VERSION >= 3
#define PY3 1
/* Define some aliases for the removed PyInt_* functions */
#define PyInt_Check(op) PyLong_Check(op)
#define PyInt_FromString PyLong_FromString
#define PyInt_FromUnicode PyLong_FromUnicode
#define PyInt_FromLong PyLong_FromLong
#define PyInt_FromSize_t PyLong_FromSize_t
#define PyInt_FromSsize_t PyLong_FromSsize_t
#define PyInt_AsLong PyLong_AsLong
#define PyInt_AsSsize_t PyLong_AsSsize_t
#define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask
#define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask
#define PyInt_AS_LONG PyLong_AS_LONG
#define PyNumber_Int PyNumber_Long
/* Weakrefs flags changed in 3.x */
#define Py_TPFLAGS_HAVE_WEAKREFS 0
/* Module init function returns new module instance. */
#define MODINIT_RETURN(x) return x
#define MODINIT_DEFINE(mod_name) PyMODINIT_FUNC PyInit_##mod_name (void)
#define DECREF_MOD(mod) Py_DECREF (mod)
/* Type header differs. */
#define TYPE_HEAD(x,y) PyVarObject_HEAD_INIT(x,y)
/* Text interface. Use unicode strings. */
#define Text_Type PyUnicode_Type
#define Text_Check PyUnicode_Check
#define Text_FromUTF8 PyUnicode_FromString
#define Text_FromUTF8AndSize PyUnicode_FromStringAndSize
#define Text_FromFormat PyUnicode_FromFormat
#define Text_GetSize PyUnicode_GetSize
#define Text_GET_SIZE PyUnicode_GET_SIZE
/* Binary interface. Use bytes. */
#define Bytes_Type PyBytes_Type
#define Bytes_Check PyBytes_Check
#define Bytes_Size PyBytes_Size
#define Bytes_AsString PyBytes_AsString
#define Bytes_AsStringAndSize PyBytes_AsStringAndSize
#define Bytes_FromStringAndSize PyBytes_FromStringAndSize
#define Bytes_AS_STRING PyBytes_AS_STRING
#define Bytes_GET_SIZE PyBytes_GET_SIZE
#define IsTextObj(x) (PyUnicode_Check(x) || PyBytes_Check(x))
/* Renamed builtins */
#define BUILTINS_MODULE "builtins"
#define BUILTINS_UNICODE "str"
#define BUILTINS_UNICHR "chr"
#else /* PY_VERSION_HEX >= 0x03000000 */
#define PY3 0
/* Module init function returns nothing. */
#define MODINIT_RETURN(x) return
#define MODINIT_DEFINE(mod_name) PyMODINIT_FUNC init##mod_name (void)
#define DECREF_MOD(mod)
/* Type header differs. */
#define TYPE_HEAD(x,y) \
PyObject_HEAD_INIT(x) \
0,
/* Text interface. Use ascii strings. */
#define Text_Type PyString_Type
#define Text_Check PyString_Check
#define Text_FromUTF8 PyString_FromString
#define Text_FromUTF8AndSize PyString_FromStringAndSize
#define Text_FromFormat PyString_FromFormat
#define Text_GetSize PyString_GetSize
#define Text_GET_SIZE PyString_GET_SIZE
/* Binary interface. Use ascii strings. */
#define Bytes_Type PyString_Type
#define Bytes_Check PyString_Check
#define Bytes_Size PyString_Size
#define Bytes_AsString PyString_AsString
#define Bytes_AsStringAndSize PyString_AsStringAndSize
#define Bytes_FromStringAndSize PyString_FromStringAndSize
#define Bytes_AS_STRING PyString_AS_STRING
#define Bytes_GET_SIZE PyString_GET_SIZE
/* Renamed builtins */
#define BUILTINS_MODULE "__builtin__"
#define BUILTINS_UNICODE "unicode"
#define BUILTINS_UNICHR "unichr"
#endif /* PY_VERSION_HEX >= 0x03000000 */
#define MODINIT_ERROR MODINIT_RETURN (NULL)
/* Module state. These macros are used to define per-module macros.
* v - global state variable (Python 2.x)
* s - global state structure (Python 3.x)
*/
#define PY2_GETSTATE(v) (&(v))
#define PY3_GETSTATE(s, m) ((struct s *) PyModule_GetState (m))
/* Pep 3123: Making PyObject_HEAD conform to standard C */
#if !defined(Py_TYPE)
#define Py_TYPE(o) (((PyObject*)(o))->ob_type)
#define Py_REFCNT(o) (((PyObject*)(o))->ob_refcnt)
#define Py_SIZE(o) (((PyVarObject*)(o))->ob_size)
#endif
#endif /* !defined(PGCOMPAT_H) */
pygame-1.9.1release/src/pgarrinter.h 0000644 0001750 0001750 00000001614 11136035450 017360 0 ustar vincent vincent /* array structure interface version 3 declarations */
const int PAI_CONTIGUOUS = 0x01;
const int PAI_FORTRAN = 0x02;
const int PAI_ALIGNED = 0x100;
const int PAI_NOTSWAPPED = 0x200;
const int PAI_WRITEABLE = 0x400;
typedef struct {
int two; /* contains the integer 2 -- simple sanity check */
int nd; /* number of dimensions */
char typekind; /* kind in array -- character code of typestr */
int itemsize; /* size of each element */
int flags; /* flags indicating how the data should be */
/* interpreted */
Py_intptr_t *shape; /* A length-nd array of shape information */
Py_intptr_t *strides; /* A length-nd array of stride information */
void *data; /* A pointer to the first element of the array */
PyObject *descr; /* NULL or a data-description */
} PyArrayInterface;
pygame-1.9.1release/src/overlay.doc 0000644 0001750 0001750 00000004004 10351473250 017200 0 ustar vincent vincent pygame.Overlay
pygame object for video overlay graphics
pygame.Overlay(format, (width, height)): return Overlay
The Overlay objects provide support for accessing hardware video overlays.
Video overlays do not use standard RGB pixel formats, and can use multiple
resolutions of data to create a single image.
The Overlay objects represent lower level access to the display hardware.
To use the object you must understand the technical details of video overlays.
The Overlay format determines the type of pixel data used. Not all hardware
will support all types of overlay formats. Here is a list of available
format types:
YV12_OVERLAY, IYUV_OVERLAY, YUV2_OVERLAY, UYVY_OVERLAY, YVYU_OVERLAY
The width and height arguments control the size for the overlay image data.
The overlay image can be displayed at any size, not just the resolution of
the overlay.
The overlay objects are always visible, and always show above the regular
display contents.
display
set the overlay pixel data
Overlay.display((y, u, v)): return None
Overlay.display(): return None
Display the yuv data in SDL's overlay planes. The y, u, and v
arguments are strings of binary data. The data must be in the correct
format used to create the Overlay.
If no argument is passed in, the Overlay will simply be redrawn with the
current data. This can be useful when the Overlay is not really hardware
accelerated.
The strings are not validated, and improperly sized strings could crash the
program.
set_location
control where the overlay is displayed
Overlay.set_location(rect): return None
Set the location for the overlay. The overlay will always be shown relative
to the main display Surface. This does not actually redraw the overlay, it
will be updated on the next call to Overlay.display().
get_hardware
test if the Overlay is hardware accelerated
Overlay.get_hardware(rect): return int
Returns a True value when the Overlay is hardware accelerated. If the platform
does not support acceleration, software rendering is used.
pygame-1.9.1release/src/overlay.c 0000644 0001750 0001750 00000017252 11207055754 016674 0 ustar vincent vincent /*
* A part of the pydfb module. Provides interface for basic overlay
* manipulation functions.
* In this implementation overlay can use only one layer out of maximum
* possible. After getting overlay, no overlay can be created.
*
* Copyright (C) 2002-2003 Dmitry Borisov
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Dmitry Borisov
*/
#include
#include "pygame.h"
#include "pgcompat.h"
#include "pygamedocs.h"
typedef struct
{
PyObject_HEAD
SDL_Overlay *cOverlay;
GAME_Rect cRect;
} PyGameOverlay;
static void
overlay_dealloc (PyGameOverlay *self)
{
if (SDL_WasInit (SDL_INIT_VIDEO) && self->cOverlay)
SDL_FreeYUVOverlay (self->cOverlay);
PyObject_Free ((PyObject*)self);
}
static PyObject*
Overlay_SetLocation (PyGameOverlay *self, PyObject *args)
{
GAME_Rect *rect, temp;
rect = GameRect_FromObject (args, &temp);
if (!rect)
return RAISE (PyExc_TypeError, "Invalid rectstyle argument");
self->cRect.x = rect->x;
self->cRect.y = rect->y;
self->cRect.w = rect->w;
self->cRect.h = rect->h;
Py_RETURN_NONE;
}
static PyObject*
Overlay_Display (PyGameOverlay *self, PyObject *args)
{
SDL_Rect cRect;
// Parse data params for frame
int ls_y, ls_u, ls_v, y;
unsigned char *src_y=0, *src_u=0, *src_v=0;
if (PyTuple_Size (args))
{
if (!PyArg_ParseTuple (args, "(s#s#s#)", &src_y, &ls_y, &src_u, &ls_u,
&src_v, &ls_v))
return NULL;
}
if (src_y)
{
Uint8 *dst_y=0, *dst_u=0, *dst_v=0;
SDL_LockYUVOverlay (self->cOverlay);
// No clipping at this time( only support for YUV420 )
dst_y = self->cOverlay->pixels[0];
dst_v = self->cOverlay->pixels[1];
dst_u = self->cOverlay->pixels[2];
for (y = 0; y < self->cOverlay->h; y++)
{
memcpy (dst_y, src_y, self->cOverlay->w);
src_y += ls_y / self->cOverlay->h;
dst_y += self->cOverlay->pitches[0];
if (!(y & 1))
{
src_u += (ls_u * 2)/self->cOverlay->h;
src_v += (ls_v * 2)/self->cOverlay->h;
dst_u += self->cOverlay->pitches[ 1 ];
dst_v += self->cOverlay->pitches[ 2 ];
}
else
{
memcpy (dst_u, src_u, (ls_u * 2) / self->cOverlay->h);
memcpy (dst_v, src_v, (ls_v * 2) / self->cOverlay->h);
}
}
SDL_UnlockYUVOverlay (self->cOverlay);
}
cRect.x = self->cRect.x;
cRect.y = self->cRect.y;
cRect.w = self->cRect.w;
cRect.h = self->cRect.h;
SDL_DisplayYUVOverlay (self->cOverlay, &cRect);
Py_RETURN_NONE;
}
static PyObject*
Overlay_GetHardware (PyGameOverlay *self)
{
return PyInt_FromLong (self->cOverlay->hw_overlay);
}
PyObject*
Overlay_New (PyTypeObject *type, PyObject *args, PyObject *kwds)
{
int pixelformat;
PyGameOverlay *self;
int w, h;
SDL_Surface *screen;
if (!PyArg_ParseTuple (args, "i(ii)", &pixelformat, &w, &h))
return NULL;
if (!SDL_WasInit (SDL_INIT_VIDEO))
return RAISE
(PyExc_SDLError,
"cannot create overlay without pygame.display initialized");
screen = SDL_GetVideoSurface ();
if (!screen)
return RAISE (PyExc_SDLError, "Display mode not set");
// Create new Overlay object
self= (PyGameOverlay *)type->tp_alloc (type, 0);
if (!self)
return NULL;
// Create layer with desired format
self->cOverlay = SDL_CreateYUVOverlay (w, h, pixelformat, screen);
if (!self->cOverlay)
return RAISE (PyExc_SDLError, "Cannot create overlay");
self->cRect.x= 0;
self->cRect.y= 0;
self->cRect.w= w;
self->cRect.h= h;
return (PyObject*)self;
}
static PyMethodDef Overlay_methods[] = {
{ "set_location", (PyCFunction) Overlay_SetLocation, METH_VARARGS,
DOC_OVERLAYSETLOCATION },
{ "display", (PyCFunction) Overlay_Display, METH_VARARGS,
DOC_OVERLAYDISPLAY },
{ "get_hardware", (PyCFunction) Overlay_GetHardware, METH_NOARGS,
DOC_OVERLAYGETHARDWARE },
{NULL, NULL, 0, NULL} /* Sentinel */
};
PyTypeObject PyOverlay_Type =
{
TYPE_HEAD (NULL, 0)
"pygame.overlay", /*tp_name*/
sizeof(PyGameOverlay), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor) overlay_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
DOC_PYGAMEOVERLAY, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
Overlay_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
Overlay_New, /* tp_new */
};
static PyMethodDef _overlay_methods[] =
{
{ NULL, NULL, 0, NULL }
};
MODINIT_DEFINE (overlay)
{
PyObject *module;
#if PY3
static struct PyModuleDef _module = {
PyModuleDef_HEAD_INIT,
"overlay",
NULL,
-1,
_overlay_methods,
NULL, NULL, NULL, NULL
};
#endif
/* imported needed apis; Do this first so if there is an error
the module is not loaded.
*/
import_pygame_base ();
if (PyErr_Occurred ()) {
MODINIT_ERROR;
}
import_pygame_rect ();
if (PyErr_Occurred ()) {
MODINIT_ERROR;
}
if (PyType_Ready (&PyOverlay_Type) == -1) {
MODINIT_ERROR;
}
/* create the module */
#if PY3
module = PyModule_Create (&_module);
#else
module = Py_InitModule (MODPREFIX "overlay", _overlay_methods );
#endif
if (module == NULL) {
MODINIT_ERROR;
}
/* create the module reference */
Py_INCREF ((PyObject *)&PyOverlay_Type);
if (PyModule_AddObject (module, "Overlay",
(PyObject *)&PyOverlay_Type) == -1) {
Py_DECREF ((PyObject *)&PyOverlay_Type);
DECREF_MOD (module);
MODINIT_ERROR;
}
MODINIT_RETURN (module);
}
pygame-1.9.1release/src/numeric_arrayobject.h 0000644 0001750 0001750 00000041523 10737363157 021253 0 ustar vincent vincent /*
* Imported Numeric-24.2 numeric/arrayobject.h header file to make the
* Numeric dependency obsolete.
*/
/*
* Legal Notice
*
* *** Legal Notice for all LLNL-contributed files ***
*
* Copyright (c) 1996. The Regents of the University of California. All
* rights reserved.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose without fee is hereby granted, provided that this entire
* notice is included in all copies of any software which is or includes
* a copy or modification of this software and in all copies of the
* supporting documentation for such software.
*
* This work was produced at the University of California, Lawrence
* Livermore National Laboratory under contract no. W-7405-ENG-48
* between the U.S. Department of Energy and The Regents of the
* University of California for the operation of UC LLNL.
*
* DISCLAIMER
*
* This software was prepared as an account of work sponsored by an
* agency of the United States Government. Neither the United States
* Government nor the University of California nor any of their
* employees, makes any warranty, express or implied, or assumes any
* liability or responsibility for the accuracy, completeness, or
* usefulness of any information, apparatus, product, or process
* disclosed, or represents that its use would not infringe
* privately-owned rights. Reference herein to any specific commercial
* products, process, or service by trade name, trademark, manufacturer,
* or otherwise, does not necessarily constitute or imply its
* endorsement, recommendation, or favoring by the United States
* Government or the University of California. The views and opinions of
* authors expressed herein do not necessarily state or reflect those of
* the United States Government or the University of California, and
* shall not be used for advertising or product endorsement purposes.
*/
#ifndef Py_ARRAYOBJECT_H
#define Py_ARRAYOBJECT_H
#ifdef __cplusplus
extern "C" {
#endif
#define REFCOUNT(obj) (((PyObject *)(obj))->ob_refcnt)
#define MAX_ELSIZE 16
#define PyArray_UNSIGNED_TYPES
enum PyArray_TYPES { PyArray_CHAR, PyArray_UBYTE, PyArray_SBYTE,
PyArray_SHORT, PyArray_USHORT,
PyArray_INT, PyArray_UINT,
PyArray_LONG,
PyArray_FLOAT, PyArray_DOUBLE,
PyArray_CFLOAT, PyArray_CDOUBLE,
PyArray_OBJECT,
PyArray_NTYPES, PyArray_NOTYPE};
typedef void (PyArray_VectorUnaryFunc) (char *, int, char *, int, int);
typedef PyObject * (PyArray_GetItemFunc) (char *);
typedef int (PyArray_SetItemFunc) (PyObject *, char *);
typedef struct {
PyArray_VectorUnaryFunc *cast[PyArray_NTYPES]; /* Functions to cast to */
/* all other types */
PyArray_GetItemFunc *getitem;
PyArray_SetItemFunc *setitem;
int type_num, elsize;
char *one, *zero;
char type;
} PyArray_Descr;
/* Array flags */
#define CONTIGUOUS 1
#define OWN_DIMENSIONS 2
#define OWN_STRIDES 4
#define OWN_DATA 8
#define SAVESPACE 16
/* type bit */
#define SAVESPACEBIT 128
typedef struct {
PyObject_HEAD
char *data;
int nd;
int *dimensions, *strides;
PyObject *base;
PyArray_Descr *descr;
int flags;
PyObject *weakreflist;
} PyArrayObject;
/* Array Interface flags */
#define FORTRAN 0x002
#define ALIGNED 0x100
#define NOTSWAPPED 0x200
#define WRITEABLE 0x400
typedef struct {
int version;
int nd;
char typekind;
int itemsize;
int flags;
Py_intptr_t *shape;
Py_intptr_t *strides;
void *data;
} PyArrayInterface;
/*
* C API
*/
/* Type definitions */
#define PyArray_Type_NUM 0
/* Function definitions */
/* The following are not intended for use in user code, only needed by umath. */
/* If you write your own match library, you might want this function. */
#define PyArray_SetNumericOps_RET int
#define PyArray_SetNumericOps_PROTO (PyObject *)
#define PyArray_SetNumericOps_NUM 1
#define PyArray_INCREF_RET int
#define PyArray_INCREF_PROTO (PyArrayObject *ap)
#define PyArray_INCREF_NUM 2
#define PyArray_XDECREF_RET int
#define PyArray_XDECREF_PROTO (PyArrayObject *ap)
#define PyArray_XDECREF_NUM 3
/* Export the array error object. Is this a good idea? */
#define PyArrayError_RET PyObject *
#define PyArrayError_PROTO (void)
#define PyArrayError_NUM 4
/* Set the array print function to be a python function */
#define PyArray_SetStringFunction_RET void
#define PyArray_SetStringFunction_PROTO (PyObject *op, int repr)
#define PyArray_SetStringFunction_NUM 5
/* Get the PyArray_Descr structure for a typecode */
#define PyArray_DescrFromType_RET PyArray_Descr *
#define PyArray_DescrFromType_PROTO (int)
#define PyArray_DescrFromType_NUM 6
/* Cast an array to a different type */
#define PyArray_Cast_RET PyObject *
#define PyArray_Cast_PROTO (PyArrayObject *, int)
#define PyArray_Cast_NUM 7
/* Check the type coercion rules */
#define PyArray_CanCastSafely_RET int
#define PyArray_CanCastSafely_PROTO (int fromtype, int totype)
#define PyArray_CanCastSafely_NUM 8
/* Return the typecode to use for an object if it was an array */
#define PyArray_ObjectType_RET int
#define PyArray_ObjectType_PROTO (PyObject *, int)
#define PyArray_ObjectType_NUM 9
#define _PyArray_multiply_list_RET int
#define _PyArray_multiply_list_PROTO (int *lp, int n)
#define _PyArray_multiply_list_NUM 10
/* The following defines the C API for the array object for most users */
#define PyArray_SIZE(mp) (_PyArray_multiply_list((mp)->dimensions, (mp)->nd))
#define PyArray_NBYTES(mp) ((mp)->descr->elsize * PyArray_SIZE(mp))
/* Obviously this needs some work. */
#define PyArray_ISCONTIGUOUS(m) ((m)->flags & CONTIGUOUS)
#define PyArray_ISSPACESAVER(m) (((PyArrayObject *)m)->flags & SAVESPACE)
#define PyScalarArray_Check(m) (PyArray_Check((m)) && (((PyArrayObject *)(m))->nd == 0))
/* Return the size in number of items of an array */
#define PyArray_Size_RET int
#define PyArray_Size_PROTO (PyObject *)
#define PyArray_Size_NUM 11
/* Array creation functions */
/* new_array = PyArray_FromDims(n_dimensions, dimensions[n_dimensions], item_type); */
#define PyArray_FromDims_RET PyObject *
#define PyArray_FromDims_PROTO (int, int *, int)
#define PyArray_FromDims_NUM 12
/* array_from_existing_data = PyArray_FromDimsAndData(n_dims, dims[n_dims], item_type, old_data); */
/* WARNING: using PyArray_FromDimsAndData is not reccommended! It should only be used to refer to */
/* global arrays that will never be freed (like FORTRAN common blocks). */
#define PyArray_FromDimsAndData_RET PyObject *
#define PyArray_FromDimsAndData_PROTO (int, int *, int, char *)
#define PyArray_FromDimsAndData_NUM 13
/* Initialize from a python object. */
/* PyArray_ContiguousFromObject(object, typecode, min_dimensions, max_dimensions) */
/* if max_dimensions = 0, then any number of dimensions are allowed. */
/* If you want an exact number of dimensions, you should use max_dimensions */
/* = min_dimensions. */
#define PyArray_ContiguousFromObject_RET PyObject *
#define PyArray_ContiguousFromObject_PROTO (PyObject *, int, int, int)
#define PyArray_ContiguousFromObject_NUM 14
/* Same as contiguous, except guarantees a copy of the original data */
#define PyArray_CopyFromObject_RET PyObject *
#define PyArray_CopyFromObject_PROTO (PyObject *, int, int, int)
#define PyArray_CopyFromObject_NUM 15
/* Shouldn't be used unless you know what you're doing and are not scared by discontiguous arrays */
#define PyArray_FromObject_RET PyObject *
#define PyArray_FromObject_PROTO (PyObject *, int, int, int)
#define PyArray_FromObject_NUM 16
/* Return either an array, or if passed a 0d array return the appropriate python scalar */
#define PyArray_Return_RET PyObject *
#define PyArray_Return_PROTO (PyArrayObject *)
#define PyArray_Return_NUM 17
#define PyArray_Reshape_RET PyObject *
#define PyArray_Reshape_PROTO (PyArrayObject *ap, PyObject *shape)
#define PyArray_Reshape_NUM 18
#define PyArray_Copy_RET PyObject *
#define PyArray_Copy_PROTO (PyArrayObject *ap)
#define PyArray_Copy_NUM 19
#define PyArray_Take_RET PyObject *
#define PyArray_Take_PROTO (PyObject *ap, PyObject *items, int axis)
#define PyArray_Take_NUM 20
/*Getting arrays in various useful forms. */
#define PyArray_As1D_RET int
#define PyArray_As1D_PROTO (PyObject **op, char **ptr, int *d1, int typecode)
#define PyArray_As1D_NUM 21
#define PyArray_As2D_RET int
#define PyArray_As2D_PROTO (PyObject **op, char ***ptr, int *d1, int *d2, int typecode)
#define PyArray_As2D_NUM 22
#define PyArray_Free_RET int
#define PyArray_Free_PROTO (PyObject *op, char *ptr)
#define PyArray_Free_NUM 23
/* array_from_existing_data = PyArray_FromDimsAndDataAndDescr(n_dims, dims[n_dims], descr, old_data); */
/* WARNING: using PyArray_FromDimsAndDataAndDescr is not reccommended! It should only be used to refer to */
/* global arrays that will never be freed (like FORTRAN common blocks). */
#define PyArray_FromDimsAndDataAndDescr_RET PyObject *
#define PyArray_FromDimsAndDataAndDescr_PROTO (int, int *, PyArray_Descr *, char *)
#define PyArray_FromDimsAndDataAndDescr_NUM 24
#define PyArray_Converter_RET int
#define PyArray_Converter_PROTO (PyObject *, PyObject **)
#define PyArray_Converter_NUM 25
#define PyArray_Put_RET PyObject *
#define PyArray_Put_PROTO (PyObject *ap, PyObject *items, PyObject* values)
#define PyArray_Put_NUM 26
#define PyArray_PutMask_RET PyObject *
#define PyArray_PutMask_PROTO (PyObject *ap, PyObject *mask, PyObject* values)
#define PyArray_PutMask_NUM 27
#define PyArray_CopyArray_RET int
#define PyArray_CopyArray_PROTO (PyArrayObject *dest, PyArrayObject *src)
#define PyArray_CopyArray_NUM 28
#define PyArray_ValidType_RET int
#define PyArray_ValidType_PROTO (int type)
#define PyArray_ValidType_NUM 29
/* Convert a Python object to a C int, if possible. Checks for
potential overflow, which is important on machines where
sizeof(int) != sizeof(long) (note that a Python int is a C long).
Handles Python ints, Python longs, and any ArrayObject that
works in int(). */
#define PyArray_IntegerAsInt_RET int
#define PyArray_IntegerAsInt_PROTO (PyObject *o)
#define PyArray_IntegerAsInt_NUM 30
/* Total number of C API pointers */
#define PyArray_API_pointers 31
#ifdef _ARRAY_MODULE
extern PyTypeObject PyArray_Type;
#define PyArray_Check(op) ((op)->ob_type == &PyArray_Type)
extern PyArray_SetNumericOps_RET PyArray_SetNumericOps \
PyArray_SetNumericOps_PROTO;
extern PyArray_INCREF_RET PyArray_INCREF PyArray_INCREF_PROTO;
extern PyArray_XDECREF_RET PyArray_XDECREF PyArray_XDECREF_PROTO;
extern PyArrayError_RET PyArrayError PyArrayError_PROTO;
extern PyArray_SetStringFunction_RET PyArray_SetStringFunction \
PyArray_SetStringFunction_PROTO;
extern PyArray_DescrFromType_RET PyArray_DescrFromType \
PyArray_DescrFromType_PROTO;
extern PyArray_Cast_RET PyArray_Cast PyArray_Cast_PROTO;
extern PyArray_CanCastSafely_RET PyArray_CanCastSafely \
PyArray_CanCastSafely_PROTO;
extern PyArray_ObjectType_RET PyArray_ObjectType PyArray_ObjectType_PROTO;
extern _PyArray_multiply_list_RET _PyArray_multiply_list \
_PyArray_multiply_list_PROTO;
extern PyArray_Size_RET PyArray_Size PyArray_Size_PROTO;
extern PyArray_FromDims_RET PyArray_FromDims PyArray_FromDims_PROTO;
extern PyArray_FromDimsAndData_RET PyArray_FromDimsAndData \
PyArray_FromDimsAndData_PROTO;
extern PyArray_FromDimsAndDataAndDescr_RET PyArray_FromDimsAndDataAndDescr \
PyArray_FromDimsAndDataAndDescr_PROTO;
extern PyArray_ContiguousFromObject_RET PyArray_ContiguousFromObject \
PyArray_ContiguousFromObject_PROTO;
extern PyArray_CopyFromObject_RET PyArray_CopyFromObject \
PyArray_CopyFromObject_PROTO;
extern PyArray_FromObject_RET PyArray_FromObject PyArray_FromObject_PROTO;
extern PyArray_Return_RET PyArray_Return PyArray_Return_PROTO;
extern PyArray_Reshape_RET PyArray_Reshape PyArray_Reshape_PROTO;
extern PyArray_Copy_RET PyArray_Copy PyArray_Copy_PROTO;
extern PyArray_Take_RET PyArray_Take PyArray_Take_PROTO;
extern PyArray_As1D_RET PyArray_As1D PyArray_As1D_PROTO;
extern PyArray_As2D_RET PyArray_As2D PyArray_As2D_PROTO;
extern PyArray_Free_RET PyArray_Free PyArray_Free_PROTO;
extern PyArray_Converter_RET PyArray_Converter PyArray_Converter_PROTO;
extern PyArray_Put_RET PyArray_Put PyArray_Put_PROTO;
extern PyArray_PutMask_RET PyArray_PutMask PyArray_PutMask_PROTO;
extern PyArray_CopyArray_RET PyArray_CopyArray PyArray_CopyArray_PROTO;
extern PyArray_ValidType_RET PyArray_ValidType PyArray_ValidType_PROTO;
extern PyArray_IntegerAsInt_RET PyArray_IntegerAsInt PyArray_IntegerAsInt_PROTO;
#else
#if defined(PY_ARRAY_UNIQUE_SYMBOL)
#define PyArray_API PY_ARRAY_UNIQUE_SYMBOL
#endif
/* C API address pointer */
#if defined(NO_IMPORT) || defined(NO_IMPORT_ARRAY)
extern void **PyArray_API;
#else
#if defined(PY_ARRAY_UNIQUE_SYMBOL)
void **PyArray_API;
#else
static void **PyArray_API;
#endif
#endif
#define PyArray_Check(op) \
((op)->ob_type == (PyTypeObject *)PyArray_API[PyArray_Type_NUM])
#define PyArray_Type *(PyTypeObject *)PyArray_API[PyArray_Type_NUM]
#define PyArray_SetNumericOps \
(*(PyArray_SetNumericOps_RET (*)PyArray_SetNumericOps_PROTO) \
PyArray_API[PyArray_SetNumericOps_NUM])
#define PyArray_INCREF \
(*(PyArray_INCREF_RET (*)PyArray_INCREF_PROTO) \
PyArray_API[PyArray_INCREF_NUM])
#define PyArray_XDECREF \
(*(PyArray_XDECREF_RET (*)PyArray_XDECREF_PROTO) \
PyArray_API[PyArray_XDECREF_NUM])
#define PyArrayError \
(*(PyArrayError_RET (*)PyArrayError_PROTO) \
PyArray_API[PyArrayError_NUM])
#define PyArray_SetStringFunction \
(*(PyArray_SetStringFunction_RET (*)PyArray_SetStringFunction_PROTO) \
PyArray_API[PyArray_SetStringFunction_NUM])
#define PyArray_DescrFromType \
(*(PyArray_DescrFromType_RET (*)PyArray_DescrFromType_PROTO) \
PyArray_API[PyArray_DescrFromType_NUM])
#define PyArray_Cast \
(*(PyArray_Cast_RET (*)PyArray_Cast_PROTO) \
PyArray_API[PyArray_Cast_NUM])
#define PyArray_CanCastSafely \
(*(PyArray_CanCastSafely_RET (*)PyArray_CanCastSafely_PROTO) \
PyArray_API[PyArray_CanCastSafely_NUM])
#define PyArray_ObjectType \
(*(PyArray_ObjectType_RET (*)PyArray_ObjectType_PROTO) \
PyArray_API[PyArray_ObjectType_NUM])
#define _PyArray_multiply_list \
(*(_PyArray_multiply_list_RET (*)_PyArray_multiply_list_PROTO) \
PyArray_API[_PyArray_multiply_list_NUM])
#define PyArray_Size \
(*(PyArray_Size_RET (*)PyArray_Size_PROTO) \
PyArray_API[PyArray_Size_NUM])
#define PyArray_FromDims \
(*(PyArray_FromDims_RET (*)PyArray_FromDims_PROTO) \
PyArray_API[PyArray_FromDims_NUM])
#define PyArray_FromDimsAndData \
(*(PyArray_FromDimsAndData_RET (*)PyArray_FromDimsAndData_PROTO) \
PyArray_API[PyArray_FromDimsAndData_NUM])
#define PyArray_FromDimsAndDataAndDescr \
(*(PyArray_FromDimsAndDataAndDescr_RET (*)PyArray_FromDimsAndDataAndDescr_PROTO) \
PyArray_API[PyArray_FromDimsAndDataAndDescr_NUM])
#define PyArray_ContiguousFromObject \
(*(PyArray_ContiguousFromObject_RET (*)PyArray_ContiguousFromObject_PROTO) \
PyArray_API[PyArray_ContiguousFromObject_NUM])
#define PyArray_CopyFromObject \
(*(PyArray_CopyFromObject_RET (*)PyArray_CopyFromObject_PROTO) \
PyArray_API[PyArray_CopyFromObject_NUM])
#define PyArray_FromObject \
(*(PyArray_FromObject_RET (*)PyArray_FromObject_PROTO) \
PyArray_API[PyArray_FromObject_NUM])
#define PyArray_Return \
(*(PyArray_Return_RET (*)PyArray_Return_PROTO) \
PyArray_API[PyArray_Return_NUM])
#define PyArray_Reshape \
(*(PyArray_Reshape_RET (*)PyArray_Reshape_PROTO) \
PyArray_API[PyArray_Reshape_NUM])
#define PyArray_Copy \
(*(PyArray_Copy_RET (*)PyArray_Copy_PROTO) \
PyArray_API[PyArray_Copy_NUM])
#define PyArray_Take \
(*(PyArray_Take_RET (*)PyArray_Take_PROTO) \
PyArray_API[PyArray_Take_NUM])
#define PyArray_As1D \
(*(PyArray_As1D_RET (*)PyArray_As1D_PROTO) \
PyArray_API[PyArray_As1D_NUM])
#define PyArray_As2D \
(*(PyArray_As2D_RET (*)PyArray_As2D_PROTO) \
PyArray_API[PyArray_As2D_NUM])
#define PyArray_Free \
(*(PyArray_Free_RET (*)PyArray_Free_PROTO) \
PyArray_API[PyArray_Free_NUM])
#define PyArray_Converter \
(*(PyArray_Converter_RET (*)PyArray_Converter_PROTO) \
PyArray_API[PyArray_Converter_NUM])
#define PyArray_Put \
(*(PyArray_Put_RET (*)PyArray_Put_PROTO) \
PyArray_API[PyArray_Put_NUM])
#define PyArray_PutMask \
(*(PyArray_PutMask_RET (*)PyArray_PutMask_PROTO) \
PyArray_API[PyArray_PutMask_NUM])
#define PyArray_CopyArray \
(*(PyArray_CopyArray_RET (*)PyArray_CopyArray_PROTO) \
PyArray_API[PyArray_CopyArray_NUM])
#define PyArray_ValidType \
(*(PyArray_ValidType_RET (*)PyArray_ValidType_PROTO) \
PyArray_API[PyArray_ValidType_NUM])
#define PyArray_IntegerAsInt \
(*(PyArray_IntegerAsInt_RET (*)PyArray_IntegerAsInt_PROTO) \
PyArray_API[PyArray_IntegerAsInt_NUM])
#define import_array() \
{ \
PyObject *numpy = PyImport_ImportModule("_numpy"); \
if (numpy != NULL) { \
PyObject *module_dict = PyModule_GetDict(numpy); \
PyObject *c_api_object = PyDict_GetItemString(module_dict, "_ARRAY_API"); \
if (PyCObject_Check(c_api_object)) { \
PyArray_API = (void **)PyCObject_AsVoidPtr(c_api_object); \
} \
} \
}
#endif
#ifdef __cplusplus
}
#endif
#endif /* !Py_ARRAYOBJECT_H */
pygame-1.9.1release/src/music.doc 0000644 0001750 0001750 00000011076 11204417377 016654 0 ustar vincent vincent pygame.mixer.music
pygame module for controlling streamed audio
The music module is closely tied to pygame.mixer. Use the music module to
control the playback of music in the sound mixer.
The difference between the music playback and regular Sound playback is that
the music is streamed, and never actually loaded all at once. The mixer system
only supports a single music stream at once.
Be aware that MP3 support is limited. On some systems an unsupported format
can crash the program, e.g. Debian Linux. Consider using OGG instead.
load
Load a music file for playback
pygame.mixer.music.load(filename): return None
pygame.mixer.music.load(object): return None
This will load a music filename/file object and prepare it for playback. If a
music stream is already playing it will be stopped. This does not start the music
playing.
play
Start the playback of the music stream
pygame.mixer.music.play(loops=0, start=0.0): return None
This will play the loaded music stream. If the music is already playing it
will be restarted.
The loops argument controls the number of repeats a music will play.
play(5) will cause the music to played once, then repeated five times,
for a total of six. If the loops is -1 then the music will repeat indefinitely.
The starting position argument controls where in the music the song starts
playing. The starting position is dependent on the format of music playing.
MP3 and OGG use the position as time (in seconds). MOD music it is the
pattern order number. Passing a startpos will raise a NotImplementedError
if it cannot set the start position
rewind
restart music
pygame.mixer.music.rewind(): return None
Resets playback of the current music to the beginning.