Compare commits

...

245 Commits

Author SHA1 Message Date
Tom Rothamel e7eb23ab5e Create layout.yesno_screen function.
Doc update.

Bump to 6.11.0d.
2010-07-14 21:47:46 -04:00
Tom Rothamel 05dd8bfcc7 Use "screen" as the screen type and mouse for screens. 2010-07-14 20:39:30 -04:00
Tom Rothamel 2c299ab079 Share code between fullscreen and displayable versions of video playback. 2010-07-14 19:00:33 -04:00
Tom Rothamel 62acff5c75 CTRL on startup aborts OpenGL mode. 2010-07-14 01:22:40 -04:00
Tom Rothamel 316d146893 Make imagedissolve use the correct texture units. 2010-07-13 22:28:41 -04:00
Tom Rothamel e69fee2108 Auto-vivification of styles.
New styles.
2010-07-13 01:09:14 -04:00
Tom Rothamel 8fe6e1cf20 Add group argument to ui functions. 2010-07-13 00:27:48 -04:00
Tom Rothamel 6fcf7dbbba Blacklist Mesa Indirect GLX renderer. 2010-07-12 21:13:32 -04:00
Tom Rothamel f55c5f0ce5 Make screen language automatically prefix unicode-containing strings with u"" - like we do for other strings. 2010-07-12 20:42:32 -04:00
Tom Rothamel aaf8369421 Deallocate textures on shutdown. 2010-07-12 20:40:41 -04:00
Tom Rothamel 8e26c7730c Finish has rename.
Fix bugs with screens.
2010-07-11 22:46:19 -04:00
Tom Rothamel 556ca0611a Add has statement. 2010-07-11 17:25:46 -04:00
Tom Rothamel e2e78c175b Tweak the parser so that it recognizes \$ as a word unto itself. 2010-07-11 15:14:44 -04:00
Tom Rothamel 7b8033e6b2 A reference loop was preventing the weakref-based way of dealing with
PyCode from working. So instead, manually control when PyCodes are
recorded.
2010-07-11 13:04:44 -04:00
Tom Rothamel d602645fee Use button_text rather than default as the default button text style. 2010-07-11 11:57:06 -04:00
Tom Rothamel f8ac9c9e83 Bump version to 6.11.0c. 2010-07-10 16:06:22 -04:00
Tom Rothamel 98c90f8ab3 Shutdown trace.
Restrict minimum window size to 256x256.

Ensure window caption and icon are set when reiniting pygame.
2010-07-10 16:03:54 -04:00
Tom Rothamel 16bb21ee62 Always have an auto-forward length of 1. 2010-07-10 13:44:00 -04:00
Tom Rothamel 46bfec93d4 Set the window caption and icon whenenver we reinit the display. 2010-07-10 13:42:38 -04:00
Tom Rothamel 00e1ecf37d Fix DBZ protection. 2010-07-10 11:45:41 -04:00
Tom Rothamel a3e7b290fb Make references to PyCode weak, so that they are not compiled if they
do not live into the final game script.
2010-07-09 01:35:40 -04:00
Tom Rothamel 27ce59963f Document ui.detached, and make it work in an init block. 2010-07-09 01:02:10 -04:00
Tom Rothamel 54e3a97447 Play test sounds on the "sound" channel. 2010-07-09 00:36:41 -04:00
Tom Rothamel f886f710b7 Make video transient.
Fix most problems with ui.textbutton.
2010-07-09 00:06:30 -04:00
Tom Rothamel a895e1dc6c Always use copy RTT.
Deinitialize pygame on shutdown, and log that deinit, so we can notice where a crash there occurs.
2010-07-08 23:22:27 -04:00
Tom Rothamel 6f24d8eebd 6.11.0b 2010-07-07 19:40:03 -04:00
Tom Rothamel 000174c2c4 Implement renpy.get_renderer_info.
Change RENPY_DRAW -> RENPY_RENDERER.
2010-07-07 14:19:53 -04:00
Tom Rothamel 192aaea186 Make a click while AFM is enabled disable AFM. 2010-07-07 14:01:20 -04:00
Tom Rothamel eb0d6b696e Adds label and ui.label. 2010-07-07 02:42:40 -04:00
Tom Rothamel 94e1b0eb56 Update gl-screen when soft mouse moves. 2010-07-07 02:05:48 -04:00
Tom Rothamel 694a1cd6d5 Ensure we always project the mouse location into virtual coordinates. 2010-07-07 01:26:40 -04:00
Tom Rothamel 0600897a26 Check the number of texture units, and give up on OpenGL if less than 4. 2010-07-06 22:32:14 -04:00
Tom Rothamel e8c52f9417 Disable texture units w/o a texture bound to them. 2010-07-06 22:19:49 -04:00
Tom Rothamel 6d86963b1d Restart the video system when switching from GL to SW rendering. 2010-07-06 21:35:40 -04:00
Tom Rothamel 01e621067a Fix spelling error. 2010-07-06 12:11:03 -04:00
Tom Rothamel cd379ef1a3 Fix aspect ratio problem. 2010-07-06 11:07:20 -04:00
Tom Rothamel 41a4fbfb4d Rewrite icon changing to use the standard PEfile library.
Fix other bugs found through testing.
2010-07-05 22:25:48 -04:00
Tom Rothamel 04db2112c3 Rewrote Character and Text so that text is only parsed once. 2010-07-04 23:40:38 -04:00
Tom Rothamel d20bfb18bc Handle syntax errors in screen language code. 2010-07-04 16:44:20 -04:00
Tom Rothamel d02d83f896 Try to ensure that runtime errors in screen language code are
reported at the right location.
2010-07-04 02:25:31 -04:00
Tom Rothamel 6b45c92a58 Rewrite screenlang.py so that it generates and compiles python code
directly.
2010-07-03 13:58:25 -04:00
Tom Rothamel 871ad8c07f Ensure the screen reflects the end of a pause before the pause finishes.
Actually limit gl framerate.
2010-06-30 01:14:13 -04:00
Tom Rothamel 997290cd28 Work on improving screen speed. 2010-06-30 00:30:20 -04:00
Tom Rothamel fcfab5ada6 spelling fix 2010-06-29 02:23:13 -04:00
Tom Rothamel 005f45bad3 Stop Popen.__del__ from throwing errors on shutdown. 2010-06-28 23:48:46 -04:00
Tom Rothamel ef64872af5 Set the projects directory to None if it no longer exists. 2010-06-27 23:15:58 -04:00
Tom Rothamel 2cd5528df9 Take the condition parameter to Characters into account when scrying to
determine if the statement interacts.
2010-06-27 22:44:45 -04:00
Tom Rothamel 0a73e6f905 Stop sounds and movies on a rollback event. 2010-06-27 22:04:46 -04:00
Tom Rothamel b9f468e3f4 Update the license.
Fix a bar regression.

Ensure that slow_done always triggers, and the ctc indicator is always shown. (Fixes lp:520276)
2010-06-27 21:01:47 -04:00
Tom Rothamel ad5631ffc1 Fix bug 595532 - wrong text in tutorial game. 2010-06-27 18:40:25 -04:00
Tom Rothamel 50767c211a Sphinx style and indexing tweaks. 2010-06-27 18:11:44 -04:00
Tom Rothamel 8223545b72 Add sphinx ATL documentation. 2010-06-27 16:55:28 -04:00
Tom Rothamel 9925fa78e7 More documentation work. 2010-06-27 12:38:48 -04:00
Tom Rothamel 7834365803 Adding various changelogs. 2010-06-27 11:16:45 -04:00
Tom Rothamel 5bfeea6e30 Finish style documentation (for now at least). 2010-06-27 10:28:09 -04:00
Tom Rothamel 1877fcfe65 Link style lists from screens. 2010-06-27 02:23:36 -04:00
Tom Rothamel 98437bc207 Adding styles documentation. 2010-06-27 02:04:56 -04:00
Tom Rothamel 49e9560e91 Rename docs a bit more.
Add dlls to distribute.py files.
2010-06-25 01:56:09 -04:00
Tom Rothamel 9c5084ef14 Move doc directory.
Add automatic keyword generation support to examples.rpy.
2010-06-25 00:32:50 -04:00
Tom Rothamel 401c503c91 Mark the newest save file as selected.
Fix a problem with buttons showing up as insensitive during a transition.
2010-06-24 23:31:36 -04:00
Tom Rothamel 73d4515f9e Fix SaveMenu. 2010-06-24 22:09:13 -04:00
Tom Rothamel 9faadbd077 Fix tutorial game ATL.
Add renpy.list_files.
2010-06-24 21:05:32 -04:00
Tom Rothamel c886f16308 Change tutorial to deal with new Transform semantics.
Change DynamicDisplayable to be sure we can always get_position.
2010-06-24 11:01:10 -04:00
Tom Rothamel 6b4b410708 Ensure that we don't fail to set a transform's pos and anchor because
we're setting it to the old default value.
2010-06-24 08:46:51 -04:00
Tom Rothamel d6e50d840f pos and anchor are now considered part of the execution state of a
transform.
2010-06-24 01:26:59 -04:00
Tom Rothamel c1848159a9 The new LiveTile displayable tiles its child, without consuming a
large amount of memory to do so.
2010-06-23 23:49:36 -04:00
Tom Rothamel 46f503ec3c Wait until the adjustment is done being created before setting the
focusable property on a bar.
2010-06-23 22:05:05 -04:00
Tom Rothamel 71f40a33f7 Add the language basics document. 2010-06-23 21:05:33 -04:00
Tom Rothamel 94e789efde More windows distribution fixes. 2010-06-23 19:02:36 -04:00
Tom Rothamel d738da4272 Update build_exe and pefile to support python 2.6. 2010-06-23 18:52:38 -04:00
Tom Rothamel 8bbf9cb618 Update modules to build on Windows.
Read the surface masks out of a surface.
2010-06-23 15:49:35 -04:00
Tom Rothamel c5276e5073 Use a screen for the tutorial game tutorials menu.
Document viewport, add XScrollValue and YScrollValue.
2010-06-21 20:34:13 -04:00
Tom Rothamel 9b0a739872 Make bar actually respect a supplied style. 2010-06-20 22:55:54 -04:00
Tom Rothamel b3e817e1d4 Make subsurfaces depend on a surface. Fixes render leak bug. 2010-06-20 21:19:25 -04:00
Tom Rothamel 96a73712eb Try fixing a bug with masks on Linux. 2010-06-20 20:51:35 -04:00
Tom Rothamel dc91721ca2 Add config to doc. 2010-06-20 20:47:10 -04:00
Tom Rothamel 7175bb664c Tweak doc look. 2010-06-20 01:00:28 -04:00
Tom Rothamel 2a49120ac2 Add special screens. 2010-06-18 00:49:57 -04:00
Tom Rothamel 4ef546649b Document python mode. 2010-06-17 22:44:28 -04:00
Tom Rothamel f1a77bd2b0 Fix bug with old load/saves and invalid files.
Fix bug with screens and rollback.
2010-06-17 14:13:05 -04:00
Tom Rothamel aa8b6d364b Moved button and bar specialness into the displayables, rather than
the ui functions.

Changed the _replaces method to be a replaces constructor parameter.

Make the periodic method take st.

Add a periodic method to BarValue.

Implement AnimatedValue.
2010-06-17 12:56:04 -04:00
Tom Rothamel 1245c6120e Wrote a lot of screen documentation. 2010-06-15 23:32:03 -04:00
Tom Rothamel 2995118cae Re-implement subsurface clipping, to improve performance in some cases.
Make call scene (and renpy.call_scene) participate in rollback, roll
forward, and set _return as appropriate.
2010-06-15 13:40:37 -04:00
Tom Rothamel a201418d1a Implement is_pixel_opaque. 2010-06-15 11:54:36 -04:00
Tom Rothamel 1b46904897 Modify yesno_prompt so it uses actions, rather than interacting.
Add FileTakeScreenshot.
2010-06-15 00:42:10 -04:00
Tom Rothamel 1cf6764a08 Allow an input screen. 2010-06-15 00:09:47 -04:00
Tom Rothamel 6527b4e198 Implement screens for NVL-mode. 2010-06-14 23:48:45 -04:00
Tom Rothamel fd4d01374f Implement the show screen, hide screen, and call screen user-statements. 2010-06-14 11:08:31 -04:00
Tom Rothamel c77a11382d Rewrite parsing in terms of a trie, for flexibility and speed reasons. 2010-06-14 09:47:37 -04:00
Tom Rothamel 1239153a1c The distribution code has been moved into launcher/distribute.py. This
file can be run from the command line to build distributions in shell
scripts and other automated processes.

Plug games.renpy.org when building distributions.

Change xoffset and yoffset in transforms so that they stack with that
of the child.
2010-06-13 22:46:28 -04:00
Tom Rothamel ae7152a5fc The renpy.music.register_channel method now has two additional
parameters, file_prefix and file_suffix. These are prepended and
appended to filenames provided to the registered channel,
respectively.
2010-06-13 21:24:02 -04:00
Tom Rothamel eec4eb73b5 Added the rotate_pad transform property, which controls how Transform
pads rotated displayables. When set to False, _not_ the default, it's
now possible to rotate a (100, 50) displayable by 90 degrees, and have
the result be (50, 100) in size.
2010-06-13 19:51:02 -04:00
Tom Rothamel 0ab3521005 The screen language (and ui) now allows you to write action rather
than clicked.
2010-06-13 17:44:13 -04:00
Tom Rothamel 660ef587c9 Add mute preferences, and SetDict/ToggleDict to support them.
Add InvertSelected.
2010-06-13 16:47:13 -04:00
Tom Rothamel 541dd7b3c3 Implement _replaced on various displayables (Text, Input, Timer, and Viewport).
Implement _ctc screen.
2010-06-13 15:19:53 -04:00
Tom Rothamel ca53e2f696 Implement the basic framework for _replaces, which is called when
one widget replaces another as part of a screen.
2010-06-13 11:54:10 -04:00
Tom Rothamel 80764e130f Make opengl logging flush the file on each write.
Make opengl fullscreen quit and reinit the video system, so that we
can properly read out the size of the desktop.
2010-06-11 22:46:55 -04:00
Tom Rothamel 6afd0120c1 Add the screenshot action. 2010-06-10 22:21:23 -04:00
Tom Rothamel 953be074f2 The config.screenshot_crop configuration variable controls the area of
the screen that it stored when the user presses the screenshot key.
2010-06-10 22:16:19 -04:00
Tom Rothamel 03781d24d6 Ensure that actions only run when they are sensitive.
Ensure we can have more than one yesno_prompt up at a time.

Add CallInNewContext.

Make the inspector show things on the screens layer.
2010-06-10 22:01:41 -04:00
Tom Rothamel 55d87064a8 config.game_menu_action allows one to specify an action that is run
when entering the game menu.
2010-06-10 20:54:35 -04:00
Tom Rothamel 512478b945 Allow the user to specify an action that is run when someone hits the
quit button. (The one in the upper-right corner of the screen.)
2010-06-10 20:45:18 -04:00
Tom Rothamel 1c19ca8062 Add yes/no prompting. 2010-06-10 09:22:47 -04:00
Tom Rothamel fc764b464d ui.add can now take transform properties as keyword arguments. If at least
one transform property is present, ui.add will create a transform that
wraps the displayable it's adding to the screen.
2010-06-09 08:56:54 -04:00
Tom Rothamel 945b4fc1cd Add python statement (short and long forms) to screen language.
Change include statement to use statement.
2010-06-09 08:32:22 -04:00
Tom Rothamel 902b17462e Implement loading and saving using Actions, and various improvements
to screens, screen language, and ui to make sure we can pull off a
sensible implementation.
2010-06-09 00:27:54 -04:00
Tom Rothamel 8b0b39829a Use renpy.context()._main_menu rather than main_menu; ensure the former is always set. 2010-06-08 01:35:04 -04:00
Tom Rothamel 356ca9cd1e Implement the Play, Queue, and Stop actions, which control music/sound/etc.
Add a periodic method to actions, which is called on a periodic basis
while a button has that action.
2010-06-08 01:04:05 -04:00
Tom Rothamel 634da84442 Implement yesno_prompt for Quit and MainMenu, make ShowMenu-shown
screens transient, and clear out the screens when we enter a new
context.
2010-06-08 00:20:17 -04:00
Tom Rothamel 1d109ddaee Implement the Preference action/value constructor. 2010-06-07 23:37:01 -04:00
Tom Rothamel c1f996da07 Various fixes required to allow a working SL preferences screen. 2010-06-07 02:08:18 -04:00
Tom Rothamel b14c9f8954 Change ShowMenu so that it takes a short screen name, without the
"_screen" suffix.
2010-06-07 00:55:19 -04:00
Tom Rothamel 126050b4f3 Able to display an operational imagemap screen based main menu.
Rewrote screens so they are now use single word names, with an
optional explicit tag parameter.
2010-06-07 00:09:54 -04:00
Tom Rothamel 313e417f28 The choice screen allows in-game menus to be defined using screens. 2010-06-05 23:32:54 -04:00
Tom Rothamel e98ef1025c Implement more Actions and BarValues.
Ensure the say screen still works.
2010-06-05 23:02:46 -04:00
Tom Rothamel 3729e4bc3a sl: Ensure execution errors are reported in a relevant location. 2010-06-05 16:16:13 -04:00
Tom Rothamel ac071777ad Implement BarValue. 2010-06-05 01:15:59 -04:00
Tom Rothamel 445972756d sl: add on statement. 2010-06-04 01:22:32 -04:00
Tom Rothamel 91732e7def sl: Implement the for statement. 2010-06-03 01:25:38 -04:00
Tom Rothamel 5b7e4af26c Add key, timer, and transform statements to ATL. 2010-05-29 23:24:55 -04:00
Tom Rothamel 2bb459cda5 screen: Implement support for transient screens. 2010-05-28 23:03:16 -04:00
Tom Rothamel d410c73074 screen: refactor screens into Screen and ScreenDisplayable classes. 2010-05-28 08:59:08 -04:00
Tom Rothamel da70f197fe screen, sl: add zorder parameter. 2010-05-27 23:03:33 -04:00
Tom Rothamel c18ffb28d0 Pass transform events to the children of a screen. Allow the screen to
respond to a hide event.
2010-05-27 21:56:02 -04:00
Tom Rothamel d5f17ef9f1 Events propagate to all children. 2010-05-25 23:42:54 -04:00
Tom Rothamel 79c3f426e5 sl: Add xmaximum and ymaximum to the list of properties we support. 2010-05-25 23:02:29 -04:00
Tom Rothamel b004dd138f Add code for customizing the say screen. 2010-05-25 22:47:58 -04:00
Tom Rothamel 45b479e324 sl: implement if statement.
screen: trigger a redraw on each interaction.
2010-05-23 22:50:22 -04:00
Tom Rothamel b07cbd4193 sl: add include statement. 2010-05-23 21:58:00 -04:00
Tom Rothamel ae2739f32d Hooked up the screen language to the screen system. 2010-05-23 20:43:37 -04:00
Tom Rothamel dd51fcb1fd Fix ui.at, get things going with visit. 2010-05-22 22:07:58 -04:00
Tom Rothamel edc26fe0a4 First working screens. 2010-05-22 19:16:08 -04:00
Tom Rothamel c9215b3b71 Add renpy.ui.remove_above, for use by screens. (Not sure I'll bother
publically documenting this.)

Improve documentation of Scene Lists.
2010-05-16 01:06:13 -04:00
Tom Rothamel 115338bdeb Basic initial implementation of screens.
Rewrote the scene lists. This added support for "replaced" images, but
more importantly, cleaned up the code quite a bit, by making it be in
terms of objects rather than tuples.
2010-05-15 20:24:28 -04:00
Tom Rothamel b0b10ac7d3 Add all existing ui functions to the screen language parser. 2010-05-11 23:42:51 -04:00
Tom Rothamel 5a6013aac9 Update changelog.
Tweak config.default_transform behavior so that it only applies to
non-transforms, so we better match the old behavior.

fix renpy.ui.Many to work with with.
2010-05-04 01:58:10 -04:00
Tom Rothamel f3aa299aa0 Remove obsolete files from the gl-renpy branch. 2010-05-04 01:30:19 -04:00
Tom Rothamel 8e44536133 Merge in changes from old mainline. 2010-05-04 01:27:59 -04:00
Tom Rothamel 0cb937298e Add checkmark background when the screen is left empty, with no background.
Fix backwards compatibility bugs.
2010-05-04 01:26:01 -04:00
Tom Rothamel 6ed0491520 Add hotbars. 2010-05-02 00:27:58 -04:00
Tom Rothamel af7748920c Add hotspots. 2010-05-01 22:55:51 -04:00
Tom Rothamel 3c1c0310d8 Merge in screen language changes. 2010-04-30 01:29:57 -04:00
Tom Rothamel 91a67304dd Rewrite the ui module in terms of wrapper code. 2010-04-30 01:28:37 -04:00
Tom Rothamel 04d0e46c3e Rewrite how things are added in renpy.ui. 2010-04-29 01:08:10 -04:00
Tom Rothamel ed27eac80b Added support for composite style properties, that allow several style
properties to be set using a single parameter. The new composite style
properties are:

* pos - takes a pair, and uses it to set xpos and ypos.
* anchor - takes a pair, and uses it to set xanchor and yanchor.
* align - takes a pair, and uses it to set xalign and yalign. (And
  hence xpos, ypos, xanchor, and yanchor.)
* area - take (x, y, height, width) pair, and tries to set properties
  such that the displayable will be placed inside the rectangle. This 
  sets the xpos, ypos, xanchor, yanchor, xfill, yfill, xminimum, yminimum,
  xmaximum, and ymaximum properties.
2010-04-28 01:19:45 -04:00
Tom Rothamel 1f3e02bbdc More SL parsing. 2010-04-28 00:31:02 -04:00
Tom Rothamel 275e938602 Snapshot of work on screen system. 2010-04-27 00:24:33 -04:00
Tom Rothamel 3f80320d37 The python compiler has been rewritten to use the python ast module.
This should both improve performance, and improve error handling for
python syntax.
2010-04-23 23:12:11 -04:00
Tom Rothamel 0e44ce7636 Update docs. 2010-04-23 22:06:24 -04:00
Tom Rothamel 8fe727a8a1 Start on sphinx documentation for build system. 2010-04-18 01:51:17 -04:00
Tom Rothamel b82f7a5548 Use default_transform as the main way of positioning images on the screen. 2010-04-17 12:15:27 -04:00
Tom Rothamel fe15242479 Allow the position properties to be specified independently when transforms are composed. 2010-04-17 00:44:06 -04:00
Tom Rothamel 677a9b0dab Transform (and ui.transform) have been changed so that their arguments
can now be prefixed with a style prefix. One can write
ui.transform(idle_rotate=30, hover_rotate=90) and have it work. [doc]
2010-04-13 23:57:37 -04:00
Tom Rothamel 309001e2fe Pick mask based on platform. Fixes a bug in ubuntu 10.4 beta. 2010-03-30 02:06:25 -04:00
Tom Rothamel 90e782c9c6 Actually put textures on the free-lists, so we can reuse them. 2010-03-23 00:03:15 -04:00
Tom Rothamel f95d9cacb5 Sleep to prevent swdraw from speeding up the CPU. 2010-03-17 11:34:44 -04:00
Tom Rothamel 308d1e6b00 Choose directory for opengl.txt. 2010-03-17 11:16:23 -04:00
Tom Rothamel c57b3004a0 Reset display after renpygame. 2010-03-17 11:12:11 -04:00
Tom Rothamel 00bd5c96e9 Shift-reload now works in GL mode. 2010-03-16 22:08:45 -04:00
Tom Rothamel 371b11370a Allow Ren'Py to keep working even if GL can't be loaded. 2010-03-16 10:13:49 -04:00
Tom Rothamel b9338a7446 Video support. 2010-03-16 01:54:05 -04:00
Tom Rothamel e39ae375f4 Refactor things so texture caching takes place in the draw modules, using
weak references.
2010-03-15 13:24:48 -04:00
Tom Rothamel 975907aebf Fixed spelling, thanks to ZeikJT. 2010-03-15 00:45:51 -04:00
Tom Rothamel ccfbdf6f3a Software mouse works in GL Ren'Py. 2010-03-15 00:42:55 -04:00
Tom Rothamel 7934d40b7c Refactor mouse code. 2010-03-15 00:21:45 -04:00
Tom Rothamel 3b569a10bd Implement screenshots. 2010-03-14 16:49:11 -04:00
Tom Rothamel 941d959ee5 Reinitialize OpenGL (except for various detection) each time the window
is resized. This allows us to work on Mac OS X, which can't share any 
OpenGL state through a window resize. (At least with SDL+Pygame.)
2010-03-13 21:20:13 -05:00
Tom Rothamel d5a51c8139 Implement pixellate in gl-mode. 2010-03-13 19:01:46 -05:00
Tom Rothamel fc79078d51 Implement RENPY_GL_VSYNC, which control OpenGL vertical sync. 2010-03-13 12:42:43 -05:00
Tom Rothamel d6615410dd Allow the user to resize the GL window by dragging (or hitting the maximize
button).
2010-03-13 12:34:30 -05:00
Tom Rothamel adee372b4b Always add a left border to images. 2010-03-13 02:06:25 -05:00
Tom Rothamel 9c7542a357 Track total texture size. 2010-03-12 01:17:21 -05:00
Tom Rothamel bc18285a61 Allow renpy_draw to pick between software and hardware rendering. 2010-03-12 00:46:53 -05:00
Tom Rothamel 7b6c3f52e0 Implement imageblend. 2010-03-12 00:30:15 -05:00
Tom Rothamel f95c6e479d Add an extra row and column of pixels to textures that aren't full, to
ensure we don't interpolate in junk during subpixel rendering.
2010-03-11 21:47:27 -05:00
Tom Rothamel e4e224348f Merge premultiplied textures. 2010-03-11 01:50:59 -05:00
Tom Rothamel 7e914da261 Initial writing of premultiplied textures. 2010-03-11 01:49:33 -05:00
Tom Rothamel ae3eb40a0e Code to read from FB to surface.
Fix shaders to handle alpha blending.
2010-03-10 22:19:48 -05:00
Tom Rothamel 2f8cd81870 Dissolve works (with copy RTT). FBO rtt is buggy. 2010-03-09 23:50:55 -05:00
Tom Rothamel a1e7b60dab Implement basic render-to-texture.
Implement non-aligned clipping.
2010-03-09 17:02:12 -05:00
Tom Rothamel 92515fca49 Implement aligned clipping. 2010-03-09 02:27:41 -05:00
Tom Rothamel 6a8abf2a79 Basic support for clipping using glClipPlane. 2010-03-09 01:24:52 -05:00
Tom Rothamel 9a47b02840 Allocate texture numbers in the GL thread. 2010-03-08 18:49:19 -05:00
Tom Rothamel 488c1c34cd Use the right direction for the transform. 2010-03-08 02:03:42 -05:00
Tom Rothamel 52bd7de14f First drawing via GL to the screen. 2010-03-08 01:36:36 -05:00
Tom Rothamel deb0f813ca Making progress towards getting gl-drawing working. 2010-03-07 18:46:00 -05:00
Tom Rothamel 5030513375 Rewrite the text handling to create textures. 2010-03-06 20:16:55 -05:00
Tom Rothamel 53deb04137 Rewrite im to use textures instead of surfaces directly.
Add support for textures (really just surfaces) to swdraw.

Move rle cache code into swdraw.
2010-02-28 23:01:58 -05:00
Tom Rothamel 2c60f5251f Rewrite RotoZoom in terms of Transform. 2010-02-26 14:47:33 -05:00
Tom Rothamel 64ac5a9317 Rewrote Zoom, FactorZoom, and SizeZoom in terms of Renders. 2010-02-26 01:33:10 -05:00
Tom Rothamel 607113b31c Move pixellate into swdraw. 2010-02-24 21:47:32 -05:00
Tom Rothamel 5a472ef44b Finished factoring out dissolve and imagedissolve. 2010-02-24 01:28:27 -05:00
Tom Rothamel c67ba9b4e4 Restructured dissolve and imagedissolve. 2010-02-24 01:04:11 -05:00
Tom Rothamel 3f36d3a881 get_parameterized -> _get_parameterized 2010-02-24 01:03:10 -05:00
Tom Rothamel d188618785 Sync with main branch. 2010-02-23 16:31:25 -05:00
Tom Rothamel e6827bdff8 * lp:526297 - im.Rotozoom()s crash when Ren'Py is scaled down. (Thanks to Spiky Caterpillar for the bug report and fix.)
Renamed the internal show and hide methods of Displayable, so those
names can once again be used by user-defined displayables.
2010-02-23 15:12:44 -05:00
Tom Rothamel 85ac26fb1e Move the drawing code from render.py to swdraw.py. Now, none of the
code in render.py should be software-renderer specific.
2010-02-23 01:52:33 -05:00
Tom Rothamel abea49df8e Massive restructuring of the display system. The methods in Display
were split between the new SWDraw class and Interface. The idea is to
separate the software renderer out from the common code.
2010-02-23 01:13:02 -05:00
Tom Rothamel bfc7de0d16 glcore -> gldraw 2010-02-22 22:05:35 -05:00
Tom Rothamel aa8c3ecec9 Move gl stuff into the display directory. 2010-02-22 22:02:11 -05:00
Tom Rothamel 7ab984972e Started work on glcore.py. 2010-02-22 21:55:57 -05:00
Tom Rothamel da09c4d04f Implement the subsurface operation. 2010-02-21 20:02:31 -05:00
Tom Rothamel c42457446f Implemented a shader-based GL environment. 2010-02-21 02:35:30 -05:00
Tom Rothamel 40bb6ca557 Can compile shaders. 2010-02-20 23:25:58 -05:00
Tom Rothamel f2cc5d25e8 Implement render-to-texture using EXT_framebuffer_object, with
acceptable performance on both Nvidia and 950.
2010-02-20 13:50:49 -05:00
Tom Rothamel 04a5460e8b Init rtt and environ in a function, so we don't have to wait for them. 2010-02-20 11:04:20 -05:00
Tom Rothamel 12ef8ee199 Refactor render-to-texture code into a class, so we can have an
alternative implementation of it.
2010-02-20 02:41:26 -05:00
Tom Rothamel 9c2d2f3a06 Implement render to texture.
Implement (GL 1.1) blank texture loading.

Add EXT_framebuffer_object to tegl.
2010-02-19 19:56:11 -05:00
Tom Rothamel 94bcfe5c58 Change to using BGRA textures for speed on Nvida chips.
Make work on the mac.
2010-02-18 10:41:22 -05:00
Tom Rothamel fecd13c733 Allow textures of various sizes, from 512 to 64 pixels. 2010-02-17 22:54:43 -05:00
Tom Rothamel a9a6595d43 Implemented fixed-function imageblend. Also, tweaked normal blend so
textures are taken in the right order.
2010-02-16 00:20:02 -05:00
Tom Rothamel e4e9ea4e87 Working blend operation. 2010-02-14 21:14:29 -05:00
Tom Rothamel 588682f0d2 Change the representation of texgrids to include a tile index, rather
than implying the tile index.

Work on environments continues.
2010-02-14 19:17:32 -05:00
Tom Rothamel 0b502d5530 C-accelerated the rectangle drawing code. 2010-02-13 23:53:27 -05:00
Tom Rothamel 86a2b5d4e5 Move the GL setup code into a module. 2010-02-13 20:05:12 -05:00
Tom Rothamel 312a657e78 Rename surface.py to gltexture.py 2010-02-11 20:00:32 -05:00
Tom Rothamel 6197597ec9 Can now draw a TextureGrid to the screen. 2010-02-11 19:35:19 -05:00
Tom Rothamel c3ee29a9b0 Work on loading textures. 2010-02-11 09:01:42 -05:00
Tom Rothamel d5b26aa973 Work on loading textures. 2010-02-11 08:58:36 -05:00
Tom Rothamel 5d926ad49b Build modules in module directory. 2010-02-10 00:38:44 -05:00
Tom Rothamel b5f133ce17 Have working direct transfer of SDL surface -> texture. 2010-02-09 00:32:01 -05:00
Tom Rothamel 6ee4474e5e Prevent completing a rollback from triggering an exception if
other code is updating objects that it uses.
2010-02-07 13:06:58 -05:00
Tom Rothamel d515d07110 Customized TEGL for our purposes. 2010-02-04 20:58:57 -05:00
Tom Rothamel 3d2e5124d4 Add a clean tegl. 2010-02-04 20:50:51 -05:00
Tom Rothamel 48a826a13d Fix bug that could cause last element of a MultipleTransition to show twice. 2010-02-04 16:53:57 -05:00
Tom Rothamel 64e82c2c62 Rewrote MultipleTransition (which is used by Fade) to fix some
problems it was exhibiting.
2010-02-04 15:43:21 -05:00
Tom Rothamel 9c5d4d7ad5 Do not query volume if a mixer is disabled, in the imagemap
preferences screen.
2010-01-26 20:42:17 -05:00
Tom Rothamel 5f006c8f4c Bump version. 2010-01-22 11:00:07 -05:00
Tom Rothamel 3d8b6cbecb Remove default_transform test code that got stuck in a release. 2010-01-22 10:56:36 -05:00
Tom Rothamel 7e2e123af7 Bump version, update changelog. 2010-01-21 18:53:32 -05:00
Tom Rothamel 14aa4c4e3d Do not display ctc when interact=False. 2010-01-21 18:04:22 -05:00
Tom Rothamel 2c15237b8a Implement renpy.config.default_transform, but don't make it the default yet. 2010-01-21 16:54:10 -05:00
Tom Rothamel b4845252c1 Bump version. 2010-01-20 13:03:58 -05:00
Tom Rothamel 2f513235b3 The launcher now accepts a RENPY_DEFAULT_PROJECTS_DIRECTORY, which sets
the default for the projects directory, if it has not already been set 
by the user. It also will report an error when creating a project fails,
rather than producing a traceback.
2010-01-20 11:16:55 -05:00
Tom Rothamel c68b3bae89 The new voice_replay function replays the voice played on the current
interaction. The new voice_can_replay function returns True if a voice
can be replayed.
2010-01-20 01:01:24 -05:00
Tom Rothamel 3825e88883 Properly purge images from the image cache. 2010-01-20 00:10:20 -05:00
Tom Rothamel bbe0fdb98f It's now possible to assign style properties to individual imagemap
buttons, by indexing style.imagemap_button. (So for example, one could 
assign to style.imagemap_button["Start Game"].hover_sound .)
2010-01-18 22:46:56 -05:00
Tom Rothamel 009969dab5 Can't pop from a tuple. 2010-01-18 03:04:02 -05:00
Tom Rothamel 376ac7ad81 Add a link to the Ren'Py Games List to the launcher. 2010-01-17 17:07:38 -05:00
Tom Rothamel de8257f459 Ren'Py now builds zip files in distributions 64k at a time. 2010-01-14 22:03:14 -05:00
Tom Rothamel 3b0fbcc55f Previously, it was impossible to pass an arguments list to a call
expression. Now, we allow the pass keyword to be used to distinguish 
the two, using code like:

call expression foo pass (bar, baz)
2010-01-14 12:48:54 -05:00
Tom Rothamel e33abc05fb Prevent infinite looping when iterating over an object with
__getitem__ defined.
2010-01-14 11:37:59 -05:00
Tom Rothamel 430ee03d45 Bump version to 6.10.2b. 2010-01-14 00:12:46 -05:00
Tom Rothamel 03477d1c75 Fix lp:506322 - MoveTransition wouldn't work on the overlay layer, even if explicitly specified. 2010-01-13 23:20:15 -05:00
Tom Rothamel ef9ee657f7 Add cache_unpin 2010-01-12 23:48:57 -05:00
133 changed files with 41185 additions and 5196 deletions
+40 -1
View File
@@ -1,3 +1,4 @@
New in Ren'Py 6.10.2
--------------------
@@ -16,13 +17,49 @@ menu.
The new renpy.cache_pin function pins images into memory, loading them
as soon as possible and keeping them loaded.
as soon as possible and keeping them loaded. The renpy.cache_unpin function
undoes this.
The new config.automatic_images_strip variable can strip out prefixes
when automatically defining images.
It's now possible to assign style properties to individual imagemap
buttons, by indexing style.imagemap_button. (So for example, one could
assign to style.imagemap_button["Start Game"].hover_sound .)
The new voice_replay function replays the voice played on the current
interaction. The new voice_can_replay function returns True if a voice
can be replayed.
The launcher now accepts a RENPY_DEFAULT_PROJECTS_DIRECTORY, which sets
the default for the projects directory, if it has not already been set
by the user. It also will report an error when creating a project fails,
rather than producing a traceback.
The launcher now links to the new Ren'Py Games List, at
http://games.renpy.org/.
Previously, it was impossible to pass an arguments list to a call
expression. Now, we allow the pass keyword to be used to distinguish
the two, using code like:
call expression foo pass (bar, baz)
Ren'Py will now not show the click-to-continue indicator when a
character is called with interact=False, unless that character is also
called with ctc_force=True.
Ren'Py now builds zip files in distributions 64k at a time.
Ren'Py will now ignore music files that do not exist. Previously, it
could loop trying to play them. (This would increase CPU usage, rather
than causing a crash.)
@@ -31,11 +68,13 @@ than causing a crash.)
The following numbered bugs were fixed:
* lp:501351 - Displaying a Frame() with tile=True crashes
* lp:506322 - MoveTransition is not applied to overlay even when explicitly stated
In addition:
* Fixed a bug that caused pixellate to crash.
* Fixed a bug that caused the overlay to display twice in some cases.
* Fix an infinite loop that could rarely occur when rolling back or saving.
+707 -667
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -0,0 +1 @@
dist/Microsoft.VC90.CRT.manifest
+7 -3
View File
@@ -1,5 +1,6 @@
#!/usr/bin/env python
import shutil
from distutils.core import setup
import py2exe
import sys
@@ -7,15 +8,15 @@ import zipfile
import traceback
# The pythonpath on my system.
sys.path.insert(0, 'c:\\msys\\1.0\\newbuild25\\install\\bin')
sys.path.insert(0, 'c:\\msys\\1.0\\newbuild25\\install\\python')
sys.path.insert(0, 'c:\\msys\\1.0\\newbuild\\install\\bin')
sys.path.insert(0, 'c:\\msys\\1.0\\newbuild\\install\\python')
def main():
sys.argv[1:] = [ 'py2exe', '--bundle', '2', '-a', '--dll-excludes', 'w9xpopen.exe', ]
# sys.argv[1:] = [ 'py2exe', '-a', '--dll-excludes', 'w9xpopen.exe', ]
setup(name="RenPy",
setup(name="Ren'Py",
windows=[ dict(script="renpy.py",
dest_base="renpy",
icon_resources=[ (1, "newicon.ico") ],
@@ -70,6 +71,9 @@ def main():
zfold.close()
zfnew.close()
shutil.copy("c:/Python26/Microsoft.VC90.CRT.manifest", "dist/Microsoft.VC90.CRT.manifest")
shutil.copy("c:/Python26/msvcr90.dll", "dist/msvcr90.dll")
try:
main()
except:
+11
View File
@@ -29,6 +29,17 @@ init -1210 python:
store.offscreenleft = Position(xpos=0.0, xanchor=1.0)
store.offscreenright = Position(xpos=1.0, xanchor=0.0)
if version <= (6, 10, 2):
# Before 6.11, we used the image placement to handle
# the location of things on the screen.
style.image_placement.xpos = 0.5
style.image_placement.ypos = 1.0
style.image_placement.xanchor = 0.5
style.image_placement.yanchor = 1.0
config.transform_uses_child_position = False
config.default_transform = None
config.start_scene_black = True
init 1210 python hide::
+15 -3
View File
@@ -7,6 +7,10 @@
# definitions.
init -1110:
transform reset:
alpha 1 rotate None zoom 1 xzoom 1 yzoom 1 align (0, 0) alignaround (0, 0) subpixel False size None crop None
# These are positions that can be used inside at clauses. We set
# them up here so that they can be used throughout the program.
transform left:
@@ -30,14 +34,18 @@ init -1110:
transform offscreenright:
xpos 1.0 xanchor 0.0 ypos 1.0 yanchor 1.0
transform default:
reset
center
python:
config.default_transform = default
init -1110 python:
_define = define = object()
# Positions ##############################################################
# Transitions ############################################################
# Simple transitions.
@@ -179,3 +187,7 @@ init 1110 python:
if not hasattr(store, 'centered'):
centered = Character(None, what_style="centered_text", window_style="centered_window")
# This is necessary to ensure that config.default_transform works.
if config.default_transform:
config.default_transform._show()
+81 -1
View File
@@ -56,6 +56,21 @@ init -1105 python hide:
joystick_preferences=layout.classic_joystick_preferences,
)
if renpy.has_screen("main_menu"):
defaults["main_menu"] = layout.screen_main_menu
if renpy.has_screen("load") and renpy.has_screen("save"):
defaults["load_save"] = layout.screen_load_save
if renpy.has_screen("yesno"):
defaults["yesno_prompt"] = layout.screen_yesno_prompt
if renpy.has_screen("preferences"):
defaults["preferences"] = layout.screen_preferences
if renpy.has_screen("joystick_preferences"):
defaults["joystick_preferences"] = layout.screen_joystick_preferences
for k, v in defaults.iteritems():
if k not in layout.provided:
v()
@@ -343,11 +358,76 @@ init -1105 python hide:
config.load_save_selected_idle[variant] = selected_idle
config.load_save_selected_hover[variant] = selected_hover
config.load_save_hotspots[variant] = hotspots
@layout
def screen_main_menu():
renpy.load_module("_layout/screen_main_menu")
@layout
def screen_load_save():
renpy.load_module("_layout/screen_load_save")
@layout
def screen_preferences():
renpy.load_module("_layout/screen_preferences")
@layout
def screen_joystick_preferences():
renpy.load_module("_layout/screen_joystick_preferences")
@layout
def screen_yesno_prompt():
renpy.load_module("_layout/screen_yesno_prompt")
layout.ARE_YOU_SURE = u"Are you sure?"
layout.DELETE_SAVE = u"Are you sure you want to delete this save?"
layout.OVERWRITE_SAVE = u"Are you sure you want to overwrite your save?"
layout.LOADING = u"Loading will lose unsaved progress.\nAre you sure you want to do this?"
layout.QUIT = u"Are you sure you want to quit?"
layout.MAIN_MENU = u"Are you sure you want to return to the main menu?\nThis will lose unsaved progress."
@layout
def yesno_screen(message, yes=None, no=None):
"""
:doc: other
This causes the a yes/no prompt screen with the given message
to be displayed. The screen will be hidden when the user hits
yes or no.
`message`
The message that will be displayed.
`yes`
An action that is run when the user chooses yes.
`no`
An action that is run when the user chooses no.
"""
if renpy.has_screen("yesno_prompt"):
yes_action = [ Hide("yesno_prompt") ]
no_action = [ Hide("yesno_prompt") ]
if yes is not None:
yes_action.append(yes)
if no is not None:
no_action.append(no)
renpy.display.show_screen(
"yesno_prompt",
message=message,
yes_action=yes_action,
no_action=no_action)
return
if renpy.invoke_in_new_context(layout.yesno_prompt, None, message):
if yes is not None:
yes()
else:
if no is not None:
no()
+56 -20
View File
@@ -47,6 +47,12 @@ init -1180 python:
# preference when the game is first run.
config.default_text_cps = None
# If not None, the default value of afm_time
config.default_afm_time = None
# If not None, the default value of afm_enable
config.default_afm_enable = None
# Should we automatically define images?
config.automatic_images = None
@@ -58,6 +64,9 @@ init -1180 python:
# Layers to clear when entering the menus.
config.menu_clear_layers = [ ]
# Should we start the game with scene black or just scene?
config.start_scene_black = False
# This is updated to give the user an idea of where a save is
# taking place.
@@ -146,11 +155,8 @@ init -1180 python:
except:
pass
init -1180 python hide:
# Called to make a screenshot happen.
def screenshot():
def _screenshot():
import os.path
import os
import __main__
@@ -181,17 +187,25 @@ init -1180 python hide:
except:
import traceback
traceback.print_exc()
init -1180 python hide:
def dump_styles():
if config.developer:
renpy.style.write_text("styles.txt")
# This is run when entering the game menu.
config.game_menu_action = None
def invoke_game_menu():
if renpy.context()._menu:
renpy.jump("_noisy_return")
else:
renpy.call_in_new_context('_game_menu')
if config.game_menu_action:
renpy.display.behavior.run(config.game_menu_action)
else:
renpy.call_in_new_context('_game_menu')
def keymap_toggle_skipping():
if renpy.context()._menu:
@@ -223,7 +237,7 @@ init -1180 python hide:
# the launcher.
km = renpy.Keymap(
rollback = renpy.rollback,
screenshot = screenshot,
screenshot = _screenshot,
toggle_fullscreen = renpy.toggle_fullscreen,
toggle_music = renpy.toggle_music,
toggle_skip = keymap_toggle_skipping,
@@ -391,6 +405,17 @@ init 1180 python:
if config.default_text_cps is not None:
_preferences.text_cps = config.default_text_cps
if config.default_afm_time is not None:
_preferences.default_afm_time = config.default_afm_time
if config.default_afm_enable is not None:
_preferences.afm_enable = config.default_afm_enable
_preferences.using_afm_enable = True
else:
_preferences.afm_enable = True
_preferences.using_afm_enable = False
if config.developer:
def _inspector(l):
@@ -402,7 +427,6 @@ init 1180 python:
ui.text("Style Inspector")
ui.text("")
if not l:
ui.text("Nothing to inspect.")
@@ -538,7 +562,7 @@ label _enter_menu:
renpy.context()._menu = True
# This may be changed, if we are already in the main menu.
renpy.context().main_menu = False
renpy.context()._main_menu = False
renpy.context_dynamic("main_menu")
renpy.context_dynamic("_window_subtitle")
renpy.context_dynamic("_window")
@@ -578,9 +602,14 @@ label _game_menu(_game_menu_screen=_game_menu_screen):
$ renpy.play(config.enter_sound)
call _enter_game_menu from _call__enter_game_menu_0
if renpy.has_label("game_menu"):
jump expression "game_menu"
if renpy.has_screen(_game_menu_screen):
$ renpy.show_screen(_game_menu_screen)
$ ui.interact()
jump _noisy_return
jump expression _game_menu_screen
@@ -622,7 +651,7 @@ label _noisy_return:
# Return to the game.
label _return:
if renpy.context().main_menu:
if renpy.context()._main_menu:
$ renpy.transition(config.game_main_transition)
jump _main_menu_screen
@@ -631,7 +660,6 @@ label _return:
return
label _confirm_quit:
call _enter_menu from _call__enter_menu_3
if renpy.has_label("confirm_quit"):
jump expression "confirm_quit"
@@ -657,6 +685,7 @@ init -1180 python hide:
# after_load.
label _after_load:
$ renpy.context()._menu = False
$ renpy.context()._main_menu = False
if config.after_load_transition:
$ renpy.transition(config.after_load_transition, force=True)
@@ -673,6 +702,7 @@ label _start:
python hide:
renpy.context()._menu = False
renpy.context()._main_menu = False
for i in config.start_callbacks:
i()
@@ -681,9 +711,12 @@ label _start:
if not _restart and config.auto_load and renpy.can_load(config.auto_load):
$ renpy.load(config.auto_load)
scene black
if config.start_scene_black:
scene black
else:
scene
if not _restart:
$ ui.pausebehavior(0)
$ ui.interact(suppress_underlay=True, suppress_overlay=True)
@@ -707,7 +740,10 @@ label _start:
$ renpy.music.stop()
# Clean out any residual scene from the splashscreen.
scene black
if config.start_scene_black:
scene black
else:
scene
# This has to be python, to deal with a case where _restart may
@@ -742,7 +778,7 @@ label _main_menu(_main_menu_screen="_main_menu_screen"):
renpy.dynamic("_load_prompt")
_load_prompt = False
renpy.context().main_menu = True
renpy.context()._main_menu = True
store.main_menu = True
jump expression _main_menu_screen
@@ -756,11 +792,11 @@ label _main_menu_screen:
jump expression "main_menu"
# New name.
if renpy.has_label("main_menu_screen"):
elif renpy.has_label("main_menu_screen"):
jump expression "main_menu_screen"
# Compatibility name.
if renpy.has_label("_library_main_menu"):
elif renpy.has_label("_library_main_menu"):
jump expression "_library_main_menu"
return
@@ -795,7 +831,7 @@ init 1180 python hide:
while name:
for i in config.automatic_images_strip:
if name[0] == i:
name.pop(0)
name = name[1:]
break
else:
break
+74 -25
View File
@@ -79,8 +79,47 @@ init -1100 python:
return s[nvl_variant]
else:
return s
def nvl_show_core():
def nvl_show_screen(screen_name, **scope):
"""
Shows an nvl-mode screen. Returns the "who" widget.
"""
widget_properties = { }
dialogue = [ ]
for i, entry in enumerate(nvl_list):
if not entry:
continue
who, what, kwargs = entry
if i == len(nvl_list) - 1:
who_id = "who"
what_id = "what"
window_id = "window"
else:
who_id = "who%d" % i
what_id = "what%d" % i
window_id = "window%d" % i
widget_properties[who_id] = kwargs["who_args"]
widget_properties[what_id] = kwargs["what_args"]
widget_properties[window_id] = kwargs["window_args"]
dialogue.append((who, what, who_id, what_id, window_id))
renpy.show_screen(screen_name, _transient=True, _widget_properties=widget_properties, dialogue=dialogue, **scope)
renpy.shown_window()
return renpy.get_widget(screen_name, "what")
def nvl_show_core(who=None, what=None):
# Screen version.
if renpy.has_screen("nvl"):
return nvl_show_screen("nvl")
if renpy.in_rollback():
nvl_window = __s(style.nvl_window)['rollback']
@@ -194,12 +233,14 @@ init -1100 python:
else:
checkpoint = True
renpy.display_say(nvl_show_core,
checkpoint=checkpoint,
**display_args)
renpy.display_say(
who,
what,
nvl_show_core,
checkpoint=checkpoint,
**display_args)
def do_done(self, who, what):
if self.clear:
nvl_clear()
@@ -227,29 +268,37 @@ init -1100 python:
if nvl_list is None:
store.nvl_list = [ ]
ui.layer("transient")
ui.clear()
ui.close()
ui.window(style=__s(style.nvl_window))
ui.vbox(style=__s(style.nvl_vbox))
if renpy.has_screen("nvl_choice"):
for i in nvl_list:
if not i:
continue
# Screen version.
nvl_show_screen("nvl_choice", items=items)
who, what, kw = i
rv = renpy.show_display_say(who, what, **kw)
else:
renpy.display_menu(items, interact=False,
window_style=__s(style.nvl_menu_window),
choice_style=__s(style.nvl_menu_choice),
choice_chosen_style=__s(style.nvl_menu_choice_chosen),
choice_button_style=__s(style.nvl_menu_choice_button),
choice_chosen_button_style=__s(style.nvl_menu_choice_chosen_button),
)
# Traditional version.
ui.layer("transient")
ui.clear()
ui.close()
ui.close()
ui.window(style=__s(style.nvl_window))
ui.vbox(style=__s(style.nvl_vbox))
for i in nvl_list:
if not i:
continue
who, what, kw = i
rv = renpy.show_display_say(who, what, **kw)
renpy.display_menu(items, interact=False,
window_style=__s(style.nvl_menu_window),
choice_style=__s(style.nvl_menu_choice),
choice_chosen_style=__s(style.nvl_menu_choice_chosen),
choice_button_style=__s(style.nvl_menu_choice_button),
choice_chosen_button_style=__s(style.nvl_menu_choice_chosen_button),
)
ui.close()
roll_forward = renpy.roll_forward_info()
+1320
View File
File diff suppressed because it is too large Load Diff
+99 -7
View File
@@ -125,7 +125,7 @@ python early hide:
if p["channel"] is not None:
channel = eval(p["channel"])
else:
channel = 7
channel = "music"
renpy.music.play(eval(p["file"]),
fadeout=eval(p["fadeout"]),
@@ -191,7 +191,7 @@ python early hide:
if p["channel"] is not None:
channel = eval(p["channel"])
else:
channel = 7
channel = "music"
renpy.music.queue(
eval(p["file"]),
@@ -229,7 +229,7 @@ python early hide:
if p["channel"] is not None:
channel = eval(p["channel"])
else:
channel = 7
channel = "music"
renpy.music.stop(fadeout=eval(p["fadeout"]), channel=channel)
@@ -246,7 +246,7 @@ python early hide:
if p["channel"] is not None:
channel = eval(p["channel"])
else:
channel = 0
channel = "sound"
fadeout = eval(p["fadeout"]) or 0
@@ -264,7 +264,7 @@ python early hide:
if p["channel"] is not None:
channel = eval(p["channel"])
else:
channel = 0
channel = "sound"
renpy.sound.queue(eval(p["file"]), channel=channel)
@@ -278,7 +278,7 @@ python early hide:
if p["channel"] is not None:
channel = eval(p["channel"])
else:
channel = 0
channel = "sound"
fadeout = eval(p["fadeout"]) or 0
@@ -439,7 +439,6 @@ python early hide:
parse=parse_pause,
lint=lint_pause,
execute=execute_pause)
init -1200 python:
@@ -453,3 +452,96 @@ init -1200 python:
except:
renpy.error('unable to evaluate %s %r' % (what, e))
##############################################################################
# Screen-related statements.
python early hide:
def parse_show_call_screen(l):
# Parse a name.
name = l.require(l.name)
# Parse a parameter list. (name -> expression string)
parameters = { }
if l.match(r"\("):
while True:
pname = l.name()
if not pname:
break
l.require(r"=")
expr = l.delimited_python(",)")
if not expr:
l.error("expected expression.")
parameters[pname] = expr
if not l.match(r','):
break
l.require(r'\)')
l.expect_eol()
return dict(name=name, parameters=parameters)
def parse_hide_screen(l):
name = l.require(l.name)
l.expect_eol()
return dict(name=name)
def execute_show_screen(p):
name = p["name"]
parameters = p["parameters"]
kwargs = { }
for k, v in parameters.iteritems():
kwargs[k] = eval(v)
renpy.show_screen(name, **kwargs)
def execute_call_screen(p):
name = p["name"]
parameters = p["parameters"]
kwargs = { }
for k, v in parameters.iteritems():
kwargs[k] = eval(v)
store._return = renpy.call_screen(name, **kwargs)
def execute_hide_screen(p):
name = p["name"]
renpy.hide_screen(name)
def lint_screen(p):
name = p["name"]
if not renpy.has_screen(name):
renpy.error("Screen %s does not exist." % name)
renpy.statements.register("show screen",
parse=parse_show_call_screen,
execute=execute_show_screen,
lint=lint_screen)
renpy.statements.register("call screen",
parse=parse_show_call_screen,
execute=execute_call_screen,
lint=lint_screen)
renpy.statements.register("hide screen",
parse=parse_hide_screen,
execute=execute_hide_screen)
+18 -13
View File
@@ -22,10 +22,14 @@ init -1200 python hide:
# Style Declarations #################################################
style.default = Style(None, help='root of style hierarchy')
style.text = Style(style.default, help='style of text')
style.fixed = Style(style.default, help='fixed layouts')
style.hbox = Style(style.default, help='horizontal boxes')
style.vbox = Style(style.default, help='vertical boxes')
style.grid = Style(style.default, help='grid layouts')
style.side = Style(style.default, help='side layouts')
style.window = Style(style.default, help='windows created with ui.window')
style.image_placement = Style(style.default, help='default placement of images on the screen')
@@ -50,7 +54,8 @@ init -1200 python hide:
style.menu_choice_chosen_button = Style(style.menu_choice_button, help='buttons containing chosen in-game menu choices')
style.menu_window = Style(style.window, help='a window containing a menu')
style.input_text = Style(style.default, help='text of an input box')
style.input = Style(style.default, help='style of an input control')
style.input_text = Style(style.input, help='text of an input box')
style.input_prompt = Style(style.default, help='prompt of an input box')
style.input_window = Style(style.window, help='window of an input box')
@@ -58,8 +63,10 @@ init -1200 python hide:
style.centered_text = Style(style.default, help='centered text')
style.imagemap = Style(style.image_placement, help='default style of imagemaps')
style.imagemap_button = Style(style.default, help='default style of buttons inside imagemaps')
style.hotspot = Style(style.default, help='default style of hotspots inside imagemaps')
style.hotbar = Style(style.default, help='default style of hotbars inside imagemaps')
style.imagemap_button = style.hotspot
style.image_button = Style(style.default, help='default style of image buttons')
style.image_button_image = Style(style.default, help='default style of images inside image buttons')
@@ -76,6 +83,8 @@ init -1200 python hide:
style.list_spacer = Style(style.default)
style.list_text = Style(style.default)
style.tile = Style(style.default, help='default style of tile')
# The base styles that can be customized by themes.
style.frame = Style(style.default, help='base style for frames.')
@@ -213,16 +222,9 @@ init -1090 python:
style.window.xfill = True
style.window.yfill = False
style.window.yminimum = 150 # Includes margins and padding.
style.window.xalign = 0.5
style.window.yalign = 1.0
# Image placement.
style.image_placement.xpos = 0.5
style.image_placement.ypos = 1.0
style.image_placement.xanchor = 0.5
style.image_placement.yanchor = 1.0
# Dialogue
style.say_label.bold = True
style.say_vbox.spacing = 8
@@ -238,7 +240,7 @@ init -1090 python:
# Menus.
style.menu_choice.idle_color = "#0ff"
style.menu_choice.hover_color = "#ff0"
style.input_text.color = "#ff0"
style.input.color = "#ff0"
# Styles used by centered.
style.centered_window.xalign = 0.5
@@ -295,7 +297,10 @@ init -1090 python:
style.list_text.color = "#000"
style.list_text.size = 14
style.list_spacer.xminimum = 15
# Tile
style.tile.clipping = True
######################################################################
+2 -6
View File
@@ -275,7 +275,7 @@ init -1110 python hide:
style.vscrollbar.hover_left_bar = img("rrvscrollbar", widget_hover, 0, 12)
style.vscrollbar.hover_right_bar = img("rrvscrollbar", widget_hover, 0, 12)
style.vscrollbar.hover_thumb = img("rrvscrollbar_thumb", widget_hover, None, None)
@theme
def roundrect(
widget = (0, 60, 120, 255),
@@ -286,10 +286,7 @@ init -1110 python hide:
disabled_text = (200, 200, 200, 255),
label = (255, 255, 255, 255),
frame = (100, 150, 200, 255),
window = (0, 0, 0, 192),
mm_root = Solid((220, 235, 255, 255)),
gm_root = Solid((220, 235, 255, 255)),
text_size=None,
small_text_size=None,
less_rounded = False,
@@ -299,7 +296,6 @@ init -1110 python hide:
button_menu = None,
rounded_window = True,
outline_bars = False,
mm_root = None,
gm_root = None):
+17 -5
View File
@@ -30,15 +30,17 @@ init -1120:
_voice.play = None
_voice.sustain = False
_voice.seen_in_lint = False
# Call this to specify the voice file that will be played for
# the user.
def voice(file, **kwargs):
if not config.has_voice:
return
_voice.play = file
_last_voice_play = file
# Call this to specify that the currently playing voice file
# should be sustained through the current interaction.
def voice_sustain(ignored="", **kwargs):
@@ -47,6 +49,14 @@ init -1120:
_voice.sustain = True
# Call this to replay the last bit of voice.
def voice_replay():
renpy.sound.play(_last_voice_play, channel="voice")
# Returns true if we can replay the voice.
def voice_can_replay():
return _last_voice_play != None
python hide:
# basics: True if the game will have voice.
@@ -60,9 +70,11 @@ init -1120:
return
if _voice.play and not config.skipping:
renpy.sound.play(_voice.play, channel=2)
renpy.sound.play(_voice.play, channel="voice")
store._last_voice_play = _voice.play
elif not _voice.sustain:
renpy.sound.stop(channel=2)
renpy.sound.stop(channel="voice")
store._last_voice_play = _voice.play
_voice.play = None
_voice.sustain = False
@@ -71,7 +83,7 @@ init -1120:
config.say_sustain_callbacks.append(voice_sustain)
def voice_afm_callback():
return not renpy.sound.is_playing(channel=2)
return not renpy.sound.is_playing(channel="voice")
config.afm_callback = voice_afm_callback
+8 -5
View File
@@ -1,6 +1,5 @@
# This file contains the developer screen, which contains tools that might
# be of interest to people making Ren'Py games.
# This file contains code that helps support the development of Ren'Py
# games.
label _developer_screen:
@@ -20,7 +19,7 @@ label _developer_screen:
layout.button(u"Variable Viewer", None, clicked=ui.jumps("_debugger_screen"), size_group=sg)
layout.button(u"Theme Test", None, clicked=ui.jumps("_theme_test"), size_group=sg)
layout.button(u"Style Hierarchy", None, clicked=ui.jumps("_style_hierarchy"), size_group=sg)
layout.button(u"FPS Meter", None, clicked=ui.jumps("_fps_meter"), size_group=sg)
# layout.button(u"FPS Meter", None, clicked=ui.jumps("_fps_meter"), size_group=sg)
layout.button(u"Image Location Picker", None, clicked=ui.jumps("_image_location_picker"), size_group=sg)
ui.close()
@@ -466,4 +465,8 @@ label _image_location_picker:
# ...
renpy.jump("_image_location_picker")
init python:
config.underlay.append(im.Tile("_transparent_tile.png"))
+5 -2
View File
@@ -188,8 +188,11 @@ init python:
else:
base += 1
return base + int((int(filename) - 1) / per_page)
try:
return base + int((int(filename) - 1) / per_page)
except:
return base
# Processes a screenshot.
def _file_picker_process_screenshot(s):
return s
@@ -133,7 +133,7 @@ init python:
a channel.
"""
def __init__(self, name, mixer, enable='True', sound='None', channel=0):
def __init__(self, name, mixer, enable='True', sound='None', channel="sound"):
"""
@param name: The name of this preference, as shown to the user.
@@ -360,15 +360,18 @@ init python hide:
_VolumePreference(u"Music Volume",
'music',
'config.has_music')
_VolumePreference(u"Sound Volume",
'sfx',
'config.has_sound',
'config.sample_sound')
'config.sample_sound',
'sound')
_VolumePreference(u'Voice Volume',
'voice',
'config.has_voice',
'config.sample_voice',
2)
'voice')
_JumpPreference(u'Joystick...',
'joystick_preferences_screen',
+5 -2
View File
@@ -151,8 +151,11 @@ init python:
else:
base += 1
return base + int((int(filename) - 1) / per_page)
try:
return base + int((int(filename) - 1) / per_page)
except:
return base
# Processes a screenshot.
def _file_picker_process_screenshot(s):
return s
+9 -6
View File
@@ -77,12 +77,12 @@ init python:
ime.button("Joystick", ui.jumps("joystick_preferences_screen"), False)
def play_sound():
renpy.sound.play(config.sample_sound)
renpy.music.play(config.sample_sound, channel="sound")
ime.button("Sound Test", play_sound, False)
def play_voice():
renpy.sound.play(config.sample_sound, channel=2)
renpy.music.play(config.sample_sound, channel="voice")
ime.button("Voice Test", play_voice, False)
@@ -124,11 +124,14 @@ init python:
_preferences.set_volume('sfx', v / 128.0)
def set_voice(v):
_preferences.set_volume('voice', v / 128.0)
ime.bar("Music Volume", 128, int(_preferences.get_volume('music') * 128), set_music)
ime.bar("Sound Volume", 128, int(_preferences.get_volume('sfx') * 128), set_sound)
ime.bar("Voice Volume", 128, int(_preferences.get_volume('voice') * 128), set_voice)
if config.has_music:
ime.bar("Music Volume", 128, int(_preferences.get_volume('music') * 128), set_music)
if config.has_sound:
ime.bar("Sound Volume", 128, int(_preferences.get_volume('sfx') * 128), set_sound)
if config.has_voice:
ime.bar("Voice Volume", 128, int(_preferences.get_volume('voice') * 128), set_voice)
ime.close()
ui.interact(mouse="gamemenu")
@@ -0,0 +1,16 @@
# Copyright 2004-2010 PyTom <pytom@bishoujo.us>
# See LICENSE.txt for license details.
init python:
layout.provides('joystick_preferences')
label joystick_preferences_screen:
$ renpy.show_screen('joystick_preferences')
$ ui.interact()
jump _noisy_return
+19
View File
@@ -0,0 +1,19 @@
# Copyright 2004-2010 PyTom <pytom@bishoujo.us>
# See LICENSE.txt for license details.
init python:
layout.provides('load_save')
label load_screen:
$ renpy.show_screen('load')
$ ui.interact()
jump _noisy_return
label save_screen:
$ renpy.show_screen('save')
$ ui.interact()
jump _noisy_return
+14
View File
@@ -0,0 +1,14 @@
# Copyright 2004-2010 PyTom <pytom@bishoujo.us>
# See LICENSE.txt for license details.
init python:
layout.provides('main_menu')
label main_menu_screen:
$ renpy.show_screen("main_menu")
$ ui.interact()
return
+16
View File
@@ -0,0 +1,16 @@
# Copyright 2004-2010 PyTom <pytom@bishoujo.us>
# See LICENSE.txt for license details.
init python:
layout.provides('preferences')
label preferences_screen:
$ renpy.show_screen('preferences')
$ ui.interact()
jump _noisy_return
+11
View File
@@ -0,0 +1,11 @@
# Copyright 2004-2010 PyTom <pytom@bishoujo.us>
# See LICENSE.txt for license details.
init python hide:
layout.provides('yesno_prompt')
def yesno_prompt(screen, message):
return renpy.call_screen('yesno_prompt', message=message, yes_action=Return(True), no_action=Return(False))
layout.yesno_prompt = yesno_prompt
Binary file not shown.

After

Width:  |  Height:  |  Size: 436 B

+21 -12
View File
@@ -175,13 +175,19 @@ def main():
"_renpybidi.c",
"renpybidicore.c",
"_renpybidi.pyx",
"_renpy_pysdlgl.c",
"_renpy_pysdlgl.pyx",
"_renpy_tegl.c",
"maketegl.py",
"maketegl.txt",
]
for i in module_files:
files.append('module/' + i)
more_files.append('python25.dll')
more_files.append('msvcr71.dll')
more_files.append('python26.dll')
more_files.append('msvcr90.dll')
more_files.append('Microsoft.VC90.CRT.manifest')
files.extend(tree('renpy'))
more_files.extend(tree('renpy.app'))
more_files.append('renpy.code')
@@ -193,15 +199,17 @@ def main():
files.extend(tree('template'))
# files.extend(tree('tools'))
files.append('doc/index.html')
files.append('doc/common.css')
files.append('doc/docs.css')
files.append('doc/monobook.css')
files.append('doc/monobook2.css')
files.append('doc/shared.css')
files.extend(tree('doc/reference'))
files.extend(tree('doc/tutorials'))
files.extend(tree('doc/images'))
files.extend(tree('doc'))
# files.append('doc/index.html')
# files.append('doc/common.css')
# files.append('doc/docs.css')
# files.append('doc/monobook.css')
# files.append('doc/monobook2.css')
# files.append('doc/shared.css')
# files.extend(tree('doc/reference'))
# files.extend(tree('doc/tutorials'))
# files.extend(tree('doc/images'))
files.sort()
more_files.sort()
@@ -211,8 +219,9 @@ def main():
zipup("dists/" + prefix + "-sdk.zip", prefix, files + more_files)
print "----"
tarup("dists/" + prefix + "-sdk.tar.bz2", prefix, files + more_files)
print "----"
tarup("dists/" + prefix + "-source.tar.bz2", prefix, files)
print "----"
# Make the 7zip.
os.chdir("dists")
os.system("unzip " + prefix + "-sdk.zip")
Symlink
+1
View File
@@ -0,0 +1 @@
sphinx/build/html/
-16
View File
@@ -1,16 +0,0 @@
#bodyContent {
font-size: medium;
background: #fff;
margin-left: 20%;
margin-right: 20%;
padding: 1.5em;
}
.editsection {
display: none;
}
#bodyContent a.external {
background: none;
padding-right: 0px;
}
-19
View File
@@ -1,19 +0,0 @@
#!/bin/sh
wget http://www.renpy.org/w/skins/common/shared.css -O shared.css
wget http://www.renpy.org/w/skins/monobook/main.css -O monobook.css
wget 'http://www.renpy.org/w/index.php?title=MediaWiki:Common.css&usemsgcache=yes&action=raw&ctype=text/css&smaxage=18000' -O common.css
wget 'http://www.renpy.org/w/index.php?title=MediaWiki:Monobook.css&usemsgcache=yes&action=raw&ctype=text/css&smaxage=18000' -O monobook2.css
rm -Rf www.renpy.org
wget -e robots=off -m -I /wiki/renpy/doc/reference/,/wiki/renpy/doc/tutorials/,/w/images -m http://www.renpy.org/wiki/renpy/doc/index
rm -Rf images
mkdir -p images
cp `find www.renpy.org -name \*.png -type f` images
No jpgs yet.
cp `find www.renpy.org -name \*.jpg -type f` images
rm -Rf reference tutorials
python2.5 process.py
-164
View File
@@ -1,164 +0,0 @@
#!/usr/bin/python2.4
import sys
import os.path
# import xml.etree.ElementTree as elementtree
# sys.modules['elementtree'] = elementtree
# from elementtree.ElementTree import ElementTree, Element, SubElement, tostring, fromstring
# from elementtidy import TidyHTMLTreeBuilder
from xml.etree.ElementTree import ElementTree, Element, SubElement, tostring, fromstring
from elementtidy import TidyHTMLTreeBuilder
# Removes everyhing we don't care about from the wikipages.
def remove_crap(n):
classes = n.attrib.get("class", "").split()
if "editsection" in classes:
return None
if "printfooter" in classes:
return None
if "magnify" in classes:
return None
id = n.attrib.get("id", None)
if "catlinks" == id:
return None
newchildren = [ ]
for i in n:
i = remove_crap(i)
if i is not None:
newchildren.append(i)
n[:] = newchildren
if n.tag == "a" and not n.text:
n.text = "SPACE REMOVE ME PLEASE"
return n
def process(src, dst, nav):
if nav:
nav = fromstring(nav)
base = "../" * (len(dst.split('/')) - 1)
if dst.startswith("./"):
base = ""
# tree = TidyHTMLTreeBuilder.parse(src)
code = file(src).read()
code = code.replace("&nbsp;", u"\u00a0".encode("utf-8"))
tree = fromstring(code)
XHTML = "{http://www.w3.org/1999/xhtml}"
for elem in tree.getiterator():
if elem.tag.startswith(XHTML):
elem.tag = elem.tag[len(XHTML):]
by_id = dict()
for n in tree.getiterator():
if "id" in n.attrib:
by_id[n.attrib["id"]] = n
html = Element("html")
head = SubElement(html, "head")
title = SubElement(head, "title")
title.text = tree.findtext(".//title")
head = SubElement(head, "link", rel="stylesheet", href=base + "shared.css")
head = SubElement(head, "link", rel="stylesheet", href=base + "monobook.css")
head = SubElement(head, "link", rel="stylesheet", href=base + "common.css")
head = SubElement(head, "link", rel="stylesheet", href=base + "monobook2.css")
head = SubElement(head, "link", rel="stylesheet", href=base + "docs.css")
body = SubElement(html, "body")
# gw = SubElement(body, "div", id="globalWrapper")
# cc = SubElement(gw, "div", id="column-content")
# content = SubElement(cc, "div", id="content")
bc = by_id['bodyContent']
body.append(bc)
bc.remove(by_id['siteSub'])
bc.remove(by_id['contentSub'])
bc.remove(by_id['jump-to-nav'])
for n in bc.findall(".//a"):
if "href" in n.attrib:
href = n.attrib['href']
if href.startswith("/wiki/Image:") or href.startswith("/w/"):
n.attrib['href'] = 'http://www.renpy.org' + href
continue
if href.startswith("#"):
continue
if href.startswith("http:"):
continue
href = href.replace("/wiki/renpy/doc/", base)
if "#" in href:
href.replace("#", ".html#")
else:
href += ".html"
n.attrib['href'] = href
for n in bc.findall(".//img"):
src = n.attrib["src"]
src = base + "images" + src[src.rfind("/"):]
n.attrib["src"] = src
if nav:
hr = Element("hr")
bc[:] = [ nav ] + list(bc) + [ hr, nav ]
html = remove_crap(html)
doc = tostring(html)
doc = doc.replace("SPACE REMOVE ME PLEASE", "")
file(dst, "w").write(doc)
def process_dir(src, dst, nav):
try:
os.makedirs(dst)
except:
pass
for fn in os.listdir(src):
if os.path.isdir(src + "/" + fn):
continue
if fn.endswith(".1"):
continue
print src + "/" + fn
process(src + "/" + fn, dst + "/" + fn + ".html", nav)
nav = '<p class="docnav"><a href="../index.html">documentation index</a></p>'
process_dir("www.renpy.org/wiki/renpy/doc/tutorials", "tutorials", nav)
nav = '<p class="docnav"><a href="../index.html">documentation index</a> &#x25e6; <a href="Reference_Manual.html">reference manual</a> &#x25e6; <a href="Function_Index.html">function index</a></p>'
process_dir("www.renpy.org/wiki/renpy/doc/reference", "reference", nav)
nav = '<p class="docnav"><a href="../../index.html">documentation index</a> &#x25e6; <a href="../Reference_Manual.html">reference manual</a> &#x25e6; <a href="../Function_Index.html">function index</a></p>'
process_dir("www.renpy.org/wiki/renpy/doc/reference/functions", "reference/functions", nav)
nav = ''
process_dir("www.renpy.org/wiki/renpy/doc/", ".", nav)
+329
View File
@@ -0,0 +1,329 @@
# http://www.csn.ul.ie/~caolan/publink/winresdump/winresdump/doc/pefile.html
# Contains a reasonable description of the format.
import struct
import sys
import array
import pefile
# This class performs various operations on memory-loaded binary files,
# including modifications.
class BinFile(object):
def set_u32(self, addr, value):
self.a[addr+0] = (value >> 0) & 0xff
self.a[addr+1] = (value >> 8) & 0xff
self.a[addr+2] = (value >> 16) & 0xff
self.a[addr+3] = (value >> 24) & 0xff
def u32(self):
addr = self.addr
rv = self.a[addr]
rv |= self.a[addr+1] << 8
rv |= self.a[addr+2] << 16
rv |= self.a[addr+3] << 24
self.addr += 4
return rv
def u16(self):
addr = self.addr
rv = self.a[addr]
rv |= self.a[addr+1] << 8
self.addr += 2
return rv
def u8(self):
rv = self.a[self.addr]
self.addr += 1
return rv
def name(self):
c = self.u16()
rv = u""
for i in range(c):
rv += unichr(self.u16())
return rv
def seek(self, addr):
self.addr = addr
def tostring(self):
return self.a.tostring()
def substring(self, start, len):
return self.a[start:start+len].tostring()
def __init__(self, data):
self.a = array.array('B')
self.a.fromstring(data)
##############################################################################
# These functions parse data out of the file. In these functions, offset is
# relative to the start of the file.
# The virtual address of the resource segment.
resource_virtual = 0
# This parses a data block out of the resources.
def parse_data(bf, offset):
bf.seek(offset)
data_offset = bf.u32()
data_len = bf.u32()
code_page = bf.u32()
bf.u32()
l = [ ]
bf.seek(data_offset - resource_virtual)
for i in range(data_len):
l.append(chr(bf.u8()))
return (code_page, "".join(l))
# This parses a resource directory.
def parse_directory(bf, offset):
bf.seek(offset)
char = bf.u32()
timedate = bf.u32()
major = bf.u16()
minor = bf.u16()
n_named = bf.u16()
n_id = bf.u16()
entries = [ ]
for i in range(n_named + n_id):
entries.append((bf.u32(), bf.u32()))
rv = { }
for name, value in entries:
if name & 0x80000000:
bf.seek((name & 0x7fffffff))
name = bf.name()
if value & 0x80000000:
value = parse_directory(bf, value & 0x7fffffff)
else:
value = parse_data(bf, value)
rv[name] = value
return rv
##############################################################################
# This utility function displays the tree of resources that have been loaded.
def show_resources(d, prefix):
if not isinstance(d, dict):
print prefix, "Codepage", d[0], "length", len(d[1])
return
for k in d:
print prefix, k
show_resources(d[k], prefix + " ")
##############################################################################
# These functions repack the resources into a new resource segment. Here,
# the offset is relative to the start of the resource segment.
class Packer(object):
def pack(self, d):
self.data = ""
self.data_offset = 0
self.entries = ""
self.entries_offset = 0
head = self.pack_dict(d, 0)
self.data = ""
self.data_offset = len(head) + len(self.entries)
self.entries = ""
self.entries_offset = len(head)
return self.pack_dict(d, 0) + self.entries + self.data
def pack_name(self, s):
rv = self.data_offset + len(self.data)
l = len(s)
s = s.encode("utf-16le")
self.data += struct.pack("<H", l) + s + "\0\0"
return rv
def pack_tuple(self, t):
codepage, data = t
rv = len(self.entries) + self.entries_offset
if len(self.data) % 2:
self.data += "P"
daddr = len(self.data) + self.data_offset
self.entries += struct.pack("<IIII", daddr + resource_virtual, len(data), codepage, 0)
self.data += data
# if len(self.data) % 1 == 1:
# self.data += 'P'
return rv
def pack_dict(self, d, offset):
name_entries = sorted((a, b) for a, b in d.iteritems() if isinstance(a, unicode))
id_entries = sorted((a, b) for a, b in d.iteritems() if isinstance(a, int))
rv = struct.pack("<IIHHHH", 0, 0, 4, 0, len(name_entries), len(id_entries))
offset += len(rv) + (len(name_entries) + len(id_entries)) * 8
rest = ""
for (name, value) in name_entries + id_entries:
if isinstance(name, unicode):
name = 0x80000000 | self.pack_name(name)
if isinstance(value, dict):
addr = offset | 0x80000000
packed = self.pack_dict(value, offset)
offset += len(packed)
rest += packed
else:
addr = self.pack_tuple(value)
rv += struct.pack("<II", name, addr)
return rv + rest
##############################################################################
# This loads in an icon file, and returns a dictionary that is suitable for
# use in the resources of an exe file.
def load_icon(fn):
f = BinFile(file(fn, "rb").read())
f.seek(0)
f.u16()
f.u16()
count = f.u16()
rv = { }
rv[3] = { }
group = struct.pack("HHH", 0, 1, count)
for i in range(count):
width = f.u8()
height = f.u8()
colors = f.u8()
reserved = f.u8()
planes = f.u16()
bpp = f.u16()
size = f.u32()
offset = f.u32()
addr = f.addr
f.seek(offset + 16)
if not f.u32():
f.set_u32(offset + 20, 0)
rv[3][i + 1] = { 0 : (1252, f.substring(offset, size)) }
group += struct.pack("BBBBHHIH", width, height, colors, reserved,
planes, bpp, size, i + 1)
f.seek(addr)
rv[14] = { 1 : { 0 : (1252, group) } }
return rv
##############################################################################
# This is the main function that should be called externally, that copies over
# the icons.
def change_icons(oldexe, icofn):
global resource_virtual
pe = pefile.PE(oldexe)
for s in pe.sections:
if s.Name == ".rsrc\0\0\0":
rsrc_section = s
break
else:
raise Exception("Couldn't find resource section.")
base = rsrc_section.PointerToRawData
resource_virtual = rsrc_section.VirtualAddress
physize = rsrc_section.SizeOfRawData
virsize = rsrc_section.Misc_VirtualSize
f = file(oldexe, "rb")
f.seek(base)
data = f.read(physize)
f.close()
bf = BinFile(data)
resources = parse_directory(bf, 0)
# show_resources(resources, "")
resources.update(load_icon(icofn))
# show_resources(resources, "")
rsrc = Packer().pack(resources)
alignment = pe.OPTIONAL_HEADER.SectionAlignment
# print "Alignment is", alignment
if len(rsrc) % alignment:
pad = alignment - (len(rsrc) % alignment)
padding = "RENPYVNE" * (pad / 8 + 1)
padding = padding[:pad]
rsrc += padding
newsize = len(rsrc)
rsrc_section.Misc_VirtualSize += newsize - virsize
rsrc_section.Misc_PhysicalAddress += newsize - virsize
rsrc_section.Misc += newsize - virsize
rsrc_section.SizeOfRawData += newsize - physize
pe.OPTIONAL_HEADER.SizeOfInitializedData += newsize - physize
# Resource size.
pe.OPTIONAL_HEADER.DATA_DIRECTORY[2].Size += newsize - virsize
# Compute the total size of the image.
total_size = 0
for i in pe.sections:
sec_size = i.Misc_VirtualSize
sec_size = sec_size - (sec_size % alignment) + alignment
print sec_size
total_size += sec_size
pe.OPTIONAL_HEADER.SizeOfImage = total_size
return pe.write()[:base] + rsrc
if __name__ == "__main__":
f = file(sys.argv[3], "wb")
f.write(change_icons(sys.argv[1], sys.argv[2]))
f.close()
+533
View File
@@ -0,0 +1,533 @@
import os
import os.path
import zipfile
import tarfile
import time
import sys
import struct
import zlib
zlib.Z_DEFAULT_COMPRESSION = 9
import binascii
import change_icon
import argparse
# The directory containing the project that we'll be distributing.
project_path = None
# The path to the Ren'Py base directory.
renpy_base = None
# A function that is called to give information about what is going
# on now.
def info(title, body):
return
# A function that is called to give a progress report.
def progress(title, total, amount):
amount += 1
if amount % 25 == 0:
print title, amount, "of", total
# A translation function.
def _(s):
return s
# These are files that are ignored wherever they are found in a
# distribution.
ignored_files = (
"thumbs.db",
"traceback.txt",
"errors.txt",
"saves"
)
# These are files (and directories) that are ignored when found in
# the root directory of the distribution.
root_ignored_files = (
"common",
"renpy",
"renpy.code",
"python23.dll",
"python24.dll",
"python25.dll",
"msvcr71.dll",
"lib",
"iliad-icon.png",
"manifest.xml",
"icon.ico",
"icon.icns",
"launcherinfo.py",
"archived",
)
# Extensions that should be made executable.
executable_extensions = (
"MacOS",
"so",
"dylib",
".sh",
"python",
"python.real",
)
class MyZipFile(zipfile.ZipFile):
"""
Modified ZipFile class that can insert a file into the archive,
using a supplied ZipInfo object. Code comes from the writestr
and write methods of ZipFile.
"""
def write_file_with_zipinfo(self, filename, zinfo, compress_type=None):
"""Put the bytes from filename into the archive under the name
arcname."""
st = os.stat(filename)
if compress_type is None:
zinfo.compress_type = self.compression
else:
zinfo.compress_type = compress_type
zinfo.file_size = st.st_size
zinfo.flag_bits = 0x00
zinfo.header_offset = self.fp.tell() # Start of header bytes
self._writecheck(zinfo)
self._didModify = True
fp = open(filename, "rb")
# Must overwrite CRC and sizes with correct data later
zinfo.CRC = CRC = 0
zinfo.compress_size = compress_size = 0
zinfo.file_size = file_size = 0
self.fp.write(zinfo.FileHeader())
if zinfo.compress_type == zipfile.ZIP_DEFLATED:
cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION,
zlib.DEFLATED, -15)
else:
cmpr = None
while 1:
buf = fp.read(1024 * 64)
if not buf:
break
file_size = file_size + len(buf)
CRC = binascii.crc32(buf, CRC)
if cmpr:
buf = cmpr.compress(buf)
compress_size = compress_size + len(buf)
self.fp.write(buf)
fp.close()
if cmpr:
buf = cmpr.flush()
compress_size = compress_size + len(buf)
self.fp.write(buf)
zinfo.compress_size = compress_size
else:
zinfo.compress_size = file_size
zinfo.CRC = CRC
zinfo.file_size = file_size
# Seek backwards and write CRC and file sizes
position = self.fp.tell() # Preserve current position in file
self.fp.seek(zinfo.header_offset + 14, 0)
self.fp.write(struct.pack("<lLL", zinfo.CRC, zinfo.compress_size,
zinfo.file_size))
self.fp.seek(position, 0)
self.filelist.append(zinfo)
self.NameToInfo[zinfo.filename] = zinfo
def tree(
src,
dest,
exclude_suffix=[ ".pyc", "~", ".bak" ],
exclude_prefix=[ "#", "." ],
exclude_files = set(ignored_files),
root_exclude_prefix = [ ],
root_exclude_suffix = [ ".py", ".sh", ".app" ],
root_exclude_files = set(root_ignored_files),
root=False):
"""
Returns a list of source-filename, destination-filename pairs.
"""
if dest[0] != "/":
raise Exception("Destination must begin with /: %r" % dest)
src = src.rstrip('/')
dest = dest.rstrip('/')
def include(fn, is_root):
"""
Returns True if the file should be included in the list of
files we are copying.
"""
for i in exclude_suffix:
if fn.endswith(i):
return False
for i in exclude_prefix:
if fn.startswith(i):
return False
if fn in exclude_files:
return False
if not root or not is_root:
return True
for i in root_exclude_suffix:
if fn.endswith(i):
return False
for i in root_exclude_prefix:
if fn.startswith(i):
return False
if fn in root_exclude_files:
return False
return True
rv = [ ]
# Walk the tree, including what is necessary.
for srcdir, dirs, files in os.walk(src):
is_root = (srcdir == src)
srcdir += "/"
destdir = dest + srcdir[len(src):]
destdir.replace("\\", "/")
rv.append((srcdir, destdir))
for fn in files:
if not include(fn, is_root):
continue
sfn = srcdir + fn
dfn = destdir + fn
rv.append((sfn, dfn))
dirs[:] = [ i for i in dirs if include(i, is_root) ]
rv = [ (a.replace("\\", "/"), b.replace("\\", "/")) for a, b in rv ]
return rv
def make_zip(t, filename, files, file_data):
"""
This creates `filename`.zip, containing `files`, placed in the
`filename` directory. `file_data` is a map from source file to
replacement data.
"""
files.sort(key=lambda a : a[1])
progress_len = len(files)
fn = os.path.join(os.path.dirname(project_path), filename)
zf = MyZipFile(fn + ".zip", "w", zipfile.ZIP_DEFLATED)
for i, (fn, an) in enumerate(files):
progress(t, progress_len, i)
if os.path.isdir(fn):
continue
zi = zipfile.ZipInfo(filename + an)
s = os.stat(fn)
zi.date_time = time.gmtime(s.st_mtime)[:6]
zi.compress_type = zipfile.ZIP_DEFLATED
zi.create_system = 3
for i in executable_extensions:
if os.path.dirname(fn).endswith(i) or fn.endswith(i):
zi.external_attr = long(0100777) << 16
break
else:
zi.external_attr = long(0100666) << 16
if fn in file_data:
data = file_data[fn]
zf.writestr(zi, data)
else:
zf.write_file_with_zipinfo(fn, zi)
zf.close()
def make_tar(t, filename, files):
"""
Makes a tarfile, as above.
"""
files.sort(key=lambda a : a[1])
progress_len = len(files)
fn = os.path.join(os.path.dirname(project_path), filename)
tf = tarfile.open(fn + ".tar.bz2", "w:bz2")
tf.dereference = True
for j, (fn, an) in enumerate(files):
progress(t, progress_len, j)
info = tf.gettarinfo(fn, filename + an)
perms = 0666
if info.isdir():
perms = 0777
for i in executable_extensions:
if fn.endswith(i):
perms = 0777
info.mode = perms
info.uid = 1000
info.gid = 1000
info.uname = "renpy"
info.gname = "renpy"
if info.isreg():
tf.addfile(info, file(fn, "rb"))
else:
tf.addfile(info)
tf.close()
def distribute(
_project_path,
_renpy_base,
base_name,
executable_name,
ignore_extensions,
documentation_extensions,
build_windows,
build_linux,
build_mac,
build_all):
global project_path
global renpy_base
project_path = _project_path
renpy_base = _renpy_base
base_name = base_name.encode("utf-8")
executable_name = executable_name.encode("utf-8")
ignore_extensions = ignore_extensions.encode("utf-8")
documentation_extensions = documentation_extensions.encode("utf-8")
# Convert some of these to more useful formats.
ignore_extensions = [ i.strip() for i in ignore_extensions.split() ]
documentation_extensions = [ i.strip() for i in documentation_extensions.split() ]
# Scan for the files we want to include in the various distributions.
info(_(u"Scanning..."), "")
# Files included in the various distributions.
multi_files = [ ]
win_files = [ ]
linux_files = [ ]
mac_files = [ ]
# A map from source file name to replacement data to be placed in
# that file.
file_data = { }
######################################################################
# Multi files.
rb = renpy_base.replace("\\", "/") + "/"
# Project files.
multi_files.extend(tree(project_path, "/", root=True, exclude_suffix=ignore_extensions))
multi_files.append((rb + "renpy.py", "/" + executable_name + ".py"))
# Renpy files.
multi_files.extend(tree(rb + "common", "/common"))
multi_files.extend(tree(rb + "renpy", "/renpy"))
multi_files.append((rb + "LICENSE.txt", "/renpy/LICENSE.txt"))
def add_script_version(fn, ignore_extensions=ignore_extensions, multi_files=multi_files, rb=rb):
"""
Add a script_version file if it does not already exist, and if the
extension is allowed by the game.
"""
for a, b in multi_files:
if b == "/game/" + fn:
return
for i in ignore_extensions:
if fn.endswith(i):
return
multi_files.append((rb + "launcher/" + fn, "/game/" + fn))
add_script_version("script_version.rpy")
add_script_version("script_version.rpyc")
######################################################################
# Windows files.
if build_windows or build_all:
win_files.append((rb + "renpy.exe", "/" + executable_name + ".exe"))
win_files.append((rb + "renpy.code", "/renpy.code"))
win_files.append((rb + "python26.dll", "/python26.dll"))
win_files.append((rb + "msvcr90.dll", "/msvcr90.dll"))
win_files.append((rb + "Microsoft.VC90.CRT.manifest", "/Microsoft.VC90.CRT.manifest"))
if os.path.exists(project_path + "/icon.ico"):
file_data[rb + "renpy.exe"] = change_icon.change_icons(
rb + "renpy.exe",
project_path + "/icon.ico",
)
######################################################################
# Linux files.
if build_linux or build_all:
linux_files.append((rb + "renpy.sh", "/" + executable_name + ".sh"))
linux_files.append((rb + "lib", "/lib"))
linux_files.append((rb + "lib/python", "/lib/python"))
linux_files.extend(tree(rb + "lib/linux-x86", "/lib/linux-x86"))
# Warning: The tar.bz2 builder doesn't support file_data.
######################################################################
# Mac (non-app) files.
if build_mac or build_all:
mac_files = tree(rb + "renpy.app",
"/" + executable_name + ".app")
# Rename executable.
mac_files = [ (fn, an.replace("Ren'Py Launcher", executable_name)) for (fn, an) in mac_files ]
# Plist file.
quoted_name = executable_name.replace("&", "&amp;").replace("<", "&lt;")
info_plist = file(rb + "renpy.app/Contents/Info.plist", "rb").read().replace("Ren'Py Launcher", quoted_name)
file_data[rb + "renpy.app/Contents/Info.plist"] = info_plist
# Launcher script.
quoted_name = executable_name.replace("\"", "\\\"")
launcher_py = file(rb + "renpy.app/Contents/Resources/launcher.py", "rb").read().replace("Ren'Py Launcher", quoted_name)
file_data[rb + "renpy.app/Contents/Resources/launcher.py"] = launcher_py
# Icon file.
if os.path.exists(project_path + "/icon.icns"):
icon_data = file(project_path + "/icon.icns", "rb").read()
file_data[rb + "renpy.app/Contents/Resources/launcher.icns"] = icon_data
######################################################################
# Now, build the various distributions.
if build_windows:
make_zip(
_(u"Building Windows..."),
base_name + "-win32",
multi_files + win_files,
file_data)
if build_linux:
make_tar(
_(u"Building Linux..."),
base_name + "-linux-x86",
multi_files + linux_files)
if build_mac:
# Reorganize the files so all the non application files live inside
# the application. If there's documentation involved, then it
# lives in both places.
macapp_files = [ ]
for fn, an in multi_files + mac_files:
if not an.startswith("/" + executable_name + ".app"):
new_an = "/" + executable_name + ".app/Contents/Resources/autorun" + an
macapp_files.append((fn, new_an))
if an.rindex('/') == 0:
for i in documentation_extensions:
if fn.endswith(i):
macapp_files.append((fn, an))
break
else:
macapp_files.append((fn, an))
make_zip(
_(u"Building Macintosh..."),
base_name + "-mac",
macapp_files,
file_data)
if build_all:
make_zip(
_(u"Building Combined..."),
base_name + "-all",
multi_files + win_files + linux_files + mac_files,
file_data)
def main():
ap = argparse.ArgumentParser(description="Prepare a Ren'Py game for distribution.")
ap.add_argument("project_path", type=str, help="The path to the directory containing the project.")
ap.add_argument("base_name", type=str, help="The base name of the archive files produced.")
ap.add_argument("executable_name", type=str, help="The name of the executables produced.")
ap.add_argument("--renpy-base", type=str, default=None, help="The path to the Ren'Py distribution.")
ap.add_argument("--ignore-extensions", type=str, default="~ .bak", help="A space-separated list of extensions to ignore.")
ap.add_argument("--documentation-extensions", type=str, default="txt html", help="A space-separated list of extensions to treat as documentation.")
ap.add_argument("--build-windows", action="store_true", default=False, help="Build the Windows distribution.")
ap.add_argument("--build-mac", action="store_true", default=False, help="Build the Mac OS X distribution.")
ap.add_argument("--build-linux", action="store_true", default=False, help="Build the Windows distribution.")
ap.add_argument("--build-all", action="store_true", default=False, help="Build the All Platforms distribution.")
args = ap.parse_args()
renpy_base = args.renpy_base
if renpy_base is None:
renpy_base = os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[0])))
distribute(
args.project_path,
renpy_base,
base_name=args.base_name,
executable_name=args.executable_name,
ignore_extensions=args.ignore_extensions,
documentation_extensions=args.documentation_extensions,
build_windows=args.build_windows,
build_mac=args.build_mac,
build_linux=args.build_linux,
build_all=args.build_all)
if __name__ == "__main__":
main()
+19 -388
View File
@@ -1,234 +1,21 @@
# This file contains the code needed to build a Ren'Py distribution.
init python:
import os
import os.path
import zipfile
import tarfile
import time
import sys
import zlib
zlib.Z_DEFAULT_COMPRESSION = 9
init 12 python:
import pefile
# These are files that are ignored wherever they are found in a
# distribution.
ignored_files = (
"thumbs.db",
"traceback.txt",
"errors.txt",
"saves"
)
import distribute
# These are files (and directories) that are ignored when found in
# the root directory of the distribution.
root_ignored_files = (
"common",
"renpy",
"renpy.code",
"python23.dll",
"python24.dll",
"python25.dll",
"msvcr71.dll",
"lib",
"iliad-icon.png",
"manifest.xml",
"icon.ico",
"icon.icns",
"launcherinfo.py",
"archived",
)
distribute.progress = progress
distribute.info = info
distribute._ = _
# Extensions that should be made executable.
executable_extensions = (
"MacOS",
"so",
"dylib",
".sh",
"python",
"python.real",
)
def tree(
src,
dest,
exclude_suffix=[ ".pyc", "~", ".bak" ],
exclude_prefix=[ "#", "." ],
exclude_files = set(ignored_files),
root_exclude_prefix = [ ],
root_exclude_suffix = [ ".py", ".sh", ".app" ],
root_exclude_files = set(root_ignored_files),
root=False):
"""
Returns a list of source-filename, destination-filename pairs.
"""
if dest[0] != "/":
raise Exception("Destination must begin with /: %r" % dest)
src = src.rstrip('/')
dest = dest.rstrip('/')
def include(fn, is_root):
"""
Returns True if the file should be included in the list of
files we are copying.
"""
for i in exclude_suffix:
if fn.endswith(i):
return False
for i in exclude_prefix:
if fn.startswith(i):
return False
if fn in exclude_files:
return False
if not root or not is_root:
return True
for i in root_exclude_suffix:
if fn.endswith(i):
return False
for i in root_exclude_prefix:
if fn.startswith(i):
return False
if fn in root_exclude_files:
return False
return True
rv = [ ]
# Walk the tree, including what is necessary.
for srcdir, dirs, files in os.walk(src):
is_root = (srcdir == src)
srcdir += "/"
destdir = dest + srcdir[len(src):]
destdir.replace("\\", "/")
rv.append((srcdir, destdir))
for fn in files:
if not include(fn, is_root):
continue
sfn = srcdir + fn
dfn = destdir + fn
rv.append((sfn, dfn))
dirs[:] = [ i for i in dirs if include(i, is_root) ]
rv = [ (a.replace("\\", "/"), b.replace("\\", "/")) for a, b in rv ]
return rv
def make_zip(t, filename, files, file_data):
"""
This creates `filename`.zip, containing `files`, placed in the
`filename` directory. `file_data` is a map from source file to
replacement data.
"""
files.sort(key=lambda a : a[1])
progress_len = len(files)
fn = os.path.join(os.path.dirname(project.path), filename)
zf = zipfile.ZipFile(fn + ".zip", "w", zipfile.ZIP_DEFLATED)
for i, (fn, an) in enumerate(files):
progress(t, progress_len, i)
if os.path.isdir(fn):
continue
zi = zipfile.ZipInfo(filename + an)
s = os.stat(fn)
zi.date_time = time.gmtime(s.st_mtime)[:6]
zi.compress_type = zipfile.ZIP_DEFLATED
zi.create_system = 3
for i in executable_extensions:
if os.path.dirname(fn).endswith(i) or fn.endswith(i):
zi.external_attr = long(0100777) << 16
break
else:
zi.external_attr = long(0100666) << 16
if fn in file_data:
data = file_data[fn]
else:
data = file(fn, "rb").read()
zf.writestr(zi, data)
zf.close()
def make_tar(t, filename, files):
"""
Makes a tarfile, as above.
"""
files.sort(key=lambda a : a[1])
progress_len = len(files)
fn = os.path.join(os.path.dirname(project.path), filename)
tf = tarfile.open(fn + ".tar.bz2", "w:bz2")
tf.dereference = True
for j, (fn, an) in enumerate(files):
progress(t, progress_len, j)
info = tf.gettarinfo(fn, filename + an)
perms = 0666
if info.isdir():
perms = 0777
for i in executable_extensions:
if fn.endswith(i):
perms = 0777
info.mode = perms
info.uid = 1000
info.gid = 1000
info.uname = "renpy"
info.gname = "renpy"
if info.isreg():
tf.addfile(info, file(fn, "rb"))
else:
tf.addfile(info)
tf.close()
def dist_exists(fn):
"""
Returns true if the given file exists in the renpy directory.
"""
return os.path.exists(os.path.join(config.renpy_base, fn))
label distribute:
call lint
@@ -368,173 +155,18 @@ label distribute:
project.save()
base_name = base_name.encode("utf-8")
executable_name = executable_name.encode("utf-8")
ignore_extensions = ignore_extensions.encode("utf-8")
documentation_extensions = documentation_extensions.encode("utf-8")
# Convert some of these to more useful formats.
ignore_extensions = [ i.strip() for i in ignore_extensions.split() ]
documentation_extensions = [ i.strip() for i in documentation_extensions.split() ]
# Scan for the files we want to include in the various distributions.
info(_(u"Scanning..."), "")
# Files included in the various distributions.
multi_files = [ ]
win_files = [ ]
linux_files = [ ]
mac_files = [ ]
# A map from source file name to replacement data to be placed in
# that file.
file_data = { }
######################################################################
# Multi files.
rb = config.renpy_base.replace("\\", "/") + "/"
# Project files.
multi_files.extend(tree(project.path, "/", root=True, exclude_suffix=ignore_extensions))
multi_files.append((rb + "renpy.py", "/" + executable_name + ".py"))
# Renpy files.
multi_files.extend(tree(rb + "common", "/common"))
multi_files.extend(tree(rb + "renpy", "/renpy"))
multi_files.append((rb + "LICENSE.txt", "/renpy/LICENSE.txt"))
def add_script_version(fn, ignore_extensions=ignore_extensions, multi_files=multi_files, rb=rb):
"""
Add a script_version file if it does not already exist, and if the
extension is allowed by the game.
"""
for a, b in multi_files:
if b == "/game/" + fn:
return
for i in ignore_extensions:
if fn.endswith(i):
return
multi_files.append((rb + "launcher/" + fn, "/game/" + fn))
add_script_version("script_version.rpy")
add_script_version("script_version.rpyc")
######################################################################
# Windows files.
if build_windows or build_all:
win_files.append((rb + "renpy.exe", "/" + executable_name + ".exe"))
win_files.append((rb + "renpy.code", "/renpy.code"))
win_files.append((rb + "python25.dll", "/python25.dll"))
win_files.append((rb + "msvcr71.dll", "/msvcr71.dll"))
if os.path.exists(project.path + "/icon.ico"):
file_data[rb + "renpy.exe"] = pefile.change_icons(
rb + "renpy.exe",
project.path + "/icon.ico",
)
######################################################################
# Linux files.
if build_linux or build_all:
linux_files.append((rb + "renpy.sh", "/" + executable_name + ".sh"))
linux_files.append((rb + "lib", "/lib"))
linux_files.append((rb + "lib/python", "/lib/python"))
linux_files.extend(tree(rb + "lib/linux-x86", "/lib/linux-x86"))
# Warning: The tar.bz2 builder doesn't support file_data.
distribute.distribute(
project.path,
config.renpy_base,
base_name=base_name,
executable_name=executable_name,
ignore_extensions=ignore_extensions,
documentation_extensions=documentation_extensions,
build_windows=build_windows,
build_mac=build_mac,
build_linux=build_linux,
build_all=build_all)
######################################################################
# Mac (non-app) files.
if build_mac or build_all:
mac_files = tree(rb + "renpy.app",
"/" + executable_name + ".app")
# Rename executable.
mac_files = [ (fn, an.replace("Ren'Py Launcher", executable_name)) for (fn, an) in mac_files ]
# Plist file.
quoted_name = executable_name.replace("&", "&amp;").replace("<", "&lt;")
info_plist = file(rb + "renpy.app/Contents/Info.plist", "rb").read().replace("Ren'Py Launcher", quoted_name)
file_data[rb + "renpy.app/Contents/Info.plist"] = info_plist
# Launcher script.
quoted_name = executable_name.replace("\"", "\\\"")
launcher_py = file(rb + "renpy.app/Contents/Resources/launcher.py", "rb").read().replace("Ren'Py Launcher", quoted_name)
file_data[rb + "renpy.app/Contents/Resources/launcher.py"] = launcher_py
# Icon file.
if os.path.exists(project.path + "/icon.icns"):
icon_data = file(project.path + "/icon.icns", "rb").read()
file_data[rb + "renpy.app/Contents/Resources/launcher.icns"] = icon_data
######################################################################
# Now, build the various distributions.
if build_windows:
make_zip(
_(u"Building Windows..."),
base_name + "-win32",
multi_files + win_files,
file_data)
if build_linux:
make_tar(
_(u"Building Linux..."),
base_name + "-linux-x86",
multi_files + linux_files)
if build_mac:
# Reorganize the files so all the non application files live inside
# the application. If there's documentation involved, then it
# lives in both places.
macapp_files = [ ]
for fn, an in multi_files + mac_files:
if not an.startswith("/" + executable_name + ".app"):
new_an = "/" + executable_name + ".app/Contents/Resources/autorun" + an
macapp_files.append((fn, new_an))
if an.rindex('/') == 0:
for i in documentation_extensions:
if fn.endswith(i):
macapp_files.append((fn, an))
break
else:
macapp_files.append((fn, an))
make_zip(
_(u"Building Macintosh..."),
base_name + "-mac",
macapp_files,
file_data)
if build_all:
make_zip(
_(u"Building Combined..."),
base_name + "-all",
multi_files + win_files + linux_files + mac_files,
file_data)
# Report success to the user.
set_tooltip(_(u"Thank you for choosing Ren'Py."))
@@ -542,7 +174,7 @@ label distribute:
ui.vbox()
title(_(u"Success"))
text(_(u"The distributions have been built. Be sure to test them before release.\n\nNote that unpacking and repacking the Macintosh, Linux, or Combined distributions on Windows is not supported.\n\nPlease announce your release at the {a=http://lemmasoft.renai.us/forums/}Lemma Soft Forums{/a}, so we can add it to the Ren'Py web site."))
text(_(u"The distributions have been built. Be sure to test them before release.\n\nNote that unpacking and repacking the Macintosh, Linux, or Combined distributions on Windows is not supported.\n\nPlease announce your release at the {a=http://lemmasoft.renai.us/forums/}Lemma Soft Forums{/a}, and add it to {a=http://games.renpy.org}games.renpy.org{/a}."))
ui.null(height=20)
@@ -551,4 +183,3 @@ label distribute:
ui.close()
interact()
+5 -2
View File
@@ -29,9 +29,12 @@ label new_project:
_(u"Please wait while we create the project."))
template = os.path.join(config.renpy_base, "template")
shutil.copytree(template, path)
try:
shutil.copytree(template, path)
except OSError, e:
error(_(u"Could not create the project directory. The error was: %s") % unicode(e))
launcherinfo = os.path.join(path, "launcherinfo.py")
if os.path.exists(launcherinfo):
os.unlink(launcherinfo)
+3872 -302
View File
File diff suppressed because it is too large Load Diff
+6 -1
View File
@@ -4,6 +4,11 @@ init python:
import sys
import platform
import subprocess
# Set the projects directory to None if it no longer exists.
if persistent.projects_directory is not None:
if not os.path.isdir(persistent.projects_directory):
persistent.projects_directory = None
ZWSP = u"\u200B"
@@ -220,7 +225,7 @@ label launch:
set_tooltip(_(u"%s has been launched.") % project.name.capitalize())
store.game_proc = proc
jump top
+2 -1
View File
@@ -26,7 +26,8 @@ label choose_projects_directory:
if path is None:
path = os.path.dirname(config.renpy_base)
path = os.environ.get("RENPY_DEFAULT_PROJECTS_DIRECTORY", path)
if EasyDialogs:
+17 -3
View File
@@ -68,7 +68,7 @@ label top:
title(_(u"Ren'Py"))
ui.grid(2, 3, transpose=True)
ui.grid(2, 4, transpose=True)
button(_(u"Select Project"),
ui.jumps("select_project"),
@@ -78,8 +78,12 @@ label top:
ui.jumps("new_project"),
_(u"Create a new project."))
button(_(u"Ren'Py Games List"),
ui.jumps("renpy_games_list"),
_(u"Visit the Ren'Py games list, at http://games.renpy.org."))
button(_(u"Quit"),
renpy.quit,
ui.jumps("launcher_quit"),
_(u"Causes the launcher to exit."))
button(_(u"Options"),
@@ -99,7 +103,8 @@ label top:
else:
ui.null()
ui.null()
ui.close()
@@ -121,6 +126,15 @@ label documentation:
jump top
label renpy_games_list:
python hide:
import webbrowser
webbrowser.open_new("http://games.renpy.org")
set_tooltip(_(u"Now showing the Ren'Py Games List in your web browser."))
jump top
label launcher_quit:
label confirm_quit:
$ renpy.quit()
+1 -1
View File
@@ -1,3 +1,3 @@
init -999:
$ config.script_version = (6, 10, 2)
$ config.script_version = (6, 11, 0)
+7 -4
View File
@@ -33,14 +33,14 @@ init python:
u"Test",
u"Left",
u"Right",
u"Not Assigned",
u"Up",
u"Down",
u"Not Assigned",
u"Select/Dismiss",
u"Rollback",
u"Hold to Skip",
u"Joystick Mapping",
u"Move the joystick or press a joystick button to create the mapping. Click the mouse to remove the mapping.",
u"Rollback",
u"Hold to Skip",
u"Toggle Skip",
u"Hide Text",
u"Menu",
@@ -177,7 +177,9 @@ init python:
u"Choose Projects Directory",
u"Please choose the directory containing your projects.",
u"Could not run zenity. The projects directory has been set to the directory immediately above the directory containing Ren'Py.",
u"Launches the Ren'Py tutorial game.",
u"Now showing the Ren'Py documentation in your web browser.",
u"Now showing the Ren'Py Games List in your web browser.",
u"Launch",
u"Launches the project.",
u"Edit Script",
@@ -195,12 +197,13 @@ init python:
u"Ren'Py",
u"Select a project to work with.",
u"Create a new project.",
u"Ren'Py Games List",
u"Visit the Ren'Py games list, at http://games.renpy.org.",
u"Causes the launcher to exit.",
u"Options",
u"Change Ren'Py launcher options.",
u"Ren'Py Help",
u"Open the Ren'Py documentation in a web browser.",
u"Tutorial Game",
u"Launches the Ren'Py tutorial game.",
]
File diff suppressed because it is too large Load Diff
+387
View File
@@ -0,0 +1,387 @@
# This file contains bindings to integrate pygame (SDL) and OpenGL.
cdef extern from "pygame/pygame.h":
struct SDL_Surface:
int w
int h
int pitch
void *pixels
SDL_Surface *PySurface_AsSurface(object)
cdef extern from "GL/glew.h":
ctypedef unsigned int GLenum
ctypedef unsigned char GLboolean
ctypedef unsigned int GLbitfield
ctypedef void GLvoid
ctypedef signed char GLbyte
ctypedef short GLshort
ctypedef int GLint
ctypedef unsigned char GLubyte
ctypedef unsigned short GLushort
ctypedef unsigned int GLuint
ctypedef int GLsizei
ctypedef float GLfloat
ctypedef float GLclampf
ctypedef double GLdouble
ctypedef double GLclampd
GLenum GLEW_OK
GLenum glewInit()
GLubyte *glewGetErrorString(GLenum)
int GL_UNPACK_ROW_LENGTH
int GL_PACK_ROW_LENGTH
void glPixelStorei(
GLint pname,
GLint param)
int GL_TEXTURE_2D
int GL_RGBA8
int GL_RGBA
int GL_BGRA
int GL_ALPHA
int GL_UNSIGNED_BYTE
void glTexImage2D(
GLenum target,
GLint level,
GLint internalformat,
GLsizei width,
GLsizei height,
GLint border,
GLenum format,
GLenum type,
void *pixels)
void glTexSubImage2D(
int target,
int level,
int xoffset,
int yoffset,
int width,
int height,
int format,
int type,
void *pixels)
GLenum GL_TEXTURE0_ARB
GLenum GL_TEXTURE1_ARB
GLenum GL_TEXTURE2_ARB
GLenum GL_TRIANGLE_STRIP
void glMultiTexCoord2fARB(GLenum, GLfloat, GLfloat)
void glVertex2f(GLfloat, GLfloat)
void glBegin(GLenum)
void glEnd()
void glActiveTextureARB(GLenum)
void glBindTexture(GLenum, GLuint texture)
GLubyte *glGetString(GLenum)
void glReadPixels(
GLint,
GLint,
GLsizei,
GLsizei,
GLenum,
GLenum,
void *)
def init_glew():
err = glewInit()
if err != GLEW_OK:
raise Exception("Glew init failed: %s" % <char *> glewGetErrorString(err))
def premultiply(
object pysurf,
int x,
int y,
int w,
int h):
"""
Creates a string containing the premultiplied image data for
for the (x, y, w, h) box inside pysurf.
"""
# Adjust the alpha if we have an alpha-free image.
cdef unsigned char alpha_and
cdef unsigned char alpha_or
if pysurf.get_masks()[3]:
alpha_and = 255
alpha_or = 0
else:
alpha_and = 0
alpha_or = 255
# Allocate an uninitialized string.
cdef unsigned char *null = NULL
rv = null[:w*h*4]
# Out is where we put the output.
cdef unsigned char *out = rv
# The pixels in the source image.
cdef unsigned char *pixels = NULL
cdef SDL_Surface *surf
# Pointer to the current pixel.
cdef unsigned char *p
# Pointer to the current output pixel.
cdef unsigned char *op
# Pointer to the row end.
cdef unsigned char *pend
# alpha value.
cdef unsigned int a
surf = PySurface_AsSurface(pysurf)
pixels = <unsigned char *> surf.pixels
pixels += y * surf.pitch
pixels += x * 4
op = out
for y from 0 <= y < h:
p = pixels + y * surf.pitch
pend = p + w * 4
while p < pend:
a = (p[3] & alpha_and) | alpha_or
op[0] = p[0] * a / 255
op[1] = p[1] * a / 255
op[2] = p[2] * a / 255
op[3] = a
p += 4
op += 4
return rv
def load_premultiplied(data, width, height, update):
cdef char *pixels
if data:
pixels = data
else:
pixels = NULL
if update:
glTexSubImage2D(
GL_TEXTURE_2D,
0,
0,
0,
width,
height,
GL_BGRA,
GL_UNSIGNED_BYTE,
pixels)
else:
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RGBA,
width,
height,
0,
GL_BGRA,
GL_UNSIGNED_BYTE,
pixels)
def store_framebuffer(
object pysurf,
):
"""
This loads the supplied pygame surface into the numbered
texture. The created texture will be of size (width, height),
and at position (xoffset, yoffset) relative to the containing
image.
"""
cdef unsigned char *pixels = NULL
cdef SDL_Surface *surf
surf = PySurface_AsSurface(pysurf)
pixels = <unsigned char *> surf.pixels
glPixelStorei(GL_PACK_ROW_LENGTH, surf.pitch / 4)
glReadPixels(
0,
0,
surf.w,
surf.h,
GL_BGRA,
GL_UNSIGNED_BYTE,
pixels)
def draw_rectangle(
float sx,
float sy,
float x,
float y,
float w,
float h,
transform,
tex0, int tex0x, int tex0y,
tex1, int tex1x, int tex1y,
tex2, int tex2x, int tex2y):
"""
This draws a rectangle (textured with up to four textures) to the
screen.
"""
# Do we have the given texture?
cdef int has_tex0, has_tex1, has_tex2
# Texture coordinates.
cdef float t0u0, t0v0, t0u1, t0v1
cdef float t1u0, t1v0, t1u1, t1v1
cdef float t2u0, t2v0, t2u1, t2v1
# Pull apart the transform.
cdef float xdx = transform.xdx
cdef float xdy = transform.xdy
cdef float ydx = transform.ydx
cdef float ydy = transform.ydy
# Transform the vertex coordinates to screen-space.
cdef float x0 = (x + 0) * xdx + (y + 0) * xdy + sx
cdef float y0 = (x + 0) * ydx + (y + 0) * ydy + sy
cdef float x1 = (x + w) * xdx + (y + 0) * xdy + sx
cdef float y1 = (x + w) * ydx + (y + 0) * ydy + sy
cdef float x2 = (x + 0) * xdx + (y + h) * xdy + sx
cdef float y2 = (x + 0) * ydx + (y + h) * ydy + sy
cdef float x3 = (x + w) * xdx + (y + h) * xdy + sx
cdef float y3 = (x + w) * ydx + (y + h) * ydy + sy
# Compute the texture coordinates, and set up the textures.
cdef float xadd, yadd, xmul, ymul
if tex0 is not None:
has_tex0 = 1
glActiveTextureARB(GL_TEXTURE0_ARB)
glBindTexture(GL_TEXTURE_2D, tex0.number)
xadd = tex0.xadd
yadd = tex0.yadd
xmul = tex0.xmul
ymul = tex0.ymul
t0u0 = xadd + xmul * (tex0x + 0)
t0u1 = xadd + xmul * (tex0x + w)
t0v0 = yadd + ymul * (tex0y + 0)
t0v1 = yadd + ymul * (tex0y + h)
else:
has_tex0 = 0
if tex1 is not None:
has_tex1 = 1
glActiveTextureARB(GL_TEXTURE1_ARB)
glBindTexture(GL_TEXTURE_2D, tex1.number)
xadd = tex1.xadd
yadd = tex1.yadd
xmul = tex1.xmul
ymul = tex1.ymul
t1u0 = xadd + xmul * (tex1x + 0)
t1u1 = xadd + xmul * (tex1x + w)
t1v0 = yadd + ymul * (tex1y + 0)
t1v1 = yadd + ymul * (tex1y + h)
else:
has_tex1 = 0
if tex2 is not None:
has_tex2 = 1
glActiveTextureARB(GL_TEXTURE2_ARB)
glBindTexture(GL_TEXTURE_2D, tex2.number)
xadd = tex2.xadd
yadd = tex2.yadd
xmul = tex2.xmul
ymul = tex2.ymul
t2u0 = xadd + xmul * (tex2x + 0)
t2u1 = xadd + xmul * (tex2x + w)
t2v0 = yadd + ymul * (tex2y + 0)
t2v1 = yadd + ymul * (tex2y + h)
else:
has_tex2 = 0
# Now, actually draw the textured rectangle.
glBegin(GL_TRIANGLE_STRIP)
if has_tex0:
glMultiTexCoord2fARB(GL_TEXTURE0_ARB, t0u0, t0v0)
if has_tex1:
glMultiTexCoord2fARB(GL_TEXTURE1_ARB, t1u0, t1v0)
if has_tex2:
glMultiTexCoord2fARB(GL_TEXTURE2_ARB, t2u0, t2v0)
glVertex2f(x0, y0)
if has_tex0:
glMultiTexCoord2fARB(GL_TEXTURE0_ARB, t0u1, t0v0)
if has_tex1:
glMultiTexCoord2fARB(GL_TEXTURE1_ARB, t1u1, t1v0)
if has_tex2:
glMultiTexCoord2fARB(GL_TEXTURE2_ARB, t2u1, t2v0)
glVertex2f(x1, y1)
if has_tex0:
glMultiTexCoord2fARB(GL_TEXTURE0_ARB, t0u0, t0v1)
if has_tex1:
glMultiTexCoord2fARB(GL_TEXTURE1_ARB, t1u0, t1v1)
if has_tex2:
glMultiTexCoord2fARB(GL_TEXTURE2_ARB, t2u0, t2v1)
glVertex2f(x2, y2)
if has_tex0:
glMultiTexCoord2fARB(GL_TEXTURE0_ARB, t0u1, t0v1)
if has_tex1:
glMultiTexCoord2fARB(GL_TEXTURE1_ARB, t1u1, t1v1)
if has_tex2:
glMultiTexCoord2fARB(GL_TEXTURE2_ARB, t2u1, t2v1)
glVertex2f(x3, y3)
glEnd()
def get_string(name):
return <char *> glGetString(name)
+10266
View File
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -785,6 +785,7 @@ static void video_image_display(VideoState *is)
rect.y = is->ytop + y;
rect.w = width;
rect.h = height;
SDL_DisplayYUVOverlay(vp->bmp, &rect);
} else {
#if 0
@@ -1125,7 +1126,7 @@ static void alloc_picture(void *opaque, PyObject *pysurf)
is->video_st->codec->height,
SDL_YV12_OVERLAY,
surf);
vp->width = is->video_st->codec->width;
vp->height = is->video_st->codec->height;
+3515
View File
File diff suppressed because it is too large Load Diff
+275
View File
@@ -0,0 +1,275 @@
TEGL
----
Tegl is Python script for generating OpenGL extenstions. I wrote it
because I was disappointed with some other OpenGL solutions for
Python.
Tegl generates a C extension that can be compiled into module to make
OpenGL available to Python programs. (You're on your own compiling
it, though.)
Unlike PyOpenGL, the C extension is a thin wrapper around OpenGL. It
performs only minor argument checking. Nevertheless, it is mostly
compatible with PyOpenGL, and depending on how the module is
generated, it should only need minor changes to migrate from PyOpenGL.
(In fact, I was able to migrate a recent application simply by adding
a couple wrapper functions that mimicked PyOpenGL semantics.)
This is version 002.
USAGE
-----
To use, simply run maketegl.py. It will generate two files, tegl.c
and teglu.c in the current directory, which you can compile it to
create Python GL and GLU modules. The modules comprise (most of)
OpenGL 1.1.
For more control, open maketegl.py with a text editor. At the top are
some options for controlling the generated code. You can change the
names of the modules, and even combine them into one. You can control
whether the "gl" and "GL_" prefixes appear on the exported symbols.
You can choose to include or exclude various OpenGL extensions, or use
more recent versions of OpenGL. I recommend plain OpenGL 1.1 for
maximum portability, and selected ARB extensions if you need more.
There are some other switches I will cover below.
If you really want fine-tuned control, you can scroll past the options
and comment out any functions and constants you don't want. This may
be a good idea since currently Tegl modules are quite large when
compiled.
USING THE MODULE
----------------
Calling OpenGL functions is simple. Just import the module with "from
tegl import *" (or just "import tegl as gl" if you have built it
without prefixes, or whatever else suits you).
Most OpenGL functions can be called just as in C:
glBegin(GL_COMPILE) or gl.Begin(gl.COMPILE)
glVertex3d(1.0,2.0,3.0) or gl.Vertex3d(1.0,2.0,3.0)
glEnable(GL_CULL_FACE)
glRotated(1.0,90.0,0.0,0.0)
texon = glIsEnabled(GL_TEXTURE_2D)
It's usually pretty straightforward to use OpenGL functions that
accept data through a pointer: you just pass it a list (or tuple, or
numpy array, or any sequence).
glVertex3dv([1.0,2.0,3.0])
glMaterialfv(GL_FRONT,GL_AMBIENT,[0.2,0.2,0.2,1.0])
OpenGL functions that return data through a pointer are somewhat
trickier, you have to pass it an empty sequence that is large enough
to contain the data the function returns. The sequence type has to be
mutable, of course.
retval = [None]*4
glGetMaterialfv(GL_FRONT,GL_AMBIENT,retval)
(This is a departure from how PyOpenGL operates; it will simply create
an array and return it. But Tegl is intended to be a thin wrapper, so
it follows the C usage closely.)
In many cases, it's preferrable to use a buffer object instead of a
Python sequence to pass data to the function; for instance, texture
data. In these cases, you would pass in an object that supports
buffer protocol, such as a string, a numpy array, or an array from the
array module.
imagedata = Image.open(imgfile).tostring()
glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,256,256,0,GL_RGBA,
GL_UNSIGNED_BYTE,imagedata)
To use an OpenGL function that returns image data, you need to pass in
a object that supports writable buffer protocol. The buffer must be
large enough to hold the output of the function, otherwise Bad Things
can happen. Strings are not mutable so you'll have to use some other
type. Arrays from the array module can be your friend here.
retval = array.array("B",[0])*640*480*4
glReadPixels(0,0,640,480,GL_RGBA,GL_UNSIGNED_BYTE,retval)
The question is, how do you know whether you should pass a buffer type
or a sequence type to OpenGL? (Currently, you can only pass one or
the other; this may change in a future version.) Here is the general
rule of thumb:
You need to use a buffer if:
* The type of the argument in C is GLvoid* (or just void*)
* OR the size of the data is theoretically unbounded.
You need to use a sequence if:
* The type if te argument is not GLvoid*
* AND the size of the data is fixed or bounded.
So glMaterialfv takes a sequence argument because it has a type
(GLfloat*) and has a size of 4 at most (it's bounded). On the other
hand, glTexImage2D uses a buffer argument because the type of the data
is GLvoid*, and the image can be arbitrarily large.
This rule of thumb does not always hold, however. I decided to go
against it where it seemed useful.
Several functions for modifying textures (glGenTextures,
glDeleteTextures, glPrioritizeTextures, and glAreTexturesResident)
accept arrays of unbounded size, but I felt that sequence types were
far more useful here, so I defined a constant (MAX_TEXTURE_ARRAY_SIZE)
that lets the user specify a bound on the size. (Otherwise I would
have had to muck around with malloc, and I did not want to do that.)
Functions for creating and destroying buffer object, occlusion
queries, and shader programs (ARB only) are treated likewise.
glCallList accepts buffer objects. Even though the size of the call
list is unbounded, it seemed as if a sequence would be more
appropriate. However, a common use case of glCallList (in conjunction
with glListBase) is to pass it a string, where each character is the
name of a display list that draws that character. Thus I left is as a
buffer.
If I chose wrongly for your application, I apologize. Numpy arrays
and arrays from the array module implement both the sequence and
buffer protocols; these may be of assistence to you. (Be careful
about numpy strides, though.)
If worse comes to worst, you can change the definition inside the
maketegl.py script to suit you.
ADVANCED: THE GIL
-----------------
It's possible that if you send a lot of data to the OpenGL pipeline
quickly enough, the OpenGL pipeline could fill up, an an OpenGL call
in progress would block until the pipeline clears up. This is
possible with functions like glCallList, which runs a display list
that could be enormous.
In threaded programs, the time spent waiting for an OpenGL block could
be used for other tasks. In Python, only a single thread can run
Python code at a given time (a thread has to have the GIL, global
interpreter lock, to run Python code). However, extensions may
release the GIL while not manipulating Python objects (which is the
case during an OpenGL call).
Therefore, there is an option in Tegl for releasing the GIL around
certain OpenGL calls, thus allowing other Python code to run if it
should happen to block. Simply add the name of the function (without
the "gl") to the set of functions to release the GIL for at the top of
maketegl.py.
UNSUPPORTED FUNCTIONS
---------------------
There are a few OpenGL functions that aren't supported by Tegl simply
because they have an unusual signature that the machinery doesn't
easily support. In this early release, I didn't bother. Here's the
list:
glGetString
glGetPointerv
glMultiDrawArrays(ARB)
glMultiDrawElements(ARB)
glGetBufferPointerv(ARB)
glGetVertexAttribPointerv(ARB)
glShaderSource(ARB)
All glu* functions that implement nurbs, tesselators, and quadrics.
Additionally, a couple functions are supported with limited
functionality:
glMapBuffer(ARB) returns a CObject. This is not too useful from
Python; however, you can get at it from a C extension. Also, ctypes
and numpy wizards should be able to map a numpy array to the pointer
location.
glShaderSource(ARB) is handcoded, and only supports passing it a
single string. (You must still pass a singleton sequence of strings;
this is to preserve upward compatibility.) For instance, you'd call
it like this:
glShaderSourceARB(shaderobj,1,[source],[len(source)])
IMPROVEMENTS
------------
The two main improvements I have in mind (aside from fixing up bugs
and adding stuff) are these:
* To take advantage of the parallelism of OpenGL to make the tegl
module a lot smaller. Many OpenGL function have the same signature
(same argument and return types) and I can save a lot of code by
generating one function with that signature, and calling it with a
function pointer (and maybe a size index or two).
* To support sequences and buffers for the same argument at the same
time. This isn't as straightforward as it looks, though, since for
objects that support both protocols, the results could be different
depending on whether it's treated as a buffer or a sequence. I have
to figure out what the most reasonable behavior is.
BUGS
----
Yes.
CHANGES FROM 001
----------------
Added #define GL_EXT_PROTOTYPES. Since Tegl depends on the C compiler
having prototypes available for typecasting arguments, this is pretty
important.
Added handcoded version of glShaderSource(ARB) that only accepts a
single string in the source.
Fixed specification of gluUnProject4.
LICENCE AND COPYRIGHT
---------------------
maketegl.py and maketegl.txt are copyrighted by Carl Banks.
These files, which comprise the tegl package, are released under a BSD
style license. See the file copying for details.
WHY NOT PYOPENGL
----------------
The standard OpenGL package in Python, PyOpenGL, has some limitations
(mostly speedwise) that made it undesirable for me.
Probably the biggest bottleneck is that PyOpenGL calls glGetError
after every call. I understand the rationale for this, but its cost
is too high for my needs. Another problem is, as far as I know, it
does not allow the user to release the GIL around some GL calls.
Thirdly, PyOpenGL 3 is based on ctypes. There's nothing wrong with
ctypes, but for a usage where speed really does matter, it's much too
slow. PyOpenGL 2 is a C extension, and is much faster than PyOpenGL
3, but doesn't support recent OpenGL extensions.
A minor thing I didn't like was that PyOpenGL didn't get rid of the gl
prefixes. I prefer namespaces, and would prefer to simply import a gl
module and call functions this way: "gl.End()". But PyOpenGL did not
support that; I had to write wrappers to pull the symbols apart.
But the most irritating thing about PyOpenGL is the setuptools entry
points, which mean that you cannot simply import the OpenGL modules;
you have to go through setuptools. This, among other things, makes
distributing programs using PyOpenGL (such as with py2exe) a pain.
+64 -22
View File
@@ -4,6 +4,7 @@ import os
import os.path
import platform
import sys
import subprocess
try:
import bdist_mpkg
@@ -105,7 +106,26 @@ def add_library(name, optional=False):
for i in checked:
print "-", i
sys.exit(-1)
def cython(fn):
"""
Use cython to generate `fn`.c from `fn`.pyx, if necessary.
"""
c = fn + ".c"
pyx = fn + ".pyx"
if not os.path.exists(pyx):
print pyx, "not in current directory, not running cython."
return
if os.path.exists(c) and os.path.getmtime(c) >= os.path.getmtime(pyx):
print pyx, "is not newer than", c
return
subprocess.call(["cython", pyx])
add_include("", "zlib.h")
add_include("", "png.h")
add_include("SDL", "SDL.h")
@@ -115,6 +135,7 @@ add_include("", "libavutil/avstring.h")
add_include("", "libavformat/avformat.h")
add_include("", "libavcodec/avcodec.h")
add_include("", "libswscale/swscale.h")
add_include("", "GL/glew.h")
add_library("libSDL")
add_library("libpng")
@@ -126,6 +147,16 @@ add_library("libfreetype")
add_library("libfribidi")
add_library("libz")
has_libglew = add_library("libGLEW", True)
has_libglew32 = add_library("libglew32", True)
cython("_renpy")
cython("_renpybidi")
cython("_renpy_pysdlgl")
cython("sound")
cython("winmixer")
extra_link_args = [ ]
sdl_libraries = [ 'SDL' ]
@@ -154,7 +185,7 @@ except:
extensions = [ ]
py_modules = [ 'pysdlsound.__init__' ]
rpe = distutils.core.Extension(
extensions.append(distutils.core.Extension(
"_renpy",
[ "IMG_savepng.c", "core.c", "rwobject.c", "_renpy.c", "subpixel.c" ],
include_dirs=include_dirs,
@@ -162,11 +193,9 @@ rpe = distutils.core.Extension(
extra_compile_args=extra_compile_args,
extra_link_args=extra_link_args,
libraries=sdl_libraries + png_libraries,
)
))
extensions.append(rpe)
renpy_font = distutils.core.Extension(
extensions.append(distutils.core.Extension(
"_renpy_font",
[ "renpy_ttf.c", "renpy_font.c"],
include_dirs=include_dirs,
@@ -174,11 +203,9 @@ renpy_font = distutils.core.Extension(
extra_compile_args=extra_compile_args,
extra_link_args=extra_link_args,
libraries=sdl_libraries + [ 'freetype', 'z' ],
)
))
extensions.append(renpy_font)
psse = distutils.core.Extension(
extensions.append(distutils.core.Extension(
"pysdlsound.sound",
[ "pss.c", "rwobject.c", "sound.c", "ffdecode.c" ],
include_dirs=include_dirs,
@@ -186,37 +213,52 @@ psse = distutils.core.Extension(
extra_compile_args=extra_compile_args,
extra_link_args=extra_link_args,
libraries=sound_libraries + sdl_libraries,
)
))
extensions.append(psse)
if winmixer:
wme = distutils.core.Extension(
extensions.append(distutils.core.Extension(
"pysdlsound.winmixer",
[ 'winmixer.c' ],
libraries=['winmm'],
)
extensions.append(wme)
))
if linmixer:
py_modules.append('pysdlsound.linmixer')
renpybidi = distutils.core.Extension(
extensions.append(distutils.core.Extension(
"_renpybidi",
["_renpybidi.c", "renpybidicore.c"],
include_dirs=include_dirs,
library_dirs=library_dirs,
libraries=['fribidi'],
)
))
extensions.append(renpybidi)
if has_libglew:
glew_libs = [ 'GLEW' ]
else:
glew_libs = [ 'glew32', "opengl32" ]
extensions.append(distutils.core.Extension(
"_renpy_tegl",
["_renpy_tegl.c"],
extra_compile_args=extra_compile_args,
include_dirs=include_dirs,
library_dirs=library_dirs,
libraries=glew_libs))
extensions.append(distutils.core.Extension(
"_renpy_pysdlgl",
["_renpy_pysdlgl.c"],
extra_compile_args=extra_compile_args,
include_dirs=include_dirs,
library_dirs=library_dirs,
libraries=glew_libs))
distutils.core.setup(
name = "renpy_module",
version = "6.10.1",
version = "6.11.0",
ext_modules = extensions,
py_modules = py_modules,
package_dir = { '' : 'lib' },
-1
View File
@@ -1 +0,0 @@
dist/msvcr71.dll
+1
View File
@@ -0,0 +1 @@
dist/msvcr90.dll
+1
View File
@@ -0,0 +1 @@
dist/python26.dll
+9
View File
@@ -86,6 +86,15 @@ def path_to_renpy_base():
macos_version = (6, 10, 1)
linux_version = (6, 10, 1)
# Doing the version check this way also doubles as an import of ast,
# which helps py2exe et al.
try:
import ast; ast
except:
raise
print "Ren'Py requires at least python 2.6."
sys.exit(0)
if __name__ == "__main__":
if not 'RENPY_NO_VERSION_CHECK' in os.environ:
+15 -3
View File
@@ -27,17 +27,17 @@
# ***** ***** ***** ***** ***** ***** **** ***** ***** ***** *****
# Be sure to change script_version in launcher/script_version.rpy, too!
# Also check to see if we have to update renpy.py.
version = "Ren'Py 6.10.2a"
version = "Ren'Py 6.11.0d"
script_version = 5003000
savegame_suffix = "-LT1.save"
def import_all():
import renpy.game
# Should probably be early, as we will add it as a base to serialized things.
import renpy.object
import renpy.game
# Adds in the Ren'Py loader.
import renpy.loader
@@ -61,6 +61,7 @@ def import_all():
import renpy.display.scale # Must be before module.
import renpy.display.module
import renpy.display.render # Most display stuff depends on this.
import renpy.display.core # object
import renpy.display.font
import renpy.display.text # core, font
@@ -76,8 +77,16 @@ def import_all():
import renpy.display.particle
import renpy.display.joystick
import renpy.display.minigame
import renpy.display.screen
import renpy.display.error
import renpy.display.swdraw
import renpy.display.glshader
import renpy.display.glenviron
import renpy.display.gltexture
import renpy.display.gldraw
# Note: For windows to work, renpy.audio.audio needs to be after
# renpy.display.module.
import renpy.audio.audio
@@ -85,6 +94,7 @@ def import_all():
import renpy.audio.sound
import renpy.ui
import renpy.screenlang
import renpy.lint
import renpy.warp
@@ -127,5 +137,7 @@ def reload_all():
import gc
gc.collect()
renpy.display.draw = None
import_all()
+52 -32
View File
@@ -82,7 +82,7 @@ class PyExpr(unicode):
__slots__ = [
'filename',
'linenumber'
'linenumber',
]
def __new__(cls, s, filename, linenumber):
@@ -104,17 +104,21 @@ class PyCode(object):
'bytecode',
]
# All PyCodes known to the system.
extent = [ ]
def __getstate__(self):
return (1, self.source, self.location, self.mode)
def __setstate__(self, state):
(_, self.source, self.location, self.mode) = state
self.bytecode = None
if renpy.game.script.record_pycode:
renpy.game.script.all_pycode.append(self)
def __init__(self, source, loc=('<none>', 1), mode='exec'):
if isinstance(source, PyExpr):
loc = (source.filename, source.linenumber, source)
# The source code.
self.source = source
@@ -126,6 +130,9 @@ class PyCode(object):
# This will be initialized later on, after we are serialized.
self.bytecode = None
if renpy.game.script.record_pycode:
renpy.game.script.all_pycode.append(self)
def chain_block(block, next):
"""
This is called to chain together all of the nodes in a block. Node
@@ -252,14 +259,6 @@ class Node(object):
else:
return [ ]
def get_pycode(self):
"""
Returns a list of PyCode objects associated with this Node,
or None if no objects are associated with it.
"""
return [ ]
def scry(self):
"""
Called to return an object with some general, user-definable information
@@ -373,7 +372,20 @@ class Say(Node):
def scry(self):
rv = Node.scry(self)
rv.interacts = True # W0201
if self.who is not None:
if self.who_fast:
who = getattr(renpy.store, self.who)
else:
who = renpy.python.py_eval(self.who)
else:
who = None
if self.interact:
renpy.exports.scry_say(who, rv)
else:
rv.interacts = False
return rv
# Copy the descriptor.
@@ -548,9 +560,6 @@ class Python(Node):
self.hide = hide
self.code = PyCode(python_code, loc=loc, mode='exec')
def get_pycode(self):
return [ self.code ]
def diff_info(self):
return (Python, self.code.source)
@@ -583,9 +592,6 @@ class EarlyPython(Node):
self.hide = hide
self.code = PyCode(python_code, loc=loc, mode='exec')
def get_pycode(self):
return [ self.code ]
def diff_info(self):
return (EarlyPython, self.code.source)
@@ -625,12 +631,6 @@ class Image(Node):
def diff_info(self):
return (Image, tuple(self.imgname))
def get_pycode(self):
if self.code:
return [ self.code ]
else:
return [ ]
def execute(self):
# Note: We should always check that self.code is None before
@@ -1381,12 +1381,6 @@ class Define(Node):
def diff_info(self):
return (Define, tuple(self.varname))
def get_pycode(self):
if self.code:
return [ self.code ]
else:
return [ ]
def execute(self):
value = renpy.python.py_eval_bytecode(self.code.bytecode)
@@ -1394,3 +1388,29 @@ class Define(Node):
setattr(renpy.store, self.varname, value)
return self.next
class Screen(Node):
__slots__ = [
'screen',
]
def __init__(self, loc, screen):
"""
@param name: The name of the image being defined.
@param expr: An expression yielding a Displayable that is
assigned to the image.
"""
super(Screen, self).__init__(loc)
self.screen = screen
def diff_info(self):
return (Screen, self.screen.name)
def execute(self):
self.screen.define()
return self.next
+21 -5
View File
@@ -69,6 +69,7 @@ PROPERTIES = {
"xalign" : float,
"yalign" : float,
"rotate" : float,
"rotate_pad" : bool,
"xzoom" : float,
"yzoom" : float,
"zoom" : float,
@@ -83,15 +84,22 @@ PROPERTIES = {
"corner2" : (float, float),
"subpixel" : bool,
"delay" : float,
"xoffset" : int,
"yoffset" : int,
"offset" : (int, int),
}
def correct_type(v, b, ty):
"""
Corrects the type of v to match ty. b is used to inform the match.
"""
if ty is position:
return type(b)(v)
if v is None:
return None
else:
return type(b)(v)
else:
return ty(v)
@@ -220,6 +228,11 @@ class ATLTransformBase(renpy.object.Object):
requires that t.atl is self.atl.
"""
super(ATLTransformBase, self).take_execution_state(t)
if t.atl is not self.atl:
return
self.done = t.done
self.block = t.block
self.atl_state = t.atl_state
@@ -325,6 +338,9 @@ class ATLTransformBase(renpy.object.Object):
# Hide request.
if trans.hide_request:
self.transform_event = "hide"
if trans.replaced_request:
self.transform_event = "replaced"
# Notice transform events.
if self.transform_event != self.last_transform_event:
@@ -1153,9 +1169,10 @@ class On(Statement):
if action == "continue":
# If it comes from a hide block, indicate that.
if name == "hide":
if name == "hide" or name == "replaced":
trans.hide_response = False
trans.replaced_response = False
return "continue", (name, start, arg), pause
# If we get a next, then try going to the default
@@ -1224,6 +1241,7 @@ class RawFunction(RawStatement):
compiling(self.loc)
return Function(self.loc, ctx.eval(self.expr))
class Function(Statement):
def __init__(self, loc, function):
@@ -1238,8 +1256,6 @@ class Function(Statement):
return "continue", None, fr
else:
return "next", 0, None
# This parses an ATL block.
+65 -13
View File
@@ -186,7 +186,7 @@ class Channel(object):
This stores information about the currently-playing music.
"""
def __init__(self, name, default_loop, stop_on_mute, tight):
def __init__(self, name, default_loop, stop_on_mute, tight, file_prefix, file_suffix):
# The name assigned to this channel. This is used to look up
# information about the channel in the MusicContext object.
@@ -250,6 +250,9 @@ class Channel(object):
# on queue clear.
self.keep_queue = 0
# A prefix and suffix that are used to create the full filenames.
self.file_prefix = file_prefix
self.file_suffix = file_suffix
if default_loop is None:
# By default, should we loop the music?
@@ -354,7 +357,7 @@ class Channel(object):
# Blacklist of old file formats we used to support, but we now
# ignore.
lfn = topq.filename.lower()
lfn = topq.filename.lower() + self.file_suffix.lower()
for i in (".mod", ".xm", ".mid", ".midi"):
if lfn.endswith(i):
topq = None
@@ -363,7 +366,7 @@ class Channel(object):
continue
try:
topf = load(topq.filename)
topf = load(self.file_prefix + topq.filename + self.file_suffix)
if depth == 0:
pss.play(self.number, topf, topq.filename, paused=self.synchro_start, fadein=topq.fadein, tight=topq.tight)
@@ -457,7 +460,6 @@ class Channel(object):
else:
pss.fadeout(self.number, int(secs * 1000))
def enqueue(self, filenames, loop=True, synchro_start=False, fadein=0, tight=None):
for filename in filenames:
@@ -493,6 +495,7 @@ class Channel(object):
return pss.playing_name(self.number)
def set_volume(self, volume):
self.chan_volume = volume
@@ -528,14 +531,51 @@ all_channels = [ ]
channels = { }
def register_channel(name, mixer=None, loop=None, stop_on_mute=True, tight=False):
def register_channel(name, mixer=None, loop=None, stop_on_mute=True, tight=False, file_prefix="", file_suffix=""):
"""
:doc: other
This registers a new audio channel named `name`. Audio can then be
played on the channel by supplying the channel name to the play or
queue statements.
`mixer`
The name of the mixer the channel uses. By default, Ren'Py
knows about the "music", "sfx", and "voice" mixers. Using
other names is possible, but may require changing the
preferences screens.
`loop`
If true, sounds on this channel loop by default.
`stop_on_mute`
If true, music on the channel is stopped when the channel is muted.
`tight`
If true, sounds will loop even when fadeout is occuring. This should
be set to True for a sound effects or seamless music channel, and False
if the music fades out on its own.
`file_prefix`
A prefix that is prepended to the filenames of the sound files being
played on this channel.
`file_suffix`
A suffix that is appended to the filenames of the sound files being
played on this channel.
"""
if not renpy.game.init_phase:
raise Exception("Can't register channel outside of init phase.")
c = Channel(name, loop, stop_on_mute, tight)
c = Channel(name, loop, stop_on_mute, tight, file_prefix, file_suffix)
c.mixer = mixer
all_channels.append(c)
channels[name] = c
def alias_channel(name, newname):
if not renpy.game.init_phase:
@@ -543,6 +583,7 @@ def alias_channel(name, newname):
c = get_channel(name)
channels[newname] = c
def get_channel(name):
@@ -672,7 +713,7 @@ def periodic():
anything_playing = False
for c in channels:
for c in all_channels:
vol = c.chan_volume * volumes[c.mixer]
max_volume = max(max_volume, vol)
@@ -759,6 +800,16 @@ def interact():
periodic()
def rollback():
"""
On rollback, we want to stop all the channels with non-empty sounds.
"""
for c in all_channels:
if not c.loop:
c.fadeout(0)
ALLOC_EVENT = pygame.USEREVENT
REFRESH_EVENT = pygame.USEREVENT + 1
@@ -773,21 +824,22 @@ def event(ev):
if not pcm_ok:
return False
if ev.type == ALLOC_EVENT:
if renpy.display.video.fullscreen or not renpy.display.video.surface:
surf = pygame.display.get_surface()
if renpy.display.video.fullscreen and renpy.display.draw.fullscreen_surface:
surf = renpy.display.draw.fullscreen_surface
else:
surf = renpy.display.video.surface
pss.alloc_event(renpy.display.scale.real(surf))
pss.alloc_event(surf)
return True
if ev.type == REFRESH_EVENT:
elif ev.type == REFRESH_EVENT:
if renpy.audio.music.get_playing("movie"):
pss.refresh_event()
renpy.game.interface.force_redraw = True
# Return False, as a Movie should get this to know when to
# redraw itself.
return False
-2
View File
@@ -37,8 +37,6 @@ def play(filename, channel="sound", fadeout=0, fadein=0, tight=False, loop=False
fadein=fadein,
tight=tight,
loop=loop)
def queue(filename, channel="sound", clear_queue=True, fadein=0, tight=False, loop=False):
renpy.audio.music.queue(filename,
+66 -58
View File
@@ -58,6 +58,10 @@ def extra_imports():
import ctypes
import ctypes.wintypes; ctypes.wintypes
import EasyDialogs; EasyDialogs
import argparse; argparse
import compiler; compiler
import textwrap; textwrap
import copy; copy
trace_file = None
trace_local = None
@@ -84,18 +88,9 @@ def mac_start(fn):
os.system("open " + fn)
# This code fixes a bug in subprocess.Popen.__del__
def popen_del(self, _deadstate=sys.maxint):
if not self._child_created:
return
self.poll(_deadstate=_deadstate)
def popen_del(self, *args, **kwargs):
return
try:
import subprocess # W0403
if self.returncode is None and subprocess._active is not None: # E1101
subprocess._active.append(self) # E1101
except:
pass
def bootstrap(renpy_base):
global renpy # W0602
@@ -229,10 +224,6 @@ def bootstrap(renpy_base):
import renpy.display.presplash # W0404
renpy.display.presplash.start(gamedir)
# Fix an exception thrown by garbage collection.
import subprocess # W0403
subprocess.Popen.__del__ = popen_del # E1101
# If we're on a mac, install our own os.start.
if sys.platform == "darwin":
os.startfile = mac_start
@@ -248,55 +239,72 @@ def bootstrap(renpy_base):
keep_running = True
report_error = None
while keep_running:
try:
renpy.game.options = options
try:
while keep_running:
try:
renpy.game.options = options
renpy.config.renpy_base = renpy_base
renpy.config.basedir = basedir
renpy.config.gamedir = gamedir
renpy.config.args = options.args
renpy.main.main()
keep_running = False
renpy.config.renpy_base = renpy_base
renpy.config.basedir = basedir
renpy.config.gamedir = gamedir
renpy.config.args = options.args
except KeyboardInterrupt:
import traceback
traceback.print_exc()
break
except renpy.game.UtterRestartException:
# Only works after a full restart.
report_error = renpy.display.error.ReportError()
# On an UtterRestart, reload Ren'Py.
renpy.reload_all()
continue
except renpy.game.ParseErrorException:
if report_error and report_error.report('a parse error'):
renpy.reload_all()
keep_running = True
else:
renpy.main.main()
keep_running = False
except KeyboardInterrupt:
import traceback
traceback.print_exc()
break
except renpy.game.UtterRestartException:
if renpy.display.draw:
renpy.display.draw.deinit()
# Only works after a full restart.
report_error = renpy.display.error.ReportError()
# On an UtterRestart, reload Ren'Py.
renpy.reload_all()
continue
except renpy.game.ParseErrorException:
if report_error and report_error.report('a parse error'):
renpy.reload_all()
keep_running = True
else:
keep_running = False
except Exception, e:
report_exception(e)
if report_error and report_error.report('an exception'):
renpy.reload_all()
keep_running = True
else:
keep_running = False
sys.exit(0)
finally:
except Exception, e:
report_exception(e)
if "RENPY_SHUTDOWN_TRACE" in os.environ:
enable_trace(int(os.environ["RENPY_SHUTDOWN_TRACE"]))
if report_error and report_error.report('an exception'):
renpy.reload_all()
keep_running = True
else:
keep_running = False
if options.leak:
memory_profile()
renpy.display.im.cache.quit()
renpy.display.im.cache.quit()
sys.exit(0)
if renpy.display.draw:
renpy.display.draw.quit()
# Prevent subprocess from throwing errors while trying to run it's
# __del__ method during shutdown.
import subprocess # W0403
subprocess.Popen.__del__ = popen_del # E1101
if options.leak:
memory_profile()
def report_tb(out, tb):
+190 -69
View File
@@ -22,6 +22,79 @@
# The Character object (and friends).
import renpy
import re
# This matches the dialogue-relevant text tags.
TAG_RE = re.compile(r'(\{\{)|(\{(p|w|nw|fast)(?:\=([^}]*))?\})', re.S)
class DialogueTextTags(object):
"""
This object parses the text tags that only make sense in dialogue,
like {fast}, {p}, {w}, and {nw}.
"""
def __init__(self, s):
# The text that we've accumulated, not including any tags.
self.text = ""
# The index in the produced string where each pause starts.
self.pause_start = [ 0 ]
# The index in the produced string where each pause ends.
self.pause_end = [ ]
# The time to delay for each pause. None to delay forever.
self.pause_delay = [ ]
# True if we've encountered the no-wait tag.
self.no_wait = False
i = iter(TAG_RE.split(s))
while True:
try:
self.text += i.next()
quoted = i.next()
full_tag = i.next()
tag = i.next()
value = i.next()
if value is not None:
value = float(value)
if quoted is not None:
self.text += quoted
continue
if tag == "p" or tag == "w":
self.pause_start.append(len(self.text))
self.pause_end.append(len(self.text))
self.pause_delay.append(value)
elif tag == "nw":
self.no_wait = True
elif tag == "fast":
self.pause_start = [ len(self.text) ]
self.pause_end = [ ]
self.pause_delay = [ ]
self.no_wait = False
self.text += full_tag
except StopIteration:
break
self.pause_end.append(len(self.text))
if self.no_wait:
self.pause_delay.append(0)
else:
self.pause_delay.append(None)
def predict_show_display_say(who, what, who_args, what_args, window_args, image=False, two_window=False, side_image=None, **kwargs):
"""
@@ -57,6 +130,7 @@ def show_display_say(who, what, who_args={}, what_args={}, window_args={},
say_vbox_properties={},
transform=None,
variant=None,
screen=None,
**kwargs):
"""
This is called (by default) by renpy.display_say to add the
@@ -144,6 +218,33 @@ def show_display_say(who, what, who_args={}, what_args={}, window_args={},
what_args = style_args(what_args)
window_args = style_args(window_args)
if screen and renpy.display.screen.has_screen(screen):
widget_properties = {
"window" : window_args,
"what" : what_args,
"who" : who_args,
}
tag = screen
index = 0
while renpy.exports.showing(tag):
index += 1
tag = "%s%d" % (screen, index)
renpy.display.screen.show_screen(
screen,
_widget_properties=widget_properties,
_transient = True,
_tag = tag,
who=who,
what=what)
renpy.exports.shown_window()
return renpy.display.screen.get_widget(screen, "what")
# Apply the transform.
if transform:
renpy.ui.at(transform)
@@ -182,46 +283,57 @@ def show_display_say(who, what, who_args={}, what_args={}, window_args={},
class SlowDone(object):
def __init__(self, ctc, ctc_position, callback, interact, type, cb_args):
delay = None
def __init__(self, ctc, ctc_position, callback, interact, type, cb_args, delay):
self.ctc = ctc
self.ctc_position = ctc_position
self.callback = callback
self.interact = interact
self.type = type
self.cb_args = cb_args
self.delay = delay
def __call__(self):
if self.ctc and self.ctc_position == "fixed":
renpy.ui.add(self.ctc)
renpy.display.screen.show_screen("_ctc", _transient=True, ctc=self.ctc)
renpy.exports.restart_interaction()
if self.delay is not None:
renpy.ui.pausebehavior(self.delay, True)
renpy.exports.restart_interaction()
for c in self.callback:
c("slow_done", interact=self.interact, type=self.type, **self.cb_args)
# This function takes care of repeatably showing the screen as part of
# an interaction.
def display_say(show_function,
interact,
slow,
afm,
ctc,
ctc_pause,
ctc_position,
all_at_once,
cb_args,
with_none,
callback,
type,
checkpoint=True,
ctc_timedpause=None):
def display_say(
who,
what,
show_function,
interact,
slow,
afm,
ctc,
ctc_pause,
ctc_position,
all_at_once,
cb_args,
with_none,
callback,
type,
checkpoint=True,
ctc_timedpause=None,
ctc_force=False):
# If we're in fast skipping mode, don't bother with say
# statements at all.
if interact and renpy.config.skipping == "fast":
# Clears out transients.
renpy.exports.with_statement(None)
return
@@ -237,7 +349,6 @@ def display_say(show_function,
callback = [ callback ]
callback = renpy.config.all_character_callbacks + callback
# Call the begin callback.
for c in callback:
@@ -259,78 +370,84 @@ def display_say(show_function,
renpy.game.context().seen_current(True))):
slow = False
# Figure out which pause we're on. (Or set the pause to None in
# order to put us in all-at-once mode.)
if not interact:
all_at_once = True
dtt = DialogueTextTags(what)
if all_at_once:
pause = None
pause_start = [ 0 ]
pause_end = [ len(dtt.text) ]
pause_delay = [ dtt.pause_delay[-1] ]
else:
pause = 0
pause_start = dtt.pause_start
pause_end = dtt.pause_end
pause_delay = dtt.pause_delay
# True if the {nw} tag was found in what_text.
no_wait = False
keep_interacting = True
slow_start = 0
while keep_interacting:
for i, (start, end, delay) in enumerate(zip(pause_start, pause_end, pause_delay)):
last_pause = (i == len(pause_start) - 1)
# If we're going to do an interaction, then saybehavior needs
# to be here.
if interact:
behavior = renpy.ui.saybehavior(allow_dismiss=renpy.config.say_allow_dismiss)
behavior = renpy.ui.saybehavior(allow_dismiss=renpy.config.say_allow_dismiss)
else:
behavior = None
# Run the show callback.
for c in callback:
c("show", interact=interact, type=type, **cb_args)
what_text = show_function()
# Show the text.
what_text = show_function(who, dtt.text)
if not isinstance(what_text, renpy.display.text.Text):
raise Exception("The say screen (or show_function) must return a Text object.")
# Update the properties of the what_text widget.
if pause is not None and pause < what_text.pauses:
if what_text.pause_lengths[pause] is not None:
if last_pause:
what_ctc = ctc
else:
if delay is not None:
what_ctc = ctc_timedpause or ctc_pause
else:
what_ctc = ctc_pause
else:
what_ctc = ctc
if not (interact or ctc_force):
what_ctc = None
what_ctc = renpy.easy.displayable_or_none(what_ctc)
if what_ctc is not None:
what_ctc = what_ctc.parameterize(('ctc',), ())
if delay == 0:
what_ctc = None
# This object is called when the slow text is done.
slow_done = SlowDone(what_ctc, ctc_position, callback, interact, type, cb_args)
slow_done = SlowDone(what_ctc, ctc_position, callback, interact, type, cb_args, delay)
what_text.slow = slow
what_text.slow_param = slow
what_text.slow_done = slow_done
what_text.slow_start = slow_start
what_text.pause = pause
what_text.slow_start = start
what_text.slow_end = end
if what_ctc and ctc_position == "nestled":
what_text.tokens.append([ ("widget", what_ctc) ])
what_text.set_ctc(what_ctc)
# Now, re-run update on what_text.
what_text.update(retokenize=False)
keep_interacting = what_text.keep_pausing
no_wait |= what_text.no_wait
if no_wait:
slow_done.ctc = None
for c in callback:
c("show_done", interact=interact, type=type, **cb_args)
if behavior and afm:
behavior.set_afm_length(what_text.get_simple_length() - slow_start) # E1103
behavior.set_afm_length(end - start)
if interact:
if interact:
rv = renpy.ui.interact(mouse='say', type=type, roll_forward=roll_forward)
# This is only the case if the user has rolled forward, {nw} happens, or
@@ -338,18 +455,14 @@ def display_say(show_function,
if rv is False:
break
slow_start = what_text.get_laidout_length()
if keep_interacting:
pause += 1
for i in renpy.config.say_sustain_callbacks:
i()
if not last_pause:
for i in renpy.config.say_sustain_callbacks:
i()
# Do the checkpoint and with None.
if interact:
if not no_wait:
if not dtt.no_wait:
if checkpoint:
renpy.exports.checkpoint(True)
else:
@@ -427,8 +540,8 @@ class ADVCharacter(object):
self.condition = v('condition')
self.dynamic = v('dynamic')
self.screen = v('screen')
self.display_args = dict(
interact = d('interact'),
slow = d('slow'),
@@ -489,13 +602,11 @@ class ADVCharacter(object):
def copy(self, name=NotSet, **properties):
return type(self)(name, kind=self, **properties)
# This is called before the interaction.
def do_add(self, who, what):
return
# A curried version of this is called to cause the interaction to
# occur.
# This is what shows the screen for a given interaction.
def do_show(self, who, what):
return self.show_function(
who,
@@ -503,6 +614,7 @@ class ADVCharacter(object):
who_args=self.who_args,
what_args=self.what_args,
window_args=self.window_args,
screen=self.screen,
**self.show_args)
# This is called after the last interaction is done.
@@ -515,8 +627,10 @@ class ADVCharacter(object):
return
# This is called to actually do the displaying.
def do_display(self, who, what, **display_args):
display_say(lambda : self.do_show(who, what),
def do_display(self, who, what, **display_args):
display_say(who,
what,
self.do_show,
**display_args)
@@ -568,8 +682,7 @@ class ADVCharacter(object):
renpy.exports.log(who)
renpy.exports.log(what)
renpy.exports.log("")
def predict(self, what):
if self.dynamic:
@@ -578,14 +691,22 @@ class ADVCharacter(object):
who = self.name
return self.do_predict(who, what)
def will_interact(self):
if not (self.condition is None or renpy.python.py_eval(self.condition)):
return False
return self.display_args['interact']
def Character(name=NotSet, kind=None, **properties):
if kind is None:
kind = renpy.store.adv
return type(kind)(name, kind=kind, **properties)
def DynamicCharacter(name_expr, **properties):
return Character(name_expr, dynamic=True, **properties)
+19 -1
View File
@@ -1,3 +1,4 @@
# Copyright 2004-2010 PyTom <pytom@bishoujo.us>
#
# Permission is hereby granted, free of charge, to any person
@@ -131,7 +132,7 @@ fade_music = 0.0
sticky_positions = False
# A list of all of the layers that we know about.
layers = [ 'master', 'transient', 'overlay' ]
layers = [ 'master', 'transient', 'screens', 'overlay' ]
# A list of layers that should be cleared when we replace
# transients.
@@ -141,6 +142,10 @@ transient_layers = [ 'transient' ]
# overlays.
overlay_layers = [ 'overlay' ]
# A list of layers that should be cleared whe we enter a
# new context.
context_clear_layers = [ 'screens' ]
# A list of layers that are displayed atop all other layers, and do
# not participate in transitions.
top_layers = [ ]
@@ -408,6 +413,19 @@ thumbnail_height = None
# The end game transition.
end_game_transition = None
# The default transform.
default_transform = None
# Should we use the child position?
transform_uses_child_position = True
# The action to use when it's time to quit.
quit_action = None
# If not None, a rectangle giving the area of the screen to crop the
# screenshots to.
screenshot_crop = None
# Various directories.
gamedir = None
basedir = None
+7 -1
View File
@@ -19,4 +19,10 @@
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# This file intentionally left blank.
# The draw object through which all drawing is routed. This object
# contains all of the distinction between the software and GL
# renderers.
draw = None
# The interface object.
interface = None
+282 -48
View File
@@ -168,7 +168,7 @@ class Keymap(renpy.display.layout.Null):
k_constant from pygame.constants, or the unicode for the key.
"""
def __init__(self, **keymap):
def __init__(self, replaces=None, **keymap):
super(Keymap, self).__init__(style='default')
self.keymap = keymap
@@ -189,8 +189,8 @@ class RollForward(renpy.display.layout.Null):
This behavior implements rollforward.
"""
def __init__(self, value):
super(RollForward, self).__init__(style='default')
def __init__(self, value, **properties):
super(RollForward, self).__init__(**properties)
self.value = value
@@ -208,19 +208,26 @@ class PauseBehavior(renpy.display.layout.Null):
return a value after a certain amount of time has elapsed.
"""
def __init__(self, delay, result=False):
super(PauseBehavior, self).__init__()
def __init__(self, delay, result=False, **properties):
super(PauseBehavior, self).__init__(**properties)
self.delay = delay
self.result = result
def event(self, ev, x, y, st):
if self.delay is not None and st >= self.delay:
return self.result
if st >= self.delay:
renpy.game.interface.timeout(self.delay - st)
# If we have been drawn since the timeout, simply return
# true. Otherwise, force a redraw, and return true when
# it comes back.
if renpy.game.interface.drawn_since(st - self.delay):
return self.result
else:
renpy.game.interface.force_redraw = True
renpy.game.interface.timeout(max(self.delay - st, 0))
class SoundStopBehavior(renpy.display.layout.Null):
"""
@@ -229,8 +236,8 @@ class SoundStopBehavior(renpy.display.layout.Null):
on the named channel.
"""
def __init__(self, channel, result=False):
super(SoundStopBehavior, self).__init__()
def __init__(self, channel, result=False, **properties):
super(SoundStopBehavior, self).__init__(**properties)
self.channel = channel
self.result = result
@@ -270,7 +277,7 @@ class SayBehavior(renpy.display.layout.Null):
self.allow_dismiss = allow_dismiss
def set_afm_length(self, afm_length):
self.afm_length = afm_length
self.afm_length = max(afm_length, 1)
def event(self, ev, x, y, st):
@@ -301,6 +308,11 @@ class SayBehavior(renpy.display.layout.Null):
renpy.exports.restart_interaction()
raise renpy.display.core.IgnoreEvent()
if renpy.game.preferences.using_afm_enable and renpy.game.preferences.afm_enable:
renpy.game.preferences.afm_enable = False
renpy.exports.restart_interaction()
raise renpy.display.core.IgnoreEvent()
if self.allow_dismiss:
if not self.allow_dismiss():
raise renpy.display.core.IgnoreEvent()
@@ -326,18 +338,105 @@ class SayBehavior(renpy.display.layout.Null):
return None
##############################################################################
# Button support.
def run(var, *args, **kwargs):
"""
Runs a variable. This is done by calling all the functions, and
iterating over the lists and tuples.
"""
if var is None:
return None
if isinstance(var, (list, tuple)):
rv = None
for i in var:
new_rv = i(*args)
if new_rv is not None:
rv = new_rv
return rv
return var(*args)
def run_periodic(var, st):
if isinstance(var, (list, tuple)):
rv = None
for i in var:
v = run_periodic(i, st)
if rv is None or v < rv:
rv = v
return rv
if isinstance(var, renpy.ui.Action):
return var.periodic(st)
def is_selected(clicked):
if isinstance(clicked, (list, tuple)):
return any(is_selected(i) for i in clicked)
elif isinstance(clicked, renpy.ui.Action):
return clicked.get_selected()
else:
return False
def is_sensitive(clicked):
if isinstance(clicked, (list, tuple)):
return all(is_sensitive(i) for i in clicked)
elif isinstance(clicked, renpy.ui.Action):
return clicked.get_sensitive()
else:
return True
##############################################################################
# Button
class Button(renpy.display.layout.Window):
keymap = { }
action = None
def __init__(self, child, style='button', clicked=None,
hovered=None, unhovered=None, role='',
def __init__(self, child=None, style='button', clicked=None,
hovered=None, unhovered=None, action=None, role=None,
time_policy=None, keymap={},
**properties):
super(Button, self).__init__(child, style=style, **properties)
if isinstance(clicked, renpy.ui.Action):
action = clicked
if action is not None:
clicked = action
if not is_sensitive(action):
clicked = None
if role is None:
if action:
if is_selected(action):
role = 'selected_'
else:
role = ''
else:
role = ''
self.action = action
self.activated = False
self.clicked = clicked
self.hovered = hovered
@@ -347,7 +446,7 @@ class Button(renpy.display.layout.Window):
self.keymap = keymap
self.time_policy_data = None
def render(self, width, height, st, at):
@@ -396,9 +495,9 @@ class Button(renpy.display.layout.Window):
return None
rv = None
if self.hovered and not default:
rv = self.hovered()
if not default:
rv = run(self.hovered)
self.set_transform_event(self.role + "hover")
self.child.set_transform_event(self.role + "hover")
@@ -412,8 +511,7 @@ class Button(renpy.display.layout.Window):
if self.activated:
return None
if self.unhovered:
self.unhovered()
run(self.unhovered)
self.set_transform_event(self.role + "idle")
self.child.set_transform_event(self.role + "idle")
@@ -422,11 +520,19 @@ class Button(renpy.display.layout.Window):
def per_interact(self):
if not self.clicked:
self.set_style_prefix(self.role + "insensitive_", True)
else:
self.set_style_prefix(self.role + "idle_", True)
super(Button, self).per_interact()
def event(self, ev, x, y, st):
# Call self.action.periodic()
timeout = run_periodic(self.action, st)
if timeout is not None:
renpy.game.interface.timeout(timeout)
# If we have a child, try passing the event to it.
rv = super(Button, self).event(ev, x, y, st)
if rv is not None:
@@ -439,10 +545,7 @@ class Button(renpy.display.layout.Window):
# Check the keymap.
for name, action in self.keymap.iteritems():
if map_event(ev, name):
rv = action()
if rv is not None:
return rv
return run(action)
# Ignore as appropriate:
if map_event(ev, "button_ignore") and self.clicked:
@@ -457,7 +560,7 @@ class Button(renpy.display.layout.Window):
if self.style.sound:
renpy.audio.music.play(self.style.sound, channel="sound")
rv = self.clicked()
rv = run(self.clicked)
if rv is not None:
return rv
@@ -509,17 +612,20 @@ class Input(renpy.display.text.Text):
prefix = ""
suffix = ""
def __init__(self, default, length=None,
style='input_text',
def __init__(self,
default="",
length=None,
style='input',
allow=None,
exclude=None,
prefix="",
suffix="",
changed=None,
button=None,
replaces=None,
**properties):
super(Input, self).__init__("", style=style, **properties)
super(Input, self).__init__("", style=style, replaces=replaces, **properties)
self.content = unicode(default)
self.length = length
@@ -544,9 +650,14 @@ class Input(renpy.display.text.Text):
self.editable = False
button.hovered = HoveredProxy(self.enable, button.hovered)
button.unhovered = HoveredProxy(self.disable, button.unhovered)
if isinstance(replaces, Input):
self.content = replaces.content
self.editable = replaces.editable
self.update_text(self.content, self.editable)
def update_text(self, content, editable):
if content != self.content or editable != self.editable:
@@ -614,16 +725,80 @@ adj_registered = { }
# This class contains information about an adjustment that can change the
# position of content.
class Adjustment(renpy.object.Object):
"""
:doc: ui
:name: ui.adjustment class
Adjustment objects represent a value that can be adjusted by a bar
or viewport. They contain information about the value, the range
of the value, and how to adjust the value in small steps and large
pages.
"""
def __init__(self, range=1, value=0, step=None, page=0, changed=None, adjustable=None, ranged=None):
"""
The following parameters correspond to fields or properties on
the adjustment object:
`range`
The range of the adjustment, a number.
`value`
The value of the adjustment, a number.
`step`
The step size of the adjustment, a number. If None, then
defaults to 1/10th of a page, if set. Otherwise, defaults
to the 1/20th of the range.
This is used when scrolling a viewport with the mouse wheel.
`page`
The page size of the adjustment. If None, this is set
automatically by a viewport. If never set, defaults to 1/10th
of the range.
It's can be used when clicking on a scrollbar.
The following parameters control the behavior of the adjustment.
`adjustable`
If True, this adjustment can be changed by a bar. If False,
it can't.
It defaults to being adjustable if a `changed` function
is given or if the adjustment is associated with a viewport,
and not adjustable otherwise.
`changed`
This function is called with the new value when the value of
the adjustment changes.
`ranged`
This function is called with the adjustment object when
the range of the adjustment is set by a viewport.
.. method:: change(value)
Changes the value of the adjustment to `value`, updating
any bars and viewports that use the adjustment.
"""
def __init__(self, range=1, value=0, step=None, page=0, changed=None, adjustable=True, ranged=None):
super(Adjustment, self).__init__()
if adjustable is None:
if changed:
adjustable = True
self._value = value
self._range = range
self._page = page
self._step = step
self.changed = changed
self.adjustable = changed or adjustable
self.adjustable = adjustable
self.ranged = ranged
def get_value(self):
@@ -698,8 +873,8 @@ class Bar(renpy.display.core.Displayable):
to clicks on that value.
"""
__version__ = 1
__version__ = 2
def after_upgrade(self, version):
if version < 1:
@@ -708,7 +883,10 @@ class Bar(renpy.display.core.Displayable):
del self.range # E1101
del self.value # E1101
del self.changed # E1101
if version < 2:
self.value = None
def __init__(self,
range=None,
value=None,
@@ -719,12 +897,37 @@ class Bar(renpy.display.core.Displayable):
step=None,
page=None,
bar=None,
style='bar',
style=None,
vertical=False,
replaces=None,
**properties):
if adjustment is None:
adjustment = Adjustment(range, value, step=step, page=page, changed=changed, adjustable=False)
self.value = None
if adjustment is None:
if isinstance(value, renpy.ui.BarValue):
if isinstance(replaces, Bar):
value.replaces(replaces.value)
self.value = value
adjustment = value.get_adjustment()
renpy.game.interface.timeout(0)
else:
adjustment = Adjustment(range, value, step=step, page=page, changed=changed)
if style is None:
if self.value is not None:
if vertical:
style = self.value.get_style()[1]
else:
style = self.value.get_style()[0]
else:
if vertical:
style = 'vbar'
else:
style = 'bar'
if width is not None:
properties['xmaximum'] = width
@@ -734,8 +937,8 @@ class Bar(renpy.display.core.Displayable):
super(Bar, self).__init__(style=style, **properties)
self.adjustment = adjustment
self.focusable = adjustment.adjustable
self.focusable = True
# These are set when we are first rendered.
self.thumb_dim = 0
self.height = 0
@@ -746,14 +949,21 @@ class Bar(renpy.display.core.Displayable):
return [ self.style.fore_bar, self.style.aft_bar, self.style.thumb, self.style.thumb_shadow ]
def per_interact(self):
self.focusable = self.adjustment.adjustable
self.adjustment.register(self)
def render(self, width, height, st, at):
# Handle redrawing.
if self.value is not None:
redraw = self.value.periodic(st)
if redraw is not None:
renpy.display.render.redraw(self, redraw)
# Store the width and height for the event function to use.
self.width = width
self.height = height
range = self.adjustment.range
value = self.adjustment.value
page = self.adjustment.page
@@ -954,8 +1164,8 @@ class Conditional(renpy.display.layout.Container):
way, as that would break rollback.
"""
def __init__(self, condition, *args):
super(Conditional, self).__init__(*args)
def __init__(self, condition, *args, **properties):
super(Conditional, self).__init__(*args, **properties)
self.condition = condition
self.null = renpy.display.layout.Null()
@@ -983,21 +1193,45 @@ class Conditional(renpy.display.layout.Container):
class Timer(renpy.display.layout.Null):
def __init__(self, delay, function, repeat=False, args=(), kwargs={}):
super(Timer, self).__init__()
started = False
def __init__(self, delay, action=None, repeat=False, args=(), kwargs={}, replaces=None, **properties):
super(Timer, self).__init__(**properties)
if action is None:
raise Exception("A timer must have an action supplied.")
if delay <= 0:
raise Exception("A timer's delay must be > 0.")
# The delay.
self.delay = delay
self.function = function
# Should we repeat the event?
self.repeat = repeat
self.next_event = delay
# The time the next event should occur.
self.next_event = None
# The function and its arguments.
self.function = action
self.args = args
self.kwargs = kwargs
# Did we start the timer?
self.started = False
if replaces is not None:
self.started = replaces.started
self.next_event = replaces.next_event
def event(self, ev, x, y, st):
if not self.started:
self.started = True
self.next_event = st + self.delay
if self.next_event is None:
return
+648 -621
View File
File diff suppressed because it is too large Load Diff
+19 -14
View File
@@ -34,30 +34,24 @@ class ReportError(object):
# In the init method, Ren'Py is functioning reasonably normally.
def __init__(self):
self.font = renpy.display.text.get_font(renpy.store.style.default.font, 14, False, False, False)
self.flags = pygame.display.get_surface().get_flags()
self.size = pygame.display.get_surface().get_size()
# self.flags = pygame.display.get_surface().get_flags()
# self.size = pygame.display.get_surface().get_size()
self.size = (renpy.config.screen_width, renpy.config.screen_height)
# In the report method, Ren'Py may be in an ill-defined state.
def report(self, error_type):
import os.path
import pygame # W0404
pygame.display.init()
pygame.display.init()
pygame.display.set_caption("Ren'Py Error - left-click reloads, right-click quits")
msg = "Ren'Py has experienced " + error_type + ".\n"
msg += "Left-click or space reloads, right-click or escape exits."
screen = pygame.display.set_mode(self.size, self.flags, 32)
screen.fill((0, 0, 0, 255))
screen = pygame.display.set_mode(self.size, 0, 32)
y = 2
for l in msg.split('\n'):
surf = self.font.render(l, True, (255, 255, 255, 255), (0, 0, 0, 255))
screen.blit(surf, (2, y))
y += self.font.get_linesize()
pygame.display.flip() # E1120
pygame.time.set_timer(pygame.USEREVENT + 1, 50)
while True:
@@ -65,6 +59,17 @@ class ReportError(object):
if commandfile and os.path.exists(commandfile):
return True
screen.fill((0, 0, 0, 255))
y = 2
for l in msg.split('\n'):
surf = self.font.render(l, True, (255, 255, 255, 255), (0, 0, 0, 255))
screen.blit(surf, (2, y))
y += self.font.get_linesize()
pygame.display.flip() # E1120
ev = pygame.event.wait()
if ev.type == pygame.MOUSEBUTTONUP:
+1 -2
View File
@@ -162,13 +162,12 @@ def before_interact(roots):
else:
set_focused(None, None)
# Finally, mark the current widget as the focused widget, and
# all other widgets as unfocused.
for f, n in fwn:
if f is not current:
f.unfocus()
if current:
current.focus(default=True)
+840
View File
@@ -0,0 +1,840 @@
# Copyright 2004-2010 PyTom <pytom@bishoujo.us>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import renpy
from renpy.display.render import IDENTITY, DISSOLVE, IMAGEDISSOLVE, PIXELLATE
import pygame
import os
import os.path
import weakref
import array
import time
try:
import _renpy_tegl as gl; gl
import _renpy_pysdlgl as pysdlgl; pysdlgl
except ImportError:
gl = None
pysdlgl = None
import gltexture
import glenviron
class GLDraw(object):
def __init__(self):
# Did we do the first-time init?
self.did_init = False
# The GL environment to use.
self.environ = None
# The GL render-to-texture to use.
self.rtt = None
# The screen.
self.window = None
# The OpenGL logfile.
try:
self.log_file = file(os.path.join(renpy.config.renpy_base, "opengl.txt"), "w")
except:
try:
self.log_file = file(os.path.join(renpy.config.savedir, "opengl.txt"), "w")
except:
self.log_file = None
# The virtual size of the screen, as requested by the game.
self.virtual_size = None
# The physical size of the window we got.
self.physical_size = None
# Is the mouse currently visible?
self.mouse_old_visible = None
# The (x, y) and texture of the software mouse.
self.mouse_info = (0, 0, None)
# This is used to cache the surface->texture operation.
self.texture_cache = weakref.WeakKeyDictionary()
# The time of the last redraw.
self.last_redraw_time = 0
# Info.
self.info = { "renderer" : "gl" }
# Old value of fullscreen.
self.old_fullscreen = None
# We don't use a fullscreen surface.
self.fullscreen_surface = None
def log(self, msg, *args):
"""
Logs a message to the logfile.
"""
if self.log_file is not None:
self.log_file.write(msg % args)
self.log_file.write("\n")
self.log_file.flush()
def set_mode(self, virtual_size, physical_size, fullscreen):
"""
This changes the video mode. It also initializes OpenGL, if it
can. It returns True if it was succesful, or False if OpenGL isn't
working for some reason.
"""
# If GL can't be loaded, give up.
if not gl:
return False
if self.did_init:
self.deinit()
if fullscreen != self.old_fullscreen:
pygame.display.quit()
pygame.display.init()
renpy.display.interface.post_init()
self.old_fullscreen = fullscreen
self.log("")
self.log(renpy.version)
self.virtual_size = virtual_size
vwidth, vheight = virtual_size
pwidth, pheight = physical_size
# Ensure we're always at least 256x256, so we have a shot at rendering
# textures.
pwidth = max(pwidth, 256)
pheight = max(pheight, 256)
# Handle swap control.
vsync = os.environ.get("RENPY_GL_VSYNC", "1")
pygame.display.gl_set_attribute(pygame.GL_SWAP_CONTROL, int(vsync))
pygame.display.gl_set_attribute(pygame.GL_ALPHA_SIZE, 8)
try:
if fullscreen:
self.log("fullscreen mode.")
self.window = pygame.display.set_mode((0, 0), pygame.FULLSCREEN | pygame.OPENGL | pygame.DOUBLEBUF)
else:
self.log("windowed mode.")
self.window = pygame.display.set_mode((pwidth, pheight), pygame.RESIZABLE | pygame.OPENGL | pygame.DOUBLEBUF)
except pygame.error, e:
self.log("Could not get pygame screen: %r", e)
return False
pwidth, pheight = self.window.get_size()
self.physical_size = (pwidth, pheight)
self.log("Screen sizes: virtual=%r physical=%r" % (self.virtual_size, self.physical_size))
pwidth = max(1, pwidth)
pheight = max(1, pheight)
# Figure out the virtual box, which includes padding around
# the borders.
physical_ar = 1.0 * pwidth / pheight
virtual_ar = 1.0 * vwidth / vheight
if physical_ar >= virtual_ar:
x_padding = physical_ar * vheight - vwidth
y_padding = 0
else:
x_padding = 0
y_padding = ( 1.0 / physical_ar ) * vwidth - vheight
self.virtual_box = (
-x_padding / 2.0,
-y_padding / 2.0,
vwidth + x_padding / 2.0,
vheight + y_padding / 2.0)
# Set some default settings.
gl.Enable(gl.BLEND)
gl.BlendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)
gl.Enable(gl.CLIP_PLANE0)
gl.Enable(gl.CLIP_PLANE1)
gl.Enable(gl.CLIP_PLANE2)
gl.Enable(gl.CLIP_PLANE3)
if not self.did_init:
if not self.init():
return False
self.did_init = True
self.environ.init()
self.rtt.init()
# Prepare a mouse call.
self.mouse_old_visible = None
return True
def deinit(self):
"""
De-initializes the system in preparation for a restart, or
quit. Flushes out all the textures while it's at it.
"""
# This should get rid of all of the cached textures.
renpy.display.render.free_memory()
self.texture_cache.clear()
gltexture.dealloc_textures()
if self.rtt:
self.rtt.deinit()
if self.environ:
self.environ.deinit()
def quit(self):
self.log("Deallocating textures.")
gltexture.dealloc_textures()
self.log("Done deallocating textures.")
self.log("About to quit GL.")
pygame.display.quit()
self.log("Finished quit GL.")
def init(self):
"""
This does the first-time initialization of OpenGL, deciding
which subsystems to use.
"""
# Init glew.
pysdlgl.init_glew()
renderer = pysdlgl.get_string(gl.RENDERER)
# Log the GL version.
self.log("Vendor: %r", pysdlgl.get_string(gl.VENDOR))
self.log("Renderer: %r", renderer)
self.log("Version: %r", pysdlgl.get_string(gl.VERSION))
self.log("Video Info: %s", pygame.display.Info())
extensions = set(pysdlgl.get_string(gl.EXTENSIONS).split(" "))
self.log("Extensions:")
for i in sorted(extensions):
self.log(" %s", i)
if renderer == "Mesa GLX Indirect":
self.log("Blacklisted renderer.")
return False
def use_subsystem(envvar, envval, *req_ext):
"""
Decides if we should used a particular subsystem, based on
environment variables and/or extensions. If the `envvar`
environment variable exists, this will return true iff
its value is `envval`. Otherwise, this will return true if
all of the required extensions are present, and false
otherwise.
"""
value = os.environ.get(envvar, "")
if value:
if value == envval:
return True
else:
return False
for i in req_ext:
if i not in extensions:
return False
return True
v = [ 0 ]
gl.GetIntegerv(gl.MAX_TEXTURE_UNITS_ARB, v)
self.log("Number of texture units: %d", v[0])
if v[0] < 4:
self.log("Not enough texture units.")
return False
# Pick a texture environment subsystem.
if use_subsystem(
"RENPY_GL_ENVIRON",
"shader",
"GL_ARB_vertex_shader",
"GL_ARB_fragment_shader"):
self.log("Using shader environment.")
self.environ = glenviron.ShaderEnviron()
self.info["environ"] = "shader"
elif use_subsystem(
"RENPY_GL_ENVIRON",
"fixed",
"GL_ARB_texture_env_crossbar",
"GL_ARB_texture_env_combine"):
self.log("Using fixed-function environment (clause 1).")
self.environ = glenviron.FixedFunctionEnviron()
self.info["environ"] = "fixed"
elif use_subsystem(
"RENPY_GL_ENVIRON",
"fixed",
"GL_NV_texture_env_combine4"):
self.log("Using fixed-function environment (clause 2).")
self.environ = glenviron.FixedFunctionEnviron()
self.info["environ"] = "fixed"
else:
self.log("Can't find a workable environment.")
return False
# Pick a Render-to-texture subsystem.
if use_subsystem(
"RENPY_GL_RTT",
"fbo",
"GL_EXT_framebuffer_object",
"RENPY_nonexistent_extension"):
self.log("Using framebuffer_object RTT.")
self.rtt = glenviron.FramebufferRtt()
self.info["rtt"] = "fbo"
else:
self.log("Using copy RTT.")
self.rtt = glenviron.CopyRtt()
self.info["rtt"] = "copy"
# Check for ctrl held down at startup - revert to software
# rendering if that's the case.
if pygame.key.get_mods() & pygame.KMOD_CTRL:
self.log("Giving up on OpenGL, because CTRL is held down.")
return False
# Do additional setup needed.
renpy.display.pgrender.set_bgra_masks()
return True
def should_redraw(self, needs_redraw, first_pass):
"""
Redraw whenever the screen needs it, but at least once every
.2 seconds. We rely on VSYNC to slow down our maximum
draw speed.
"""
rv = False
if needs_redraw:
rv = True
elif first_pass:
rv = True
elif time.time() > self.last_redraw_time + .20:
rv = True
else:
# Redraw if the mouse moves.
mx, my, tex = self.mouse_info
if tex and (mx, my) != pygame.mouse.get_pos():
rv = True
# Log the redraw time.
if rv:
self.last_redraw_time = time.time()
return True
else:
return False
def mutated_surface(self, surf):
if surf in self.texture_cache:
del self.texture_cache[surf]
def load_texture(self, surf, transient=False):
# Turn a surface into a texture grid.
rv = self.texture_cache.get(surf, None)
if rv is None:
rv = gltexture.texture_grid_from_surface(surf)
self.texture_cache[surf] = rv
return rv
# private
def undefine_clip(self):
"""
This makes the clipping undefined. It needs to be called when the
various matrices change, to ensure that the next call to set_clip
will re-set-up the clipping. Note that it does not remove the
clipping, but rather merely causes set_clip to change it.
"""
self.clip_cache = None
# private
def set_clip(self, clip):
if self.clip_cache == clip:
return
self.clip_cache = clip
minx, miny, maxx, maxy = clip
# OpenGL clipping works by only allowing coordinates where:
# a*x + b*y + c*z + d >= 0.
gl.ClipPlane(gl.CLIP_PLANE0, [1.0, 0.0, 0.0, -minx])
gl.ClipPlane(gl.CLIP_PLANE1, [0.0, 1.0, 0.0, -miny])
gl.ClipPlane(gl.CLIP_PLANE2, [-1.0, 0.0, 0.0, maxx])
gl.ClipPlane(gl.CLIP_PLANE3, [0.0, -1.0, 0.0, maxy])
def draw_screen(self, surftree, fullscreen_video):
"""
Draws the screen.
"""
forward = reverse = IDENTITY
surftree.is_opaque()
self.draw_render_textures(surftree, forward, reverse)
gl.Viewport(0, 0, self.physical_size[0], self.physical_size[1])
gl.MatrixMode(gl.PROJECTION)
gl.LoadIdentity()
gl.Ortho(self.virtual_box[0], self.virtual_box[2], self.virtual_box[3], self.virtual_box[1], -1.0, 1.0)
gl.MatrixMode(gl.MODELVIEW)
gl.ClearColor(0.0, 0.0, 0.0, 0.0)
gl.Clear(gl.COLOR_BUFFER_BIT)
clip = (0, 0, self.virtual_size[0], self.virtual_size[1])
self.undefine_clip()
if renpy.audio.music.get_playing("movie") and renpy.display.video.fullscreen:
tex = renpy.display.video.get_movie_texture(self.virtual_size)
# self.load_texture(self.fullscreen_surface, transient=True)
self.draw_transformed(tex, clip, 0, 0, 1.0, forward, reverse)
else:
self.draw_transformed(surftree, clip, 0, 0, 1.0, forward, reverse)
self.draw_mouse()
# Release the CPU while we're waiting for things to actually
# draw to the screen.
renpy.display.core.cpu_idle.set()
pygame.display.flip()
renpy.display.core.cpu_idle.clear()
def draw_render_textures(self, what, forward, reverse):
"""
This is responsible for rendering things to textures,
as necessary.
"""
if not isinstance(what, renpy.display.render.Render):
return
render_what = False
if what.clipping:
if forward.xdy != 0 or forward.ydx != 0:
render_what = True
forward = reverse = IDENTITY
for child, cxo, cyo, focus, main in what.visible_children:
if what.forward:
child_forward = forward * what.forward
child_reverse = what.reverse * reverse
else:
child_forward = forward
child_reverse = reverse
self.draw_render_textures(child, child_forward, child_reverse)
if what.operation == DISSOLVE or what.operation == IMAGEDISSOLVE:
child.render_to_texture(what.operation_alpha)
if what.operation == PIXELLATE:
p = what.operation_parameter
pc = child
while p > 1:
p /= 2
pc = self.get_half(pc)
if render_what:
what.render_to_texture(True)
def draw_transformed(self, what, clip, xo, yo, alpha, forward, reverse):
# If our alpha has hit 0, don't do anything.
if alpha <= 0.003: # (1 / 256)
return
if isinstance(what, gltexture.TextureGrid):
self.set_clip(clip)
gltexture.blit(
what,
xo,
yo,
reverse,
alpha,
self.environ)
return
if not isinstance(what, renpy.display.render.Render):
raise Exception("Unknown drawing type. " + repr(what))
if isinstance(what, renpy.display.pgrender.Surface):
tex = self.load_texture(what)
self.draw_transformed(tex, clip, xo, yo, alpha, forward, reverse)
return
# Other draw modes.
if what.operation == DISSOLVE:
self.set_clip(clip)
gltexture.blend(
what.children[0][0].render_to_texture(what.operation_alpha),
what.children[1][0].render_to_texture(what.operation_alpha),
xo,
yo,
reverse,
alpha,
what.operation_complete,
self.environ)
return
elif what.operation == IMAGEDISSOLVE:
self.set_clip(clip)
gltexture.imageblend(
what.children[0][0].render_to_texture(what.operation_alpha),
what.children[1][0].render_to_texture(what.operation_alpha),
what.children[2][0].render_to_texture(what.operation_alpha),
xo,
yo,
reverse,
alpha,
what.operation_complete,
what.operation_parameter,
self.environ)
return
if what.operation == PIXELLATE:
self.set_clip(clip)
p = what.operation_parameter
pc = what.children[0][0]
while p > 1:
p /= 2
pc = self.get_half(pc)
reverse *= renpy.display.render.Matrix2D(1.0 * what.width / pc.width, 0, 0, 1.0 * what.height / pc.height)
gltexture.blit(
pc,
xo,
yo,
reverse,
alpha,
self.environ,
nearest=True)
return
# Compute clipping.
if what.clipping:
# Non-aligned clipping uses RTT.
if forward.ydx != 0 or forward.xdy != 0:
tex = what.render_to_texture(True)
self.draw_transformed(tex, clip, xo, yo, alpha, forward, reverse)
return
minx, miny, maxx, maxy = clip
# Figure out the transformed width and height of this
# surface.
tw, th = reverse.transform(what.width, what.height)
minx = max(minx, min(xo, xo + tw))
maxx = min(maxx, max(xo, xo + tw))
miny = max(miny, min(yo, yo + th))
maxy = min(maxy, max(yo, yo + th))
clip = (minx, miny, maxx, maxy)
for child, cxo, cyo, focus, main in what.visible_children:
cxo, cyo = reverse.transform(cxo, cyo)
if what.forward:
child_forward = forward * what.forward
child_reverse = what.reverse * reverse
else:
child_forward = forward
child_reverse = reverse
self.draw_transformed(child, clip, xo + cxo, yo + cyo, alpha * what.alpha, child_forward, child_reverse)
def render_to_texture(self, what, alpha):
forward = reverse = IDENTITY
def draw_func():
if alpha:
gl.ClearColor(0.0, 0.0, 0.0, 0.0)
else:
gl.ClearColor(0.0, 0.0, 0.0, 1.0)
gl.Clear(gl.COLOR_BUFFER_BIT)
self.undefine_clip()
clip = (0, 0, what.width, what.height)
self.draw_transformed(what, clip, 0, 0, 1.0, forward, reverse)
what.is_opaque()
rv = gltexture.texture_grid_from_drawing(what.width, what.height, draw_func, self.rtt)
return rv
def is_pixel_opaque(self, what, x, y):
"""
Returns true if the pixel is not 100% transparent.
"""
if x < 0 or y < 0 or x >= what.width or y >= what.height:
return 0
what = what.subsurface((x, y, 1, 1))
forward = reverse = IDENTITY
gl.Viewport(0, 0, 1, 1)
gl.ClearColor(0.0, 0.0, 0.0, 0.0)
gl.Clear(gl.COLOR_BUFFER_BIT)
gl.MatrixMode(gl.PROJECTION)
gl.LoadIdentity()
gl.Ortho(0, 1, 0, 1, -1, 1)
gl.MatrixMode(gl.MODELVIEW)
self.undefine_clip()
clip = (0, 0, 1, 1)
self.draw_transformed(what, clip, 0, 0, 1.0, forward, reverse)
a = array.array('b', (0,))
gl.ReadPixels(0, 0, 1, 1, gl.ALPHA, gl.BYTE, a)
what.kill()
return a[0]
def get_half(self, what):
"""
Gets a texture grid that's half the size of what..
"""
if what.half_cache:
return what.half_cache
reverse = renpy.display.render.Matrix2D(0.5, 0, 0, .5)
forward = renpy.display.render.Matrix2D(2.0, 0, 0, 2.0)
width = max(what.width / 2, 1)
height = max(what.height / 2, 1)
def draw_func():
gl.ClearColor(0.0, 0.0, 0.0, 1.0)
gl.Clear(gl.COLOR_BUFFER_BIT)
self.undefine_clip()
clip = (0, 0, width, height)
self.draw_transformed(what, clip, 0, 0, 1.0, forward, reverse)
if isinstance(what, renpy.display.render.Render):
what.is_opaque()
rv = gltexture.texture_grid_from_drawing(width, height, draw_func, self.rtt)
what.half_cache = rv
return rv
def update_mouse(self):
# The draw routine updates the mouse. There's no need to
# redraw it event-by-event.
return
def translate_mouse(self, x, y):
# Screen sizes.
pw, ph = self.physical_size
vw, vh = self.virtual_size
vx0, vy0, vx1, vy1 = self.virtual_box
# Translate to fractional screen.
x = 1.0 * x / pw
y = 1.0 * y / ph
# Translate to virtual size.
x = vx0 + (vx1 - vx0) * x
y = vy0 + (vy1 - vy0) * y
x = int(x)
y = int(y)
x = max(0, x)
x = min(vw, x)
y = max(0, y)
y = min(vh, y)
return x, y
def mouse_event(self, ev):
x, y = getattr(ev, 'pos', pygame.mouse.get_pos())
return self.translate_mouse(x, y)
def get_mouse_pos(self):
x, y = pygame.mouse.get_pos()
return self.translate_mouse(x, y)
# Private.
def draw_mouse(self):
hardware, mx, my, tex = renpy.game.interface.get_mouse_info()
self.mouse_info = (mx, my, tex)
if self.mouse_old_visible != hardware:
pygame.mouse.set_visible(hardware)
self.mouse_old_visible = hardware
if not tex:
return
x, y = pygame.mouse.get_pos()
x -= mx
y -= my
pw, ph = self.physical_size
gl.MatrixMode(gl.PROJECTION)
gl.LoadIdentity()
gl.Ortho(0, pw, ph, 0, -1.0, 1.0)
gl.MatrixMode(gl.MODELVIEW)
self.undefine_clip()
self.set_clip((0, 0, pw, ph))
gltexture.blit(
tex,
x,
y,
IDENTITY,
1.0,
self.environ)
def screenshot(self):
rv = renpy.display.pgrender.surface_unscaled(self.physical_size, False)
pysdlgl.store_framebuffer(rv)
rv = renpy.display.pgrender.flip_unscaled(rv, False, True)
return rv
def free_memory(self):
self.texture_cache.clear()
gltexture.dealloc_textures()
def event_peek_sleep(self):
pass
+588
View File
@@ -0,0 +1,588 @@
# Copyright 2004-2010 PyTom <pytom@bishoujo.us>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# This file contains the code required to set up (and change) OpenGL texture
# environments to implement various effects.
try:
import _renpy_tegl as gl; gl
import _renpy_pysdlgl as pysdlgl; pysdlgl
except ImportError:
gl = None
pysdlgl = None
import glshader
# Constants, that are used to store the last kind of blend a class was
# used for. (So we can avoid changing the GL state unnecessarily.)
NONE = 0
BLIT = 1
BLEND = 2
IMAGEBLEND = 3
class Environ(object):
def blit(self):
"""
Set up a normal blit environment. The texture to be blitted should
be TEXTURE0.
"""
raise Exception("Not implemented.")
def blend(self, fraction):
"""
Set up an environment that blends from TEXTURE0 to TEXTURE1.
`fraction` is the fraction of the blend complete.
"""
raise Exception("Not implemented.")
def imageblend(self, fraction, ramp):
"""
Setup an environment that does an imageblend from TEXTURE1 to TEXTURE2.
The controlling image is TEXTURE0.
`fraction` is the fraction of the blend complete.
`ramp` is the length of the ramp.
"""
raise Exception("Not implemented.")
class FixedFunctionEnviron(Environ):
"""
This is an OpenGL environment that uses the fixed-function pipeline.
It requires ARB_texture_env_combine and ARB_texture_env_crossbar to
work.
"""
def init(self):
# The last blend environ used.
self.last = NONE
# The last ramp length asked for.
self.last_ramp = -1
# The last ramplen actually used.
self.last_ramplen = -1
# A table that maps ramp lengths to the setup of the fixed-function
# units.
self.ramp_setup = [
# Fields are:
# ramp length,
# unit 1 scale,
# unit 2 function,
# unit 2 scale,
(256, 1.0, gl.REPLACE, 1.0),
(128, 1.0, gl.REPLACE, 2.0),
(64, 1.0, gl.REPLACE, 4.0),
(32, 1.0, gl.ADD, 4.0),
(16, 2.0, gl.ADD, 4.0),
(8, 4.0, gl.ADD, 4.0),
]
def deinit(self):
"""
Called before changing the GL context.
"""
return
def disable(self, unit):
"""
Disables the given texture combiner.
"""
gl.ActiveTextureARB(unit)
gl.Disable(gl.TEXTURE_2D)
def combine_mode(self, unit,
color_function=gl.MODULATE,
color_arg0=gl.TEXTURE,
color_arg1=gl.PREVIOUS_ARB,
color_arg2=gl.CONSTANT_ARB,
color_source0=gl.SRC_COLOR,
color_source1=gl.SRC_COLOR,
color_source2=gl.SRC_COLOR,
color_scale=1.0,
alpha_function=gl.MODULATE,
alpha_arg0=gl.TEXTURE,
alpha_arg1=gl.PREVIOUS_ARB,
alpha_arg2=gl.CONSTANT_ARB,
alpha_source0=gl.SRC_ALPHA,
alpha_source1=gl.SRC_ALPHA,
alpha_source2=gl.SRC_ALPHA,
alpha_scale=1.0,
enable=True):
gl.ActiveTextureARB(unit)
if enable:
gl.Enable(gl.TEXTURE_2D)
else:
gl.Disable(gl.TEXTURE_2D)
gl.TexEnvi(gl.TEXTURE_ENV, gl.TEXTURE_ENV_MODE, gl.COMBINE_ARB)
gl.TexEnvi(gl.TEXTURE_ENV, gl.COMBINE_RGB_ARB, color_function)
gl.TexEnvi(gl.TEXTURE_ENV, gl.COMBINE_ALPHA_ARB, alpha_function)
gl.TexEnvi(gl.TEXTURE_ENV, gl.SOURCE0_RGB_ARB, color_arg0)
gl.TexEnvi(gl.TEXTURE_ENV, gl.OPERAND0_RGB_ARB, color_source0)
gl.TexEnvi(gl.TEXTURE_ENV, gl.SOURCE1_RGB_ARB, color_arg1)
gl.TexEnvi(gl.TEXTURE_ENV, gl.OPERAND1_RGB_ARB, color_source1)
gl.TexEnvi(gl.TEXTURE_ENV, gl.SOURCE2_RGB_ARB, color_arg2)
gl.TexEnvi(gl.TEXTURE_ENV, gl.OPERAND2_RGB_ARB, color_source2)
gl.TexEnvi(gl.TEXTURE_ENV, gl.SOURCE0_ALPHA_ARB, alpha_arg0)
gl.TexEnvi(gl.TEXTURE_ENV, gl.OPERAND0_ALPHA_ARB, alpha_source0)
gl.TexEnvi(gl.TEXTURE_ENV, gl.SOURCE1_ALPHA_ARB, alpha_arg1)
gl.TexEnvi(gl.TEXTURE_ENV, gl.OPERAND1_ALPHA_ARB, alpha_source1)
gl.TexEnvi(gl.TEXTURE_ENV, gl.SOURCE2_ALPHA_ARB, alpha_arg2)
gl.TexEnvi(gl.TEXTURE_ENV, gl.OPERAND2_ALPHA_ARB, alpha_source2)
gl.TexEnvf(gl.TEXTURE_ENV, gl.RGB_SCALE_ARB, color_scale)
gl.TexEnvf(gl.TEXTURE_ENV, gl.ALPHA_SCALE, alpha_scale)
def blit(self):
if self.last != BLIT:
# Set unit 0 to modulate.
self.combine_mode(gl.TEXTURE0_ARB,
color_function=gl.MODULATE,
alpha_function=gl.MODULATE)
# Disable units 1, 2 and 3.
self.disable(gl.TEXTURE1_ARB)
self.disable(gl.TEXTURE2_ARB)
self.disable(gl.TEXTURE3_ARB)
self.last = BLIT
def blend(self, fraction):
if self.last != BLEND:
# Get texture 0.
self.combine_mode(gl.TEXTURE0_ARB,
color_function=gl.REPLACE,
alpha_function=gl.REPLACE)
# Use interpolate to combine texture 0 with texture 1, as
# controlled by the constant of texture unit 1.
self.combine_mode(gl.TEXTURE1_ARB,
color_function=gl.INTERPOLATE_ARB,
color_arg0=gl.TEXTURE1_ARB,
color_arg1=gl.TEXTURE0_ARB,
alpha_function=gl.INTERPOLATE_ARB,
alpha_arg0=gl.TEXTURE1_ARB,
alpha_arg1=gl.TEXTURE0_ARB)
# Combine the interpolated result with the primary color, to
# allow for tinting and alpha adjustments.
self.combine_mode(gl.TEXTURE2_ARB,
color_function=gl.MODULATE,
color_arg0=gl.PREVIOUS_ARB,
color_arg1=gl.PRIMARY_COLOR_ARB,
alpha_function=gl.MODULATE,
alpha_arg0=gl.PREVIOUS_ARB,
alpha_arg1=gl.PRIMARY_COLOR_ARB,
enable=False)
# Disable texture unit 3.
self.disable(gl.TEXTURE3_ARB)
self.last = BLEND
gl.ActiveTextureARB(gl.TEXTURE1_ARB)
gl.TexEnvfv(gl.TEXTURE_ENV, gl.TEXTURE_ENV_COLOR, (fraction, fraction, fraction, fraction))
def imageblend(self, fraction, ramp):
if self.last != IMAGEBLEND or self.last_ramp != ramp:
# Figure out the details of the ramp.
for i in self.ramp_setup:
ramplen, t0scale, t1function, t1scale = i
# We round the ramplen down, unless we're below the
# smallest size, in which case we increase it.
if ramplen <= ramp:
break
# Unit 0 loads in the control image, and adds/subtracts an
# offset to/from it. (We'll set it up to subtract here,
# and change this later on as necessary.)
#
# It multiplies this result by up to 4.
self.combine_mode(gl.TEXTURE0_ARB,
color_function=gl.SUBTRACT_ARB,
alpha_function=gl.SUBTRACT_ARB,
color_arg1=gl.CONSTANT_ARB,
alpha_arg1=gl.CONSTANT_ARB,
color_scale=t0scale,
alpha_scale=t0scale)
# Unit 1 will multiply the result of stage 1 by up to 8.
#
# It also takes the first source texture, but we don't
# access it directly yet.
self.combine_mode(gl.TEXTURE1_ARB,
color_function=t1function,
alpha_function=t1function,
color_arg0=gl.PREVIOUS_ARB,
color_arg1=gl.PREVIOUS_ARB,
alpha_arg0=gl.PREVIOUS_ARB,
alpha_arg1=gl.PREVIOUS_ARB,
color_scale=t1scale,
alpha_scale=t1scale)
# Unit 2 uses the result of unit 1 to interpolate between the
# unit 1 and unit 2 textures.
self.combine_mode(gl.TEXTURE2_ARB,
color_function=gl.INTERPOLATE_ARB,
alpha_function=gl.INTERPOLATE_ARB,
color_arg0=gl.TEXTURE2_ARB,
color_arg1=gl.TEXTURE1_ARB,
color_arg2=gl.PREVIOUS_ARB,
alpha_arg0=gl.TEXTURE2_ARB,
alpha_arg1=gl.TEXTURE1_ARB,
alpha_arg2=gl.PREVIOUS_ARB)
# Finally, Unit 3 modulates the result of unit 2 with the color.
self.combine_mode(gl.TEXTURE3_ARB,
color_function=gl.MODULATE,
color_arg0=gl.PREVIOUS_ARB,
color_arg1=gl.PRIMARY_COLOR_ARB,
alpha_function=gl.MODULATE,
alpha_arg0=gl.PREVIOUS_ARB,
alpha_arg1=gl.PRIMARY_COLOR_ARB,
enable=False)
self.last = IMAGEBLEND
self.last_ramp = ramp
self.last_ramplen = ramplen
# Compute the offset to apply to the alpha.
start = -1.0
end = self.last_ramplen / 256.0
offset = start + ( end - start) * fraction
# Decide if we're adding or subtracting.
if offset < 0:
function = gl.SUBTRACT_ARB
offset = -offset
else:
function = gl.ADD
# Setup unit 0 as appropriate.
gl.ActiveTextureARB(gl.TEXTURE0_ARB)
gl.TexEnvi(gl.TEXTURE_ENV, gl.COMBINE_RGB_ARB, function)
gl.TexEnvi(gl.TEXTURE_ENV, gl.COMBINE_ALPHA_ARB, function)
gl.TexEnvfv(gl.TEXTURE_ENV, gl.TEXTURE_ENV_COLOR, (offset, offset, offset, offset))
class ShaderEnviron(object):
"""
This is an environment that uses shaders.
"""
def init(self):
self.blit_program = glshader.blit_program()
self.blit_tex0_uniform = gl.GetUniformLocationARB(
self.blit_program,
"tex0")
self.blend_program = glshader.blend_program()
self.blend_done_uniform = gl.GetUniformLocationARB(
self.blend_program,
"done")
self.blend_tex0_uniform = gl.GetUniformLocationARB(
self.blend_program,
"tex0")
self.blend_tex1_uniform = gl.GetUniformLocationARB(
self.blend_program,
"tex1")
self.imageblend_program = glshader.imageblend_program()
self.imageblend_tex0_uniform = gl.GetUniformLocationARB(
self.imageblend_program,
"tex0")
self.imageblend_tex1_uniform = gl.GetUniformLocationARB(
self.imageblend_program,
"tex1")
self.imageblend_tex2_uniform = gl.GetUniformLocationARB(
self.imageblend_program,
"tex2")
self.imageblend_offset_uniform = gl.GetUniformLocationARB(
self.imageblend_program,
"offset")
self.imageblend_multiplier_uniform = gl.GetUniformLocationARB(
self.imageblend_program,
"multiplier")
self.last = NONE
def deinit(self):
"""
Called before changing the GL context.
"""
gl.DeleteObjectARB(self.blit_program)
gl.DeleteObjectARB(self.blend_program)
gl.DeleteObjectARB(self.imageblend_program)
return
def blit(self):
if self.last != BLIT:
gl.UseProgramObjectARB(self.blit_program)
gl.Uniform1iARB(self.blit_tex0_uniform, 0)
self.last = BLIT
def blend(self, fraction):
if self.last != BLEND:
gl.UseProgramObjectARB(self.blend_program)
gl.Uniform1iARB(self.blend_tex0_uniform, 0)
gl.Uniform1iARB(self.blend_tex1_uniform, 1)
self.last = BLEND
gl.Uniform1fARB(self.blend_done_uniform, fraction)
def imageblend(self, fraction, ramp):
if self.last != IMAGEBLEND:
gl.UseProgramObjectARB(self.imageblend_program)
gl.Uniform1iARB(self.imageblend_tex0_uniform, 0)
gl.Uniform1iARB(self.imageblend_tex1_uniform, 1)
gl.Uniform1iARB(self.imageblend_tex2_uniform, 2)
self.last = IMAGEBLEND
# Prevent a DBZ if the user gives us a 0 ramp.
if ramp < 1:
ramp = 1
# Compute the offset to apply to the alpha.
start = -1.0
end = ramp / 256.0
offset = start + ( end - start) * fraction
# Setup the multiplier and the offset.
gl.Uniform1fARB(self.imageblend_multiplier_uniform, 256.0 / ramp)
gl.Uniform1fARB(self.imageblend_offset_uniform, offset)
class Rtt(object):
"""
Subclasses of this class handle rendering to a texture.
"""
def begin(self):
"""
This function should be called when a Render-to-texture
session begins. It's responsible for setting the GPU to
RTT mode.
"""
raise Exception("Not implemented.")
def render(self, texture, x, y, w, h, draw_func):
"""
This function is called to trigger a rendering to a texture.
`x`, `y`, `w`, and `h` specify the location and dimensions of
the sub-image to render to the texture. `draw_func` is called
to render the texture.
"""
raise Exception("Not implemented.")
def end(self):
"""
This is called when a Render-to-texture session ends.
"""
raise Exception("Not implemented.")
class CopyRtt(object):
"""
This class uses texture copying to implement Render-to-texture.
"""
def init(self):
pass
def deinit(self):
"""
Called before changing the GL context.
"""
return
def begin(self):
"""
This function should be called when a Render-to-texture
session begins. It's responsible for setting the GPU to
RTT mode.
"""
def render(self, texture, x, y, w, h, draw_func):
"""
This function is called to trigger a rendering to a texture.
`x`, `y`, `w`, and `h` specify the location and dimensions of
the sub-image to render to the texture. `draw_func` is called
to render the texture.
"""
gl.Viewport(0, 0, w, h)
gl.MatrixMode(gl.PROJECTION)
gl.LoadIdentity()
gl.Ortho(x, x + w, y, y + h, -1, 1)
gl.MatrixMode(gl.MODELVIEW)
draw_func()
gl.BindTexture(gl.TEXTURE_2D, texture)
gl.CopyTexSubImage2D(
gl.TEXTURE_2D,
0,
0,
0,
0,
0,
w,
h)
def end(self):
"""
This is called when a Render-to-texture session ends.
"""
class FramebufferRtt(object):
"""
This class uses the framebuffer object to do RTT.
"""
def init(self):
# This maps a texture to the framebuffer object that
# can write to that texture.
self.texture_to_fbo = { }
def deinit(self):
"""
Called before changing the GL context.
"""
for i in self.texture_to_fbo.itervalues():
gl.DeleteFramebuffersEXT(1, [ i ])
self.texture_to_fbo.clear()
def get_fbo(self, texture):
if texture in self.texture_to_fbo:
return self.texture_to_fbo[texture]
fbos = [ 0 ]
gl.GenFramebuffersEXT(1, fbos)
fbo = fbos[0]
gl.BindFramebufferEXT(gl.FRAMEBUFFER_EXT, fbo)
gl.FramebufferTexture2DEXT(
gl.FRAMEBUFFER_EXT,
gl.COLOR_ATTACHMENT0_EXT,
gl.TEXTURE_2D,
texture,
0)
self.texture_to_fbo[texture] = fbo
return fbo
def begin(self):
"""
This function should be called when a Render-to-texture
session begins. It's responsible for setting the GPU to
RTT mode.
"""
def render(self, texture, x, y, w, h, draw_func):
"""
This function is called to trigger a rendering to a texture.
`x`, `y`, `w`, and `h` specify the location and dimensions of
the sub-image to render to the texture. `draw_func` is called
to render the texture.
"""
fbo = self.get_fbo(texture)
gl.BindFramebufferEXT(gl.FRAMEBUFFER_EXT, fbo)
gl.Viewport(0, 0, w, h)
gl.MatrixMode(gl.PROJECTION)
gl.LoadIdentity()
gl.Ortho(x, x + w, y, y + h, -1, 1)
gl.MatrixMode(gl.MODELVIEW)
draw_func()
def end(self):
"""
This is called when a Render-to-texture session ends.
"""
gl.BindFramebufferEXT(gl.FRAMEBUFFER_EXT, 0)
+168
View File
@@ -0,0 +1,168 @@
# Copyright 2004-2010 PyTom <pytom@bishoujo.us>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# This file contains GLSL shader code, and code to load shaders.
import array
try:
import _renpy_tegl as gl; gl
import _renpy_pysdlgl as pysdlgl; pysdlgl
except ImportError:
gl = None
pysdlgl = None
VERTEX_SHADER = """
void main() {
gl_TexCoord[0] = gl_MultiTexCoord0;
gl_TexCoord[1] = gl_MultiTexCoord1;
gl_TexCoord[2] = gl_MultiTexCoord2;
gl_ClipVertex = gl_ModelViewMatrix * gl_Vertex;
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
gl_FrontColor = gl_Color;
gl_BackColor = gl_Color;
}
"""
BLIT_SHADER = """
uniform sampler2D tex0;
void main()
{
vec4 color0 = texture2D(tex0, gl_TexCoord[0].st);
gl_FragColor = color0 * gl_Color;
}
"""
BLEND_SHADER = """
uniform sampler2D tex0;
uniform sampler2D tex1;
uniform float done;
void main()
{
vec4 color0 = texture2D(tex0, gl_TexCoord[0].st);
vec4 color1 = texture2D(tex1, gl_TexCoord[1].st);
gl_FragColor = mix(color0, color1, done) * gl_Color;
}
"""
IMAGEBLEND_SHADER = """
uniform sampler2D tex0;
uniform sampler2D tex1;
uniform sampler2D tex2;
uniform float offset;
uniform float multiplier;
void main()
{
vec4 color0 = texture2D(tex0, gl_TexCoord[0].st);
vec4 color1 = texture2D(tex1, gl_TexCoord[1].st);
vec4 color2 = texture2D(tex2, gl_TexCoord[2].st);
float a = clamp((color0.a + offset) * multiplier, 0.0, 1.0);
gl_FragColor = mix(color1, color2, a) * gl_Color;
}
"""
def check_status(handle, type):
"""
Checks the status of a shader or program. If it fails, then an
exception is raised.
"""
status = [ 0 ]
gl.GetObjectParameterivARB(handle, type, status)
if status[0] == 0:
log_length_list = [ 0 ]
gl.GetObjectParameterivARB(handle, gl.OBJECT_INFO_LOG_LENGTH_ARB, log_length_list)
log_length = log_length_list[0]
log = array.array('c', ' ' * log_length)
gl.GetInfoLogARB(handle, log_length, [ 0 ], log)
raise Exception("Shader error: %s" % log.tostring())
def compile_shader(kind, source):
"""
Allocates and compiles a shader.
"""
handle = gl.CreateShaderObjectARB(kind)
gl.ShaderSourceARB(handle, 1, [ source ], [ len(source) ])
gl.CompileShaderARB(handle)
check_status(handle, gl.OBJECT_COMPILE_STATUS_ARB)
return handle
def compile_program(vertex, fragment):
"""
Compiles a pair of shaders into a program.
"""
vertex_shader = compile_shader(gl.VERTEX_SHADER_ARB, vertex)
fragment_shader = compile_shader(gl.FRAGMENT_SHADER_ARB, fragment)
program = gl.CreateProgramObjectARB()
gl.AttachObjectARB(program, vertex_shader)
gl.AttachObjectARB(program, fragment_shader)
gl.LinkProgramARB(program)
check_status(program, gl.OBJECT_LINK_STATUS_ARB)
gl.UseProgramObjectARB(program)
gl.DeleteObjectARB(vertex_shader)
gl.DeleteObjectARB(fragment_shader)
return program
# These return the standard programs, compiled and ready to use.
def blit_program():
return compile_program(VERTEX_SHADER, BLIT_SHADER)
def blend_program():
return compile_program(VERTEX_SHADER, BLEND_SHADER)
def imageblend_program():
return compile_program(VERTEX_SHADER, IMAGEBLEND_SHADER)
+916
View File
@@ -0,0 +1,916 @@
# Copyright 2004-2010 PyTom <pytom@bishoujo.us>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import collections
import pygame; pygame # other modules might depend on pygame.
try:
import _renpy_tegl as gl; gl
import _renpy_pysdlgl as pysdlgl; pysdlgl
except ImportError:
gl = None
pysdlgl = None
import renpy
# The maximum size of a texture.
MAX_SIZE = 512
# Possible sizes for a texture.
SIZES = [ 512, 256, 128, 64 ]
def check_error():
"""
This checks for an opengl error, and throws an exception if it occurs.
"""
err = gl.GetError()
if err:
raise Exception("GL Error: 0x%x" % err)
# A list of texture number allocated.
texture_numbers = [ ]
class Texture(object):
"""
This object stores information about an OpenGL texture.
"""
def __init__(self, width, height):
# The width and height of this texture.
self.width = width
self.height = height
# The number of the OpenGL texture this texture object
# represents.
self.generation = 0
self.number = None
# True if the texture has been created inside the GPU.
self.created = False
# These are used to map an index into texture coordinates.
self.xmul = 0
self.xadd = 0
self.ymul = 0
self.yadd = 0
# These contained the premultiplied (but not GPU-loaded)
# surface. They allow us to defer loading until the surface is
# needed.
self.premult = None
self.premult_size = None
# True if we're in NEAREST mode. False if we're in LINEAR mode.
self.nearest = False
# The free list we should be put on, or None if we're already on
# a free list.
self.free_list = None
def __del__(self):
# Release the surface.
self.premult = None
self.premult_size = None
# The test needs to be here so we don't try to append during
# interpreter shutdown.
if self.free_list is not None:
try:
self.free_list.append(self)
self.free_list = None
except TypeError:
pass # Let's not error on shutdown.
def load_surface(self, surf, x, y, w, h):
"""
Loads a pygame surface into this texture rectangle.
"""
# This just queues the surface up for loading. The actual loading
# occurs when the texture is first needed. This ensures that the
# texture loading only occurs in the GL thread.
self.premult = pysdlgl.premultiply(surf, x, y, w, h)
self.premult_size = (w, h)
def make_nearest(self):
"""
Causes this texture to be rendered in nearest-neighbor mode.
"""
if self.nearest:
return
gl.BindTexture(gl.TEXTURE_2D, self.number)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
self.nearest = True
def make_linear(self):
"""
Causes this texture to be rendered in linear interpolation mode.
"""
if not self.nearest:
return
gl.BindTexture(gl.TEXTURE_2D, self.number)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
self.nearest = False
def make_ready(self):
"""
Makes the texture ready for use.
"""
self.allocate()
if self.premult:
w, h = self.premult_size
gl.BindTexture(gl.TEXTURE_2D, self.number)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
self.nearest = False
# If we haven't initalized the texture yet, and we're
# smaller than it, load in the empty texture.
if w < self.width or h < self.height:
if not self.created:
pysdlgl.load_premultiplied(
None,
self.width,
self.height,
0)
self.created = True
# Otherwise, either load or replace the texture.
pysdlgl.load_premultiplied(
self.premult,
w,
h,
self.created)
# Needs to be here twice, since we may not go through the w < SIDE
# h < SIDE thing all the time.
self.created = True
# Finally, load in the default math.
self.xadd = self.yadd = 0
self.xmul = 1.0 / self.width
self.ymul = 1.0 / self.height
# We don't need to be loaded anymore.
self.premult = None
self.premult_size = None
def render_to(self, x, y, draw_func, rtt):
self.allocate()
if not self.created:
gl.BindTexture(gl.TEXTURE_2D, self.number)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
self.nearest = False
pysdlgl.load_premultiplied(
None,
self.width,
self.height,
0)
self.created = True
rtt.render(self.number, x, y, self.width, self.height, draw_func)
self.xadd = 0
self.yadd = 0
self.xmul = 1.0 / self.width
self.ymul = 1.0 / self.height
def allocate(self):
"""
This allocates a texture number, if necessary.
"""
if self.number is not None:
return
texnums = [ 0 ]
gl.GenTextures(1, texnums)
self.number = texnums[0]
self.created = False
texture_numbers.append(texnums[0])
# This is a map from texture sizes to a list of free textures of that
# size.
free_textures = collections.defaultdict(list)
# The total size (in bytes) of all the textures that have been allocated.
total_texture_size = 0
# This allocates a texture, either from the free list, or by asking
# gl.
def alloc_texture(width, height):
"""
Allocate a texture, either from the freelist or by asking GL. The
returned texture has a reference count of 1.
"""
global total_texture_size
l = free_textures[width, height]
if l:
rv = l.pop()
else:
rv = Texture(width, height)
total_texture_size += width * height * 4
rv.free_list = l
return rv
def dealloc_textures():
global texture_numbers
for t in texture_numbers:
gl.DeleteTextures(1, [ t ])
texture_numbers = [ ]
free_textures.clear()
def compute_subrow(row, offset, width):
"""
Given a row (or column), this computes a subrow starting at the given
offset and having the given width.
It returns two list. The first is a list of (offset, width,
output-tile) tuples. The second is a list of integers, giving the
input tile corresponding to each output tile.
"""
# An iterator over row.
rowi = iter(row)
# The output row and the output tile list.
outrow = [ ]
tiles = [ ]
# The output tile index.
outtile = 0
try:
ioff, iwidth, itile = rowi.next()
# Consume the offset.
while True:
if offset < iwidth:
ioff += offset
iwidth -= offset
break
offset -= iwidth
ioff, iwidth, itile = rowi.next()
# Consume the width.
while True:
if width < iwidth:
outrow.append((ioff, width, outtile))
tiles.append(itile)
outtile += 1
break
outrow.append((ioff, iwidth, outtile))
tiles.append(itile)
outtile += 1
width -= iwidth
ioff, iwidth, itile = rowi.next()
except StopIteration:
pass
return outrow, tiles
class TextureGrid(object):
"""
This represents one or more textures that cover a rectangular
area.
"""
def __init__(self, width, height):
# The width and height of this TextureGrid
self.width = width
self.height = height
# For each row of tiles, a tuple giving:
# - The y offset within the texture.
# - The height of the row.
# - The rowindex in tiles.
self.rows = [ ]
# For each column of tiles, a tuple giving.
# - The x offset within the texture.
# - The width of the column.
# - The colindex in tiles.
self.columns = [ ]
# The actual grid of texture titles, a list of lists of
# textures. This is looked up by looking up rowindex and
# colindex.
self.tiles = [ ]
# If it exists, a TextureGrid that is half the size of this
# one.
self.half_cache = None
def get_size(self):
return self.width, self.height
def subsurface(self, (x, y, w, h)):
"""
This produces a texture grid containing a rectangle "cut out"
of this texture grid.
"""
rv = TextureGrid(w, h)
rv.rows, rowtiles = compute_subrow(self.rows, y, h)
rv.columns, coltiles = compute_subrow(self.columns, x, w)
for i in rowtiles:
row = [ ]
for j in coltiles:
row.append(self.tiles[i][j])
rv.tiles.append(row)
return rv
def make_ready(self, nearest=False):
"""
Makes ready all the tile-textures in this texture grid.
"""
for row in self.tiles:
for t in row:
t.make_ready()
if nearest:
t.make_nearest()
else:
t.make_linear()
# This is a cache from (width, size) to the results of compute_tiling.
tiling_cache = { }
def compute_tiling(width, max_size=MAX_SIZE):
"""
This computes a tiling for an image with the given width (or
height). It takes a width as an argument, and returns two lists.
The first is a list of (offset, width, index) tuples, as are used
in TextureGrid to determine how to blit an image to the screen.
The second is a list of (offset, copy-width, total-width) tuples
that are used to create the tiles.
While we're thinking about this as if it's working horizontally
(x, width, etc), it
"""
# Check the cache.
key = (width, max_size)
if key in tiling_cache:
return tiling_cache[key]
# width is the remaining width, not including any borders
# required.
# The x-offset, relative to the left side of the surface.
x = 0
# The list of row tuples.
row = [ ]
# The list of tile tuples.
tiles = [ ]
# The index into the row.
row_index = 0
while width:
# The size of the left border of this tile.
left_border = 1
# Figure out the texture size to use.
for size in SIZES:
if size > max_size:
continue
# Ensure each texture is at least 2/3rds full. (Except the
# smallest.)
if size * .66 <= width + left_border:
break
# Figure out if we want to use a border.
if size < width + left_border:
right_border = 1
else:
right_border = 0
# The number of pixels to display to the user from this tile.
row_size = min(width, size - left_border - right_border)
# Ensure we have an extra pixel to our right, so we don't
# get garbage.
if row_size + left_border != size:
right_border = 1
#Add to the results.
row.append((left_border, row_size, row_index))
tiles.append((x - left_border, row_size + left_border + right_border, size))
# Update the counters.
row_index += 1
x += row_size
width -= row_size
tiling_cache[key] = (row, tiles)
return row, tiles
def texture_grid_from_surface(surf):
"""
This takes a Surface and turns it into a TextureGrid.
"""
width, height = surf.get_size()
rv = TextureGrid(width, height)
rv.columns, texcolumns = compute_tiling(width)
rv.rows, texrows = compute_tiling(height)
for y, height, texheight in texrows:
row = [ ]
for x, width, texwidth in texcolumns:
tex = alloc_texture(texwidth, texheight)
tex.load_surface(surf, x, y, width, height)
row.append(tex)
rv.tiles.append(row)
return rv
def texture_grid_from_drawing(width, height, draw_func, rtt):
"""
This creates a texture grid of `width` by `height` by using
draw_func to draw to the screen.
"""
rtt.begin()
rv = TextureGrid(width, height)
pwidth, pheight = renpy.display.draw.physical_size
rv.columns, texcolumns = compute_tiling(width, pwidth)
rv.rows, texrows = compute_tiling(height, pheight)
for y, height, texheight in texrows:
row = [ ]
for x, width, texwidth in texcolumns:
tex = alloc_texture(texwidth, texheight)
tex.render_to(x, y, draw_func, rtt)
row.append(tex)
rv.tiles.append(row)
rtt.end()
return rv
def align_axes(*args):
"""
This takes n axes, each a list consisting of (offset, size, index)
tuples. It returns a list of n lists. For each of the n lists, the
ith element will be the same size. The indexes will appear in the
same order they did in the original list.
This is used to combine the grids of two or more texgrids into a
single grid.
"""
# The lists we're building.
rv = [ [] for i in args ]
# The index of the current element, for each member of args.
cur = [ 0 for i in args ]
# The parts of the current element.
offset = [ i[0][0] for i in args ]
size = [ i[0][1] for i in args ]
index = [ i[0][2] for i in args ]
# Cache it here to save function calls.
nargs = len(args)
loop = True
while loop:
# Figure out the minimum size.
minsize = min(size)
for i in xrange(nargs):
# Create an entry of minsize.
rv[i].append((offset[i], minsize, index[i]))
# Adjust the offset and size.
offset[i] += minsize
size[i] -= minsize
# If the size fell to 0, then load the next element from
# the arguments into offset, size, index. If we can't
# we're done.
if size[i] == 0:
cur[i] += 1
if cur[i] >= len(args[i]):
loop = False
else:
offset[i], size[i], index[i] = args[i][cur[i]]
return rv
def blit(tg, sx, sy, transform, alpha, environ, nearest=False):
"""
This draws texgrid `tg` to the screen. `sx` and `sy` are offsets from
the upper-left corner of the screen.
`transform` is the transform to apply to the texgrid, when going from
texgrid coordinates to screen coordinates.
`alpha` is the alpha multiplier applied, from 0.0 to 1.0.
"""
tg.make_ready(nearest)
environ.blit()
gl.Color4f(alpha, alpha, alpha, alpha)
y = 0
for texy, texh, rowindex in tg.rows:
x = 0
for texx, texw, colindex in tg.columns:
tex = tg.tiles[rowindex][colindex]
pysdlgl.draw_rectangle(
sx, sy,
x, y,
texw, texh,
transform,
tex, texx, texy,
None, 0, 0,
None, 0, 0)
x += texw
y += texh
def blend(tg0, tg1, sx, sy, transform, alpha, fraction, environ):
"""
Blends two textures to the screen.
`tg0` and `tg1` are the texture.
`sx` and `sy` are the offsets from the upper-left corner of the screen.
`transform` is the transform to apply to the texgrid, when going from
texgrid coordinates to screen coordinates.
`alpha` is the alpha multiplier applied, from 0.0 to 1.0.
`fraction` is the fraction of the second texture to show.
"""
tg0.make_ready()
tg1.make_ready()
environ.blend(fraction)
gl.Color4f(alpha, alpha, alpha, alpha)
y = 0
rows0, rows1 = align_axes(tg0.rows, tg1.rows)
cols0, cols1 = align_axes(tg0.columns, tg1.columns)
# t0 = texture 0, t1 = texture 1.
# x, y - index into the texture.
# w, h - width and height to draw.
# ri, ci - row index, column index in tiles.
for (t0y, t0h, t0ri), (t1y, t1h, t1ri) in zip(rows0, rows1):
x = 0
for (t0x, t0w, t0ci), (t1x, t1w, t1ci) in zip(cols0, cols1):
t0 = tg0.tiles[t0ri][t0ci]
t1 = tg1.tiles[t1ri][t1ci]
pysdlgl.draw_rectangle(
sx, sy,
x, y,
t0w, t0h,
transform,
t0, t0x, t0y,
t1, t1x, t1y,
None, 0, 0)
x += t0w
y += t0h
def imageblend(tg0, tg1, tg2, sx, sy, transform, alpha, fraction, ramp, environ):
"""
This uses texture 0 to control the blending of tetures 1 and 2 to
the screen.
`tg0`, `tg1`, and `tg2` are the textures.
`sx` and `sy` are the offsets from the upper-left corner of the screen.
`transform` is the transform to apply to the texgrid, when going from
texgrid coordinates to screen coordinates.
`alpha` is the alpha multiplier applied, from 0.0 to 1.0.
`fraction` is the fraction of the second texture to show.
`ramp` is the length of the blending ramp to use.
"""
tg0.make_ready()
tg1.make_ready()
tg2.make_ready()
environ.imageblend(fraction, ramp)
gl.Color4f(alpha, alpha, alpha, alpha)
y = 0
rows0, rows1, rows2 = align_axes(tg0.rows, tg1.rows, tg2.rows)
cols0, cols1, cols2 = align_axes(tg0.columns, tg1.columns, tg2.columns)
# t0 = texture 0, t1 = texture 1.
# x, y - index into the texture.
# w, h - width and height to draw.
# ri, ci - row index, column index in tiles.
for (t0y, t0h, t0ri), (t1y, t1h, t1ri), (t2y, t2h, t2ri) in zip(rows0, rows1, rows2):
x = 0
for (t0x, t0w, t0ci), (t1x, t1w, t1ci), (t2x, t2w, t2ci) in zip(cols0, cols1, cols2):
t0 = tg0.tiles[t0ri][t0ci]
t1 = tg1.tiles[t1ri][t1ci]
t2 = tg2.tiles[t2ri][t2ci]
pysdlgl.draw_rectangle(
sx, sy,
x, y,
t0w, t0h,
transform,
t0, t0x, t0y,
t1, t1x, t1y,
t2, t2x, t2y)
x += t0w
y += t0h
def draw_rectangle(
sx,
sy,
x,
y,
w,
h,
transform,
tex0, tex0x, tex0y,
tex1, tex1x, tex1y,
tex2, tex2x, tex2y):
"""
This draws a rectangle (textured with up to four textures) to the
screen.
"""
# Pull apart the transform.
xdx = transform.xdx
xdy = transform.xdy
ydx = transform.ydx
ydy = transform.ydy
# Transform the vertex coordinates to screen-space.
x0 = (x + 0) * xdx + (y + 0) * xdy + sx
y0 = (x + 0) * ydx + (y + 0) * ydy + sy
x1 = (x + w) * xdx + (y + 0) * xdy + sx
y1 = (x + w) * ydx + (y + 0) * ydy + sy
x2 = (x + 0) * xdx + (y + h) * xdy + sx
y2 = (x + 0) * ydx + (y + h) * ydy + sy
x3 = (x + w) * xdx + (y + h) * xdy + sx
y3 = (x + w) * ydx + (y + h) * ydy + sy
# Compute the texture coordinates, and set up the textures.
if tex0 is not None:
has_tex0 = 1
gl.ActiveTextureARB(gl.TEXTURE0_ARB)
gl.BindTexture(gl.TEXTURE_2D, tex0.number)
xadd = tex0.xadd
yadd = tex0.yadd
xmul = tex0.xmul
ymul = tex0.ymul
t0u0 = xadd + xmul * (tex0x + 0)
t0u1 = xadd + xmul * (tex0x + w)
t0v0 = yadd + ymul * (tex0y + 0)
t0v1 = yadd + ymul * (tex0y + h)
else:
has_tex0 = 0
if tex1 is not None:
has_tex1 = 1
gl.ActiveTextureARB(gl.TEXTURE1_ARB)
gl.BindTexture(gl.TEXTURE_2D, tex1.number)
xadd = tex1.xadd
yadd = tex1.yadd
xmul = tex1.xmul
ymul = tex1.ymul
t1u0 = xadd + xmul * (tex1x + 0)
t1u1 = xadd + xmul * (tex1x + w)
t1v0 = yadd + ymul * (tex1y + 0)
t1v1 = yadd + ymul * (tex1y + h)
else:
has_tex1 = 0
if tex2 is not None:
has_tex2 = 1
gl.ActiveTextureARB(gl.TEXTURE2_ARB)
gl.BindTexture(gl.TEXTURE_2D, tex2.number)
xadd = tex2.xadd
yadd = tex2.yadd
xmul = tex2.xmul
ymul = tex2.ymul
t2u0 = xadd + xmul * (tex2x + 0)
t2u1 = xadd + xmul * (tex2x + w)
t2v0 = yadd + ymul * (tex2y + 0)
t2v1 = yadd + ymul * (tex2y + h)
else:
has_tex2 = 0
# Now, actually draw the textured rectangle.
gl.Begin(gl.TRIANGLE_STRIP)
if has_tex0:
gl.MultiTexCoord2fARB(gl.TEXTURE0_ARB, t0u0, t0v0)
if has_tex1:
gl.MultiTexCoord2fARB(gl.TEXTURE1_ARB, t1u0, t1v0)
if has_tex2:
gl.MultiTexCoord2fARB(gl.TEXTURE2_ARB, t2u0, t2v0)
gl.Vertex2f(x0, y0)
if has_tex0:
gl.MultiTexCoord2fARB(gl.TEXTURE0_ARB, t0u1, t0v0)
if has_tex1:
gl.MultiTexCoord2fARB(gl.TEXTURE1_ARB, t1u1, t1v0)
if has_tex2:
gl.MultiTexCoord2fARB(gl.TEXTURE2_ARB, t2u1, t2v0)
gl.Vertex2f(x1, y1)
if has_tex0:
gl.MultiTexCoord2fARB(gl.TEXTURE0_ARB, t0u0, t0v1)
if has_tex1:
gl.MultiTexCoord2fARB(gl.TEXTURE1_ARB, t1u0, t1v1)
if has_tex2:
gl.MultiTexCoord2fARB(gl.TEXTURE2_ARB, t2u0, t2v1)
gl.Vertex2f(x2, y2)
if has_tex0:
gl.MultiTexCoord2fARB(gl.TEXTURE0_ARB, t0u1, t0v1)
if has_tex1:
gl.MultiTexCoord2fARB(gl.TEXTURE1_ARB, t1u1, t1v1)
if has_tex2:
gl.MultiTexCoord2fARB(gl.TEXTURE2_ARB, t2u1, t2v1)
gl.Vertex2f(x3, y3)
gl.End()
C_DRAW=True
if C_DRAW:
if pysdlgl:
draw_rectangle = pysdlgl.draw_rectangle
else:
print "Warning: Draw not using C code."
+49 -70
View File
@@ -29,8 +29,6 @@ import zipfile
import cStringIO
import threading
import pygame
# This is an entry in the image cache.
class CacheEntry(object):
@@ -80,17 +78,18 @@ class Cache(object):
# Is the preload_thread alive?
self.keep_preloading = True
# A list of images that want to be pinned into memory.
self.global_pins = [ ]
# A map from image object to surface, only for objects that have
# been pinned into memory.
self.pin_cache = { }
# Images that we tried, and failed, to preload.
self.preload_blacklist = set()
# The preload thread.
self.preload_thread = threading.Thread(target=self.preload_thread_main, name="preloader")
self.preload_thread.setDaemon(True)
self.preload_thread.start()
def quit(self):
if not self.preload_thread.isAlive():
@@ -109,6 +108,7 @@ class Cache(object):
def cache_limit(self):
return renpy.config.image_cache_size * renpy.config.screen_width * renpy.config.screen_height
# Clears out the cache.
def clear(self):
self.lock.acquire()
@@ -156,20 +156,6 @@ class Cache(object):
return
self.preloads.append(image)
# Called to report that a given image would like to be pinned into memory.
def pin_image(self, image):
if renpy.config.debug_image_cache:
print "IC Request Pin", image
if not isinstance(image, ImageBase):
if renpy.config.debug_image_cache:
print "IC Can't pin non image: ", image
else:
return
if image not in self.global_pins:
self.global_pins.append(image)
# This returns the pygame surface corresponding to the provided
# image. It also takes care of updating the age of images in the
@@ -224,32 +210,9 @@ class Cache(object):
if renpy.config.debug_image_cache:
print "IC Added %r (%.02f%%)" % (ce.what, 100.0 * self.total_cache_size / self.cache_limit())
# RLE detection. (ce.size is used to check that we're not
# 0 pixels big.)
if id(ce.surf) not in rle_cache and ce.size:
renpy.display.draw.load_texture(ce.surf)
rle = not renpy.game.less_memory
if rle:
# We must copy the surface, so we have a RLE-specific version.
idsurf = id(ce.surf)
if idsurf in pin_rle_cache:
rle_surf = pin_rle_cache[idsurf]
else:
rle_surf = renpy.display.pgrender.copy_surface(ce.surf)
rle_surf.set_alpha(255, pygame.RLEACCEL)
renpy.display.render.mutated_surface(rle_surf)
rle_cache[idsurf] = rle_surf
if renpy.config.debug_image_cache:
print "Added to rle cache:", image
self.lock.release()
# Move it into the current generation. This isn't protected by
# a lock, so in certain circumstances we could have an
@@ -275,9 +238,6 @@ class Cache(object):
self.total_cache_size -= ce.size
del self.cache[ce.what]
if id(ce.surf) in rle_cache:
del rle_cache[id(ce.surf)]
if renpy.config.debug_image_cache:
print "IC Removed", ce.what
@@ -348,7 +308,7 @@ class Cache(object):
def preload_thread_main(self):
while self.keep_preloading:
self.lock.acquire()
self.lock.wait()
self.lock.release()
@@ -371,7 +331,14 @@ class Cache(object):
try:
image = self.preloads.pop(0)
self.get(image)
if image not in self.preload_blacklist:
try:
self.get(image)
except:
self.preload_blacklist.add(image)
except:
pass
@@ -382,12 +349,29 @@ class Cache(object):
# If we have time, preload pinned images.
if self.keep_preloading and not renpy.game.less_memory:
# Compute the pin worklist.
pin_worklist = [ i for i in self.global_pins if i not in self.pin_cache ]
workset = set(renpy.store._cache_pin_set)
# Remove things that are not in the workset from the pin cache,
# and remove things that are in the workset from pin cache.
for i in self.pin_cache.keys():
if i in workset:
workset.remove(i)
else:
if renpy.config.debug_image_cache:
print "IC Pin Clear", image
surf = self.pin_cache[i]
del self.pin_cache[i]
# For each image in the worklist...
for image in pin_worklist:
for image in workset:
if image in self.preload_blacklist:
continue
# If we have normal preloads, break out.
if self.preloads:
break
@@ -396,33 +380,26 @@ class Cache(object):
if renpy.config.debug_image_cache:
print "IC Pin Preload", image
surf = image.load()
try:
surf = image.load()
self.pin_cache[image] = surf
renpy.display.draw.load_texture(surf)
self.pin_cache[image] = surf
rle_surf = renpy.display.pgrender.copy_surface(surf)
rle_surf.set_alpha(255, pygame.RLEACCEL)
pin_rle_cache[id(surf)] = rle_surf
except:
self.preload_blacklist.add(image)
# The cache object.
cache = Cache()
# A map from id(cached surface) to rle version of cached surface.
rle_cache = { }
# Same thing, for pinned surfaces.
pin_rle_cache = { }
def free_memory():
"""
Frees some memory.
"""
renpy.display.draw.free_memory()
cache.clear()
rle_cache.clear()
pin_rle_cache.clear()
class ImageBase(renpy.display.core.Displayable):
"""
@@ -471,10 +448,11 @@ class ImageBase(renpy.display.core.Displayable):
def render(self, w, h, st, at):
im = cache.get(self)
texture = renpy.display.draw.load_texture(im)
w, h = im.get_size()
rv = renpy.display.render.Render(w, h)
rv.blit(im, (0, 0))
rv.blit(texture, (0, 0))
return rv
def predict_one(self, callback):
@@ -1474,4 +1452,5 @@ def load_image(fn):
This loads an image from the given filename, using the cache.
"""
return cache.get(image(fn))
surf = cache.get(image(fn))
return renpy.display.draw.load_texture(surf)
+7 -34
View File
@@ -26,41 +26,15 @@
import renpy
from renpy.display.render import render, Render
Image = renpy.display.im.image
def wrap_render(child, w, h, st, at):
rend = render(child, w, h, st, at)
rv = Render(rend.width, rend.height)
rv.blit(rend, (0, 0))
return rv
class UncachedImage(renpy.display.core.Displayable):
"""
An image that is loaded immediately and not cached.
"""
def __init__(self, file, hint=None, scale=None, style='image_placement',
**properties):
super(UncachedImage, self).__init__(style=style, **properties)
self.surf = renpy.display.pgrender.load_image(file, hint)
if scale:
renpy.display.render.blit_lock.acquire()
self.surf = renpy.display.pgrender.transform_scale(self.surf, scale)
renpy.display.render.blit_lock.release()
renpy.display.render.mutated_surface(self.surf)
def render(self, w, h, st, at):
sw, sh = self.surf.get_size()
rv = renpy.display.render.Render(sw, sh)
rv.blit(self.surf, (0, 0))
return rv
class ImageReference(renpy.display.core.Displayable):
"""
@@ -83,9 +57,9 @@ class ImageReference(renpy.display.core.Displayable):
self.name = name
def get_parameterized(self):
def _get_parameterized(self):
if self.param_target:
return self.param_target.get_parameterized()
return self.param_target._get_parameterized()
return self
@@ -140,19 +114,17 @@ class ImageReference(renpy.display.core.Displayable):
return False
def hide(self, st, at):
def _hide(self, st, at, kind):
if not self.target:
self.find_target()
return self.target.hide(st, at)
return self.target._hide(st, at, kind)
def set_transform_event(self, event):
if not self.target:
self.find_target()
return self.target.set_transform_event(event)
def event(self, ev, x, y, st):
if not self.target:
@@ -281,7 +253,8 @@ class Frame(renpy.display.core.Displayable):
def visit(self):
return [ self.image ]
class ImageButton(renpy.display.behavior.Button):
"""
Used to implement the guts of an image button.
+59 -25
View File
@@ -169,7 +169,6 @@ class Container(renpy.display.core.Displayable):
return None
def visit(self):
return self.children
@@ -178,23 +177,14 @@ class Container(renpy.display.core.Displayable):
def __enter__(self):
if renpy.ui.current is self and not renpy.ui.current_once:
return self
raise Exception("%r cannot be used as a context manager.", type(self).__name__)
renpy.ui.context_enter(self)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type:
return False
if renpy.ui.current is not self:
raise Exception("Widget %r left open at end of block.")
renpy.ui.close()
renpy.ui.context_exit(self)
return False
@@ -317,7 +307,7 @@ class Grid(Container):
def __init__(self, cols, rows, padding=None,
transpose=False,
style='default', **properties):
style='grid', **properties):
"""
@param cols: The number of columns in this widget.
@@ -436,8 +426,9 @@ class MultiBox(Container):
self.anim_times.append(anim_time)
def append_scene_list(self, l):
for tag, zo, start, anim, d in l:
self.add(d, start, anim)
for sle in l:
self.add(sle.displayable, sle.show_time, sle.animation_time)
if self.scene_list is None:
self.scene_list = [ ]
@@ -823,6 +814,7 @@ class DynamicDisplayable(renpy.display.core.Displayable):
self.child = None
def __init__(self, function, *args, **kwargs):
super(DynamicDisplayable, self).__init__()
self.child = None
@@ -865,8 +857,12 @@ class DynamicDisplayable(renpy.display.core.Displayable):
i.predict(callback)
def get_placement(self):
if not self.child:
self.child, redraw = self.function(0, 0, *self.args, **self.kwargs)
return self.child.get_placement()
def event(self, ev, x, y, st):
if self.child:
return self.child.event(ev, x, y, st)
@@ -939,8 +935,8 @@ def ShowingSwitch(*args, **kwargs):
class IgnoresEvents(Container):
def __init__(self, child):
super(IgnoresEvents, self).__init__(style='default')
def __init__(self, child, **properties):
super(IgnoresEvents, self).__init__(**properties)
self.add(child)
def render(self, w, h, st, at):
@@ -957,8 +953,6 @@ class IgnoresEvents(Container):
# Ignores events.
def event(self, ev, x, y, st):
return None
class Viewport(Container):
@@ -985,6 +979,7 @@ class Viewport(Container):
mousewheel=False,
draggable=False,
style='viewport',
replaces=None,
**properties):
super(Viewport, self).__init__(style=style, **properties)
@@ -1001,6 +996,16 @@ class Viewport(Container):
else:
self.yadjustment = yadjustment
if isinstance(replaces, Viewport):
self.xadjustment.value = replaces.xadjustment.value
self.yadjustment.value = replaces.yadjustment.value
if self.xadjustment.adjustable is None:
self.xadjustment.adjustable = True
if self.yadjustment.adjustable is None:
self.yadjustment.adjustable = True
self.set_adjustments = set_adjustments
self.child_width, self.child_height = child_size
@@ -1010,7 +1015,7 @@ class Viewport(Container):
self.width = 0
self.height = 0
def per_interact(self):
self.xadjustment.register(self)
self.yadjustment.register(self)
@@ -1133,7 +1138,7 @@ class Side(Container):
def after_setstate(self):
self.sized = False
def __init__(self, positions, style='default', **properties):
def __init__(self, positions, style='side', **properties):
super(Side, self).__init__(style=style, **properties)
@@ -1321,8 +1326,8 @@ class Alpha(renpy.display.core.Displayable):
class AdjustTimes(Container):
def __init__(self, child, start_time, anim_time):
super(AdjustTimes, self).__init__(style='default')
def __init__(self, child, start_time, anim_time, **properties):
super(AdjustTimes, self).__init__(**properties)
self.start_time = start_time
self.anim_time = anim_time
@@ -1353,3 +1358,32 @@ class AdjustTimes(Container):
return self.child.get_placement()
class LiveTile(Container):
"""
:doc: other
Tiles the `child` displayable until it fills the area allocated to
this displayable.
The size of the displayable can be set with the :propref:`xmaximum` and
:propref:`ymaximum` style properties.
"""
def __init__(self, child, style='tile', **properties):
super(LiveTile, self).__init__(style=style, **properties)
self.add(child)
def render(self, width, height, st, at):
cr = renpy.display.render.render(self.child, width, height, st, at)
cw, ch = cr.get_size()
rv = renpy.display.render.Render(width, height)
for y in range(0, height, ch):
for x in range(0, width, cw):
rv.blit(cr, (x, y), focus=False)
return rv
+2 -2
View File
@@ -245,8 +245,8 @@ transform = _renpy.transform
blend = _renpy.blend
def imageblend(a, b, dst, img, amap):
red = byte_offset(img)[0]
_renpy.imageblend(a, b, dst, img, red, amap)
alpha = byte_offset(img)[3]
_renpy.imageblend(a, b, dst, img, alpha, amap)
def colormatrix(src, dst, matrix):
+468 -384
View File
File diff suppressed because it is too large Load Diff
+39 -2
View File
@@ -19,8 +19,9 @@
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# This module deals with pygame-specific rendering tasks.
# This module wraps the pygame surface class (and associated functions).
import sys
import pygame
import renpy
@@ -57,15 +58,51 @@ def set_mode(resolution, flags=0, depth=0):
sample_noalpha = s.convert(rv)
return rv
set_mode_unscaled = set_mode
def set_bgra_masks():
"""
This rebuilds the sample surfaces, to ones that use the given
masks.
"""
# Annoyingly, the value for the big mask seems to vary from
# platform to platform. So we read it out of a surface.
global sample_alpha
global sample_noalpha
# Create a sample surface.
s = opygame.Surface((10, 10), 0, 32)
sample_alpha = s.convert_alpha()
# Sort the compoents by absolute value.
masks = list(sample_alpha.get_masks())
masks.sort(key=lambda a : abs(a))
# Choose the masks.
if sys.byteorder == 'little':
masks = ( masks[2], masks[1], masks[0], masks[3] )
else:
masks = ( masks[1], masks[2], masks[3], masks[0] )
# Create the sample surface.
sample_alpha = opygame.Surface((10, 10), 0, 32, masks)
sample_noalpha = opygame.Surface((10, 10), 0, 32, masks[:3] + (0,))
class Surface(opygame.Surface):
"""
This allows us to wrap around pygame's surface, to change
its mode, as necessary.
"""
opaque = False
def is_opaque(self):
return self.opaque
def convert_alpha(self, surface=None):
return copy_surface_unscaled(self, True)
-1
View File
@@ -46,7 +46,6 @@ def start(gamedir):
break
else:
return
try:
import subprocess
+204 -630
View File
File diff suppressed because it is too large Load Diff
+6 -2
View File
@@ -366,10 +366,14 @@ def load_scaling():
def copy(self):
return ScaledSurface(self.surface.copy(), wh=self.get_size())
def convert(self):
return ScaledSurface(self.surface.convert(), wh=self.get_size())
def convert_alpha(self):
return ScaledSurface(self.surface.convert_alpha(), wh=self.get_size())
def fill(self, color):
self.surface.fill(color)
def get_alpha(self):
return self.surface.get_alpha()
@@ -533,7 +537,7 @@ def load_scaling():
def rotozoom(surf, angle, scale):
new_surf = pgrender.rotozoom(surf.surface, angle, scale)
new_surf = pgrender.rotozoom_unscaled(surf.surface, angle, scale)
return ScaledSurface(new_surf)
pgrender.rotozoom = rotozoom
+397
View File
@@ -0,0 +1,397 @@
# Copyright 2004-2010 PyTom <pytom@bishoujo.us>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import renpy
class Screen(renpy.object.Object):
"""
A screen is a collection of widgets that are displayed together.
This class stores information about the screen.
"""
def __init__(self,
name,
function,
predict_function=None,
modal=False,
zorder=0,
tag=None):
# The name of this screen.
if isinstance(name, basestring):
name = tuple(name.split())
self.name = name
screens[name] = self
# The function that is called to display this screen.
self.function = function
# The function that is called to predict the images that
# will be used by the screen.
self.predict_function = predict_function
# Are we modal? (A modal screen ignores screens under it.)
self.modal = modal
# Our zorder.
self.zorder = zorder
# The tag associated with the screen.
self.tag = tag or name[0]
class ScreenDisplayable(renpy.display.layout.Container):
"""
A screen is a collection of widgets that are displayed together. This
class is responsible for managing the display of a screen.
"""
no_save = [ 'screen' ]
def after_setstate(self):
self.screen = screens[self.screen_name]
def __init__(self, screen, tag, layer, widget_properties={}, scope={}, **properties):
super(ScreenDisplayable, self).__init__(**properties)
# The screen, and it's name. (The name is used to look up the
# screen on save.)
self.screen = screen
self.screen_name = screen.name
# The tag this and layer screen was displayed with.
self.tag = tag
self.layer = layer
# The scope associated with this statement. This is passed in
# as keyword arguments to the displayable.
self.scope = renpy.python.RevertableDict(scope)
# The child associated with this screen.
self.child = None
# Widget properties given to this screen the last time it was
# shown.
self.widget_properties = widget_properties
old_screen = get_screen(tag, layer)
# A map from name to the widget with that name.
self.widgets = { }
# A map from name to the transform with that name. (This is
# taken from the old version of the screen, if it exists.
if old_screen:
self.transforms = old_screen.transforms
else:
self.transforms = { }
# What widgets and transforms were the last time this screen was
# updated. Used to communicate with the ui module, and only
# valid during an update - not used at other times.
self.old_widgets = None
self.old_transforms = None
# The current transform event, and the last transform event to
# be processed.
self.current_transform_event = None
def visit(self):
return [ self.child ]
def per_interact(self):
renpy.display.render.redraw(self, 0)
self.update()
def set_transform_event(self, event):
super(ScreenDisplayable, self).set_transform_event(event)
self.current_transform_event = event
def _hide(self, st, at, kind):
rv = None
for i in self.transforms:
c = self.transforms[i]._hide(st, at, kind)
if c is not None:
self.transforms[i] = c
rv = self
self.current_transform_event = kind
renpy.display.render.redraw(self, 0)
return rv
def update(self):
# Update _current_screen
global _current_screen
old_screen = _current_screen
_current_screen = self
# Cycle widgets and transforms.
self.old_widgets = self.widgets
self.old_transforms = self.transforms
self.widgets = { }
self.transforms = { }
# Render the child.
old_ui_screen = renpy.ui.screen
renpy.ui.screen = self
renpy.ui.detached()
self.child = renpy.ui.fixed()
self.children = [ self.child ]
self.scope["_scope"] = self.scope
self.scope["_name"] = 0
self.screen.function(**self.scope)
renpy.ui.close()
renpy.ui.screen = old_ui_screen
_current_screen = old_screen
# Visit all the children, to get them started.
self.child.visit_all(lambda c : c.per_interact())
# Finish up.
self.old_widgets = None
self.old_transforms = None
if self.current_transform_event:
for i in self.child.children:
i.set_transform_event(self.current_transform_event)
self.current_transform_event = None
return self.widgets
def render(self, w, h, st, at):
if not self.child:
self.update()
return renpy.display.render.render(self.child, w, h, st, at)
def get_placement(self):
if not self.child:
self.update()
return self.child.get_placement()
def event(self, ev, x, y, st):
global _current_screen
old_screen = _current_screen
_current_screen = self
rv = self.child.event(ev, x, y, st)
_current_screen = old_screen
if rv is not None:
return rv
if self.screen.modal:
raise renpy.display.core.IgnoreEvent()
# The name of the screen that is currently being displayed, or
# None if no screen is being currently displayed.
_current_screen = None
# A map from screen name to screen object.
screens = { }
def define_screen(*args, **kwargs):
"""
:doc: screens
:args: (name, function, modal=True, zorder=0, tag=None)
Defines a screen with `name`, which should be a string.
`function`
The function that is called to display the screen. The
function is called with the screen scope as keyword
arguments. It should ignore additional keyword arguments.
The function should call the ui functions to add things to the
screen.
`modal`
Determines if this screen is modal. A modal screen
prevents screens underneath it from receiving input events.
`zorder`
Controls the order in which screens are displayed. A screen
with a greater zorder number is displayed above screens with a
lesser zorder number.
`tag`
The tag associated with this screen. When the screen is shown,
it replaces any other screen with the same tag. The tag
defaults to the name of the screen.
"""
Screen(*args, **kwargs)
def get_screen(name, layer="screens"):
"""
:doc: screens
Returns the ScreenDisplayable with the given `tag`, on
`layer`. If no displayable with the tag is not found, it is
interpreted as screen name. If it's still not found, None is returned.
"""
if isinstance(name, basestring):
name = tuple(name.split())
tag = name[0]
sl = renpy.exports.scene_lists()
sd = sl.get_displayable_by_tag(layer, tag)
if sd is None:
sd = sl.get_displayable_by_name(layer, name)
return sd
def has_screen(name):
"""
Returns true if a screen with the given name exists.
"""
if not isinstance(name, tuple):
name = tuple(name.split())
return name in screens
def show_screen(_screen_name, _layer='screens', _tag=None, _widget_properties={}, _transient=False, **kwargs):
"""
:doc: screens
The programmatic equivalent of the show screen statement.
Shows the named screen.
`_screen_name`
The name of the screen to show.
`_layer`
The layer to show the screen on.
`_tag`
The tag to show the screen with. If not specified, defaults to
the tag associated with the screen. It that's not specified,
defaults to the name of the screen.,
`_widget_properties`
A map from the id of a widget to a property name -> property
value map. When a widget with that id is shown by the screen,
the specified properties are added to it.
`_transient`
If true, the screen will be automatically hidden at the end of
the current interaction.
Keyword arguments not beginning with underscore (_) are used to
initialize the screen's scope.
"""
name = _screen_name
if not isinstance(name, tuple):
name = tuple(name.split())
if not name in screens:
raise Exception("Screen %r is not known.\n", (name,))
screen = screens[name]
if _tag is None:
_tag = screen.tag
d = ScreenDisplayable(screen, _tag, _layer, _widget_properties, kwargs)
renpy.exports.show(name, tag=_tag, what=d, layer=_layer, zorder=screen.zorder, transient=_transient, munge_name=False)
def hide_screen(tag, layer='screens'):
"""
:doc: screens
The programmatic equivalent of the hide screen statement.
Hides the screen with `tag` on `layer`.
"""
tag = tag.split()[0]
renpy.exports.hide(tag, layer=layer)
def use_screen(_screen_name, _name=(), **kwargs):
name = _screen_name
if not isinstance(name, tuple):
name = tuple(name.split())
if name not in screens:
raise Exception("Screen %r is not known." % name)
screen = screens[name]
scope = kwargs["_scope"].copy() or { }
scope.update(kwargs)
scope["_scope"] = scope
scope["_name"] = _name
screen.function(**scope)
def current_screen():
return _current_screen
def get_widget(screen, id, layer='screens'):
"""
:doc: screens
From the `screen` on `layer`, returns the widget with
`id`. Returns None if the screen doesn't exist, or there is no
widget with that id on the screen.
"""
if screen is None:
screen = current_screen()
else:
screen = get_screen(screen, layer)
if not isinstance(screen, ScreenDisplayable):
return None
if screen.child is None:
screen.update()
rv = screen.widgets.get(id, None)
return rv
+983
View File
@@ -0,0 +1,983 @@
# Copyright 2004-2010 PyTom <pytom@bishoujo.us>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import renpy
import pygame
import math
import weakref
import time
from renpy.display.render import blit_lock, IDENTITY, BLIT, DISSOLVE, IMAGEDISSOLVE, PIXELLATE
# A map from cached surface to rle version of cached surface.
rle_cache = weakref.WeakKeyDictionary()
class Clipper(object):
"""
This is used to calculate the clipping rectangle and update rectangles
used for a particular draw of the screen.
"""
def __init__(self):
# Lists of (x0, y0, x1, y1, clip, surface, transform) tuples,
# representing how a displayable is drawn to the screen.
self.blits = [ ]
self.old_blits = [ ]
# Sets of (x0, y0, x1, y1) tuples, representing areas that
# aren't part of any displayable.
self.forced = set()
self.old_forced = set()
# The set of surfaces that have been mutated recently.
self.mutated = set()
def compute(self, full_redraw):
"""
This returns a clipping rectangle, and a list of update rectangles
that cover the changes between the old and new frames.
"""
# First, get things out of the fields, and update them. This
# allows us to just return without having to do any cleanup
# code.
bl0 = self.old_blits
bl1 = self.blits
old_forced = self.old_forced
forced = self.forced
mutated = self.mutated
self.old_blits = bl1
self.blits = [ ]
self.old_forced = forced
self.forced = set()
self.mutated = set()
sw = renpy.config.screen_width
sh = renpy.config.screen_height
sa = sw * sh
# A tuple representing the size of the fullscreen.
fullscreen = (0, 0, sw, sh)
# Check to see if a full redraw has been forced, and return
# early.
if full_redraw:
return fullscreen, [ fullscreen ]
# Quick checks to see if a dissolve is happening, or something like
# that.
changes = forced | old_forced
if fullscreen in changes:
return fullscreen, [ fullscreen ]
# Compute the differences between the two sets, and add those
# to changes.
i0 = 0
i1 = 0
bl1set = set(bl1)
while True:
if i0 >= len(bl0) or i1 >= len(bl1):
break
b0 = bl0[i0]
b1 = bl1[i1]
if b0 == b1:
if id(b0[5]) in mutated:
changes.add(b0[:5])
i0 += 1
i1 += 1
elif b0 not in bl1set:
changes.add(b0[:5])
i0 += 1
else:
changes.add(b1[:5])
i1 += 1
changes.update(i[:5] for i in bl0[i0:])
changes.update(i[:5] for i in bl1[i1:])
# No changes? Quit.
if not changes:
return None, [ ]
# Compute the sizes of the updated rectangles.
sized = [ ]
for x0, y0, x1, y1, (sx0, sy0, sx1, sy1) in changes:
if x0 < sx0:
x0 = sx0
if y0 < sy0:
y0 = sy0
if x1 > sx1:
x1 = sx1
if y1 > sy1:
y1 = sy1
w = x1 - x0
h = y1 - y0
if w <= 0 or h <= 0:
continue
area = w * h
if area >= sa:
return fullscreen, [ fullscreen ]
sized.append((area, x0, y0, x1, y1))
sized.sort()
# The list of non-contiguous updates.
noncont = [ ]
# The total area of noncont.
nca = 0
# Pick the largest area, merge with all overlapping smaller areas, repeat
# until no merge possible.
while sized:
area, x0, y0, x1, y1 = sized.pop()
merged = False
if nca + area >= sa:
return (0, 0, sw, sh), [ (0, 0, sw, sh) ]
i = 0
while i < len(sized):
iarea, ix0, iy0, ix1, iy1 = sized[i]
if (x0 <= ix0 <= x1 or x0 <= ix1 <= x1) and \
(y0 <= iy0 <= y1 or y0 <= iy1 <= y1):
merged = True
x0 = min(x0, ix0)
x1 = max(x1, ix1)
y0 = min(y0, iy0)
y1 = max(y1, iy1)
area = (x1 - x0) * (y1 - y0)
sized.pop(i)
else:
i += 1
if merged:
sized.append((area, x0, y0, x1, y1))
else:
noncont.append((x0, y0, x1, y1))
nca += area
if not noncont:
return None, [ ]
x0, y0, x1, y1 = noncont.pop()
x0 = int(x0)
y0 = int(y0)
x1 = int(math.ceil(x1))
y1 = int(math.ceil(y1))
# A list of (x, y, w, h) tuples for each update.
updates = [ (x0, y0, x1 - x0, y1 - y0) ]
for ix0, iy0, ix1, iy1 in noncont:
ix0 = int(ix0)
iy0 = int(iy0)
ix1 = int(math.ceil(ix1))
iy1 = int(math.ceil(iy1))
x0 = min(x0, ix0)
y0 = min(y0, iy0)
x1 = max(x1, ix1)
y1 = max(y1, iy1)
updates.append((ix0, iy0, ix1 - ix0, iy1 - iy0))
return (x0, y0, x1 - x0, y1 - y0), updates
clippers = [ Clipper() ]
def draw_special(what, dest, x, y):
"""
This handles the special drawing operations, such as dissolve and
image dissolve. `x` and `y` are the offsets of the thing to be drawn
relative to the destination rectangle, and are always negative.
"""
dw, dh = dest.get_size()
w = min(dw, what.width + x)
h = min(dh, what.height + y)
if w <= 0 or h <= 0:
return
if what.operation == DISSOLVE:
bottom = what.children[0][0].render_to_texture(what.operation_alpha)
top = what.children[1][0].render_to_texture(what.operation_alpha)
if what.operation_alpha:
target = renpy.display.pgrender.surface((w, h), True)
else:
target = dest.subsurface((0, 0, w, h))
renpy.display.module.blend(
bottom.subsurface((-x, -y, w, h)),
top.subsurface((-x, -y, w, h)),
target,
int(what.operation_complete * 255))
if what.operation_alpha:
dest.blit(target, (0, 0))
elif what.operation == IMAGEDISSOLVE:
image = what.children[0][0].render_to_texture(what.operation_alpha)
bottom = what.children[1][0].render_to_texture(what.operation_alpha)
top = what.children[2][0].render_to_texture(what.operation_alpha)
if what.operation_alpha:
target = renpy.display.pgrender.surface((w, h), True)
else:
target = dest.subsurface((0, 0, w, h))
ramplen = what.operation_parameter
ramp = "\x00" * 256
for i in xrange(0, ramplen):
ramp += chr(255 * i / ramplen)
ramp += "\xff" * 256
step = int( what.operation_complete * (256 + ramplen) )
ramp = ramp[step:step+256]
renpy.display.module.imageblend(
bottom.subsurface((-x, -y, w, h)),
top.subsurface((-x, -y, w, h)),
target,
image.subsurface((-x, -y, w, h)),
ramp)
if what.operation_alpha:
dest.blit(target, (0, 0))
elif what.operation == PIXELLATE:
surf = what.children[0][0].render_to_texture(False)
px = what.operation_parameter
renpy.display.module.pixellate(
surf.subsurface((-x, -y, w, h)),
dest.subsurface((0, 0, w, h)),
px, px, px, px)
else:
raise Exception("Unknown operation: %d" % what.operation)
def draw(dest, clip, what, xo, yo, screen):
"""
This is the simple draw routine, which only works when alpha is 1.0
and the matrices are None. If those aren't the case, draw_complex
is used instead.
`dest` - Either a destination surface, or a clipper.
`clip` - If None, we should draw. Otherwise we should clip, and this is
the rectangle to clip to.
`what` - The Render or Surface we're drawing to.
`xo` - The X offset.
`yo` - The Y offset.
`screen` - True if this is a blit to the screen, False otherwise.
"""
if not isinstance(what, renpy.display.render.Render):
# Pixel-Aligned blit.
if isinstance(xo, int) and isinstance(yo, int):
if screen:
what = rle_cache.get(what, what)
if clip:
w, h = what.get_size()
dest.blits.append((xo, yo, xo + w, yo + h, clip, what, None))
else:
try:
blit_lock.acquire()
dest.blit(what, (xo, yo))
finally:
blit_lock.release()
# Subpixel blit.
else:
if clip:
w, h = what.get_size()
dest.blits.append((xo, yo, xo + w, yo + h, clip, what, None))
else:
renpy.display.module.subpixel(what, dest, xo, yo)
return
# Deal with draw functions.
if what.operation != BLIT:
xo = int(xo)
yo = int(yo)
if clip:
dx0, dy0, dx1, dy1 = clip
dw = dx1 - dx0
dh = dy1 - dy0
else:
dw, dh = dest.get_size()
if xo >= 0:
newx = 0
subx = xo
else:
newx = xo
subx = 0
if yo >= 0:
newy = 0
suby = yo
else:
newy = yo
suby = 0
if subx >= dw or suby >= dh:
return
# newx and newy are the offset of this render relative to the
# subsurface. They can only be negative or 0, as otherwise we
# would make a smaller subsurface.
subw = min(dw - subx, what.width + newx)
subh = min(dh - suby, what.height + newy)
if subw <= 0 or subh <= 0:
return
if clip:
dest.forced.add((subx, suby, subx + subw, suby + subh, clip))
else:
newdest = dest.subsurface((subx, suby, subw, subh))
# what.draw_func(newdest, newx, newy)
draw_special(what, newdest, newx, newy)
return
# Deal with clipping, if necessary.
if what.clipping:
if clip:
cx0, cy0, cx1, cy1 = clip
cx0 = max(cx0, xo)
cy0 = max(cy0, yo)
cx1 = min(cx1, xo + what.width)
cy1 = min(cy1, yo + what.height)
if cx0 > cx1 or cy0 > cy1:
return
clip = (cx0, cy0, cx1, cy1)
else:
# After this code, x and y are the coordinates of the subsurface
# relative to the destination. xo and yo are the offset of the
# upper-left corner relative to the subsurface.
if xo >= 0:
x = xo
xo = 0
else:
x = 0
# xo = xo
if yo >= 0:
y = yo
yo = 0
else:
y = 0
# yo = yo
dw, dh = dest.get_size()
width = min(dw - x, what.width + xo)
height = min(dh - y, what.height + yo)
if width < 0 or height < 0:
return
dest = dest.subsurface((x, y, width, height))
# Deal with alpha and transforms by passing them off to draw_transformed.
if what.alpha != 1 or what.forward:
for child, cxo, cyo, focus, main in what.visible_children:
draw_transformed(dest, clip, child, xo + cxo, yo + cyo,
what.alpha, what.forward, what.reverse)
return
for child, cxo, cyo, focus, main in what.visible_children:
draw(dest, clip, child, xo + cxo, yo + cyo, screen)
def draw_transformed(dest, clip, what, xo, yo, alpha, forward, reverse):
# If our alpha has hit 0, don't do anything.
if alpha <= 0.003: # (1 / 256)
return
if forward is None:
forward = IDENTITY
reverse = IDENTITY
if not isinstance(what, renpy.display.render.Render):
# Figure out where the other corner of the transformed surface
# is on the screen.
sw, sh = what.get_size()
if clip:
dx0, dy0, dx1, dy1 = clip
dw = dx1 - dx0
dh = dy1 - dy0
else:
dw, dh = dest.get_size()
x0, y0 = 0.0, 0.0
x1, y1 = reverse.transform(sw, 0.0)
x2, y2 = reverse.transform(sw, sh)
x3, y3 = reverse.transform(0.0, sh)
minx = math.floor(min(x0, x1, x2, x3) + xo)
maxx = math.ceil(max(x0, x1, x2, x3) + xo)
miny = math.floor(min(y0, y1, y2, y3) + yo)
maxy = math.ceil(max(y0, y1, y2, y3) + yo)
if minx < 0:
minx = 0
if miny < 0:
miny = 0
if maxx > dw:
maxx = dw
if maxy > dh:
maxy = dh
if minx > dw or miny > dh:
return
cx, cy = forward.transform(minx - xo, miny - yo)
if clip:
dest.blits.append(
(minx, miny, maxx + dx0, maxy + dy0, clip, what,
(cx, cy,
forward.xdx, forward.ydx,
forward.xdy, forward.ydy,
alpha)))
else:
dest = dest.subsurface((minx, miny, maxx - minx, maxy - miny))
renpy.display.module.transform(
what, dest,
cx, cy,
forward.xdx, forward.ydx,
forward.xdy, forward.ydy,
alpha, True)
return
if what.clipping:
if reverse.xdy or reverse.ydx:
draw_transformed(dest, clip, what.pygame_surface(True), xo, yo, alpha, forward, reverse)
return
# raise Exception("Non-axis-aligned clipping is not supported.")
width = what.width * reverse.xdx
height = what.height * reverse.ydy
if clip:
cx0, cy0, cx1, cy1 = clip
cx0 = max(cx0, xo)
cy0 = max(cy0, yo)
cx1 = min(cx1, xo + width)
cy1 = min(cy1, yo + height)
if cx0 > cx1 or cy0 > cy1:
return
clip = (cx0, cy0, cx1, cy1)
else:
# After this code, x and y are the coordinates of the subsurface
# relative to the destination. xo and yo are the offset of the
# upper-left corner relative to the subsurface.
if xo >= 0:
x = xo
xo = 0
else:
x = 0
# xo = xo
if yo >= 0:
y = yo
yo = 0
else:
y = 0
# yo = yo
dw, dh = dest.get_size()
width = min(dw - x, width + xo)
height = min(dh - y, height + yo)
if width < 0 or height < 0:
return
dest = dest.subsurface((x, y, width, height))
if what.draw_func:
child = what.pygame_surface(True)
draw_transformed(dest, clip, child, xo, yo, alpha, forward, reverse)
# raise Exception("Using a draw_func on a transformed surface is not supported.")
for child, cxo, cyo, focus, main in what.visible_children:
cxo, cyo = reverse.transform(cxo, cyo)
if what.forward:
child_forward = forward * what.forward
child_reverse = what.reverse * reverse
else:
child_forward = forward
child_reverse = reverse
draw_transformed(dest, clip, child, xo + cxo, yo + cyo, alpha * what.alpha, child_forward, child_reverse)
def do_draw_screen(screen_render, full_redraw):
"""
Draws the render produced by render_screen to the screen.
"""
yoffset = xoffset = 0
screen_render.is_opaque()
clip = (xoffset, yoffset, xoffset + screen_render.width, yoffset + screen_render.height)
clipper = clippers[0]
draw(clipper, clip, screen_render, xoffset, yoffset, True)
cliprect, updates = clipper.compute(full_redraw)
if cliprect is None:
return [ ]
x, y, w, h = cliprect
dest = pygame.display.get_surface().subsurface(cliprect)
draw(dest, None, screen_render, -x, -y, True)
return updates
class SWDraw(object):
"""
This uses the software renderer to draw to the screen.
"""
def __init__(self):
# Should we draw the screen?
self.suppressed_blit = False
# The earliest time at which the next frame can be redrawn.
self.next_frame = 0
# Mouse re-drawing.
self.mouse_location = None
self.mouse_backing = None
self.mouse_backing_pos = None
self.mouse_info = None
# Is the mouse currently visible?
self.mouse_old_visible = None
# This is used to cache the surface->texture operation.
self.texture_cache = weakref.WeakKeyDictionary()
# This is used to display video to the screen.
self.fullscreen_surface = None
# Info.
self.info = { "renderer" : "sw" }
pygame.display.init()
renpy.display.interface.post_init()
# Scaling?
renpy.display.scale.init()
def set_mode(self, virtual_size, physical_size, fullscreen):
width, height = virtual_size
fsflag = 0
if fullscreen:
fsflag = pygame.FULLSCREEN
# If a window exists of the right size and flags, use it. Otherwise,
# make our own window.
old_window = pygame.display.get_surface()
if ((old_window is not None) and
(old_window.get_size() == (width, height)) and
(old_window.get_flags() & pygame.FULLSCREEN == fsflag)):
self.window = old_window
else:
self.window = renpy.display.pgrender.set_mode(
(width, height),
fsflag,
32)
# Should we redraw the screen from scratch?
self.full_redraw = True
# The surface used to display fullscreen video.
self.fullscreen_surface = renpy.display.scale.real(self.window)
# Reset this on a mode change.
self.mouse_location = None
self.mouse_backing = None
self.mouse_backing_pos = None
self.mouse_info = None
return True
# private
def show_mouse(self, pos, info):
"""
Actually shows the mouse.
"""
self.mouse_location = pos
self.mouse_info = info
mxo, myo, tex = info
mx, my = pos
mw, mh = tex.get_size()
bx = mx - mxo
by = my - myo
self.mouse_backing_pos = (bx, by)
self.mouse_backing = renpy.display.pgrender.surface((mw, mh), False)
self.mouse_backing.blit(self.window, (0, 0), (bx, by, mw, mh))
self.window.blit(tex, (bx, by))
return bx, by, mw, mh
# private
def hide_mouse(self):
"""
Actually hides the mouse.
"""
size = self.mouse_backing.get_size()
self.window.blit(self.mouse_backing, self.mouse_backing_pos)
rv = self.mouse_backing_pos + size
self.mouse_backing = None
self.mouse_backing_pos = None
self.mouse_location = None
return rv
# private
def draw_mouse(self, show_mouse):
"""
This draws the mouse to the screen, if necessary. It uses the
buffer to minimize the amount of the screen that needs to be
drawn, and only redraws if the mouse has actually been moved.
"""
hardware, x, y, tex = renpy.game.interface.get_mouse_info()
if self.mouse_old_visible != hardware:
pygame.mouse.set_visible(hardware)
self.mouse_old_visible = hardware
# The rest of this is for the software mouse.
if self.suppressed_blit:
return [ ]
if not show_mouse:
tex = None
info = (x, y, tex)
pos = pygame.mouse.get_pos()
if (pos == self.mouse_location and tex and info == self.mouse_info):
return [ ]
updates = [ ]
if self.mouse_location:
updates.append(self.hide_mouse())
if tex and pos and renpy.game.interface.focused:
updates.append(self.show_mouse(pos, info))
return updates
def update_mouse(self):
"""
Draws the mouse, and then updates the screen.
"""
updates = self.draw_mouse(True)
if updates:
pygame.display.update(updates)
def mouse_event(self, ev):
x, y = getattr(ev, 'pos', pygame.mouse.get_pos())
return x, y
def get_mouse_pos(self):
return pygame.mouse.get_pos()
def screenshot(self):
"""
Returns a pygame surface containing a screenshot.
"""
return self.window
def should_redraw(self, needs_redraw, first_pass):
"""
Uses the framerate to determine if we can and should redraw.
"""
if not needs_redraw:
return False
framerate = renpy.config.framerate
if framerate is None:
return True
next_frame = self.next_frame
now = pygame.time.get_ticks()
frametime = 1000.0 / framerate
# Handle timer rollover.
if next_frame > now + frametime:
next_frame = now
# It's not yet time for the next frame.
if now < next_frame and not first_pass:
return False
# Otherwise, it is. Schedule the next frame.
# if next_frame + frametime < now:
next_frame = now + frametime
# else:
# next_frame += frametime
self.next_frame = next_frame
return True
def draw_screen(self, surftree, fullscreen_video):
"""
Draws the screen.
"""
if not fullscreen_video:
updates = [ ]
updates.extend(self.draw_mouse(False))
damage = do_draw_screen(surftree, self.full_redraw)
if damage:
updates.extend(damage)
self.full_redraw = False
updates.extend(self.draw_mouse(True))
pygame.display.update(updates)
else:
self.full_redraw = True
renpy.display.render.kill_old_screen()
renpy.display.focus.take_focuses()
self.suppressed_blit = fullscreen_video
def render_to_texture(self, render, alpha):
rv = renpy.display.pgrender.surface((render.width, render.height), alpha)
draw(rv, None, render, 0, 0, False)
return rv
def is_pixel_opaque(self, what, x, y):
if x < 0 or y < 0 or x >= what.width or y >= what.height:
return 0
for (child, xo, yo, focus, main) in what.visible_children:
cx = x - xo
cy = y - yo
if what.forward:
cx, cy = what.forward.transform(cx, cy)
if isinstance(child, renpy.display.render.Render):
if self.is_pixel_opaque(child, x, y):
return True
else:
cw, ch = child.get_size()
if cx >= cw or cy >= ch:
return False
if not child.get_masks()[3] or child.get_at((cx, cy))[3]:
return True
return False
def mutated_surface(self, surf):
"""
Called to indicate that the given surface has changed.
"""
for i in clippers:
i.mutated.add(id(surf))
if surf in rle_cache:
del rle_cache[surf]
def load_texture(self, surf, transient=False):
"""
Creates a texture from the surface. In the software implementation,
the only difference between a texture and a surface is that a texture
is in the RLE cache.
"""
if transient:
return surf
if renpy.game.less_memory:
return surf
if surf not in rle_cache:
rle_surf = renpy.display.pgrender.copy_surface(surf)
rle_surf.set_alpha(255, pygame.RLEACCEL)
self.mutated_surface(rle_surf)
rle_cache[surf] = rle_surf
return surf
def free_memory(self):
"""
Frees up memory.
"""
rle_cache.clear()
def quit(self):
"""
Shuts down the drawing system.
"""
pygame.display.quit()
return
def event_peek_sleep(self):
"""
Wait a little bit so the CPU doesn't speed up.
"""
time.sleep(.0001)
+129 -262
View File
@@ -49,7 +49,8 @@ text_tags = dict(
)
text_tags[""] = True
def color(s):
"""
This function converts a hexcode into a color/alpha tuple. Leading
@@ -90,6 +91,7 @@ def color(s):
return (r, g, b, a)
class TextStyle(object):
"""
This is used to represent the style of text that will be displayed
@@ -188,6 +190,7 @@ class TextStyle(object):
def length(self, text):
return len(text)
class WidgetStyle(object):
"""
@@ -618,25 +621,31 @@ class Text(renpy.display.core.Displayable):
A displayable that can format and display text on the screen.
"""
nosave = [ 'laidout', 'laidout_lineheights', 'laidout_linewidths',
'laidout_width', 'laidout_height', 'laidout_start',
'laidout_length', 'laidout_hyperlinks', 'laidout_lines_last',
'width', 'tokens', 'children', 'child_pos']
__version__ = 2
# This can keep around a reference to a Font, which prevents
# us from saving.
nosave = [ 'laidout' ]
__version__ = 3
def after_upgrade(self, version):
if version <= 0:
if version < 1:
self.activated = None
if version <= 1:
if version < 2:
self.slow_done_time = None
if version < 3:
self.ctc = None
self.slow_start = 0
self.slow_end = None
def after_setstate(self):
self.update()
self.laidout = None
self.needs_update = True
def __init__(self, text, slow=None, slow_done=None,
slow_start=0, pause=None, tokenized=False,
style='default', **properties):
style='default', replaces=None, **properties):
"""
@param text: The text that will be displayed on the screen.
@@ -655,13 +664,10 @@ class Text(renpy.display.core.Displayable):
@param tokenized: True if the text is already tokenized.
"""
super(Text, self).__init__(style=style, **properties)
self.text = text
self.pause = pause
self.keep_pausing = False
self.pause_length = None
self.tokenized = tokenized
if slow or slow is None:
@@ -672,6 +678,8 @@ class Text(renpy.display.core.Displayable):
self.slow_param = slow
self.slow_done = slow_done
self.slow_start = slow_start
self.slow_end = None
# The time when slow_done was called.
self.slow_done_time = None
@@ -680,153 +688,92 @@ class Text(renpy.display.core.Displayable):
self.tokens = None
# The duration of each pause, or None if the pause is infinite.
self.pause_lengths = [ ]
# The width we've been laid out for.
self.width = -1
self.update(redraw=False)
# The displayable that was added to us to supporte nestled ctc.
self.ctc = None
if isinstance(replaces, Text):
self.slow = replaces.slow
self.slow_param = replaces.slow_param
self.slow_start = replaces.slow_start
self.slow_end = replaces.slow_end
self.slow_done = replaces.slow_done
self.slow_done_time = replaces.slow_done_time
self.ctc = replaces.ctc
self.needs_update = True
def per_interact(self):
self.update()
def set_ctc(self, ctc):
"""
Sets the nestled CTC indicator of this text.
"""
self.ctc = ctc
self.needs_update = True
renpy.display.render.redraw(self, 0)
def set_text(self, new_text):
"""
Changes the text display by this object to new_text.
"""
self.text = new_text
self.update()
self.needs_update = True
renpy.display.render.redraw(self, 0)
def set_style(self, style):
"""
Changes the style assocated with this object.
"""
self.style = style
self.update()
def update(self, redraw=True, retokenize=True):
"""
This is called after this widget has been updated by
set_text or set_style.
"""
self.laidout = None
self.child_pos = [ ]
if self.text:
text = self.text
else:
text = u" "
def update(self):
"""
This is called to break this displayable up into tokens.
"""
if not self.needs_update:
return True
# Annoyingly, we can't tokenize until styles get built.
if not renpy.style.styles_built:
return
if retokenize:
if not self.tokenized:
self.tokens = input_tokenizer(text, self.style)
else:
self.tokens = self.text
new_tokens = [ ]
fasts = 0
self.no_wait = False # W0201
self.no_wait_once = False # W0201
self.no_wait_done = False # W0201
self.pauses = 0 # W0201
self.pause_lengths = [ ] # W0201
self.needs_update = False
for i in self.tokens[0]:
type, text = i
if type == "tag":
if text == "p":
new_tokens.append(("tag", 'w'))
new_tokens.append(("newline", "\n"))
self.pauses += 1
self.pause_lengths.append(None)
self.laidout = None
self.child_pos = [ ]
continue
if self.tokenized:
self.tokens = self.text
elif text.startswith("p="):
new_tokens.append(("tag", 'w=' + text[2:]))
new_tokens.append(("newline", "\n"))
self.pauses += 1
self.pause_lengths.append(float(text[2:]))
else:
text = self.text
continue
if self.slow_end is not None:
text = text[:self.slow_end]
elif text == "nw":
self.no_wait = True
if not text:
text = " "
elif text == "fast":
self.no_wait = False
fasts += 1
self.pauses = 0
self.pause_lengths = [ ]
elif text == "w":
self.pauses += 1
self.pause_lengths.append(None)
# Exists and is not 0.
if self.slow_start:
text = text[:self.slow_start] + "{_start}" + text[self.slow_start:]
elif text.startswith("w="):
self.pauses += 1
self.pause_lengths.append(float(text[2:]))
new_tokens.append(i)
self.tokens = input_tokenizer(text, self.style)
self.tokens[0] = new_tokens
# Add the CTC indicator.
if self.ctc is not None:
self.tokens.append([ ("widget", self.ctc) ])
if self.pause is not None:
pause = self.pause
new_tokens = [ ]
for i in self.tokens[0]:
new_tokens.append(i)
type, text = i
if type == "tag":
if text == "fast":
fasts -= 1
if text == "nw":
new_tokens.pop()
# If we have a fast to go, then ignore keep_pausing.
if fasts:
continue
if text == "nw":
self.no_wait_once = True
break
elif text == "w":
if pause == 0:
self.keep_pausing |= True
self.pause_length = None
break
else:
pause -= 1
elif text[:2] == "w=":
if pause == 0:
self.keep_pausing |= True
self.pause_length = float(text[2:])
break
else:
pause -= 1
self.tokens[0] = new_tokens
if not self.slow:
self.no_wait = False
self.no_wait_once = False
# Postprocess the tokens list to create widgets, as necessary.
self.children = [ ] # W0201
@@ -835,52 +782,33 @@ class Text(renpy.display.core.Displayable):
for tl in self.tokens:
ntl = [ ]
tliter = iter(tl)
for kind, i in tl:
if kind == "tag":
if i.startswith("image="):
name = i[6:]
for kind, i in tliter:
kind = "widget"
i = renpy.easy.displayable(name)
if kind == "tag" and i.startswith("image="):
m = re.match(r'image=(.*)', i)
if not m:
raise Exception('Image tag %s could not be parsed.' % i)
i = renpy.easy.displayable(m.group(1))
ntl.append(("widget", i))
if kind == "widget":
self.children.append(i)
else:
if kind == "widget":
self.children.append(i)
ntl.append((kind, i))
ntl.append((kind, i))
newtokens.append(ntl)
self.tokens = newtokens
if redraw:
renpy.display.render.redraw(self, 0)
def event(self, ev, x, y, st):
"""
Space, Enter, or Click ends slow, if it's enabled.
"""
if (self.slow_done_time is not None) and (self.pause_length is not None):
if st > (self.slow_done_time + self.pause_length):
return True
else:
renpy.game.interface.timeout((self.slow_done_time + self.pause_length) - st)
if self.slow and self.style.slow_abortable and renpy.display.behavior.map_event(ev, "dismiss"):
self.slow = False
self.call_slow_done(st)
raise renpy.display.core.IgnoreEvent()
if self.no_wait_done:
return False
for child, xo, yo in self.child_pos:
rv = child.event(ev, x - xo, y - yo, st)
@@ -902,14 +830,10 @@ class Text(renpy.display.core.Displayable):
renpy.display.render.redraw(self, 0)
return rv
def visit(self):
if self.tokens is None:
self.update()
self.update()
return self.children
def layout(self, width, time):
"""
@@ -918,12 +842,11 @@ class Text(renpy.display.core.Displayable):
self.laidout_height.
"""
self.update()
if self.laidout and self.width == width:
return
if self.tokens is None:
self.update()
# Set this, so caching works.
self.width = width
@@ -948,13 +871,6 @@ class Text(renpy.display.core.Displayable):
self.laidout_hyperlinks = [ ] # W0201
# if not self.text:
# text = " "
# else:
# text = self.text
# for i in re.split(r'( |\{[^{}]+\}|\{\{|\n)', text):
tokens = [ ]
for l in self.tokens:
tokens.extend(l)
@@ -980,11 +896,15 @@ class Text(renpy.display.core.Displayable):
continue
if i == "w":
if i == "w" or i.startswith("w="):
# Automatically closes.
continue
elif i == "p" or i.startswith("p="):
# Automatically closes.
triples.append(("newline", tsl[-1], "\n"))
continue
elif i == "nw":
# Automatically closes.
continue
@@ -994,18 +914,18 @@ class Text(renpy.display.core.Displayable):
continue
elif i == "fast":
# Automatically closes.
continue
elif i == "_start":
# Automatically closes.
triples.append(("start", tsl[-1], ""))
continue
elif i.startswith("a="):
m = re.match(r'a=(.*)', i)
if not m:
raise Exception('Hyperlink tag %s could not be parsed.' % i)
elif i.startswith("a="):
# TODO: check to see if we need to be focused.
target = m.group(1)
target = i[2:]
hls = renpy.config.hyperlink_styler(target)
old_prefix = hls.prefix
@@ -1077,20 +997,12 @@ class Text(renpy.display.core.Displayable):
tsl[-1].black_color = style.black_color
tsl[-1].update()
elif i.startswith("font="):
elif i.startswith("font"):
m = re.match(r'font=(.*)', i)
if not m:
raise Exception('Font tag %s could not be parsed.' % i)
tsl[-1].font = m.group(1)
tsl[-1].font = i[5:]
tsl[-1].update()
elif i.startswith("size"):
elif i.startswith("size="):
m = re.match(r'size=(\+|-|)(\d+)', i)
@@ -1105,14 +1017,9 @@ class Text(renpy.display.core.Displayable):
tsl[-1].size = int(m.group(2))
tsl[-1].update()
elif i.startswith("color"):
elif i.startswith("color="):
m = re.match(r'color=(\#?[a-fA-F0-9]+)', i)
if not m:
raise Exception('Color tag %s could not be parsed.' % i)
tsl[-1].color = color(m.group(1))
tsl[-1].color = color(i[6:])
tsl[-1].update()
else:
@@ -1134,7 +1041,6 @@ class Text(renpy.display.core.Displayable):
elif kind == "word":
triples.append(("word", tsl[-1], i))
elif kind == "widget":
pass
@@ -1172,7 +1078,6 @@ class Text(renpy.display.core.Displayable):
if not l:
l.append(('word', tsl[-1], ' '))
justify = self.style.justify
for l in linetriples:
@@ -1209,7 +1114,6 @@ class Text(renpy.display.core.Displayable):
if oldts:
line.append((oldts, cur))
if renpy.config.rtl:
@@ -1253,50 +1157,9 @@ class Text(renpy.display.core.Displayable):
# For the newline.
self.laidout_length += 1
def get_simple_length(self):
def render_pass(self, dest_render, dest_surface, xo, yo, color, black_color, user_colors, length, time, at, child_pos, add_focus, expand):
"""
Returns a simple length of the text in the first segment of
the tokens. Doesn't use the same algorithm as get_laidout_length,
so isn't suitable for slow_start.
"""
rv = 0
for tl in self.tokens:
for type, text in tl:
if type == "newline":
rv += len(text)
elif type == "word":
rv += len(text)
elif type == "space":
rv += len(text)
elif type == "widget":
rv += 1
elif type == "tag" and text == "fast":
rv = 0
return rv
def get_laidout_length(self):
"""
The (reasonably arbitrary) length this text field was laidout
to. This can only be called after the text field was drawn
(that is, after it has been on the screen for an interaction
with the user. Otherwise, it returns sys.maxint.
"""
if not self.laidout:
return sys.maxint
return self.laidout_length
def render_pass(self, r, xo, yo, color, black_color, user_colors, length, time, at, child_pos, add_focus, expand):
"""
Renders the text to r at the offsets. Color is the base color,
Renders the text at the offsets. Color is the base color,
and user_colors controls if the user can override those colors.
Returns True if all characters were rendered, or False if a
@@ -1360,10 +1223,13 @@ class Text(renpy.display.core.Displayable):
actual_y = y + max_ascent - ts.get_ascent()
if surf:
r.blit(surf, (x + xo, actual_y + yo))
if isinstance(surf, renpy.display.render.Render):
dest_render.blit(surf, (x + xo, actual_y + yo))
else:
dest_surface.blit(surf, (x + xo, actual_y + yo))
if add_focus and ts.hyperlink is not None:
r.add_focus(self, ts.hyperlink, x + xo, y + yo, sw, sh)
dest_render.add_focus(self, ts.hyperlink, x + xo, y + yo, sw, sh)
if not isinstance(text, (str, unicode)):
child_pos.append((text, x + xo, actual_y + yo))
@@ -1394,13 +1260,7 @@ class Text(renpy.display.core.Displayable):
self.slow_done = None
self.slow_done_time = st
if self.pause_length:
renpy.game.interface.timeout(self.pause_length)
if self.no_wait_once:
self.no_wait_done = True
renpy.game.interface.timeout(0)
def render(self, width, height, st, at):
if self.slow:
@@ -1450,26 +1310,33 @@ class Text(renpy.display.core.Displayable):
self.layout(width + mindsx - maxdsx, st)
if self.slow and speed:
start = max(self.slow_start, self.laidout_start)
start = self.laidout_start
length = start + int(st * speed)
else:
length = sys.maxint
self.call_slow_done(st)
final_width = self.laidout_width - mindsx + maxdsx
final_height = self.laidout_height - mindsy + maxdsy
rv = renpy.display.render.Render(self.laidout_width - mindsx + maxdsx, self.laidout_height - mindsy + maxdsy)
rv = renpy.display.render.Render(final_width, final_height)
surf = renpy.display.pgrender.surface((final_width, final_height), True)
for dsxo, dsyo in dslist:
self.render_pass(rv, dsxo - mindsx, dsyo - mindsy, self.style.drop_shadow_color, self.style.drop_shadow_color, False, length, st, at, [ ], False, 0)
self.render_pass(rv, surf, dsxo - mindsx, dsyo - mindsy, self.style.drop_shadow_color, self.style.drop_shadow_color, False, length, st, at, [ ], False, 0)
for expand, color, dsxo, dsyo in outlines:
self.render_pass(rv, dsxo - mindsx - expand, dsyo - mindsy - expand, color, color, False, length, st, at, [ ], False, expand)
self.render_pass(rv, surf, dsxo - mindsx - expand, dsyo - mindsy - expand, color, color, False, length, st, at, [ ], False, expand)
self.child_pos = [ ]
if self.render_pass(rv, -mindsx, -mindsy, self.style.color, self.style.black_color, True, length, st, at, self.child_pos, True, 0):
if self.render_pass(rv, surf, -mindsx, -mindsy, self.style.color, self.style.black_color, True, length, st, at, self.child_pos, True, 0):
if self.slow:
self.call_slow_done(st)
tex = renpy.display.draw.load_texture(surf, transient=True)
rv.blit(tex, (0, 0), index=0)
if self.slow:
renpy.display.render.redraw(self, 0)
+104 -265
View File
@@ -19,17 +19,6 @@
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# This file contains code contributed by Brian Turcotte, the copyright
# assignment follows:
#
# Copyright for nonlinear ramp code added to ImageDissolve is hereby
# assigned to PyTom <pytom@bishoujo.us>.
#
# And feel free to change, improve, fold, spindle, or mutilate it,
# obviously.
#
# Cheers, Brian Turcotte (shaja).
# NOTE:
# Transitions need to be able to work even when old_widget and new_widget
# are None, at least to the point of making it through __init__. This is
@@ -60,6 +49,11 @@ class Transition(renpy.display.core.Displayable):
def visit(self):
return [ self.new_widget, self.old_widget ] # E1101
def per_interact(self):
self.new_widget.per_interact()
self.old_widget.per_interact()
def null_render(d, width, height, st, at):
d.events = True
@@ -109,7 +103,7 @@ class MultipleTransition(Transition):
and the last will be True.
"""
def __init__(self, args, old_widget=None, new_widget=None):
def __init__(self, args, old_widget=None, new_widget=None, **properties):
if len(args) % 2 != 1 or len(args) < 3:
raise Exception("MultipleTransition requires an odd number of arguments, and at least 3 arguments.")
@@ -133,57 +127,54 @@ class MultipleTransition(Transition):
self.transitions.append(trans(old_widget=old, new_widget=new))
super(MultipleTransition, self).__init__(sum([i.delay for i in self.transitions]), **properties)
super(MultipleTransition, self).__init__(sum([i.delay for i in self.transitions]))
self.event_target = None
self.time_offset = 0
self.new_widget = self.transitions[-1]
self.events = False
def visit(self):
return [ i for i in self.screens if isinstance(i, renpy.display.core.Displayable)] + self.transitions
def per_interact(self):
for i in self.visit():
i.per_interact()
def render(self, width, height, st, at):
if renpy.game.less_updates:
return null_render(self, width, height, st, at)
while True:
trans = self.transitions[0]
stoff = st - self.time_offset
for trans in self.transitions[:-1]:
if stoff < trans.delay:
if trans.delay > st:
break
if len(self.transitions) == 1:
break
self.time_offset += trans.delay
self.transitions.pop(0)
st -= trans.delay
if len(self.transitions) == 1:
else:
trans = self.transitions[-1]
self.events = True
self.event_target = trans
surf = renpy.display.render.render(trans, width, height, stoff, at)
surf = renpy.display.render.render(trans, width, height, st, at)
width, height = surf.get_size()
rv = renpy.display.render.Render(width, height)
rv.blit(surf, (0, 0))
if stoff > 0:
renpy.display.render.redraw(self, stoff)
if st < trans.delay:
renpy.display.render.redraw(self, trans.delay - st)
return rv
def Fade(out_time, hold_time, in_time,
old_widget=None, new_widget=None,
def Fade(out_time,
hold_time,
in_time,
old_widget=None,
new_widget=None,
color=None,
widget=None,
alpha=False,
):
"""
@@ -224,12 +215,12 @@ def Fade(out_time, hold_time, in_time,
if not widget:
widget = renpy.display.image.Solid((0, 0, 0, 255))
args = [ False, dissolve(out_time), widget ]
args = [ False, dissolve(out_time, alpha=alpha), widget ]
if hold_time:
args.extend([ notrans(hold_time), widget, ])
args.extend([dissolve(in_time), True ])
args.extend([dissolve(in_time, alpha=alpha), True ])
return MultipleTransition(args, old_widget=old_widget, new_widget=new_widget)
@@ -274,21 +265,14 @@ class Pixellate(Transition):
visible = self.new_widget
self.events = True
rdr = render(visible, width, height, st, at)
surf = rdr.pygame_surface(False)
size = surf.get_size()
newsurf = renpy.display.pgrender.surface(size, surf)
px = 2 ** step
renpy.display.module.pixellate(surf, newsurf, px, px, px, px)
renpy.display.render.mutated_surface(newsurf)
rv = renpy.display.render.Render(rdr.width, rdr.height)
rv.blit(newsurf, (0, 0))
rv.depends_on(rdr)
rv.blit(rdr, (0, 0))
rv.operation = renpy.display.render.PIXELLATE
rv.operation_parameter = 2 ** step
renpy.display.render.redraw(self, 0)
@@ -329,50 +313,25 @@ class Dissolve(Transition):
self.events = True
return render(self.new_widget, width, height, st, at)
if st < self.time:
renpy.display.render.redraw(self, 0)
alpha = min(255, int(255 * st / self.time))
complete = min(1.0, st / self.time)
bottom = render(self.old_widget, width, height, st, at)
top = render(self.new_widget, width, height, st, at)
bottom_surface = bottom.pygame_surface(self.alpha)
top_surface = top.pygame_surface(self.alpha)
width = min(top.width, bottom.width)
height = min(top.height, bottom.height)
def draw(dest, x, y):
dw, dh = dest.get_size()
rv = renpy.display.render.Render(width, height, opaque=not self.alpha)
w = min(dw, width + x)
h = min(dh, height + y)
rv.operation = renpy.display.render.DISSOLVE
rv.operation_alpha = self.alpha
rv.operation_complete = complete
rv.blit(bottom, (0, 0), focus=False, main=False)
rv.blit(top, (0, 0), focus=True, main=True)
if w <= 0 or h <= 0:
return
renpy.display.render.redraw(self, 0)
renpy.display.module.blend(
bottom_surface.subsurface((-x, -y, w, h)),
top_surface.subsurface((-x, -y, w, h)),
dest.subsurface((0, 0, w, h)),
alpha)
if self.alpha:
surf = renpy.display.pgrender.surface((width, height), True)
draw(surf, 0, 0)
renpy.display.render.mutated_surface(surf)
rv = renpy.display.render.Render(width, height)
rv.blit(surf, (0, 0))
else:
rv = renpy.display.render.Render(width, height, draw_func=draw, opaque=True)
rv.depends_on(top, True)
rv.depends_on(bottom)
return rv
@@ -380,38 +339,6 @@ class ImageDissolve(Transition):
"""
This dissolves the old scene into the new scene, using an image
to control the dissolve process.
A list of values is used to control this mapping. This list of
values consists 256 fully transparent values, a ramp (of a
specified number of steps) from full transparency to full opacity,
and 256 fully opaque values. A 256 entry window is slid over this
list, and the values found within are used to map the red channel
of the image onto the opacity of the new scene.
Basically, this means that while pixels come in first, black last,
and the ramp controls the sharpness of the transition.
@param image: The image that will be used to control this
transition. The image should be the same size as the scene being
dissolved.
@param time: The amount of time the dissolve will take.
@param ramplen: The number of pixels of ramp to use. This defaults
to 8.
@param ramptype: Type of alpha ramp. Possible types are: linear, cube,
dcube, mcube. Default is linear. Non-linear types must have
ramplen >= 8. "cube": Ease in, sharp out. "dcube": Sharp in, sharp out.
"mcube": Ease in, ease out.
@param ramp: If given, this is expected to be a sequence of
integers in the range 0 to 255. This sequence explicitly gives the
ramp to be used. If given, this overrides ramplen and ramptype.
@param reverse: This reverses the ramp and the direction of the window
slide. When True, black pixels dissolve in first, and while pixels come
in last.
"""
__version__ = 1
@@ -420,171 +347,89 @@ class ImageDissolve(Transition):
if version < 1:
self.alpha = False
def generate_ramp(self, ramplen, ramptype, explicit_ramp, reverse):
"""
Precomputes the ramp.
"""
def __init__(
self,
image,
time,
ramplen=8,
ramptype='linear',
ramp=None,
reverse=False,
alpha=False,
old_widget=None,
new_widget=None,
**properties):
ramp = '\x00' * 256
if explicit_ramp is not None:
for i in explicit_ramp:
ramp += chr(i)
else:
if ramptype == 'cube':
# make sure ramplen is big enough, to avoid div-by-0 errors
# Not much point in nonlinear if the size is that small, anyway
if ramplen >= 8:
table = []
for i in range(ramplen):
table.append(i * i * i)
scale = max(table) / 255.0
for i in range(ramplen):
#print i, table[i], table[i] / scale
ramp += chr(int(table[i] / scale))
else:
ramptype = 'linear'
elif ramptype == 'dcube':
if ramplen >= 8:
table = []
for i in range(ramplen / 2 - ramplen, ramplen / 2):
table.append(i * i * i)
adj = abs(min(table))
for i in range(len(table)):
table[i] += adj
scale = max(table) / 255.0
#print "scale:", scale
for i in range(ramplen):
#print i, table[i], table[i] / scale
ramp += chr(int(table[i] / scale))
else:
ramptype = 'linear'
elif ramptype == 'mcube':
if ramplen >= 8:
ramplen = (ramplen / 2) * 2 # make sure it's even
table = []
for i in range(ramplen / 2):
table.append(i * i * i)
adj = table[-1]
tmptable = []
for i in table:
tmptable.append(i)
for i in range(1, len(table) + 1):
tmptable.append(abs(table[len(table) - i] - adj) + adj)
table = tmptable
scale = max(table) / 255.0
#print "scale:", scale
for i in range(ramplen):
#print i, table[i], table[i] / scale
ramp += chr(int(table[i] / scale))
else:
ramptype = 'linear'
if ramptype == 'linear':
for i in range(ramplen):
ramp += chr(255 * i / ramplen)
ramp += '\xff' * 256
if reverse:
ramp = list(ramp)
ramp.reverse()
ramp = ''.join(ramp)
return ramp
# ramptype and ramp are now unused, but are kept for compatbility with
# older code.
def __init__(self, image, time, ramplen=8, ramptype='linear', ramp=None, reverse=False, alpha=False,
old_widget=None, new_widget=None, **properties):
super(ImageDissolve, self).__init__(time, **properties)
self.time = time
self.old_widget = old_widget
self.new_widget = new_widget
self.events = False
self.alpha = alpha
self.image = renpy.display.im.image(image)
if not reverse:
# Copies red -> alpha
matrix = renpy.display.im.matrix(
0, 0, 0, 0, 1,
0, 0, 0, 0, 1,
0, 0, 0, 0, 1,
1, 0, 0, 0, 0)
else:
# Copies 1-red -> alpha
matrix = renpy.display.im.matrix(
0, 0, 0, 0, 1,
0, 0, 0, 0, 1,
0, 0, 0, 0, 1,
-1, 0, 0, 0, 1)
self.image = renpy.display.im.MatrixColor(image, matrix)
if ramp is not None:
ramplen = len(ramp)
self.ramp = self.generate_ramp(ramplen, ramptype, ramp, reverse)
self.steps = ramplen + 256
self.reverse = reverse
# The length of the ramp.
self.ramplen = max(ramplen, 1)
def visit(self):
return super(ImageDissolve, self).visit() + [ self.image ]
def render(self, width, height, st, at):
if renpy.game.less_updates:
return null_render(self, width, height, st, at)
if st >= self.time:
if st >= self.delay:
self.events = True
return render(self.new_widget, width, height, st, at)
image = renpy.display.im.cache.get(self.image)
if st < self.time:
renpy.display.render.redraw(self, 0)
step = int(self.steps * st / self.time)
if self.reverse:
step = self.steps - step
ramp = self.ramp[step:step+256]
image = render(self.image, width, height, st, at)
bottom = render(self.old_widget, width, height, st, at)
top = render(self.new_widget, width, height, st, at)
width = min(bottom.width, top.width, image.width)
height = min(bottom.height, top.height, image.height)
rv = renpy.display.render.Render(width, height, opaque=not self.alpha)
rv.operation = renpy.display.render.IMAGEDISSOLVE
rv.operation_alpha = self.alpha
rv.operation_complete = st / self.delay
rv.operation_parameter = self.ramplen
rv.blit(image, (0, 0), focus=False, main=False)
rv.blit(bottom, (0, 0), focus=False, main=False)
rv.blit(top, (0, 0), focus=True, main=True)
bottom_surface = bottom.pygame_surface(self.alpha)
top_surface = top.pygame_surface(self.alpha)
renpy.display.render.redraw(self, 0)
iw, ih = image.get_size()
width = min(bottom.width, top.width, iw)
height = min(bottom.height, top.height, ih)
def draw(dest, x, y):
dw, dh = dest.get_size()
w = min(dw, width + x)
h = min(dh, height + y)
renpy.display.module.imageblend(
bottom_surface.subsurface((-x, -y, w, h)),
top_surface.subsurface((-x, -y, w, h)),
dest.subsurface((0, 0, w, h)),
image.subsurface((-x, -y, w, h)),
ramp)
if self.alpha:
surf = renpy.display.pgrender.surface((width, height), True)
draw(surf, 0, 0)
renpy.display.render.mutated_surface(surf)
rv = renpy.display.render.Render(width, height)
rv.blit(surf, (0, 0))
else:
rv = renpy.display.render.Render(width, height, draw_func=draw, opaque=True)
rv.depends_on(top, True)
rv.depends_on(bottom)
return rv
@@ -961,9 +806,8 @@ def MoveTransition(delay, old_widget=None, new_widget=None, factory=None, enter
if (isinstance(f, renpy.display.layout.MultiBox)
and layer in layers
and f.scene_list is not None
and layer not in renpy.config.overlay_layers):
and f.scene_list is not None):
f = merge_slide(old.layers[layer], new.layers[layer])
rv.layers[layer] = f
@@ -977,19 +821,16 @@ def MoveTransition(delay, old_widget=None, new_widget=None, factory=None, enter
# Wraps the displayable found in SLE so that the various timebases
# are maintained.
def wrap(sle):
key, zorder, st, at, d = sle
return renpy.display.layout.AdjustTimes(d, st, at)
return renpy.display.layout.AdjustTimes(sle.displayable, sle.show_time, sle.animation_time)
def tag(sle):
if sle[0] is None:
tag = sle[4]
else:
tag = sle[0]
return tag
return sle.tag or sle.displayable
def merge(sle, d):
return (sle[0], sle[1], 0, sle[3], d)
rv = sle.copy()
rv.show_time = 0
rv.displayable = d
return rv
# A list of tags on the new layer.
new_tags = set()
@@ -1083,8 +924,6 @@ def MoveTransition(delay, old_widget=None, new_widget=None, factory=None, enter
return rv
def ComposeTransition(trans, before=None, after=None, new_widget=None, old_widget=None):
if before is not None:
old = before(new_widget=new_widget, old_widget=old_widget)
+30 -17
View File
@@ -34,7 +34,6 @@ surface_file = None
# The surface to display the movie on, if not fullscreen.
surface = None
def movie_stop(clear=True, only_fullscreen=False):
"""
Stops the currently playing movie.
@@ -81,7 +80,6 @@ def early_interact():
global fullscreen
fullscreen = True
def interact():
"""
This is called each time the screen is redrawn. It helps us decide if
@@ -93,43 +91,58 @@ def interact():
else:
return False
def get_movie_texture(size):
"""
Gets a movie texture we can draw to the screen.
"""
global surface
global surface_file
playing = renpy.audio.music.get_playing("movie")
if (surface is None) or (surface.get_size() != size) or (surface_file != playing):
surface = renpy.display.pgrender.surface(size, False)
surface_file = playing
surface.fill((0, 0, 0, 255))
tex = None
if playing is not None:
renpy.display.render.mutated_surface(surface)
tex = renpy.display.draw.load_texture(surface)
return tex
class Movie(renpy.display.core.Displayable):
"""
This is a displayable that shows the current movie.
"""
fullscreen = False
def __init__(self, fps=24, size=None, **properties):
"""
@param fps: The framerate that the movie should be shown at.
"""
super(Movie, self).__init__(**properties)
self.size = size
def render(self, width, height, st, at):
global surface
global surface_file
size = self.size
if size is None:
size = default_size
playing = renpy.audio.music.get_playing("movie")
if (surface is None) or (surface.get_size() != size) or (surface_file != playing):
surface = renpy.display.pgrender.surface(size, False)
surface_file = playing
surface.fill((0, 0, 0, 255))
width, height = size
rv = renpy.display.render.Render(width, height)
rv = renpy.display.render.Render(width, height, opaque=True)
tex = get_movie_texture(size)
if playing is not None:
renpy.display.render.mutated_surface(surface)
rv.blit(surface, (0, 0))
if tex is not None:
rv.blit(tex, (0, 0))
return rv
+11 -2
View File
@@ -82,8 +82,12 @@ class Context(renpy.object.Object):
self.music = { }
def __init__(self, rollback, context=None):
def __init__(self, rollback, context=None, clear=False):
"""
`clear`
True if we should clear out the context_clear_layers.
"""
super(Context, self).__init__()
self.current = None
@@ -133,6 +137,11 @@ class Context(renpy.object.Object):
self.make_dynamic([ "_return", "_args", "_kwargs", "mouse_visible", "suppress_overlay" ])
self.dynamic_stack.append({ })
if clear:
for i in renpy.config.context_clear_layers:
self.scene_lists.clear(layer=i)
def make_dynamic(self, names, context=False):
"""
+165 -33
View File
@@ -32,6 +32,7 @@ from renpy.display.text import ParameterizedText
from renpy.display.font import register_sfont, register_mudgefont, register_bmfont
from renpy.display.behavior import Keymap
from renpy.display.minigame import Minigame
from renpy.display.screen import define_screen, show_screen, hide_screen, use_screen, current_screen, has_screen, get_screen, get_widget
from renpy.curry import curry, partial
from renpy.audio.sound import play
@@ -69,10 +70,11 @@ def public_api():
sound
music
time
define_screen, show_screen, hide_screen, use_screen, has_screen
current_screen, get_screen, get_widget
del public_api
import collections
# This is a map from image name to a Displayable object corresponding
@@ -115,14 +117,8 @@ def predict(img):
img = renpy.easy.displayable(img)
renpy.game.interface.preloads.append(img)
def scene_lists(index=-1):
"""
Returns either the current scenelists object, or the one for the
context at the given index.
"""
return renpy.game.context(index).scene_lists
scene_lists = renpy.display.core.scene_lists
def count_displayables_in_layer(layer):
"""
Returns how many displayables are in the supplied layer.
@@ -193,7 +189,7 @@ def showing(name, layer='master'):
return renpy.game.context().predict_info.images.showing(layer, name)
def show(name, at_list=[ ], layer='master', what=None, zorder=0, tag=None, behind=[ ], atl=None):
def show(name, at_list=[ ], layer='master', what=None, zorder=0, tag=None, behind=[ ], atl=None, transient=False, munge_name=True):
"Documented in wiki as renpy.show."
if renpy.game.init_phase:
@@ -214,8 +210,15 @@ def show(name, at_list=[ ], layer='master', what=None, zorder=0, tag=None, behin
elif isinstance(what, basestring):
what = tuple(what.split())
base = img = renpy.display.image.ImageReference(what, style='image_placement')
if isinstance(what, renpy.display.core.Displayable):
base = img = what
else:
base = img = renpy.display.image.ImageReference(what, style='image_placement')
if not base.find_target() and renpy.config.missing_show:
if renpy.config.missing_show(name, what, layer):
return
for i in at_list:
if isinstance(i, renpy.display.motion.Transform):
img = i(child=img)
@@ -225,17 +228,14 @@ def show(name, at_list=[ ], layer='master', what=None, zorder=0, tag=None, behin
# Update the list of images we have ever seen.
renpy.game.persistent._seen_images[name] = True
if tag:
if tag and munge_name:
name = (tag,) + name[1:]
if not base.find_target() and renpy.config.missing_show:
if renpy.config.missing_show(name, what, layer):
return
if renpy.config.missing_hide:
renpy.config.missing_hide(name, layer)
sls.add(layer, img, key, zorder, behind, at_list=at_list, name=name, atl=atl)
sls.add(layer, img, key, zorder, behind, at_list=at_list, name=name, atl=atl, default_transform=renpy.config.default_transform, transient=transient)
def hide(name, layer='master'):
@@ -321,13 +321,21 @@ def input(prompt, default='', allow=None, exclude='{}', length=None, with_none=N
takes the value from config.implicit_with_none.
"""
renpy.ui.window(style='input_window')
renpy.ui.vbox()
if has_screen("input"):
widget_properties = { }
widget_properties["input"] = dict(default=default, length=length, allow=allow, exclude=exclude)
renpy.ui.text(prompt, style='input_prompt')
renpy.ui.input(default, length=length, style='input_text', allow=allow, exclude=exclude)
show_screen("input", _transient=True, _widget_properties=widget_properties, prompt=prompt)
renpy.ui.close()
else:
renpy.ui.window(style='input_window')
renpy.ui.vbox()
renpy.ui.text(prompt, style='input_prompt')
renpy.ui.input(default, length=length, style='input_text', allow=allow, exclude=exclude)
renpy.ui.close()
renpy.exports.shown_window()
@@ -444,8 +452,13 @@ def display_menu(items, window_style='menu_window', interact=True, with_none=Non
random.choice(choices))
# Show the menu.
renpy.ui.window(style=window_style)
renpy.ui.menu(items, location=renpy.game.context().current, focus="choices", default=True, **kwargs)
if has_screen("choice"):
item_actions = [ (label, renpy.ui.returns(val)) for (label, val) in items if label is not None ]
show_screen("choice", items=item_actions, _transient=True)
else:
renpy.ui.window(style=window_style)
renpy.ui.menu(items, location=renpy.game.context().current, focus="choices", default=True, **kwargs)
renpy.exports.shown_window()
@@ -518,7 +531,17 @@ def predict_say(who, what):
return predict(what)
else:
return [ ]
def scry_say(who, scry):
"""
Called when scry is called on a say statement. Needs to set
the interacts field.
"""
try:
scry.interacts = who.will_interact()
except:
scry.interacts = True
def say(who, what, interact=True):
"""
@@ -575,8 +598,8 @@ def imagemap(ground, selected, hotspots, unselected=None, overlays=False,
takes the value from config.implicit_with_none.
"""
renpy.ui.imagemap(ground, selected, hotspots, unselected=unselected,
style=style, **properties)
renpy.ui.imagemap_compat(ground, selected, hotspots, unselected=unselected,
style=style, **properties)
roll_forward = renpy.exports.roll_forward_info()
if roll_forward not in [ result for x0, y0, x1, y1, result in hotspots]:
@@ -817,7 +840,7 @@ def screenshot(filename):
Saves a screenshot in the named filename.
"""
renpy.game.interface.display.save_screenshot(filename)
renpy.game.interface.save_screenshot(filename)
def windows():
"""
@@ -1076,7 +1099,7 @@ def force_full_redraw():
to redraw the screen directly.
"""
renpy.game.interface.display.full_redraw = True
renpy.game.interface.full_redraw = True
def do_reshow_say(who, what, interact=False):
@@ -1124,6 +1147,16 @@ def file(fn):
return renpy.loader.load(fn)
def image_size(im):
"""
:doc: other
Given an image manipulator, loads it and returns a (``width``,
``height``) tuple giving its size.
This reads the image in from disk and decompresses it, without
using the image cache. This can be slow.
"""
# Index the archives, if we haven't already.
renpy.loader.index_archives()
@@ -1162,7 +1195,7 @@ def quit_event():
renpy.game.interface.quit_event()
def iconify():
renpy.game.interface.display.iconify()
renpy.game.interface.iconify()
# New context stuff.
call_in_new_context = renpy.game.call_in_new_context
@@ -1185,7 +1218,6 @@ def pop_error_handler():
def error(msg):
_error_handlers[-1](msg)
def timeout(seconds):
renpy.game.interface.timeout(seconds)
@@ -1278,10 +1310,110 @@ def get_roll_forward():
return renpy.game.interface.shown_window
def cache_pin(*args):
for i in args:
renpy.display.im.cache.pin_image(renpy.easy.displayable(i))
new_pins = renpy.python.RevertableSet()
for i in args:
im = renpy.easy.displayable(i)
if not isinstance(im, renpy.display.im.ImageBase):
raise Exception("Cannot pin non-image-manipulator %r" % im)
new_pins.add(im)
renpy.store._cache_pin_set = new_pins | renpy.store._cache_pin_set
def cache_unpin(*args):
new_pins = renpy.python.RevertableSet()
for i in args:
im = renpy.easy.displayable(i)
if not isinstance(im, renpy.display.im.ImageBase):
raise Exception("Cannot unpin non-image-manipulator %r" % im)
new_pins.add(im)
renpy.store._cache_pin_set = renpy.store._cache_pin_set - new_pins
# This is a map from a definition to the place where it was
# defined.
definitions = collections.defaultdict(list)
def call_screen(_screen_name, **kwargs):
"""
:doc: screens
The programmatic equivalent of the show screen statement.
This shows `_screen_name` as a screen, then causes an interaction
to occur. The screen is hidden at the end of the interaction, and
the result of the interaction is returned.
Keyword arguments not beginning with _ are passed to the scope of
the screen.
"""
show_screen(_screen_name, _transient=True, **kwargs)
roll_forward = renpy.exports.roll_forward_info()
rv = None
try:
rv = renpy.ui.interact(mouse="screen", type="screen", roll_forward=roll_forward)
return rv
finally:
renpy.exports.checkpoint(rv)
with_none = renpy.config.implicit_with_none
if with_none:
renpy.game.interface.do_with(None, None)
def list_files(common=False):
"""
:doc: other
Lists the files in the game directory and archive files. Returns
a list of files, with / as the directory separator.
`common`
If true, files in the common directory are included in the
listing.
"""
rv = [ ]
for dir, fn in renpy.loader.listdirfiles():
if not common and dir == renpy.config.commondir:
continue
rv.append(fn)
return rv
def get_renderer_info():
"""
:doc: other
Returns a dictionary, giving information about the renderer Ren'Py is
currently using. The dictionary has one required key:
``"renderer"``
One of ``"gl"`` or ``"sw"``, corresponding to the OpenGL and
software renderers, respectively.
Other, renderer-specific, keys may also exist. The dictionary should
be treated as immutable. This should only be called once the display
has been started (that is, after the init code is finished).
"""
return renpy.display.draw.info
+22 -17
View File
@@ -111,23 +111,29 @@ class Persistent(object):
# The persistent data that's kept from session to session
persistent = None
class Preferences(object):
class Preferences(renpy.object.Object):
"""
Stores preferences that will one day be persisted.
"""
def reinit(self):
__version__ = 2
def after_upgrade(self, version):
if version < 1:
self.mute_volumes = 0
if version < 2:
self.using_afm_enable = False
def __init__(self):
self.fullscreen = False # W0201
self.skip_unseen = False # W0201
self.text_cps = 0 # W0201
self.afm_time = 0 # W0201
self.afm_enable = True # W0201
# These will be going away soon.
self.sound = True # W0201
self.music = True # W0201
# 2 - All transitions.
# 1 - Only non-default transitions.
# 0 - No transitions.
@@ -136,7 +142,12 @@ class Preferences(object):
self.skip_after_choices = False # W0201
# Mixer channel info.
# A map from channel name to the current volume (between 0 and 1).
self.volumes = { } # W0201
# True if the channel should not play music. False
# otherwise. (Not used anymore.)
self.mute = { } # W0201
# Joystick mappings.
@@ -148,23 +159,17 @@ class Preferences(object):
joy_dismiss="Button 0.0")
def set_volume(self, mixer, volume):
if volume == 0:
self.mute[mixer] = True
else:
self.mute[mixer] = False
self.volumes[mixer] = volume
def get_volume(self, mixer):
return self.volumes[mixer]
def __setstate__(self, state):
self.reinit()
vars(self).update(state)
def __init__(self):
self.reinit()
def set_mute(self, mixer, mute):
self.mute[mixer] = mute
def get_mute(self, mixer):
return self.mute[mixer]
# The current preferences.
preferences = None
@@ -249,7 +254,7 @@ def invoke_in_new_context(callable, *args, **kwargs):
inside an interaction.
"""
context = renpy.execution.Context(False, contexts[-1])
context = renpy.execution.Context(False, contexts[-1], clear=True)
contexts.append(context)
try:
@@ -272,7 +277,7 @@ def call_in_new_context(label, *args, **kwargs):
inside an interaction.
"""
context = renpy.execution.Context(False, contexts[-1])
context = renpy.execution.Context(False, contexts[-1], clear=True)
contexts.append(context)
+8
View File
@@ -318,21 +318,29 @@ def load(name):
raise IOError("Couldn't find file '%s'." % name)
loadable_cache = { }
def loadable(name):
"""
Returns True if the name is loadable with load, False if it is not.
"""
if name in loadable_cache:
return loadable_cache[name]
try:
transfn(name)
loadable_cache[name] = True
return True
except:
pass
for prefix, index in archives:
if name in index:
loadable_cache[name] = True
return True
loadable_cache[name] = False
return False
+22 -6
View File
@@ -37,6 +37,9 @@ import platform
import renpy
# This is used to cache information about saved games.
cache = { }
# Dump that choses which pickle to use:
def dump(o, f):
@@ -137,6 +140,8 @@ def save(filename, extra_info='',
renpy.take_screenshot) before this is called.
"""
cache.pop(filename, None)
filename = filename + savegame_suffix
try:
@@ -164,7 +169,6 @@ def save(filename, extra_info='',
# Extra info.
zf.writestr("extra_info", extra_info.encode("utf-8"))
# The actual game.
zf.writestr("log", logf.getvalue())
@@ -174,6 +178,9 @@ def save(filename, extra_info='',
def scan_saved_game(name):
if name in cache:
return cache[name]
try:
f = name + savegame_suffix
@@ -196,11 +203,14 @@ def scan_saved_game(name):
screenshot = renpy.display.im.ZipFileImage(renpy.config.savedir + '/' + f, "screenshot.png", mtime)
else:
screenshot = renpy.display.im.ZipFileImage(renpy.config.savedir + '/' + f, "screenshot.tga", mtime)
return extra_info, screenshot, mtime
rv = extra_info, screenshot, mtime
except:
return None
rv = None
cache[name] = rv
return rv
@@ -269,11 +279,15 @@ def rename_save(old, new):
os.rename(renpy.config.savedir + "/" + old + savegame_suffix,
renpy.config.savedir + "/" + new + savegame_suffix)
cache.pop(old, None)
cache.pop(new, None)
def unlink_save(filename):
if os.path.exists(renpy.config.savedir + "/" + filename + savegame_suffix):
os.unlink(renpy.config.savedir + "/" + filename + savegame_suffix)
cache.pop(filename, None)
def cycle_saves(name, count):
@@ -343,6 +357,7 @@ def autosave():
force_autosave(True)
# This assumes a screenshot has already been taken.
def force_autosave(take_screenshot=False):
@@ -383,7 +398,8 @@ class _MultiPersistent(object):
except:
os.unlink(fn)
os.rename(fn + ".new", fn)
def MultiPersistent(name):
if not renpy.game.init_phase:
+3 -3
View File
@@ -170,7 +170,7 @@ def main():
# Load the script.
renpy.game.exception_info = 'While loading the script.'
game.script = renpy.script.load_script()
renpy.script.load_script() # sets renpy.game.script.
if renpy.parser.report_parse_errors():
raise renpy.game.ParseErrorException()
@@ -296,8 +296,7 @@ def main():
# (Perhaps) Initialize graphics.
if not game.interface:
game.interface = renpy.display.core.Interface()
renpy.display.core.Interface()
# Start things running.
restart = None
@@ -322,3 +321,4 @@ def main():
# This is stuff we do on a normal, non-error return.
renpy.display.render.check_at_shutdown()
+430 -357
View File
@@ -20,7 +20,7 @@
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# This module contains the parser for the Ren'Py script language. It's
# called when parsing is necessary, and creats an AST from the script.
# called when parsing is necessary, and creates an AST from the script.
import codecs
import re
@@ -352,29 +352,35 @@ class Lexer(object):
# A list of keywords which should not be parsed as names, because
# there is a huge chance of confusion.
#
# Note: We need to be careful with what's in here, because thse
# are banned in simple_expressions, where we might want to use
# some of them.
keywords = set([
'as',
'at',
'behind',
'call',
'expression',
'hide',
'if',
'image',
'init',
'jump',
'menu',
'onlayer',
'python',
'return',
'scene',
'set',
'show',
'with',
'while',
'zorder',
'transform',
])
'$',
'as',
'at',
'behind',
'call',
'expression',
'hide',
'if',
'in',
'image',
'init',
'jump',
'menu',
'onlayer',
'python',
'return',
'scene',
'set',
'show',
'with',
'while',
'zorder',
'transform',
])
def __init__(self, block, init=False):
@@ -815,7 +821,7 @@ class Lexer(object):
break
return self.text[start:self.pos]
return renpy.ast.PyExpr(self.text[start:self.pos], self.filename, self.number)
def checkpoint(self):
"""
@@ -1044,7 +1050,6 @@ def parse_with(l, node):
node,
ast.With(loc, expr) ]
def parse_menu(stmtl, loc):
@@ -1161,6 +1166,7 @@ def parse_menu(stmtl, loc):
return rv
def parse_parameters(l):
parameters = [ ]
@@ -1235,6 +1241,7 @@ def parse_parameters(l):
return renpy.ast.ParameterInfo(parameters, positional, extrapos, extrakw)
def parse_arguments(l):
"""
Parse a list of arguments, if one is present.
@@ -1283,30 +1290,90 @@ def parse_arguments(l):
l.require(r',')
return renpy.ast.ArgumentInfo(arguments, extrapos, extrakw)
##############################################################################
# The parse trie.
class ParseTrie(object):
"""
This is a trie of words, that's used to pick a parser function.
"""
def __init__(self):
self.default = None
self.words = { }
def add(self, name, function):
def parse_statement(l):
if not name:
self.default = function
return
first = name[0]
rest = name[1:]
if first not in self.words:
self.words[first] = ParseTrie()
self.words[first].add(rest, function)
def parse(self, l):
old_pos = l.pos
word = l.word() or l.match(r'\$')
if not word in self.words:
l.pos = old_pos
return self.default
return self.words[word].parse(l)
# The root of the parse trie.
statements = ParseTrie()
def statement(keywords):
"""
This parses a Ren'Py statement. l is expected to be a Ren'Py lexer
that has been advanced to a logical line. This function will
advance l beyond the last logical line making up the current
statement, and will return an AST object representing this
statement, or a list of AST objects representing this statement.
A function decorator used to declare a statement. Keywords is a string
giving the keywords that precede the statement.
"""
# Store the current location.
loc = l.get_location()
keywords = keywords.split()
### If statement
if l.keyword('if'):
entries = [ ]
def wrap(f):
statements.add(keywords, f)
return f
return wrap
##############################################################################
# Statement functions.
@statement("if")
def if_statement(l, loc):
entries = [ ]
condition = l.require(l.python_expression)
l.require(':')
l.expect_eol()
l.expect_block('if statement')
block = parse_block(l.subblock_lexer())
entries.append((condition, block))
l.advance()
while l.keyword('elif'):
condition = l.require(l.python_expression)
l.require(':')
l.expect_eol()
l.expect_block('if statement')
l.expect_block('elif clause')
block = parse_block(l.subblock_lexer())
@@ -1314,293 +1381,333 @@ def parse_statement(l):
l.advance()
while l.keyword('elif'):
condition = l.require(l.python_expression)
l.require(':')
l.expect_eol()
l.expect_block('elif clause')
block = parse_block(l.subblock_lexer())
entries.append((condition, block))
l.advance()
if l.keyword('else'):
l.require(':')
l.expect_eol()
l.expect_block('else clause')
block = parse_block(l.subblock_lexer())
entries.append(('True', block))
l.advance()
return ast.If(loc, entries)
if l.keyword('elif'):
l.error('elif clause must be associated with an if statement.')
if l.keyword('else'):
l.error('else clause must be associated with an if statement.')
### While statement
if l.keyword('while'):
condition = l.require(l.python_expression)
l.require(':')
l.expect_eol()
l.expect_block('while statement')
l.expect_block('else clause')
block = parse_block(l.subblock_lexer())
l.advance()
return ast.While(loc, condition, block)
### Pass statement
if l.keyword('pass'):
l.expect_noblock('pass statement')
l.expect_eol()
l.advance()
return ast.Pass(loc)
### Menu statement.
if l.keyword('menu'):
l.expect_block('menu statement')
label = l.name()
l.require(':')
l.expect_eol()
menu = parse_menu(l, loc)
entries.append(('True', block))
l.advance()
rv = [ ]
return ast.If(loc, entries)
if label:
rv.append(ast.Label(loc, label, [], None))
rv.extend(menu)
@statement("while")
def while_statement(l, loc):
condition = l.require(l.python_expression)
l.require(':')
l.expect_eol()
l.expect_block('while statement')
block = parse_block(l.subblock_lexer())
l.advance()
return rv
### Return statement.
if l.keyword('return'):
l.expect_noblock('return statement')
rest = l.rest()
if not rest:
rest = None
l.expect_eol()
l.advance()
return ast.Return(loc, rest)
### Jump statement
if l.keyword('jump'):
l.expect_noblock('jump statement')
if l.keyword('expression'):
expression = True
target = l.require(l.simple_expression)
else:
expression = False
target = l.require(l.name)
l.expect_eol()
l.advance()
return ast.Jump(loc, target, expression)
return ast.While(loc, condition, block)
### Call/From statement.
if l.keyword('call'):
l.expect_noblock('call statment')
@statement("pass")
def pass_statement(l, loc):
l.expect_noblock('pass statement')
l.expect_eol()
l.advance()
if l.keyword('expression'):
expression = True
target = l.require(l.simple_expression)
else:
expression = False
target = l.require(l.name)
return ast.Pass(loc)
arguments = parse_arguments(l)
rv = [ ast.Call(loc, target, expression, arguments) ]
if l.keyword('from'):
name = l.require(l.name)
rv.append(ast.Label(loc, name, [], None))
else:
rv.append(ast.Pass(loc))
@statement("menu")
def menu_statement(l, loc):
l.expect_block('menu statement')
label = l.name()
l.require(':')
l.expect_eol()
l.expect_eol()
l.advance()
menu = parse_menu(l, loc)
return rv
l.advance()
### Scene statement.
if l.keyword('scene'):
rv = [ ]
if l.keyword('onlayer'):
layer = l.require(l.name)
else:
layer = "master"
if label:
rv.append(ast.Label(loc, label, [], None))
# Empty.
if l.eol():
l.advance()
return ast.Scene(loc, None, layer)
rv.extend(menu)
imspec = parse_image_specifier(l)
stmt = ast.Scene(loc, imspec, imspec[4])
rv = parse_with(l, stmt)
return rv
if l.match(':'):
stmt.atl = renpy.atl.parse_atl(l.subblock_lexer())
else:
l.expect_noblock('scene statement')
l.expect_eol()
l.advance()
@statement("return")
def return_statement(l, loc):
l.expect_noblock('return statement')
return rv
rest = l.rest()
if not rest:
rest = None
### Show statement.
if l.keyword('show'):
imspec = parse_image_specifier(l)
stmt = ast.Show(loc, imspec)
rv = parse_with(l, stmt)
l.expect_eol()
l.advance()
if l.match(':'):
stmt.atl = renpy.atl.parse_atl(l.subblock_lexer())
else:
l.expect_noblock('show statement')
l.expect_eol()
l.advance()
return rv
### Hide statement.
if l.keyword('hide'):
imspec = parse_image_specifier(l)
rv = parse_with(l, ast.Hide(loc, imspec))
l.expect_eol()
l.expect_noblock('hide statement')
l.advance()
return rv
### With statement.
if l.keyword('with'):
expr = l.require(l.simple_expression)
l.expect_eol()
l.expect_noblock('with statement')
l.advance()
return ast.With(loc, expr)
return ast.Return(loc, rest)
### Image statement.
if l.keyword('image'):
name = parse_image_name(l)
@statement("jump")
def jump_statement(l, loc):
l.expect_noblock('jump statement')
if l.match(':'):
l.expect_eol()
expr = None
atl = renpy.atl.parse_atl(l.subblock_lexer())
else:
l.require('=')
expr = l.rest()
atl = None
l.expect_noblock('image statement')
if l.keyword('expression'):
expression = True
target = l.require(l.simple_expression)
else:
expression = False
target = l.require(l.name)
rv = ast.Image(loc, name, expr, atl)
l.expect_eol()
l.advance()
if not l.init:
rv = ast.Init(loc, [ rv ], 990)
l.advance()
return ast.Jump(loc, target, expression)
return rv
### Define statement.
if l.keyword('define'):
@statement("call")
def call_statement(l, loc):
l.expect_noblock('call statment')
priority = l.integer()
if priority:
priority = int(priority)
else:
priority = 0
if l.keyword('expression'):
expression = True
target = l.require(l.simple_expression)
else:
expression = False
target = l.require(l.name)
# Optional pass, to let someone write:
# call expression foo pass (bar, baz)
l.keyword('pass')
arguments = parse_arguments(l)
rv = [ ast.Call(loc, target, expression, arguments) ]
if l.keyword('from'):
name = l.require(l.name)
rv.append(ast.Label(loc, name, [], None))
else:
rv.append(ast.Pass(loc))
l.expect_eol()
l.advance()
return rv
@statement("scene")
def scene_statement(l, loc):
if l.keyword('onlayer'):
layer = l.require(l.name)
else:
layer = "master"
# Empty.
if l.eol():
l.advance()
return ast.Scene(loc, None, layer)
imspec = parse_image_specifier(l)
stmt = ast.Scene(loc, imspec, imspec[4])
rv = parse_with(l, stmt)
if l.match(':'):
stmt.atl = renpy.atl.parse_atl(l.subblock_lexer())
else:
l.expect_noblock('scene statement')
l.expect_eol()
l.advance()
return rv
@statement("show")
def show_statement(l, loc):
imspec = parse_image_specifier(l)
stmt = ast.Show(loc, imspec)
rv = parse_with(l, stmt)
if l.match(':'):
stmt.atl = renpy.atl.parse_atl(l.subblock_lexer())
else:
l.expect_noblock('show statement')
l.expect_eol()
l.advance()
return rv
@statement("hide")
def hide_statement(l, loc):
imspec = parse_image_specifier(l)
rv = parse_with(l, ast.Hide(loc, imspec))
l.expect_eol()
l.expect_noblock('hide statement')
l.advance()
return rv
@statement("with")
def with_statement(l, loc):
expr = l.require(l.simple_expression)
l.expect_eol()
l.expect_noblock('with statement')
l.advance()
return ast.With(loc, expr)
@statement("image")
def image_statement(l, loc):
name = parse_image_name(l)
if l.match(':'):
l.expect_eol()
expr = None
atl = renpy.atl.parse_atl(l.subblock_lexer())
else:
l.require('=')
expr = l.rest()
atl = None
l.expect_noblock('image statement')
l.expect_noblock('define statement')
rv = ast.Image(loc, name, expr, atl)
rv = ast.Define(loc, name, expr)
if not l.init:
rv = ast.Init(loc, [ rv ], 990)
if not l.init:
rv = ast.Init(loc, [ rv ], priority)
l.advance()
l.advance()
return rv
return rv
### Transform statement.
if l.keyword('transform'):
priority = l.integer()
if priority:
priority = int(priority)
else:
priority = 0
name = l.require(l.name)
parameters = parse_parameters(l)
if parameters and (parameters.extrakw or parameters.extrapos):
l.error('transform statement does not take a variable number of parameters')
@statement("define")
def define_statement(l, loc):
l.require(':')
l.expect_eol()
priority = l.integer()
if priority:
priority = int(priority)
else:
priority = 0
atl = renpy.atl.parse_atl(l.subblock_lexer())
name = l.require(l.name)
l.require('=')
expr = l.rest()
rv = ast.Transform(loc, name, atl, parameters)
l.expect_noblock('define statement')
if not l.init:
rv = ast.Init(loc, [ rv ], priority)
l.advance()
rv = ast.Define(loc, name, expr)
return rv
### One-line python statement.
if l.match(r'\$'):
python_code = l.rest()
l.expect_noblock('one-line python statement')
l.advance()
if not l.init:
rv = ast.Init(loc, [ rv ], priority)
return ast.Python(loc, python_code)
l.advance()
return rv
@statement("transform")
def transform_statement(l, loc):
priority = l.integer()
if priority:
priority = int(priority)
else:
priority = 0
name = l.require(l.name)
parameters = parse_parameters(l)
if parameters and (parameters.extrakw or parameters.extrapos):
l.error('transform statement does not take a variable number of parameters')
l.require(':')
l.expect_eol()
atl = renpy.atl.parse_atl(l.subblock_lexer())
rv = ast.Transform(loc, name, atl, parameters)
if not l.init:
rv = ast.Init(loc, [ rv ], priority)
l.advance()
return rv
@statement("$")
def one_line_python(l, loc):
python_code = l.rest()
l.expect_noblock('one-line python statement')
l.advance()
return ast.Python(loc, python_code)
@statement("python")
def python_statement(l, loc):
hide = False
early = False
if l.keyword('early'):
early = True
if l.keyword('hide'):
hide = True
l.require(':')
l.expect_block('python block')
python_code = l.python_block()
l.advance()
if early:
return ast.EarlyPython(loc, python_code, hide)
else:
return ast.Python(loc, python_code, hide)
@statement("label")
def label_statement(l, loc):
name = l.require(l.name)
parameters = parse_parameters(l)
l.require(':')
l.expect_eol()
# Optional block here. It's empty if no block is associated with
# this statement.
block = parse_block(l.subblock_lexer())
l.advance()
return ast.Label(loc, name, block, parameters)
@statement("init")
def init_statement(l, loc):
p = l.integer()
if p:
priority = int(p)
else:
priority = 0
### Python block.
if l.keyword('python'):
hide = False
early = False
if l.keyword('early'):
early = True
if l.keyword('hide'):
hide = True
@@ -1610,106 +1717,46 @@ def parse_statement(l):
python_code = l.python_block()
l.advance()
block = [ ast.Python(loc, python_code, hide) ]
if early:
return ast.EarlyPython(loc, python_code, hide)
else:
return ast.Python(loc, python_code, hide)
### Label Statement
if l.keyword('label'):
name = l.require(l.name)
parameters = parse_parameters(l)
else:
l.require(':')
l.expect_eol()
# Optional block here. It's empty if no block is associated with
# this statement.
block = parse_block(l.subblock_lexer())
l.expect_eol()
l.expect_block('init statement')
block = parse_block(l.subblock_lexer(True))
l.advance()
return ast.Label(loc, name, block, parameters)
### Init Statement
if l.keyword('init'):
return ast.Init(loc, block, priority)
p = l.integer()
if p:
priority = int(p)
else:
priority = 0
@statement("screen")
def screen_statement(l, loc):
# The guts of screen language parsing is in screenlang.py. It
# assumes we ate the "screen" keyword before it's called.
screen = renpy.screenlang.parse_screen(l)
l.advance()
if l.keyword('python'):
if not screen:
return [ ]
hide = False
if l.keyword('hide'):
hide = True
rv = ast.Screen(loc, screen)
l.require(':')
l.expect_block('python block')
if not l.init:
rv = ast.Init(loc, [ rv ], -500)
python_code = l.python_block()
l.advance()
block = [ ast.Python(loc, python_code, hide) ]
else:
l.require(':')
l.expect_eol()
l.expect_block('init statement')
block = parse_block(l.subblock_lexer(True))
l.advance()
return ast.Init(loc, block, priority)
# Try parsing as a user-statement. If that doesn't work, revert and
# try as a say.
return rv
@statement("")
def say_statement(l, loc):
state = l.checkpoint()
word = l.word()
if (word,) in renpy.statements.registry:
text = l.text
l.expect_noblock(word + ' statement')
l.advance()
renpy.exports.push_error_handler(l.error)
try:
rv = ast.UserStatement(loc, text)
finally:
renpy.exports.pop_error_handler()
return rv
l.revert(state)
# Try parsing as the default statement.
if () in renpy.statements.registry:
text = l.text
l.expect_noblock('default statement')
l.advance()
renpy.exports.push_error_handler(l.error)
try:
rv = ast.UserStatement(loc, text)
finally:
renpy.exports.pop_error_handler()
return rv
# The one and two arguement say statements are ambiguous in terms
# of lookahead. So we first try parsing as a one-argument, then a
# two-argument.
# We're using the checkpoint from above.
# Try for a single-argument say statement.
what = l.string()
if l.keyword('with'):
@@ -1740,8 +1787,34 @@ def parse_statement(l):
l.advance()
return ast.Say(loc, who, what, with_)
# This reports a parse error for any bad statement.
l.error('expected statement.')
##############################################################################
# Functions called to parse things.
def parse_statement(l):
"""
This parses a Ren'Py statement. l is expected to be a Ren'Py lexer
that has been advanced to a logical line. This function will
advance l beyond the last logical line making up the current
statement, and will return an AST object representing this
statement, or a list of AST objects representing this statement.
"""
# Store the current location.
loc = l.get_location()
pf = statements.parse(l)
if pf is None:
l.error("expected statement.")
return pf(l, loc)
def parse_block(l):
"""
This parses a block of Ren'Py statements. It returns a list of the
+123 -96
View File
@@ -23,11 +23,8 @@
# contained within the script file. It also handles rolling back the
# game state to some time in the past.
from compiler import parse
from compiler.pycodegen import ModuleCodeGenerator, ExpressionCodeGenerator
# from compiler.misc import set_filename
import compiler.ast as ast
# Import the python ast module, not ours.
ast = __import__("ast", { })
import marshal
import random
@@ -72,9 +69,9 @@ def reached(obj, reachable, wait):
pass
try:
# Treat as iterable
# Treat as iterable
if not isinstance(obj, basestring):
for v in obj:
for v in obj.__iter__():
reached(v, reachable, wait)
except:
pass
@@ -111,48 +108,47 @@ def reached_vars(store, reachable, wait):
##### Code that replaces literals will calls to magic constructors.
def wrap_node(n):
"""
Replaces literal lists and dictionaries, and list comprehensions,
with calls to the appropriate Ren'Py constructors.
"""
class WrapNode(ast.NodeTransformer):
if isinstance(n, (ast.List, ast.ListComp)):
n = ast.CallFunc(node=ast.Name('__renpy__list__'),
args=[ n ],
star_args=None,
dstar_args=None,
)
def visit_ListComp(self, n):
return ast.Call(
func = ast.Name(
id="__renpy__list__",
ctx=ast.Load()
),
args = [ self.generic_visit(n) ],
keywords = [ ],
starargs = None,
kwargs = None)
elif isinstance(n, ast.Dict):
n = ast.CallFunc(node=ast.Name('__renpy__dict__'),
args=[ n ],
star_args=None,
dstar_args=None,
)
def visit_List(self, n):
if not isinstance(n.ctx, ast.Load):
return self.generic_visit(n)
return n
return ast.Call(
func = ast.Name(
id="__renpy__list__",
ctx=ast.Load()
),
args = [ self.generic_visit(n) ],
keywords = [ ],
starargs = None,
kwargs = None)
def visit_Dict(self, n):
def recursively_replace(o, func):
"""
Walks through a compiler AST, calling the supplied function when a
node is encountered, and replacing the node with the return value.
"""
return ast.Call(
func = ast.Name(
id="__renpy__dict__",
ctx=ast.Load()
),
args = [ self.generic_visit(n) ],
keywords = [ ],
starargs = None,
kwargs = None)
if isinstance(o, list):
return [ recursively_replace(i, func) for i in o ]
wrap_node = WrapNode()
if isinstance(o, tuple):
return tuple([ recursively_replace(i, func) for i in o ])
if isinstance(o, ast.Node):
for k in vars(o):
setattr(o, k, recursively_replace(getattr(o, k), func))
return func(o)
return o
def set_filename(filename, offset, tree):
"""Set the filename attribute to filename on every node in tree"""
@@ -168,7 +164,7 @@ def set_filename(filename, offset, tree):
worklist.extend(node.getChildNodes())
def make_unicode(m):
def unicode_sub(m):
"""
If the string s contains a unicode character, make it into a
unicode string.
@@ -192,6 +188,13 @@ def make_unicode(m):
string_re = re.compile(r'([uU]?[rR]?)("""|"|\'\'\'|\')((\\.|.)*?)\2')
def escape_unicode(s):
s = s.encode("raw_unicode_escape")
if "\\u" in s:
s = string_re.sub(unicode_sub, s)
return s
def py_compile(source, mode, filename='<none>', lineno=1):
"""
@@ -199,7 +202,7 @@ def py_compile(source, mode, filename='<none>', lineno=1):
Lists, List Comprehensions, and Dictionaries are wrapped when
appropriate.
@param source: The sourccode, as a string.
@param source: The source code, as a string.
@param mode: 'exec' or 'eval'.
@@ -208,52 +211,42 @@ def py_compile(source, mode, filename='<none>', lineno=1):
@param lineno: The line number of the first line of the source code.
"""
if isinstance(source, ast.Module):
return compile(source, filename, mode)
if isinstance(source, renpy.ast.PyExpr):
filename = source.filename
lineno = source.linenumber
orig_source = source
source = source.replace("\r", "")
source = source.encode('raw_unicode_escape')
if "\\u" in source:
source = string_re.sub(make_unicode, source)
if mode == "exec":
source = "from __future__ import with_statement\n" + source
line_offset = 2
else:
line_offset = 1
source = escape_unicode(source)
try:
tree = parse(source, mode)
except SyntaxError, e:
line_offset = lineno - 1
tree = ast.parse(source, filename, mode)
tree = wrap_node.visit(tree)
ast.fix_missing_locations(tree)
ast.increment_lineno(tree, lineno - 1)
line_offset = 0
return compile(tree, filename, mode)
except SyntaxError, e:
if e.lineno is not None:
msg = "Syntax error on line %d of %s" % (e.lineno + lineno - line_offset, filename)
e.lineno += line_offset
if len(source) < 128:
msg += ":\n " + orig_source
raise Exception(msg)
else:
raise
recursively_replace(tree, wrap_node)
if mode == 'exec':
set_filename(filename, lineno - line_offset, tree)
cg = ModuleCodeGenerator(tree)
else:
set_filename(filename, lineno - line_offset, tree)
cg = ExpressionCodeGenerator(tree)
return cg.getCode()
raise e
def py_compile_exec_bytecode(source, **kwargs):
code = py_compile(source, 'exec', **kwargs)
return marshal.dumps(code)
def py_compile_eval_bytecode(source, **kwargs):
source = source.strip()
code = py_compile(source, 'eval', **kwargs)
@@ -561,7 +554,7 @@ class Rollback(renpy.object.Object):
Rollback was first created.
"""
for obj, roll in self.objects:
for obj, roll in reversed(self.objects):
obj.rollback(roll)
for t in self.store:
@@ -681,26 +674,48 @@ class RollbackLog(renpy.object.Object):
store.append((k, v))
self.ever_been_changed[k] = True
for k in new_store:
if k not in self.old_store:
store.append((k, ))
self.ever_been_changed[k] = True
for i in range(4):
try:
for k in new_store:
if k not in self.old_store:
store.append((k, ))
self.ever_been_changed[k] = True
break
except RuntimeError:
# This can occur when new_store is updated as we're
# iterating over it.
pass
self.current.store = store
# Update the list of mutated objects, and what we need to do
# to restore them.
self.current.objects = [ ]
for k, (ref, roll) in self.mutated.iteritems():
for i in range(4):
obj = ref()
if obj is None:
continue
self.current.objects = [ ]
self.current.objects.append((obj, roll))
try:
for k, (ref, roll) in self.mutated.iteritems():
obj = ref()
if obj is None:
continue
self.current.objects.append((obj, roll))
break
except RuntimeError:
# This can occur when self.mutated is changed as we're
# iterating over it.
pass
def get_roots(self):
"""
Return a map giving the current roots of the store. This is a
@@ -868,6 +883,9 @@ class RollbackLog(renpy.object.Object):
# Flag that we're in the transition immediately after a rollback.
renpy.game.after_rollback = True
# Stop the sounds.
renpy.audio.audio.rollback()
# Restart the game with the new state.
raise renpy.game.RestartException(renpy.game.contexts[:], label)
@@ -925,16 +943,18 @@ class RollbackLog(renpy.object.Object):
# We never make it this far.
def py_exec_bytecode(bytecode, hide=False):
store = vars(renpy.store)
def py_exec_bytecode(bytecode, hide=False, globals=None, locals=None):
if hide:
locals = { }
else:
locals = store
exec marshal.loads(bytecode) in store, locals
if globals is None:
globals = renpy.store.__dict__
if locals is None:
locals = globals
exec bytecode in globals, locals
def py_exec(source, hide=False, store=None):
@@ -949,9 +969,17 @@ def py_exec(source, hide=False, store=None):
exec py_compile(source, 'exec') in store, locals
def py_eval_bytecode(bytecode):
return eval(marshal.loads(bytecode), vars(renpy.store))
def py_eval_bytecode(bytecode, globals=None, locals=None):
if globals is None:
globals = renpy.store.__dict__
if locals is None:
locals = globals
return eval(bytecode, globals, locals)
def py_eval(source, globals=None, locals=None):
@@ -966,7 +994,6 @@ def py_eval(source, globals=None, locals=None):
return eval(py_compile(source, 'eval'), globals, locals)
# Code for pickling bound methods.
def method_pickle(method):
+1155
View File
File diff suppressed because it is too large Load Diff
+34 -16
View File
@@ -30,6 +30,7 @@ import imp
import difflib
import md5
import time
import marshal
from cPickle import loads, dumps
@@ -94,6 +95,10 @@ class Script(object):
walking the various ASTs to initialize this Script object.
"""
# Set us up as renpy.game.script, so things can use us while
# we're loading.
renpy.game.script = self
# A key that's used to lock the script file, should that
# prove necessary.
self.key = renpy.game.options.lock
@@ -105,7 +110,8 @@ class Script(object):
self.namemap = { }
self.all_stmts = [ ]
self.all_pycode = [ ]
self.record_pycode = True
# Bytecode caches.
self.bytecode_oldcache = { }
self.bytecode_newcache = { }
@@ -241,11 +247,15 @@ class Script(object):
# See if we have a corresponding .rpyc file. If so, then
# we want to try to upgrade our .rpy file with it.
try:
self.record_pycode = False
old_data, old_stmts = self.load_file_core(dir, fn + "c")
self.merge_names(old_stmts, stmts)
del old_data
del old_stmts
except:
pass
finally:
self.record_pycode = True
self.assign_names(stmts, fullfn)
@@ -281,12 +291,9 @@ class Script(object):
return None, None
return data, stmts
def load_file(self, dir, fn, initcode):
# Actually do the loading.
data, stmts = self.load_file_core(dir, fn)
if data is None:
@@ -330,9 +337,6 @@ class Script(object):
if init:
initcode.append(init)
# Add any PyCode to all_pycode.
self.all_pycode.extend(node.get_pycode())
if isinstance(node, renpy.ast.EarlyPython):
early.append(node)
@@ -425,19 +429,34 @@ class Script(object):
old_ei = renpy.game.exception_info
renpy.game.exception_info = "While compiling python block starting at line %d of %s." % (i.location[1], i.location[0])
if i.mode == 'exec':
code = renpy.python.py_compile_exec_bytecode(i.source, filename=i.location[0], lineno=i.location[1])
elif i.mode == 'eval':
code = renpy.python.py_compile_eval_bytecode(i.source, filename=i.location[0], lineno=i.location[1])
try:
if i.mode == 'exec':
code = renpy.python.py_compile_exec_bytecode(i.source, filename=i.location[0], lineno=i.location[1])
elif i.mode == 'eval':
code = renpy.python.py_compile_eval_bytecode(i.source, filename=i.location[0], lineno=i.location[1])
except SyntaxError, e:
pem = renpy.parser.ParseError(
filename = e.filename,
number = e.lineno,
msg = e.msg,
line = e.text,
pos = e.offset)
renpy.parser.parse_errors.append(pem.message)
continue
renpy.game.exception_info = old_ei
codes[magic] = code
i.source = None
i.bytecode = code
i.bytecode = marshal.loads(code)
self.bytecode_newcache[i.location] = codes
self.all_pycode = [ ]
@@ -477,7 +496,6 @@ class Script(object):
return label in self.namemap
def load_script():
rv = Script()
return rv
Script()
+29 -36
View File
@@ -27,16 +27,12 @@ import renpy
# statements to dictionaries giving the methods used for that statement.
registry = { }
parsers = renpy.parser.ParseTrie()
def register(name, parse=None, lint=None, execute=None, predict=None, next=None, scry=None):
if name == "":
name = ()
else:
name = tuple(name.split())
name = tuple(name.split())
if registry.get(name) is not None:
renpy.exports.error("The statement '%s' has already been registered." % (" ".join(name)))
registry[name] = dict(parse=parse,
lint=lint,
execute=execute,
@@ -44,14 +40,29 @@ def register(name, parse=None, lint=None, execute=None, predict=None, next=None,
next=next,
scry=scry)
while True:
name = name[:-1]
if not name:
break
# The function that is called to create an ast.UserStatement.
def parse_user_statement(l, loc):
renpy.exports.push_error_handler(l.error)
try:
rv = renpy.ast.UserStatement(loc, l.text)
l.expect_noblock(" ".join(name) + " statement.")
l.advance()
finally:
renpy.exports.pop_error_handler()
return rv
renpy.parser.statements.add(name, parse_user_statement)
# The function that is called to get our parse data.
def parse_data(l):
return (name, registry[name]["parse"](l))
parsers.add(name, parse_data)
if name not in registry:
registry[name] = None
def parse(node, line):
block = [ (node.filename, node.linenumber, line, [ ]) ]
@@ -61,29 +72,11 @@ def parse(node, line):
renpy.exports.push_error_handler(l.error)
try:
name = ()
pf = parsers.parse(l)
if pf is None:
l.error("Could not find user-defined statement at runtime.")
while True:
cpt = l.checkpoint()
word = l.word()
if word is None:
break
newname = name + (word,)
if newname not in registry:
break
name = newname
l.revert(cpt)
if registry[name] is None:
renpy.exports.error("'%s' is the prefix of a statement, but not a statement." % (" ".join(name)))
return None
return ( name, registry[name]["parse"](l) )
return pf(l)
finally:
renpy.exports.pop_error_handler()
+15 -1
View File
@@ -53,6 +53,10 @@ _config = renpy.config
# The special character used for name-only dialogue.
name_only = None
# Used by the ui functions.
_widget_by_id = None
_widget_properties = { }
class _Config(object):
def register(self, name, default, cat=None, help=None):
@@ -109,6 +113,8 @@ from renpy.python import revertable_sorted as sorted
eval = renpy.python.py_eval
# Displayables.
Bar = renpy.display.behavior.Bar
Button = renpy.display.behavior.Button
@@ -121,6 +127,8 @@ Solid = renpy.display.image.Solid
LiveComposite = renpy.display.layout.LiveComposite
LiveCrop = renpy.display.layout.LiveCrop
LiveTile = renpy.display.layout.LiveTile
Null = renpy.display.layout.Null
Window = renpy.display.layout.Window
Viewport = renpy.display.layout.Viewport
@@ -171,6 +179,9 @@ Speaker = Character = renpy.character.Character
DynamicCharacter = renpy.character.DynamicCharacter
MultiPersistent = renpy.loadsave.MultiPersistent
Action = renpy.ui.Action
BarValue = renpy.ui.BarValue
Style = renpy.style.Style
absolute = renpy.display.core.absolute
@@ -280,7 +291,8 @@ adv = ADVCharacter(None,
who_style='say_label',
what_style='say_dialogue',
window_style='say_window',
screen='say',
kind=False)
def predict_say(who, what):
@@ -298,6 +310,8 @@ def say(who, what, interact=True):
_last_say_who = None
_last_say_what = None
# Used to store the things pinned into the cache.
_cache_pin_set = set()
__name__ = 'store'
+133 -33
View File
@@ -109,7 +109,8 @@ def expand_anchor(v):
"""
return anchors.get(v, v)
# A map of properties that we know about. The properties may take a
# function that is called to convert the argument to something more
# useful.
@@ -186,27 +187,106 @@ style_properties = dict(
ypos = None,
)
def index_0(a):
return a[0]
def index_1(a):
return a[1]
def index_2(a):
return a[2]
def index_3(a):
return a[3]
def always_true(a):
return True
def always_0(a):
return 0
substitutes = dict(
xmargin = [ 'left_margin', 'right_margin' ],
ymargin = [ 'top_margin', 'bottom_margin' ],
xalign = [ 'xpos', 'xanchor' ],
yalign = [ 'ypos', 'yanchor' ],
xpadding = [ 'left_padding', 'right_padding' ],
ypadding = [ 'top_padding', 'bottom_padding' ],
minwidth = [ 'min_width' ],
textalign = [ 'text_align' ],
slow_speed = [ 'slow_cps' ],
xmargin = [
('left_margin', None),
('right_margin', None)
],
ymargin = [
('top_margin', None),
('bottom_margin', None),
],
xalign = [
('xpos', None),
('xanchor', None),
],
yalign = [
('ypos', None),
('yanchor', None),
],
xpadding = [
('left_padding', None),
('right_padding', None),
],
ypadding = [
('top_padding', None),
('bottom_padding', None),
],
minwidth = [ ('min_width', None) ],
textalign = [ ('text_align', None) ],
slow_speed = [ ('slow_cps', None) ],
enable_hover = [ ],
left_gutter = [ 'fore_gutter' ],
right_gutter = [ 'aft_gutter' ],
top_gutter = [ 'fore_gutter' ],
bottom_gutter = [ 'aft_gutter' ],
left_bar = [ 'fore_bar' ],
right_bar = [ 'aft_bar'],
top_bar = [ 'fore_bar' ],
bottom_bar = [ 'aft_bar'],
box_spacing = [ 'spacing' ],
box_first_spacing = [ 'first_spacing' ],
left_gutter = [ ('fore_gutter', None) ],
right_gutter = [ ('aft_gutter', None) ],
top_gutter = [ ('fore_gutter', None) ],
bottom_gutter = [ ('aft_gutter', None) ],
left_bar = [ ('fore_bar', none_is_null) ],
right_bar = [ ('aft_bar', none_is_null) ],
top_bar = [ ('fore_bar', none_is_null) ],
bottom_bar = [ ('aft_bar', none_is_null) ],
box_spacing = [ ( 'spacing', None ) ],
box_first_spacing = [ ( 'first_spacing', None) ],
pos = [
('xpos', index_0),
('ypos', index_1),
],
anchor = [
('xanchor', index_0),
('yanchor', index_1),
],
# Conflicts w/ a variable used in the Style implementation.
# offset = [
# ('xoffset', index_0),
# ('yoffset', index_1),
# ],
align = [
('xpos', index_0),
('ypos', index_1),
('xanchor', index_0),
('yanchor', index_1),
],
maximum = [
('xmaximum', index_0),
('ymaximum', index_1),
],
area = [
('xpos', index_0),
('ypos', index_1),
('xanchor', always_0),
('yanchor', always_0),
('xfill', always_true),
('yfill', always_true),
('xmaximum', index_2),
('ymaximum', index_3),
('xminimum', index_2),
('yminimum', index_3),
],
)
# Map from property to number.
@@ -247,12 +327,20 @@ def init():
func = style_properties[prop]
expansions[prefix + prop] = [ (prio, propn + prefix_offset[a], func) for a in alts ]
# Expand out substitutes.
for k in substitutes.keys():
for r in roles:
for p in prefixes + [ '' ]:
expansions[r + p + k] = [ a for b in substitutes[k] for a in expansions[r + p + b] ]
# Expand out substitutes.
for prefix, (prio, alts) in prefix_subs.iteritems():
for virtual_prop, replacements in substitutes.iteritems():
expansions[prefix + virtual_prop] = [ ]
for real_prop, function in replacements:
propn = property_number[real_prop]
for a in alts:
expansions[prefix + virtual_prop].append((prio, propn + prefix_offset[a], function))
# Cache mappings for position properties.
for i in ('xpos', 'xanchor', 'xoffset', 'ypos', 'yanchor', 'yoffset', 'subpixel'):
globals()["prop_" + i] = property_number[i]
@@ -296,14 +384,28 @@ def reset():
class StyleManager(object):
"""
This is the singleton object that is exported into the store
as style
as style.
"""
def __getattr__(self, name):
try:
return style_map[name]
except:
raise Exception('The style %s does not exist.' % name)
pass
# Automatically create styles, maybe.
if not styles_built:
if "_" in name:
first, rest = name.split("_", 1)
if rest in style_map:
s = Style(rest)
self.__setattr__(name, s)
return s
else:
raise Exception("The style %s does not exist, and couldn't be auto-created because %s doesn't exist, either." % (name, rest))
raise Exception('The style %s does not exist.' % name)
def __setattr__(self, name, value):
@@ -389,7 +491,7 @@ def expand_properties(properties):
# This builds the style.
def build_style(style):
if style.cache is not None:
return
@@ -504,7 +606,7 @@ def build_styles():
global styles_pending
global styles_built
for s in styles_pending:
build_style(s)
@@ -564,7 +666,8 @@ def style_metaclass(name, bases, attrs):
self.delattr(k)
attrs[k] = property(None, setter_a, deleter_a)
for k, number in property_number.iteritems():
def getter_b(self, number=number):
return self.cache[self.offset + number]
@@ -660,9 +763,6 @@ class Style(object):
if properties:
self.properties.append(properties)
# for prio, prop, val in expand_properties(properties):
# self.properties[prop] = val
if heavy:
if styles_built:
+732 -211
View File
File diff suppressed because it is too large Load Diff
+278
View File
@@ -0,0 +1,278 @@
<!-- -*- wikipedia -*- -->
= Screen Language =
__TOC__
The user interface of a Ren'Py game is divided into screens. Some screens are shown to the user inside the game, including the screens for dialogue and menu choices. Other screens are used for the main menu and the game menu. Ren'Py's screen language provides a flexible and mostly-declarative way of defining these screens.
Widgets are displayables that have a user interface function. A screen is a collection of widgets. There can be more than one screen displayed at a time, provided that a screen doesn't conflict with other shown screens. Generally, only the uppermost screen will accept input from the user, but screens are able to declare that they pass input to the next lower screen.
== Screen Language Basics ==
'''Syntax.''' Statements in the screen language share a common syntax. Each statement consists of a single logical line, followed by an optional block.
The first logical line begins with the statement names, which determines what kind of statement this is. The name is followed by space-separated positional arguments, if the statement takes any. The positional arguments are followed by space-separated keyword parameters. The first line ends with a colon if it takes a block. Otherwise, the statement ends at the end of the line.
A keyword parameter consists of a name, a space, and then a value for the parameter. The value is parsed as a simple_expression, unless a more specific parsing method is noted in the parameter's description.
There are two kinds of lines that can go in the block of a screen language statement. The first kind of line is a keyword parameter line, which consists of one or more space-separated keyword parameters. The second is a screen language statement, that defines a widget to be placed within this one. As a matter of good style, all optional parameters in a block should be placed before the first screen language statement in that block, but Ren'Py does not enforce this restriction.
'''Relative Placement.''' When a child widget is contained within a parent widget, it is positioned relative to the area offered to it by the parent widget.
'''child-fixed Placement.''' Several widgets place their children using child-fixed placement. This means that:
* If the widget has exactly one child widget, then the child is added directly.
* Otherwise, a fixed layout is added to the widget, and the children are added to the child widget. Since a fixed widget will expand to consume all space, it will often be necessary to allocate a particular amount of space using ''area'' or other style properties.
'''Namespaces.''' When screens execute python code, they execute it in a context that consists of three namespaces:
# The local namespace contains parameters passed in when the scene is shown, and variables updated over the course of displaying the scene. This is the only namespace that can be updated when displaying the scene.
# The scene language namespace contains the Actions and Adjustments given below. This namespace is available as the sl module, which is imported into the default Ren'Py namespace.
# The default Ren'Py namespace, which is the namespace where Python variables are stored by default.
When a variable is accessed, the namespaces are searched in order.
== Common Keyword Arguments ==
There are several kinds of keyword arguments that are common to many of the screen language statements. We define those keyword arguments here, so we don't have to repeat them for each statement below.
''id'' - (string) The id argument is used to assign a name to the widget created by this statement. This has two purposes. The first is to make the widget available to the code that displays the screen. The second is to allow the code that displays the screen to associate additional style information with the widget.
For example, a screen that's used for dialogue is expected to have widgets with the ids of "who", "what", and "window" defined. These widgets receive style information from the Character class. The "what" widget is also used to pause dialogue, and to inform the auto-forward mode how much dialogue is being displayed.
''at'' - (comma-separated list of simple expressions) The at statement is used to specify a list of transforms that are applied to the widget before being added to its parent. The transforms are applied to the widget in a left-to-right order, which means that the rightmost transform takes priority.
''style'' - (simple expression) This is evaluated to yield a style, which is used for the widget. The style may be:
* A string, in which case it is the style name.
* A style object, of the form style.style_name.
=== Style Properties ===
Many widgets also take style properties from one or more style property groups as keyword arguments. Each keyword argument should consist of a style property prefix and style property name. These property arguments are used to override aspects of the default widget style.
The ''area'' property is quite useful for screen language widgets, as it allows them to be positioned and sized on the screen.
== Declaring Screens ==
The screen statement is used to declare a screen. The screen statement is a statement in the Ren'Py script language, rather than the screen language proper. It is parsed using screen language rules.
The screen statement takes two positional argument:
* The first argument is optional. If present, it should be an integer, which gives the init level that the statement runs at, when the screen statement is not inside an init statement.
* The second argument is mandatory. It is a name, that gives the name of the screen that is being defined.
The root widget of a screen is a fixed layout. The fixed layout is implicitly created when the screen is; child widgets are added to the fixed layouts.
A screen takes the following optional common keyword arguments, which are applied to the fixed layout within it:
* ''id''
* ''at''
* ''style'' (defaults to "screen")
* Position Style Properties
== Imagemap Widget Statements ==
The screen language contains three statements that work with imagemaps. The imagemap statement is used to declare an imagemap, optionally placing a base image onto the screen. The hotspot and hotbar statements are used to declare areas of the images that the user can interact with.
=== imagemap ===
The imagemap statement is used to declare an imagemap. The imagemap is used by hotspots and hotbars that are contained within the imagemap.
''auto'' - (string) A string that is used to generate default values for all of the other imagemap parameters. The string is expected to contain %s in it. For each of the parameters given below, the %s is replaced with the parameter name. If the file exists, it becomes the value of the parameter. Auto conflicts with the rest of the keyword parameters.
''ground'' - (Displayable) Used for parts of the imagemap that are not part of a hotspot or hotbar.
''insensitive'' - (Displayable) Used for hotspots and hotbars that are insensitive. Defaults to ''ground''.
''idle'' - (Displayable) Used for unfocused unselected hotspots, and the empty part of unfocused hotbars. Defaults to ''ground''.
''hover'' - (Displayable) Used for focused unselected hotspots, and the empty part of focused hotbars. Defaults to ''ground''.
''selected_idle'' - (Displayable) Used for unfocused selected hotspots, and for the filled part of unfocused hotbars. Defaults to ''idle''.
''selected_hover'' - (Displayable) Used for focused selected hotspots, and for the filled part of focused hotbars. Defaults to ''idle''.
An imagemap is really a fixed layout that images are added to. As such, it can contain any widget, but hotspots and hotbars are the most useful.
The imagemap statement takes the following optional common keyword arguments:
* ''id''
* ''at''
* ''style'' (defaults to "imagemap")
* Position Style Properties
== Non-Imagemap Widget Statements ==
These statements declare widgets that do not use an imagemap.
=== text ===
The text statement is used to show text. The text statement takes a single mandatory positional argument, a simple_expression giving the text to show on the screen.
The text statement takes the following optional common keyword arguments:
* ''id''
* ''at''
* ''style'' (defaults to "default")
* Position Style Properties
* Text Style Properties
Text cannot contain child widgets.
=== button ===
The button statement is used to create a button the user can focus and activate. It takes no positional arguments. It takes the following optional keyword arguments:
''clicked'' - (Action) The action to take when the button is activated. The clicked action is also used to determine of if the button should be styled in a selected, normal, or insensitive style.
''hovered'' - (Action) The action to take when the button gains focus.
''unhovered'' - (Action) The action to take when the button loses focus.
''keymap'' - (dict of key to Action) The keymap that is in place when the button is focused. When the given key is pressed, the action is run. The keys of the dictionary are either keysyms (like "mouseup_1", "K_F1", or "m") or key bindings defined in config.keymap (like "skip" or "save_delete").
The button statement takes the following optional common keyword arguments:
* ''id''
* ''at''
* ''style'' (defaults to "button")
* Position Style Properties
* Window Style Properties
* Button Style Properties
A button may have any number of children, using child-fixed placement.
=== textbutton ===
The textbutton statement is used to create a button containing text in a single declaration. It takes a single mandatory positional argument, a simple_expression giving the text to display in the button.
These optional keyword arguments are given the same meaning as they have in the button statement:
* ''clicked''
* ''hovered''
* ''unhovered''
* ''keymap''
The textbutton statement takes the following optional common keyword arguments:
* ''id''
* ''at''
* ''style'' (defaults to "button")
* Position Style Properties
* Window Style Properties
* Button Style Properties
When the ''style'' argument is a string, the style of the text contained within the button is set to style + "_text". For example, if the style is "button", then the text is given the style "button_text".
A textbutton cannot have any child widgets.
=== hbox ===
The hbox statement creates a box that lays out its child widgetshorizontally. It takes no positional arguments. It takes the following optional common keyword arguments:
* ''id''
* ''at''
* ''style'' (defaults to "hbox")
* Position Style Properties
* Box Style Properties
A hbox is expected to have one or more child widgets.
=== vbox ===
The vbox statement creates a box that lays out its child widgets horizontally. It takes no positional arguments. It takes the following optional common keyword arguments:
* ''id''
* ''at''
* ''style'' (defaults to "hbox")
* Position Style Properties
* Box Style Properties
A vbox is expected to have one or more child widgets.
=== fixed ===
The fixed statement creates a box that lays out its child widgets according to the position provided by the child widget. It takes no positional arguments. It takes the following optional common keyword arguments:
* ''id''
* ''at''
* ''style'' (defaults to "hbox")
* Position Style Properties
* Box Style Properties
A fixed layout is expected to have one or more child widgets.
=== window/frame ===
The window and frame statements create windows that can contain the other widget. The only difference between the two statements is the default style. The window statement uses a style that is appropriate for the display of in-game text, while the frame statement uses a style that is designed to contain user-interface widgets.
These statements do not take positional arguments. They take the following optional common keyword arguments:
* ''id''
* ''at''
* ''style'' (defaults to "hbox")
* Position Style Properties
* Window Style Properties
Windows and frames can have any number of children, using child-fixed placement.
=== key ===
The key statement creates a keybinding that causes an action to occur when the key is pressed. It takes one positional argument, the name of the keysym. It takes the following optional keyword argument:
''action'' - (Action) An action to run when the key is pressed.
The key statement is useless if an action argument is not defined. Keys cannot have child widgets.
transform
input
image
hotspot
hotbar
imagebutton
bar
slider?
vbar
vslider
autobar?
timer
== Screen Language Control Statements ==
== Actions ==
== Adjustments ==
== Using Screens ==
== Python Equivalent ==
button area (100, 200, 100, 200)
+135
View File
@@ -0,0 +1,135 @@
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/TheRenPyVisualNovelEngine.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/TheRenPyVisualNovelEngine.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/TheRenPyVisualNovelEngine"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/TheRenPyVisualNovelEngine"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
make -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
upload:
rsync -a build/html tom@onegeek.org:/home/tom/WWW.renpyorg/doc
rsync -a build/latex tom@onegeek.org:/home/tom/WWW.renpyorg/doc
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
DIR="`readlink -f $0`"
DIR="`dirname $DIR`"
echo $DIR
cd $DIR
../renpy.py .
sphinx-build -a source build/html
+230
View File
@@ -0,0 +1,230 @@
import inspect
import re
import collections
import keyword
import renpy
import shutil
# Keywords in the Ren'Py script language.
KEYWORD1 = """\
$
as
at
behind
call
expression
hide
if
in
image
init
jump
menu
onlayer
python
return
scene
set
show
with
while
zorder
transform
play
queue
stop
pause
define
screen
"""
# Words that are sometimes statement keywords, like for ATL
# or Screen language statements.
KEYWORD2 = """\
nvl
window
repeat
block
contains
parallel
choice
on
time
function
event
animation
clockwise
counterclockwise
circles
knot
null
text
hbox
vbox
fixed
grid
side
frame
key
timer
input
button
imagebutton
textbutton
bar
vbar
viewport
imagemap
hotspot
hotbar
transform
add
use
has
"""
def write_keywords():
f = file("source/keywords.py", "w")
kwlist = list(keyword.kwlist)
kwlist.extend(KEYWORD1.split())
kwlist.extend(KEYWORD2.split())
kwlist.sort()
f.write("keywords = %r\n" % kwlist)
properties = list(i for i in renpy.screenlang.all_keyword_names if i not in kwlist)
properties.sort()
f.write("properties = %r\n" % properties)
f.close()
shutil.copy("source/keywords.py", "../tutorial/game/keywords.py")
# A map from filename to a list of lines that are supposed to go into
# that file.
line_buffer = collections.defaultdict(list)
def scan(name, o):
# The type of object we're dealing with.
doc_type = "function"
# The section it's going into.
section = None
# The formatted arguments.
args = None
# Get the function's docstring.
doc = inspect.getdoc(o)
if not doc:
return
# Break up the doc string, scan it for specials.
lines = [ ]
for l in doc.split("\n"):
m = re.match(r':doc: *(\w+) *(\w+)?', l)
if m:
section = m.group(1)
if m.group(2):
doc_type = m.group(2)
continue
m = re.match(r':args: *(.*)', l)
if m:
args = m.group(1)
continue
m = re.match(r':name: *(\S+)', l)
if m:
if name != m.group(1):
return
continue
lines.append(l)
if section is None:
return
if args is None:
# Get the arguments.
if inspect.isclass(o):
init = getattr(o, "__init__", None)
if not init:
return
init_doc = inspect.getdoc(init)
if init_doc:
doc += "\n\n"
doc += init_doc
try:
args = inspect.getargspec(init)
except:
args = None
elif inspect.isfunction(o):
args = inspect.getargspec(o)
else:
return
# Format the arguments.
if args is not None:
args = inspect.formatargspec(*args)
args = args.replace("(self, ", "(")
else:
args = "()"
# Put it into the line buffer.
lb = line_buffer[section]
lb.append(".. %s:: %s%s" % (doc_type, name, args))
for l in lines:
lb.append(" " + l)
lb.append("")
def scan_section(name, o):
"""
Scans object o. Assumes it has the name name.
"""
for n in dir(o):
scan(name + n, getattr(o, n))
def write_line_buffer():
for k, v in line_buffer.iteritems():
print "Generating", k
f = file("source/inc/" + k, "w")
print >>f, ".. Automatically generated file - do not modify."
print >>f
for l in v:
print >>f, l
f.close()

Some files were not shown because too many files have changed in this diff Show More