Compare commits

...

358 commits

Author SHA1 Message Date
Shadowfacts 08c5bb1927 Build for arm64 macOS 2022-01-17 11:54:19 -05:00
Ioannis Tsakpinis 2df01dd762 Reset resizable state on destroy. Close #142 2016-12-08 21:50:34 +02:00
Ioannis Tsakpinis 8bb7dfefc6 Store XRandR frequencies in the original format to improve #64
Also, reset the screen configuration on exit only if there has been a display mode change.
2016-09-09 17:25:50 +03:00
Ioannis Tsakpinis d0c96dfef2 Add warnings that the project is not actively maintained 2016-07-14 21:41:59 +03:00
Ioannis Tsakpinis ff352b63dd Merge pull request #124 from chrobione/patch-1
Add mkdir bin to build-generator.xml
2015-12-27 14:54:12 +02:00
Ioannis Tsakpinis 669689f288 Merge pull request #123 from chrobione/patch-2
Update InfoUtilFactory.java
2015-12-27 14:51:49 +02:00
Chrobi 9fd235ddf6 Update InfoUtilFactory.java
Update `calculateImage2DSize` and `calculateImage3DSize` method calls per issue https://github.com/LWJGL/lwjgl/issues/74#issuecomment-167174311
2015-12-26 22:49:01 -07:00
Chrobi 5d716b2b5a Build Error because bin directory not found
From a `git clone` trying to `ant generate-all` on Ubuntu Linux on Odroid XU4 I got the error:  
lwjgl/platform_build/build-generator.xml:26 destination directory  lgwjgl/bin does exist or is not a directory.
2015-12-26 22:28:04 -07:00
Ioannis Tsakpinis a5d81379f7 Fix clCreateImage2D/3D checks 2015-10-11 22:52:50 +03:00
Ioannis Tsakpinis 6650201a6d NV_path_rendering fixes to make it usable 2015-07-28 12:00:33 +03:00
Ioannis Tsakpinis 40694134ab Simplify event to KeySym mapping. Fix #28 2015-05-22 23:48:47 +03:00
Ioannis Tsakpinis a5c4462a3e Ignore setDisplayMode when the Display parent is set. Fix #98 2015-05-20 15:24:16 +03:00
Ioannis Tsakpinis 1dbca8b623 Merge pull request #116 from tfg13/master
further fixes for exotic xrandr outputs
2015-05-14 01:20:20 +03:00
tulius 0b83683ed1 further fixes for exotic xrandr outputs 2015-04-29 21:14:04 +02:00
Ioannis Tsakpinis a33e83ee38 Merge pull request #114 from metc/master
Fix a `java.lang.NullPointerException`.
2015-04-29 20:23:49 +03:00
Christopher Métrailler 36e7e73043 Fix a java.lang.NullPointerException.
See this previous commit 093bfe9698 (diff-9db50c9a42c2d4171ea35b48e3bfcbd3R146)
2015-04-29 19:18:07 +02:00
Ioannis Tsakpinis ef5149a3c3 Merge pull request #113 from Blunderchips/master
Fixed typo in the constructor comments
2015-04-27 12:04:47 +03:00
Matthew 'siD' Van der Bijl 589ce0bd5c Fixed typo in the constructor comments
Fixed a typo above one of the constructors in the Vector2f class.
"Constructor for Vector3f." -> "Constructor for Vector2f."
2015-04-27 10:36:27 +02:00
Ioannis Tsakpinis e4b098c5e2 Do not reset cursor clipping when releasing mouse grab in fullscreen mode. Fix #106
Also refactored and optimized cursor handling.
2015-02-09 17:08:38 +02:00
Ioannis Tsakpinis ae4606c53f Bump version to 2.9.4 2015-01-19 20:41:13 +02:00
Ioannis Tsakpinis 70a8746f9a Fix window resizing when mouse is grabbed and optimize cursor clipping 2015-01-14 01:38:21 +02:00
Ioannis Tsakpinis 89b22fa151 Fix cursor stuttering/drifting with mouse grab and high keyboard repeat rates
In those situations we get multiple WM_MOUSEMOVE events per frame. The problem was that we moved the cursor back to the window center after every such event, right in the middle of the event loop. The fix was to only center the cursor once, after the event buffer has been drained.
2015-01-14 01:09:42 +02:00
Ioannis Tsakpinis 831ac15619 Reset mouse tracking state on window recreation 2015-01-07 20:23:22 +02:00
Ioannis Tsakpinis 67d29a75a0 Fix javadoc error 2015-01-07 20:22:38 +02:00
Ioannis Tsakpinis 301a37c5fe Revert 849511784b 2015-01-05 20:16:56 +02:00
Ioannis Tsakpinis ee2a1c79a3 Improvements to setTitle on Linux
WM_CLASS should not change after window creation. It's illegal (may only change while the window is in the Withdrawn state) and causes flickering issues on the taskbar.

The native setTitle implementation has been changed to use a better fallback when XChangeProperty fails and _NET_WM_ICON_NAME is also set, in addition to _NET_WM_NAME.
2014-12-30 14:50:40 +02:00
Ioannis Tsakpinis 85e5488e4d Enable parallel compilation 2014-12-30 14:35:00 +02:00
Ioannis Tsakpinis 54df7fb066 Fix nightly build link 2014-12-30 14:34:40 +02:00
Ioannis Tsakpinis 6ae9382a11 Bump version to 2.9.3 2014-12-30 14:33:04 +02:00
Ioannis Tsakpinis 4a8e5bf4f7 Merge pull request #104 from md-5/patch-1
Force high performance GPU for Nvidia Optimus systems
2014-12-14 19:00:49 +02:00
md-5 e503ea631c Force high performance GPU for Nvidia Optimus systems 2014-12-14 08:41:37 +11:00
Ioannis Tsakpinis 8cdaf59905 Replace .jnilib with .dylib on OS X with JDK 6. Resolve #100 2014-11-28 13:26:26 +02:00
Ioannis Tsakpinis 45678633f9 Fix libjawt.dylib detection. 2014-11-21 20:06:48 +02:00
Ioannis Tsakpinis e429e2699c Ignore .eh symbols 2014-11-21 20:06:31 +02:00
Ioannis Tsakpinis 132cecf861 Added missing "gl" prefix. 2014-11-03 17:25:46 +02:00
Ioannis Tsakpinis 751e1023f7 Merge pull request #97 from piotr-piastucki/master
Add missing functionality to create empty textures with glCompressedTexImage1/2/3D
2014-10-24 15:07:36 +03:00
Piotr Piastucki 37ebf89df0 Add missing functionality to create empty textures with glCompressedTexImageXD 2014-10-22 23:09:33 +02:00
Ioannis Tsakpinis 4d451457b4 Use OpenAL64 on Windows x64. Fixes #95. 2014-10-08 12:21:46 +03:00
Ioannis Tsakpinis 220f55d914 Merge pull request #93 from b23prodtm/macosx
OS X x86_64 build: fixed typo
2014-10-04 20:01:44 +03:00
b23prodtm ca19ebd11b x86_64 : build symbols issue was fixed 2014-10-03 18:52:58 +02:00
Ioannis Tsakpinis b44f503882 Build the symbols list in the x86_64 only build. 2014-10-02 17:34:03 +03:00
Ioannis Tsakpinis f25e503ce0 Refactored the OS X script for better readability and to enable builds on newer versions.
Issues resolved:

- Added support for the 10.8 (Mountain Lion) and 10.9 (Mavericks) SDKs.
- Dropped universal builds on 10.8 or higher, x86 is not supported anymore.
- Use clang instead of gcc on 10.8 or higher. Fixes a system header compilation error on 10.9.
- Fixed issue with the libjawt path on certain JDKs.
2014-10-01 22:35:25 +03:00
Ioannis Tsakpinis 42ccc83499 Create virtual key up events for all pressed keys when the display loses focus.
This is a workaround for missed key events and incorrect key state reporting. This is actually a cleaner solution to the previous workaround on Windows and works nicely on Linux too.
2014-10-01 21:04:50 +03:00
Ioannis Tsakpinis 035a4d679b Merge pull request #92 from dc740/master
Finally fix support for OpenBSD
2014-09-30 11:15:43 +03:00
Emilio Moretti 079a4b2e9c Fix the last bug and finally support OpenBSD 2014-09-29 22:36:59 -03:00
Ioannis Tsakpinis 76867b161f Merge pull request #54 from qbit/master
enable build on OpenBSD
2014-09-29 20:33:14 +03:00
Ioannis Tsakpinis 1dff231df3 Removed obsolete @Optional annotations. 2014-09-24 23:20:36 +03:00
Ioannis Tsakpinis a570c1c085 Fixed EXT_Cg_shader filename. 2014-09-21 15:33:17 +03:00
Ioannis Tsakpinis e08c0fbf56 Finished work on the annotation processing port from apt to javac.
LWJGL now requires JDK 6 or later to build, but will continue to work on Java 5. In this commit: removed native file "last modified time" handling.
2014-09-15 01:45:48 +03:00
Ioannis Tsakpinis e4fc386372 Fixed field/method order so that javac output matches apt output. 2014-09-15 01:31:22 +03:00
Ioannis Tsakpinis d17c19fe01 Restored check that skips generation if the source template has not changed.
Note that javac still always recompiles everything. This makes the build process slower than before (apt was using the already compiled templates as input). Will investigate some other time if this can be mitigated.
2014-09-14 22:04:51 +03:00
Ioannis Tsakpinis 78911cc0d4 Made the javac-based Generator compatible with JDK 6. 2014-09-14 21:59:47 +03:00
Ioannis Tsakpinis 59323ff03f Automatic code reformatting.
Nothing to see here, just a cleanup so that subsequent commits are cleaner.
2014-09-14 17:16:51 +03:00
Ioannis Tsakpinis 774bd17ece Ported annotation processing from apt to javac.
This is a manual merge of request #86 by @b23prodtm. The original patch is fantastic, but as expected has a few issues that will be fixed in subsequent commits.
2014-09-14 17:07:56 +03:00
Ioannis Tsakpinis 202ce1d522 OpenGL ES build fixes. 2014-09-14 12:42:18 +03:00
Ioannis Tsakpinis f760abeb81 Backported LWJGL 3's handling of System.loadLibrary errors. Resolves #87. 2014-09-13 13:39:22 +03:00
Ioannis Tsakpinis f05778f073 Fixed optional error check. 2014-09-13 12:39:54 +03:00
Ioannis Tsakpinis 46f602f0c6 Code clean-up and minor optimizations. Also made sure that the current mode is always first. 2014-09-13 12:18:40 +03:00
Ioannis Tsakpinis 818adb7312 Merge pull request #88 from tfg13/master
linux: fix parsing of xrandr output for rare screen configurations
2014-09-13 11:35:10 +03:00
tulius e74811e5e7 linux: fix parsing of xrandr output for rare screen configurations
fixes not detecting the current mode if it is not the first on in its list
fixes crash when preferred mode is not current mode
2014-09-03 22:33:40 +02:00
Ioannis Tsakpinis 30412de229 Added support for OpenGL 4.5 and new extensions released with it. 2014-08-16 15:58:50 +03:00
Ioannis Tsakpinis 1ea14545f6 Simplified pattern matching when stripping types and the 'v' postfix, which fixed a few corner cases. 2014-08-16 15:39:04 +03:00
Ioannis Tsakpinis 33e50400d2 Removed obsolete buffer size methods. 2014-08-16 01:59:37 +03:00
Ioannis Tsakpinis 5f5b39d3ca Updated class documentation, added additional constructor (version + profile mask), skip validations if LWJGLUtil.CHECKS is disabled. 2014-08-15 23:36:56 +03:00
Ioannis Tsakpinis 99afa57380 Refactored ContextAttribs: there's now an additional constructor that accepts the profile mask and context flags.
Also simplified the internal state, added more documentation and validation, added support for CONTEXT_RELEASE_BEHAVIOR_ARB, dropped the GLX & WGL helper classes and publicly exposed the attribute tokens.
2014-08-15 14:15:30 +03:00
Ioannis Tsakpinis 52933da812 Merge pull request #81 from tfg13/master
linux: basic compatibility for systems with multiple monitors
2014-08-15 02:01:05 +03:00
tulius 518ad21d6c linux: improved xrandr-based display mode changing
- fullscreen windows appear on primary screen
- bits per pixel is derived from old getAvailableDisplayModes
- removed debug output
2014-08-10 01:38:00 +02:00
Ioannis Tsakpinis 5d094b5763 Removed duplicate constants. 2014-08-06 12:29:16 +03:00
Ioannis Tsakpinis cb759158e7 Fixed some native compilation warnings. 2014-08-04 22:25:12 +03:00
Ioannis Tsakpinis 4aac231951 Application menu: Disabled activation on ALT/F10 key press and enabled on mouse click. 2014-07-22 00:37:47 +03:00
Ioannis Tsakpinis 2b3e069d3a Merge pull request #73 from msteiger/master
Fixed util applet permissions.
2014-07-13 14:28:08 +03:00
Ioannis Tsakpinis fcc0d679b0 Fixed GRAVE (`/~) mapping. Resolves #75. 2014-07-10 13:58:44 +03:00
Ioannis Tsakpinis e38fa15535 Bugfix: Clear(Named)BufferSubData requires an explicit size argument. 2014-07-04 21:04:15 +03:00
Ioannis Tsakpinis 5cf86767bb Fixed WM_WINDOWPOSCHANGED coordinate bug. 2014-06-17 21:05:33 +03:00
kappaOne 85b7a2f5bb Merge pull request #76 from philipwhiuk/master
Fix some straightforward Javadoc problems
2014-05-20 11:17:01 +01:00
Philip Whitehouse fd726e545f Fix some straightforward Javadoc problems 2014-05-20 00:05:53 +01:00
tulius b83d29e265 linux: use xrandr for all display mode changing 2014-05-11 18:04:21 +02:00
Ioannis Tsakpinis 50c0c30499 Use NSOpenGLProfileVersion3_2Core for any OpenGL 3.2+ version. 2014-05-02 23:00:44 +03:00
Martin Steiger 92f309d7ce Fix util applet permissions 2014-04-26 20:51:12 +02:00
kappaOne 132ff0191d Fix a viewport issue on OS X with retina displays when going fullscreen 2014-04-21 12:44:25 +01:00
Ioannis Tsakpinis c17617175b Workaround to preserve case when checking availability of APPLE OpenCL extensions. 2014-04-02 13:36:25 +03:00
kappaOne 3ac0b43efd Merge pull request #63 from b23prodtm/master
macosx CALayer Display.create() / .setParent() / setFullscreen()
2014-03-27 00:55:50 +00:00
kappaOne a6bb6e31d8 Rename native *.jnilib files to *.dylib to allow Java 8 compatibility 2014-03-25 22:02:27 +00:00
Brian Matzon e6522d930d Merge pull request #66 from tfg13/master
Fix  120Hz-reset issue on linux
2014-03-11 21:15:54 +01:00
Ioannis Tsakpinis b699797a27 Removed tokens already defined in previous OpenGL versions. 2014-03-11 11:02:27 +02:00
tulius fc5749e42e Fixed reverting screen settings on exit for multi-monitor setups 2014-03-03 14:44:31 +01:00
tulius a595fe1a5a Test: Read frequency with xrandr 2014-02-16 17:03:49 +01:00
b23prodtm 7a81bde884 Peer lookup fixed. Canvas as parent is displayed fully covered by the CALayer . Need to check if windowed Display works again. 2014-02-02 20:31:19 +01:00
b23prodtm 211b14c8d5 Fixed Mac OS Canvas / CALayer.
http://hg.openjdk.java.net/jdk8/awt/jdk/rev/65d874d16d59
JAWT native CALayer not positioned over Canvas
(Reviewed-by: art, anthony)
Initialy, the layer bounds have the Y coord originating not as
expected. java7 only seems to provoke that issue. so cpeer would update
bounds as necessary now.
by broumbroum
2014-02-01 21:20:27 +01:00
Ioannis Tsakpinis d5d9f06160 Convert local WindowsDisplay jclass reference to global. 2014-01-14 17:11:39 +02:00
kappaOne 2976194124 Merge pull request #61 from Unh0lyTigg/patch-1
Fix javadoc typo in DisplayMode
2014-01-13 03:40:58 -08:00
Unh0lyTigg 5c7b35fa96 Fix javadoc typo in DisplayMode
This has been here for a while...
2014-01-12 19:47:59 -08:00
Ioannis Tsakpinis 55bfecf514 Reverted resizable workaround. 2013-12-22 16:56:00 +02:00
Ioannis Tsakpinis 561a80af3c Removed unnecessary TEXTURE_COORD_ARRAY enable. Caused a crash on NV GPUs. 2013-12-16 18:53:57 +02:00
Ioannis Tsakpinis 5747615c41 Another attempt at fixing the client area bug when toggling resizable. 2013-12-14 16:36:57 +02:00
Ioannis Tsakpinis 66c987f9c2 Fixed Rect/RECT conversion and added a workaround that resets the OpenGL client area when we toggle resizable after window creation. 2013-12-13 15:33:13 +02:00
Ioannis Tsakpinis 1703b62ed5 Removed fullscreen CDS_TEST. It's very slow and unnecessary. 2013-12-03 17:42:03 +02:00
Brian Matzon 0d70b5a8d5 bumped version to 2.9.2 2013-12-02 21:41:21 +01:00
Brian Matzon e7f46b99e2 changed default behavior to not use SecureClassLoader, as it was causing issues since the latest security update 2013-12-02 20:50:04 +01:00
kappaOne 408ac906bb Fix issue where the scaled desktop resolution was not included as part
of the Display.getAvailableDisplayModes() list on OS X
2013-11-22 22:35:14 +00:00
kappaOne 5c288b8d75 Fix the LWJGL AppletLoader so that it works on Java 7u45 2013-11-16 19:05:41 +00:00
kappaOne 38a60ec533 Enable High DPI mode by default (where available) when using fullscreen
mode on OS X as no special changes/scaling is required by applications.
2013-11-14 15:22:39 +00:00
kappaOne d20d5546a3 Finalise implementation of HiDPI mode for OS X 2013-11-12 01:25:06 +00:00
kappaOne eb2e7176b8 Add new LWJGL API Display.getPixelScaleFactor() for use in high DPI
modes, like HiDPI retina mode on OS X.
2013-11-11 23:12:51 +00:00
kappaOne 225bd176cb Implement initial support for High DPI mode on OS X 2013-11-11 00:08:23 +00:00
kappaOne ed95cd0f27 Tweak OS X Fullscreen API mode behaviour, where available its enabled by
default now, can be disabled using the
org.lwjgl.opengl.Display.disableOSXFullscreenModeAPI switch
2013-11-10 02:51:42 +00:00
kappaOne 507bdb6824 Finalise OS X Fullscreen Mode API behaviour 2013-11-10 02:14:55 +00:00
kappaOne 98f8bddce3 Implement 8 bit Icon transparency support on Linux, now using the modern
_NET_WM_ICON method to set the icon, removed legacy
method and associated code.
2013-11-09 19:47:32 +00:00
Ioannis Tsakpinis 4d0aebb39d Make sure clearAWTFocus() runs in the EDT. 2013-11-07 17:04:04 +02:00
kappaOne 75fe62bbea Implement initial support for the OS X 10.7+ fullscreen mode API,
currently enabled using the VM parameter
org.lwjgl.opengl.Display.enableOSXFullscreenModeAPI
2013-11-06 23:41:16 +00:00
kappaOne 675838f692 Don't autoresize CALayer's when using the Java 7 workaround 2013-11-03 22:47:32 +00:00
kappaOne cd666c66cf Fix CALayer/Display.setParent() initial position bug on OS X. 2013-11-03 14:02:22 +00:00
computer ec9b14090b Merge branch 'master' of https://github.com/LWJGL/lwjgl.git 2013-11-03 00:18:36 +00:00
kappaOne e90e5dc172 Fix issue on OS X when using Command + Tab caused the command key to
become stuck.
2013-11-03 00:17:37 +00:00
Ioannis Tsakpinis f97ac09641 Removed NondirectBufferWrapper. It was only used in the Cursor constructor and in a way that could cause crashes: Passing heap buffers to both the images and delays arguments would result in both sharing the same direct memory. 2013-10-30 17:20:28 +02:00
Ioannis Tsakpinis 59a9a970b9 Fixed grabFocus to work when a parented Display is first shown. 2013-10-30 16:26:53 +02:00
Ioannis Tsakpinis 4ff2240b57 Do not apply SW_RESTORE when the window receives focus. Fixes #53. 2013-10-30 15:32:02 +02:00
kappaOne 6c4de65e20 Slight tweak to the controller patch, rename getEventButtonStatus() to
getEventButtonState() to make it consistent with Keyboard and Mouse
classes and remove unused import.
2013-10-29 22:06:20 +00:00
kappaOne aacd16acd1 Merge pull request #39 from momokan/controller_event_buffer
Add controller's button state, x and y axis value to the controller's event buffer.
2013-10-29 14:59:56 -07:00
kappaOne 43a6a8bfbb Implement right mouse click on OS X when pressing control + click. This
restores the previous mouse behaviour as found in LWJGL 2.8.5 and below.
2013-10-28 23:51:44 +00:00
kappaOne 46cbd89430 Remove dependencies on AWT inside the Cursor.getMaxCursorSize() and
Cursor.getMinCursorSize() methods. Fixes a crash on OS X 10.9, thx to
nbf for finding and reporting.
2013-10-27 21:28:11 +00:00
kappaOne 5fb66cce46 Make the WM_CLASS implementation more flexible by giving users
an option to set it manually by VM parameter or system property
2013-10-27 15:07:07 +00:00
kappaOne 8154abe073 Set the WM_CLASS property on Linux as its needed for some WM to display
the app name/class, currently its the same as the window title.
2013-10-27 01:38:37 +01:00
kappaOne dfbb8d3cbc Fix another edge case bug with Display.setParent() on OS X. Thx to
ihkbob for providing test case to reproduce it.
2013-10-26 17:05:44 +01:00
kappaOne 38a3f6696c Fix NPE and position bug with Display.setParent() on OS X 2013-10-26 16:12:18 +01:00
kappaOne adf780c63d Further fixes for Display.setParent() canvas position & size bugs on OS
X
2013-10-22 22:34:03 +01:00
Aaron Bieber 27d444ed74 enable build on OpenBSD 2013-10-22 08:00:50 -06:00
kappaOne ce43cfabd7 Fix Display.setParent() canvas position bug on OS X 2013-10-20 19:25:33 +01:00
Ioannis Tsakpinis 849511784b Only consider the workaround if both shift buttons are pressed. 2013-10-20 15:39:50 +03:00
Ioannis Tsakpinis 7cb0207eef Fixed missing key up events when both shift keys are pressed at the same time. 2013-10-20 15:31:47 +03:00
kappaOne eb85196a0c Fix string index out of bounds exception, credit to @void256 for finding
and reporting.
2013-10-13 19:17:04 +01:00
kappaOne d3254e00f3 Fix keyboard key codes to return Unicode characters instead of ASCII
characters
2013-10-13 15:45:08 +01:00
kappaOne 6b15398855 Fix compilation issue in LWJGLUtil.java 2013-09-05 09:58:13 +01:00
kappaOne 76e400955f Merge pull request #44 from frustaci/patch-1
fix wrong log message in LWJGLUtil.java, credit to frustaci for patch.
2013-09-03 03:04:44 -07:00
kappaOne 248274bace Merge pull request #47 from sashok7241/patch-1
Fix BigEndian issue when reading files with WaveData.java, full credit to sashok7241 for patch.
2013-09-03 03:02:23 -07:00
Ioannis Tsakpinis 4b48355093 Enable POINT_SPRITE on compatibility contexts. Improved platform/device choice when multiple CL implementations are available. 2013-07-31 20:14:33 +03:00
Ioannis Tsakpinis ec09c41edc Added support for AMD_shader_atomic_counter_ops. 2013-07-30 18:02:45 +03:00
Ioannis Tsakpinis cad14be3eb Added new OpenCL extensions. 2013-07-24 15:35:59 +03:00
Ioannis Tsakpinis bafa7a1972 Added support for OpenGL 4.4 and new extensions. 2013-07-23 01:58:46 +03:00
Ioannis Tsakpinis 1df5d25560 Added support for PointerBuffer parameters to OpenGL. 2013-07-23 01:57:41 +03:00
Ioannis Tsakpinis c324b6c215 Added @CLPlatformExtension to APPLE extensions that are exposed in the PLATFORM_EXTENSIONS string. 2013-07-22 21:41:42 +03:00
Ioannis Tsakpinis e3974d5b74 Fixed getInfoBinaries bug when multiple devices exist. 2013-07-22 20:19:25 +03:00
Ioannis Tsakpinis 274cd1c3c1 Fixed GetProgramInfo alternatives for PROGRAM_BINARIES. 2013-07-22 20:13:37 +03:00
Ioannis Tsakpinis 3caf672e42 Fixed pointer array init for NIO buffers. 2013-07-22 20:13:01 +03:00
sashok724 fc023b0041 Update WaveData.java
Fix of BigEndian incorrect reading
2013-07-20 15:22:14 -07:00
Ioannis Tsakpinis 67d4e7c64d Added a DrawElements version with explicit count & type parameters. 2013-07-17 15:57:39 +03:00
frustaci dfe0fc6bb4 Update LWJGLUtil.java
Im trying to debug a error while loading lwjgl binaries but i get a strange message.
[LWJGL] Failure locating java.lang.NoSuchMethodException: findLibrary using classloader:java.lang.NoSuchMethodException: findLibrary

I guess it's a typo c instead of e again.
2013-07-16 15:33:06 -03:00
momokan dc580e2584 I correct that it was pointed out in my pull request
・src/java/org/lwjgl/input/Controllers.java, line 265: Should be "The timestamp assigned to the current event"
・src/java/org/lwjgl/input/JInputController.java, line 211: Consider splitting on two lines.
2013-07-12 05:58:31 +09:00
kappaOne 476dbf74a7 Add equals method to Vector2f, Vector3f and Vector4f. 2013-07-09 17:18:08 +01:00
kappaOne cc14c026ef fix OS X issue where mouse was moving on mouse scroll wheel events. 2013-07-09 16:07:42 +01:00
Erik Broes 11a6a30391 And some more 10.5.8 compat fixes. 2013-07-09 15:37:12 +02:00
kappaOne e3441a4075 Further fixes/amendments for OS X 10.5 compatibility 2013-07-09 01:01:18 +01:00
kappaOne 0965ef8f46 Fixed small typo in code for OS X 10.5, totally the fault of GCC for not
flagging up the error :)
2013-07-08 21:50:01 +01:00
kappaOne 83053798ca another fix for OS X 10.5 2013-07-07 22:04:50 +01:00
kappaOne 5b41d75e7d Add code to support OS X 10.5, hopefully should allow LWJGL to also now
run on OS X 10.5
2013-07-06 21:52:59 +01:00
momokan a9e492d93a Add controller's status to event buffer 2013-06-30 12:28:01 +09:00
Ioannis Tsakpinis e5aada8c45 Fixed typo in KHRDebug callback pointer. 2013-06-21 14:44:29 +03:00
Ioannis Tsakpinis fe0f7b3d26 Workaround for weird Intel driver behavior. 2013-06-20 15:20:45 +03:00
Ioannis Tsakpinis 76a977777e Added alternative GetVertexAttribPointerv method. 2013-06-03 17:33:56 +03:00
Ioannis Tsakpinis 876157a8c4 Added alternative GetVertexAttribPointerv method. 2013-06-03 17:02:33 +03:00
kappaOne 94f16d6b1f Merge pull request #34 from lquesada/master
Modified browser launchers in Linux Sys.openURL method
2013-05-26 10:43:02 -07:00
Luis Quesada 0e1b392058 Modified browser launchers in Linux Sys.openURL method.
Added `sensible-browser' as the first browser launcher option, even before `xdg-open'.
`sensible-browser' tries to open an URL using the preferred web browser, while `xdg-open' just to open a resource (not just an URL) with the preferred application.
Since the method is called openURL and a URL (Uniform Resource Locator) is a web address, `sensible-browser' fits the functionality better.
A notable difference would be calling Sys.openURL('localhost').
Since `localhost' has no leading `http://', `xdg-open' would try to open a `localhost' file and fail, while `sensible-browser' would launch the appropriate browser.

While `sensible-browser' is particular of Debian-based systems and is not as common as xdg-open, this does not negatively affect systems that do not have `sensible-browser':
Were it not present in the system, the rest of the browser launchers would be tried, starting by `xdg-open'.

Added `iceweasel' after `firefox'. `iceweasel' is the Debian fork of Firefox.

Added `google-chrome' and `chromium'. `chromium' is provided in Debian instead of `google-chrome'.
Since the stats in http://www.w3schools.com/browsers/browsers_stats.asp show that Google Chrome is used by more users than Firefox, I put both Google Chrome and Chromium before Firefox in the list.
This change will not affect most of the users, as they will have a preferred browser set up with either `sensible-browser' or `xdg-open'.
2013-05-26 18:20:33 +02:00
kappaOne 83763eb873 Merge pull request #33 from void256/master
Mac OS X: fix custom mouse cursor image
2013-05-25 09:05:52 -07:00
void bc37a79798 Mac OS X: fix custom mouse cursor image
According to
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/A
pplicationKit/Classes/nsbitmapimagerep_Class/Reference/Reference.html
the data referenced by the "planes" parameter will not be copied into
the NSBitmapImageRep class.

This means that when the referenced data changes (which is very likely
in our case since the data is retrieved from Java by
GetDirectBufferAddress()) we see exactly the effect described in the
LWJGL forum here: http://lwjgl.org/forum/index.php/topic,5007.0.html

The Apple class reference documentation linked above also describes
that when the "planes" parameter is NULL then the NSBitmapImageRep
class will allocate enough memory to store the image data and will
automatically free the allocated memory when the NSBitmapImageRep
instance is freed. In this case the data can be accessed with the
"bitmapData" method.

Which is exactly what we'll do now: pass NULL into the method to let it
allocate memory and then simply memcpy our image data into that area.

This seems to fix the mouse cursor image.
2013-05-25 17:56:05 +02:00
kappaOne 1bbca2c7db Merge branch 'master' of https://github.com/LWJGL/lwjgl.git 2013-05-09 00:31:32 +01:00
kappaOne 310f0085cf Correct the Y position of Display.setLocation(x, y) on OS X 2013-05-09 00:30:38 +01:00
Ioannis Tsakpinis bb0bbabef1 [GL] Added support for AMD_interleaved_elements. 2013-05-08 12:47:10 +03:00
Brian Matzon ea1ee59996 Merge pull request #26 from tfg13/master
fix: correctly parse current config with xrandr 1.4
2013-04-27 16:47:48 -07:00
tulius ad78b69d3a fix: correctly parse current config with xrandr 1.4 2013-04-27 21:49:29 +02:00
Ioannis Tsakpinis aee9bc4f84 [Windows] Attempt to fix Display.setParent focus behavior in applets. 2013-04-25 18:39:56 +03:00
Ioannis Tsakpinis caf21d89dc [Windows] Restored grabFocus() on WM_MOUSEACTIVATE. 2013-04-24 11:45:01 +03:00
Ioannis Tsakpinis b66a3243a8 [Windows] Cleaner activation by relaying mouse presses to parent Canvas, similarly to the Linux implementation. 2013-04-24 03:24:16 +03:00
Brian Matzon 5fe5cc057d applying frogs bsd build patch 2013-04-23 22:04:23 +02:00
Ioannis Tsakpinis 7df84ba1a2 [Windows] Close any open AWT menus on WM_MOUSEACTIVATE. 2013-04-22 17:53:39 +03:00
Brian Matzon f0aafd17a9 bumping version to 2.9.1 2013-04-21 23:00:51 +02:00
Brian Matzon b1390f8035 fixed path to CI 2013-04-21 22:59:02 +02:00
kappaOne 8deac76a5b Update author information 2013-04-21 15:37:02 +01:00
kappaOne f528f38c60 Fix OS X CALayer positioning and workaround Java 7 bug
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7172187
2013-04-20 23:21:01 +01:00
kappaOne 5628e751bf Revert "Fix OS X CALayer positioning and workaround Java 7 bug http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7172187"
This reverts commit 1cceacb3cd.
2013-04-19 21:34:57 +01:00
kappaOne 1cceacb3cd Fix OS X CALayer positioning and workaround Java 7 bug
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7172187
2013-04-19 21:32:31 +01:00
Ioannis Tsakpinis 6fd210fdb3 [Windows] Wait for the big icon to update on setIcon. This normally happens asynchronously, but we block until it's done and only then return from setIcon. 2013-04-19 19:05:23 +03:00
Ioannis Tsakpinis 9a895b1dba Attempt to fix focus transfer issue between Display and AWT components in JDK 7:
- Instead of grabbing focus directly to our window, we call requestFocus on the Canvas component. This will clear focus from any other AWT component.
- When the parent Canvas gets focus, we detect it in update and that's when we grab focus to our window. We can't use a listener, setFocus must be called in our thread.
- Alt-tabbing out/in also works because focus goes to the Canvas. The above check will trigger again and our window will be refocused.
2013-04-18 17:02:48 +03:00
Ioannis Tsakpinis c0b19b7743 Another attempt to fix focus problems with Display.setParent on Windows:
- Reverted to WS_CHILD in window flags.
- Added WM_MOUSEACTIVATE handling: Focus the display + return MA_NOACTIVATE.
- Removed unnecessary appActivate calls in WM_ACTIVATE. We don't receive WM_ACTIVATE with WS_CHILD and the focus events do the job just fine.
- Detect parent window focus in update and force focus the display. This is useful when we alt-tab to the parent window and we don't receive any events.
2013-04-17 22:19:38 +03:00
kappaOne 1f81b30f66 map horizontal scroll wheel events to vertical scroll wheel events,
should fix the no event issue when using shift + scroll wheel
2013-04-14 15:19:49 +01:00
kappaOne 5378a48083 Bump OS X native version 2013-04-14 14:56:00 +01:00
kappaOne 0c07657edf Fix a resizing issue with AWTGLCanvas on OS X 2013-04-14 14:54:11 +01:00
kappaOne a7c704ae2f Workaround Nvidia driver bug which crashed the OS when releasing a
shared context by not releasing shared contexts.
2013-04-14 14:14:36 +01:00
kappaOne 529acd40ff Clean up used resources when destroying an OS X / CALayer 2013-04-14 13:19:57 +01:00
kappaOne f3dc48ba6e Merge branch 'master' of https://github.com/LWJGL/lwjgl.git 2013-04-13 18:18:53 -07:00
kappaOne 2bbd7ebe5b Fix a crash with CALayers/OSX when running on Java 7 2013-04-13 18:14:32 -07:00
Brian Matzon 18285fa832 Merge pull request #22 from DziNeIT/patch-1
Fixed JavaDoc for Mouse#next()
2013-04-11 14:43:07 -07:00
Ollie 5631c5a3ba Fixed JavaDoc for Mouse#next()
Mouse does not contain a getEventDZ() method, so the JavaDoc was invalid.

Signed-off-by: Ollie <dzineit@live.co.uk>
2013-04-11 23:02:11 +02:00
kappaOne ca39cb3cdb fix a crash which occurs sometimes when setting the window title 2013-04-09 15:29:02 -07:00
kappaOne 79b5f755d7 Update to latest build of OpenAL-Soft 1.15.1
43b406ad9bb32ebde78d26255a2a4f4a09a29926
2013-04-06 23:58:40 +01:00
kappaOne f45f1e79d9 Fix OSX/CALayer issue where it is not initially visible when running on
Java 7
2013-04-05 01:36:07 +01:00
Ioannis Tsakpinis c9a057db73 Fixed CL_GL_NUM_SAMPLES value. 2013-04-03 15:18:15 +03:00
Ioannis Tsakpinis a9c15cd1b0 Added missing CL12 tokens. 2013-03-29 01:12:26 +02:00
Ioannis Tsakpinis 523fab4417 cl_device_type is a cl_bitfield, ie. long. 2013-03-28 14:22:55 +02:00
Ioannis Tsakpinis 82fc3bf6bf Merge branch 'master' of https://github.com/LWJGL/lwjgl 2013-03-27 13:11:51 +02:00
Ioannis Tsakpinis b83264e296 Added 4.3 in GL versions. 2013-03-27 13:11:29 +02:00
kappaOne 27f66983fc bump OS X JNI version 2013-03-25 23:08:45 +00:00
kappaOne 76f02c9187 Fix the now infamous "Could not get the JAWT interface" exception when
running on OS X and Java 7
2013-03-25 22:55:46 +00:00
kappaOne 38612a402d third attempt to revert changes and fix nightly build server, gah! 2013-03-25 22:14:17 +00:00
kappaOne bc7061717e Another attempt to try fix nightly builds 2013-03-25 14:06:42 +00:00
kappaOne b83f27e970 undo some changes to the OS X build.xml file as it broke the nightly
build server
2013-03-25 12:35:06 +00:00
kappaOne c53e957833 Remove dependency on Java Native Foundation framework, remove non
working JAWT manually loading, change to use headers from
JavaVM.framework when compiling due to JDK7 bug
2013-03-24 20:49:23 +00:00
kappaOne 14de6c518d Fix crash on close of the Display when using Java 7 on OS X 2013-03-24 17:39:39 +00:00
Ioannis Tsakpinis 7b955ee86b Merge branch 'master' of https://github.com/LWJGL/lwjgl 2013-03-22 21:31:33 +02:00
Ioannis Tsakpinis ead1abc2b8 Made glBitmap buffer parameter nullable. 2013-03-22 21:31:22 +02:00
kappaOne 58932fcdbf tweak how glViewport is set when using Display.setParent/AWTGLCanvas 2013-03-15 01:17:24 +00:00
kappaOne 5738477a7b Merge pull request #19 from LWJGL/osx-java7
LWJGL OS X Java 7 Branch is Ready!
2013-03-14 04:49:43 -07:00
kappaOne d8297e7583 set correct size on glViewport when using CALayer 2013-03-14 02:58:14 +00:00
kappaOne d462208c4c Implement AWTGLCanvas, fix initial glViewport size when using
Display.setParent
2013-03-13 00:51:32 +00:00
Ioannis Tsakpinis 50688c825d Merge branch 'master' of https://github.com/LWJGL/lwjgl 2013-03-09 21:41:52 +02:00
Ioannis Tsakpinis 3509384629 clCreateImage fixes:
- Corrected image_desc byte-size calculation on x64.
- Allow null host_ptr.
2013-03-09 21:41:40 +02:00
Ioannis Tsakpinis 96d65d716e Merge pull request #17 from Lekensteyn/master
Fix build error on Linux.

On some Linux distributions, there is no static libXxf86vm.a, only a shared library. In order to succeed a build, link against the shared library. Since the linker options are the same for 32-bit installations and Solaris, merge the options.
2013-02-22 09:19:11 -08:00
Peter Wu 6642ab736c Fix Linux build error w.r.t. Xxf86vm linking 2013-02-22 17:55:13 +01:00
Ioannis Tsakpinis 8faf5f4f35 Reverted commit b333b029 that affected GLX extension detection. Fixes #16.
We now only query glXQueryExtensionsString instead of the server & client
GLX_EXTENSIONS strings.
2013-02-22 18:22:22 +02:00
kappaOne 0cbe94d9e3 Tweak to fix a crash on exit, attempt to fix missing jawt error on
Java 7
2013-02-20 22:20:23 +00:00
kappaOne 6cd860525f fix potential crash on exit when closing the Display window 2013-02-19 22:28:14 +00:00
kappaOne f381eb1f35 Simplify code in AWTSurfaceLock for CALayer support 2013-02-17 16:50:56 +00:00
kappaOne af1ae935d8 fix CALayer/Display.setParent driver crash on resize 2013-02-17 15:09:31 +00:00
kappaOne 6663ee037c Attempt fix for no JAWT on OS X Java 7 issue 2013-02-16 14:07:16 +00:00
kappaOne d28381e1cd minor tweak to comments 2013-02-16 00:31:10 +00:00
kappaOne e67d717c4e simplify mouse code a little 2013-02-15 21:49:19 +00:00
kappaOne 10b8d633d0 push 2013-02-15 21:40:33 +00:00
kappaOne 1b48b704bc Move entire Display nCreate and nDestroy onto the Main Thread 0 2013-02-15 21:35:12 +00:00
kappaOne 817cada066 move nswindow close to main thread 0 to fix a potential crash on exit 2013-02-12 22:00:11 +00:00
kappaOne ed9ab95419 fix crash on startup when creating a second window Display after a
destroy in the same app
2013-02-12 21:53:49 +00:00
kappaOne e725ca7d34 further tweak to pbuffer support 2013-02-12 21:41:47 +00:00
kappaOne e28f8554f9 tweak to pbuffer support 2013-02-12 21:40:48 +00:00
kappaOne e0a52b20c3 fix and reimplement pbuffer support 2013-02-10 21:33:28 +00:00
kappaOne 9929d0fac9 release mouse grab when destroying the Mouse or Display 2013-02-10 20:32:07 +00:00
kappaOne 93bfa246c6 reduce use of window specific code in the context implementation code 2013-02-10 17:57:52 +00:00
kappaOne f6c0f17c79 Fix freeze/hang when calling AL.create() before Display.create() 2013-02-09 00:59:11 +00:00
kappaOne 4e0c593644 Tweak native cursor behaviour 2013-02-08 23:55:45 +00:00
kappaOne db4eb9c5c8 Replace AWT code for getAvailableDisplayMode and other DisplayModes
stuff to use pure native Cococa code.
2013-02-08 23:29:15 +00:00
kappaOne 409b3fea6d Correctly catch quit events instead of manually catching OS X hotkeys 2013-02-07 21:55:53 +00:00
kappaOne 93a169b27b Catch Command+Q shortcut and get it to call Display.isCloseRequested() 2013-02-05 21:28:08 +00:00
kappaOne e15d172087 report Mouse.getX()/getY() values correctly on initial display creation. 2013-02-03 20:55:33 +00:00
kappaOne c57c27abaf remove nsview on main thread to avoid thread issues 2013-02-03 20:54:27 +00:00
kappaOne f6a2bc8327 Detect correctly if mouse is inside or outside the Display on
creation and resize.
2013-02-03 18:58:00 +00:00
kappaOne c328463776 Implement Cursor.destroy and release memory used by native cursors 2013-02-03 17:47:09 +00:00
kappaOne bf13ed9cc3 Restore default mouse cursor on mouse destroy 2013-02-03 16:52:45 +00:00
kappaOne 65beebb379 fix crash related to mouse being dragging whilst Display is destroyed. 2013-02-03 16:39:02 +00:00
kappaOne 2d43265d10 Fix Display.getWidth()/getHeight() to return size of NSView instead of
NSWindow, fix a crash on exit
2013-02-02 20:30:12 +00:00
kappaOne a5c7ec0017 Return correct OS X Cursor.getCapabilities() value 2013-02-02 19:58:18 +00:00
kappaOne 4e1d539095 Further fix Native Mouse Cursor behaviour 2013-02-02 01:15:41 +00:00
kappaOne abeb9f389c Fix Mouse.isInsideWindow() when starting in fullscreen mode 2013-02-01 22:28:10 +00:00
kappaOne 549f07fd28 Release NSView object on Display.destroy() 2013-01-31 23:47:50 +00:00
kappaOne b27754089a Fix Display.setParent() on Java 7 by forcing CALayer usage as
classic NSView method is no long available.
2013-01-31 23:01:19 +00:00
kappaOne 0d25914029 Fix colors on OS X native cursors 2013-01-31 22:44:43 +00:00
Ioannis Tsakpinis 1c671598aa Reverted warning level to 2, until we modify the generator to emit explicit casts. 2013-01-30 02:07:40 +02:00
kappaOne 4e023eec16 Implement animated cursor support on OS X 2013-01-29 22:59:40 +00:00
Ioannis Tsakpinis 5400bb27db Misc fixes and improvements on Windows:
- Cleaned up cl flags and enabled parallel compilation. Native compilation
  is now multiple times faster.
- Fixed all /W3 compilation warnings.
- Changed window flag from WS_CHILDWINDOW to WS_POPUP when Display.setParent
  is used, in an attempt to fix focus-related issues.
2013-01-29 22:53:11 +02:00
kappaOne 27cfdf646e Improve native cursor behaviour 2013-01-27 23:45:08 +00:00
kappaOne 6c090f1f61 Implement Mouse.isInsideWindow() on OS X 2013-01-27 23:01:21 +00:00
kappaOne f0219aed1a Fix native cursor global handle passing 2013-01-26 22:47:36 +00:00
Ioannis Tsakpinis 62b8d36002 Changed Get(Async)KeyState return type to short. 2013-01-25 15:28:17 +02:00
Ioannis Tsakpinis 6b68ff17b8 Added missing null-termination checks. 2013-01-25 15:26:55 +02:00
kappaOne fc2889cc27 Fix ARGB order on Native Cursors 2013-01-25 01:03:13 +00:00
kappaOne 486ff0edea Added initial work towards getting native cursors working, not
implemented yet
2013-01-25 00:28:26 +00:00
kappaOne 4735a6040f Fix crash when dragging mouse and switching from fullscreen to windowed
mode
2013-01-16 22:37:50 +00:00
kappaOne fbb490bb3a Reenable the AWT Robot for CALayer mode 2013-01-16 19:02:09 +00:00
kappaOne b8ba6ee6e5 Fix a small memory leak when using CALayer mode 2013-01-16 18:39:19 +00:00
kappaOne fc9e4f4bda Tweak CALayer mode to active correctly 2013-01-15 23:09:03 +00:00
kappaOne 02c0e80fb6 fix crash when switching to/from fullscreen when using CALayer mode. 2013-01-15 22:34:50 +00:00
Ioannis Tsakpinis d721194cf3 Corrected JavaDoc param order. 2013-01-15 22:59:46 +02:00
Ioannis Tsakpinis 074f6f2d63 Fixed typos. 2013-01-15 17:51:19 +02:00
kappaOne fe2f06f36e Implement Keyboard and Mouse input when using CALayer mode 2013-01-14 23:35:46 +00:00
kappaOne f2ad9f470d Tweak CALayer resizing behavior 2013-01-13 18:37:20 +00:00
kappaOne 03b669fb4d Fix garbage being displayed when resizing in CALayer mode 2013-01-13 16:13:13 +00:00
kappaOne 0dda33cd2d Implement CALayer rendering, no input yet 2013-01-13 15:34:24 +00:00
Ioannis Tsakpinis d1c1fcb01e Fixed DrawIndirect buffer size checks and removed null-termination checks (ARB_base_instance changes the reservedMustBeZero field to the baseInstance offset). 2013-01-12 20:49:26 +02:00
kappaOne 790f895220 Set CALayer OpenGL Context to be shared with the current LWJGL context.
Make code OS X 10.5 compatible (change from NSOpenGLLayer to
CAOpenGLLayer)
2013-01-04 00:11:12 +00:00
Ioannis Tsakpinis 517d6cfb3b Properly escape '_' in native method stubs. 2013-01-01 18:12:53 +02:00
Ioannis Tsakpinis 76ba12ad38 Fixed depth_buffer_float tokens to use the ARB values instead of the NV ones. 2012-12-30 16:15:22 +02:00
Ioannis Tsakpinis 683f488444 Template fixes. 2012-12-28 18:17:28 +02:00
kappaOne f13f35d250 Add further work to the CALayer to prepare it for allowing an FBO to be
blit to its internal FBO
2012-12-28 01:11:12 +00:00
Ioannis Tsakpinis a59964ccae Fixed function dependency typos.
Added GL error check in VersionTest, for drivers that expose the deprecated function addresses and throw GL errors when used.
2012-12-26 22:20:43 +02:00
kappaOne d0759e9c12 remove unneeded code in MacOSXDisplay.getPbufferCapabilities() 2012-12-25 14:14:05 +00:00
kappaOne a4c5be3781 fix OS X Mouse.setCursorPosition to use
CGDisplayMoveCursorToPoint instead of CGWarpMouseCursorPosition to allow
working on multiple monitor setups, also obtain correct window screen
instead of screen with keyboard focus
2012-12-25 14:00:09 +00:00
kappaOne fffa870418 correct behavior on OS X Display.getY() by using the screen the
window is on rather than the screen with keyboard focus
2012-12-25 13:51:24 +00:00
kappaOne 0d6eac80f7 Implement initial work for enabling CALayer rendering 2012-12-23 22:09:57 +00:00
kappaOne 284f6135f3 Refactoring to prepare for implementing OS X CALayer based
Display.setParent, temporarily breaks Display.setParent on Java 7 and
Java 6 Applets.
2012-12-22 20:20:48 +00:00
kappaOne f7c64c89dc Don't use Display.setParent when fullscreen set, some refactoring 2012-12-18 22:10:44 +00:00
Ioannis Tsakpinis 8437f28abd Fixed BackgroundLoadTest to work on NV/Intel and improved context synchronization. 2012-12-18 13:21:15 +02:00
Ioannis Tsakpinis 5dea782de8 Fixed pbuffer + MSAA pixel format config on NV drivers. 2012-12-17 13:57:14 +02:00
kappaOne d235ae5bf0 Fix crash on exit when using Display.setParent() on OS X 2012-12-16 17:50:48 +00:00
kappaOne 21f994a039 remove unused code 2012-12-16 16:24:33 +00:00
kappaOne 45992fc378 Implement Display.isActive() on OS X 2012-12-16 16:19:44 +00:00
kappaOne 70842b92aa Implement Display.getX() and Display.getY() for OS X 2012-12-16 16:02:40 +00:00
Ioannis Tsakpinis 778765c6de Now generates @Deprecated annotation for deprecated methods. 2012-12-12 19:18:35 +02:00
Ioannis Tsakpinis ce4153e883 Fixed put on external ByteBuffer. 2012-12-12 19:17:50 +02:00
kappaOne 970fc2d7d9 Implement OS X Mouse.setCursorPosition() for windowed mode 2012-12-11 22:59:30 +00:00
kappaOne a576c3fb0f fix mouse scroll wheel direction 2012-12-11 21:30:04 +00:00
kappaOne 93d1d3ea03 fix 'invalid drawable' error message 2012-12-11 21:24:04 +00:00
kappaOne ccf738dfaf Implement OS X Mouse.setCursorPosition() when in fullscreen mode 2012-12-09 22:12:02 +00:00
kappaOne 2a820ed94f remove unused variable 2012-12-09 21:22:45 +00:00
kappaOne 07499c30dd fix default viewport size when switching to fullscreen mode 2012-12-09 16:27:19 +00:00
kappaOne 2cc6affcd1 Use correct back buffer size when creating a new context and going
straight into fullscreen
2012-12-09 15:39:26 +00:00
kappaOne c2081c5c1a Remove old/redundant code for OS X 10.4 or lower. 2012-12-05 23:08:53 +00:00
kappaOne 8c4aeef4f4 remove use of depreciated CGTableCount 2012-12-04 22:45:47 +00:00
kappaOne 11d6db5f35 remove use of the now depreciated CGTableCount 2012-12-04 22:28:35 +00:00
kappaOne 83aeba5910 remove use of depreciated CGTableCount 2012-12-04 22:22:42 +00:00
kappaOne 76238f038c remove unneeded call to release memory on close of window 2012-12-04 22:11:16 +00:00
Brian Matzon 31a4517205 ignore missing bsd dir 2012-12-04 21:05:29 +01:00
kappaOne 804f09da47 Fixed resizing when using Display.setParent 2012-12-03 23:04:30 +00:00
kappaOne 415f25bf97 Do Context clean up on proper thread, remove hacks, enable memory
clean up on Mac Display.destroy()
2012-12-03 21:39:54 +00:00
Ioannis Tsakpinis 3cde95d9e4 OpenCL 1.2 update. 2012-12-02 18:52:08 +02:00
kappaOne b3b5e95bf4 Use a fixed back buffer for proper resolution in fullscreen mode 2012-11-30 23:24:12 +00:00
kappaOne b72cdb3064 Wait for NSView to be correctly removed before closing window 2012-11-30 01:11:03 +00:00
kappaOne b6a89d3bd4 Correct Mouse Coordinates in Fullscreen Mode 2012-11-30 01:02:04 +00:00
Erik Broes 129d0711c5 Modifiers now report the correct side they are pressed. Added 'fn'-key as modifier. 2012-11-29 18:27:08 +01:00
Erik Broes bc8040a1d0 Shrink .gitignore 2012-11-27 20:18:16 +01:00
Erik Broes 52d46a8408 Shrink .gitignore 2012-11-27 20:12:15 +01:00
Erik Broes 9d4f22034c Allow the use of F16-F19, SECTION, INSERT, HOME, END, DELETE, NUMPADENTER, CLEAR, LMETA keys. 2012-11-27 19:29:26 +01:00
Erik Broes ee69763707 Don't resolve a key to a deprecated name. 2012-11-27 19:28:49 +01:00
kappaOne ef62a8371b remove white flash when switch to/from fullscreen 2012-11-25 20:34:45 +00:00
kappaOne 6eccb8b971 clean up debug code printf's 2012-11-25 20:24:51 +00:00
kappaOne b5a87d818e Implement ScrollWheel functionality again 2012-11-25 20:14:48 +00:00
kappaOne 9a968e8c41 fix crash on exit by removing NSView before destroying the NSWindow, so
that it doesn't draw after being removed
2012-11-25 18:38:46 +00:00
kappaOne c2159989f5 remove unused code for hiding OS menubar and dock as its no longer
needed.
2012-11-25 17:12:42 +00:00
kappaOne 7b5d596c9b remove observer as it was causing a crash on exit 2012-11-25 15:33:56 +00:00
kappaOne 7f46fb2fbd Reimplement fullscreen support, correct resizing behaviour on window
creation and to work reliably during runtime.
2012-11-25 15:07:20 +00:00
Ioannis Tsakpinis 1c4dfae74c Fixed duplicate fields in GL References. 2012-11-25 12:01:24 +02:00
Ioannis Tsakpinis 3e3ffb23b0 More alternate *Pointer functions with explicit type. 2012-11-25 03:32:51 +02:00
Ioannis Tsakpinis 3118499020 Added alternative VertexAttribPointer with ByteBuffer data and explicit type. 2012-11-25 02:52:51 +02:00
kappaOne 9931e5dbfc Fix native crash when closing the OS X Display window using the
close button
2012-11-22 22:43:43 +00:00
kappaOne 5f37b11857 just a test commit to see if git is working, will undo in next patch 2012-11-20 23:18:11 +00:00
Ioannis Tsakpinis 38ce21abeb Added GREMEDY_frame_terminator. 2012-11-20 21:03:29 +02:00
Brian Matzon 0ea13620de Merge pull request #3 from yerenkow/freebsd
FreeBSD initial support
2012-11-19 11:11:17 -08:00
Alexander Yerenkow 503f8780d3 FreeBSD initial support 2012-11-19 20:28:28 +02:00
Ioannis Tsakpinis 41d37b1e03 Merge branch 'master' of https://github.com/LWJGL/lwjgl 2012-11-19 18:58:59 +02:00
Ioannis Tsakpinis f57c236373 Fixed GetAsyncKeyState usage. We read the MSB, not the LSB. 2012-11-19 18:49:34 +02:00
Brian Matzon baeda5e65b Adding README file 2012-11-18 00:32:14 +01:00
Erik Broes 5d3cffc6af Added .gitignore 2012-11-16 22:46:46 +01:00
Erik Broes 1cfdd27184 Added .gitignore 2012-11-16 22:46:28 +01:00
kappa1 141b9c2632 Implement Mouse Dragging when using the Right Mouse Button or the Scroll Wheel Button 2012-11-16 13:36:41 +01:00
kappa1 4f4cb832af Cleaned up code by removing unneeded java classes MacOSXFrame and MacOSXMouseEventQueue and native code by removing mouse.c 2012-11-13 21:13:11 +00:00
kappa1 7bbfcadcef fix resizing when using Display.setParent() 2012-11-11 19:03:50 +00:00
kappa1 a749ad5c10 implement missing functionality for Display.getWidth() and Display.getHeight() not updating correctly on resize 2012-11-11 18:43:14 +00:00
kappa1 f7012a3020 Run some Cocoa methods in nCreateWindow on the main thread (Thread-0) instead of the JNI thread. 2012-11-11 15:48:08 +00:00
kappa1 49f92189ec Switch to using the correct Cocoa method for Display.isCloseRequested() 2012-11-10 00:42:34 +00:00
kappa1 7291d72274 Fix main build file to generate MacOSXNativeKeyboard and MacOSXNativeMouse native headers 2012-11-06 21:55:11 +00:00
kappa1 3e96cded2b upload mc78's latest build.xml fixes, gets rid of the depreciated warnings 2012-11-06 21:45:45 +00:00
Ioannis Tsakpinis 12ee2ecb3d Added missing alternative signature functions. 2012-11-06 16:18:28 +00:00
Ioannis Tsakpinis be5655a254 Removed redundant GLsync definition and replaced APIENTRY with GL_APIENTRY. 2012-11-06 12:14:03 +00:00
kappa1 9655b45e55 remove unused AWT import 2012-11-06 00:34:36 +00:00
kappa1 ce6f4b71f0 Remove unneeded old hack for OS X 10.3 in the mac Sys class implementation which loaded the AWT Toolkit 2012-11-05 23:19:46 +00:00
kappa1 bb8045b471 Added support to the OS X build.xml for Xcode location discovery, Mac OS SDK discovery, JavaVM.framework discovery and gcc vs gcc-4.2 discovery, special thanks to MC78 for providing this patch 2012-11-05 23:17:34 +00:00
kappa1 4eaea5850c Tiny Clean up and remove some more references to JNF 2012-11-04 20:11:03 +00:00
kappa1 0c4008c885 Remove unused dependency on JavaNativeFoundation 2012-11-04 20:04:30 +00:00
Brian Matzon 6417afb180 Bumping version number 2012-11-04 19:50:22 +00:00
kappa1 94c23298c8 Fix a native crash on startup of some applications 2012-11-03 18:06:08 +00:00
kappa1 460b6f05dd Fix memory leaks by adding an NSAutoreleasePool when creating a windows and draining it on window destroy 2012-11-01 22:39:22 +00:00
kappa1 2c811ac289 Updated macosx_ant build.xml, removed PPC support, bumped the minimum OS X SDK for 32/64bit native to SDK 10.5. Commented out some code in Display.m that required SDK 10.7+, namely NSApplicationPresentationFullScreen, etc 2012-11-01 22:21:23 +00:00
Brian Matzon c09f5698b4 Comitting EmuMogs 28008537/src.zip drop to branch 2012-11-01 20:54:17 +00:00
289 changed files with 12032 additions and 5804 deletions

17
.github/CONTRIBUTING.md vendored Normal file
View file

@ -0,0 +1,17 @@
## WARNING
This is the repository of the original LWJGL, which is no longer actively maintained. Unless you have released a product that uses LWJGL 2.x, you should probably be looking at [LWJGL 3](https://github.com/LWJGL/lwjgl3).
If you decide to proceed, it is very likely that:
- LWJGL maintainers won't be able to address your issue. Your best hope is an external contribution, which happens very rarely.
- Your issue is not an issue in LWJGL 3.
- Your issue has already been fixed in LWJGL 3.
If it is impossible for you to migrate to LWJGL 3, make sure to:
- Describe your issue as clearly as possible.
- Include information about your system/environment.
- Include a minimal code sample that reproduces the issue.
In any case, feature requests will almost certainly be ignored. If you need new features, you're very welcome to open an issue in the LWJGL 3 repository.

22
.gitignore vendored Normal file
View file

@ -0,0 +1,22 @@
*.*~
.*.sw[a-p]
/.classpath
/.nbattrs
/.project
/bin
/dist
/doc/javadoc
/libs
/src/generated
/src/native/generated
/src/native/common/Debug
/src/native/common/Release
/src/native/windows/Debug
/src/native/windows/Release
/temp
/src/native/*/org_lwjgl_*.h
/src/native/*/*/org_lwjgl_*.h
/src/native/linux/org_lwjgl_opengl_Display.c
nbproject/project.xml
/nbproject/private/

24
README.md Normal file
View file

@ -0,0 +1,24 @@
[LEGACY] LWJGL - Lightweight Java Game Library
======
> **WARNING**
>
> This is the repository of the original LWJGL, which is no longer actively maintained. Unless you have released a product that uses LWJGL 2.x, you should probably be looking at [LWJGL 3](https://github.com/LWJGL/lwjgl3).
The Lightweight Java Game Library (LWJGL) is a solution aimed directly at professional and amateur Java programmers alike to enable commercial quality games to be written in Java.
LWJGL provides developers access to high performance crossplatform libraries such as OpenGL (Open Graphics Library), OpenCL (Open Computing Language) and OpenAL (Open Audio Library) allowing for state of the art 3D games and 3D sound.
Additionally LWJGL provides access to controllers such as Gamepads, Steering wheel and Joysticks.
All in a simple and straight forward API.
Website: [http://legacy.lwjgl.org](http://legacy.lwjgl.org)
Forum: [http://forum.lwjgl.org](http://forum.lwjgl.org)
Bugs/Suggestions: [https://github.com/LWJGL/lwjgl/issues](https://github.com/LWJGL/lwjgl/issues)
Compilation
-----------
LWJGL requires a JDK and Ant installed to compile, as well as your platforms native compiler to compile the JNI.
* ant generate-all
* ant compile
* ant compile_native

320
build.xml
View file

@ -32,6 +32,8 @@
<mkdir dir="${lwjgl.temp}/native" taskname="initialiazing temp/native folder" />
<mkdir dir="${lwjgl.temp}/native/windows" taskname="initialiazing temp/windows folder" />
<mkdir dir="${lwjgl.temp}/native/linux" taskname="initialiazing temp/linux folder" />
<mkdir dir="${lwjgl.temp}/native/freebsd" taskname="initialiazing temp/freebsd folder" />
<mkdir dir="${lwjgl.temp}/native/openbsd" taskname="initialiazing temp/openbsd folder" />
<mkdir dir="${lwjgl.temp}/native/macosx" taskname="initialiazing temp/macosx folder" />
<mkdir dir="${lwjgl.temp}/native/solaris" taskname="initialiazing temp/solaris folder" />
</target>
@ -56,7 +58,7 @@
<!-- Creates a distribution of LWJGL -->
<target name="release" description="Creates a distribution of LWJGL using supplied native binaries">
<!-- Warn user -->
<echo message="Before running the release target, please manually compile all platforms and place required files in ${lwjgl.lib}/windows, ${lwjgl.lib}/linux and ${lwjgl.lib}/macosx${line.separator}Missing files will result in a successfull built, but with incomplete release zips"/>
<echo message="Before running the release target, please manually compile all platforms and place required files in ${lwjgl.lib}/windows, ${lwjgl.lib}/linux, ${lwjgl.lib}/freebsd and ${lwjgl.lib}/macosx${line.separator}Missing files will result in a successfull built, but with incomplete release zips"/>
<input
message="All data in the ${lwjgl.dist} folder will be deleted. Continue? "
validargs="yes,no"
@ -86,8 +88,8 @@
<antcall target="-createjars" />
<antcall target="-jars_NoDEP" />
<antcall target="javadoc" />
<antcall target="applet-release" />
<!-- <antcall target="javadoc" /> -->
<!-- <antcall target="applet-release" /> -->
<!-- copy resources to res folder -->
<copy todir="${lwjgl.temp}/res">
@ -95,15 +97,15 @@
</copy>
<!-- copy docs -->
<copy todir="${lwjgl.temp}/doc">
<fileset dir="${lwjgl.docs}">
<patternset refid="lwjgl-docs.fileset" />
</fileset>
</copy>
<!-- <copy todir="${lwjgl.temp}/doc"> -->
<!-- <fileset dir="${lwjgl.docs}"> -->
<!-- <patternset refid="lwjgl-docs.fileset" /> -->
<!-- </fileset> -->
<!-- </copy> -->
<!-- create distribution from files in libs/ and temp/ -->
<antcall target="-distribution_javadoc" />
<antcall target="-distribution_source" />
<!-- <antcall target="-distribution_javadoc" /> -->
<!-- <antcall target="-distribution_source" /> -->
<antcall target="-distribute" />
</target>
@ -157,6 +159,11 @@
<fileset refid="lwjgl_util_applet.fileset" />
<manifest>
<attribute name="Sealed" value="true"/>
<attribute name="Trusted-Library" value="true"/>
<attribute name="Permissions" value="all-permissions"/>
<attribute name="Codebase" value="*"/>
<attribute name="Caller-Allowable-Codebase" value="*"/>
<attribute name="Application-Library-Allowable-Codebase" value="*"/>
</manifest>
</jar>
@ -238,6 +245,16 @@
<patternset refid="lwjgl-linux.fileset" />
</fileset>
</copy>
<copy todir="${lwjgl.temp}/native/freebsd" failonerror="false">
<fileset dir="${lwjgl.lib}/freebsd">
<patternset refid="lwjgl-freebsd.fileset" />
</fileset>
</copy>
<copy todir="${lwjgl.temp}/native/openbsd" failonerror="false">
<fileset dir="${lwjgl.lib}/openbsd">
<patternset refid="lwjgl-openbsd.fileset" />
</fileset>
</copy>
<copy todir="${lwjgl.temp}/native/macosx">
<fileset dir="${lwjgl.lib}/macosx">
<patternset refid="lwjgl-macosx.fileset" />
@ -278,80 +295,88 @@
<!-- Generates the native headers from source files -->
<target name="headers" description="invokes javah on java classes" depends="compile">
<javah classpath="${lwjgl.bin}" destdir="${lwjgl.src.native}/linux" force="yes">
<class name="org.lwjgl.LinuxSysImplementation" />
<class name="org.lwjgl.opengl.LinuxEvent" />
<class name="org.lwjgl.opengl.LinuxMouse" />
<class name="org.lwjgl.opengl.LinuxKeyboard" />
<class name="org.lwjgl.opengl.LinuxDisplay" />
<class name="org.lwjgl.opengl.LinuxPeerInfo" />
</javah>
<!-- <javah classpath="${lwjgl.bin}" destdir="${lwjgl.src.native}/linux"> -->
<!-- <class name="org.lwjgl.LinuxSysImplementation" /> -->
<!-- <class name="org.lwjgl.opengl.LinuxEvent" /> -->
<!-- <class name="org.lwjgl.opengl.LinuxMouse" /> -->
<!-- <class name="org.lwjgl.opengl.LinuxKeyboard" /> -->
<!-- <class name="org.lwjgl.opengl.LinuxDisplay" /> -->
<!-- <class name="org.lwjgl.opengl.LinuxPeerInfo" /> -->
<!-- </javah> -->
<javah classpath="${lwjgl.bin}" destdir="${lwjgl.src.native}/linux/opengl" force="yes">
<class name="org.lwjgl.opengl.LinuxPbufferPeerInfo"/>
<class name="org.lwjgl.opengl.LinuxDisplayPeerInfo"/>
<class name="org.lwjgl.opengl.LinuxAWTGLCanvasPeerInfo"/>
<class name="org.lwjgl.opengl.LinuxContextImplementation"/>
<class name="org.lwjgl.opengl.LinuxCanvasImplementation"/>
</javah>
<!-- <javah classpath="${lwjgl.bin}" destdir="${lwjgl.src.native}/linux/opengl"> -->
<!-- <class name="org.lwjgl.opengl.LinuxPbufferPeerInfo"/> -->
<!-- <class name="org.lwjgl.opengl.LinuxDisplayPeerInfo"/> -->
<!-- <class name="org.lwjgl.opengl.LinuxAWTGLCanvasPeerInfo"/> -->
<!-- <class name="org.lwjgl.opengl.LinuxContextImplementation"/> -->
<!-- <class name="org.lwjgl.opengl.LinuxCanvasImplementation"/> -->
<!-- </javah> -->
<javah classpath="${lwjgl.bin}" destdir="${lwjgl.src.native}/windows" force="yes">
<class name="org.lwjgl.WindowsSysImplementation"/>
<class name="org.lwjgl.opengl.WindowsKeyboard" />
<class name="org.lwjgl.opengl.WindowsRegistry" />
<class name="org.lwjgl.opengl.WindowsDisplay"/>
<class name="org.lwjgl.opengl.WindowsDisplayPeerInfo"/>
<class name="org.lwjgl.opengl.WindowsAWTGLCanvasPeerInfo"/>
</javah>
<!-- <javah classpath="${lwjgl.bin}" destdir="${lwjgl.src.native}/windows"> -->
<!-- <class name="org.lwjgl.WindowsSysImplementation"/> -->
<!-- <class name="org.lwjgl.opengl.WindowsKeyboard" /> -->
<!-- <class name="org.lwjgl.opengl.WindowsRegistry" /> -->
<!-- <class name="org.lwjgl.opengl.WindowsDisplay"/> -->
<!-- <class name="org.lwjgl.opengl.WindowsDisplayPeerInfo"/> -->
<!-- <class name="org.lwjgl.opengl.WindowsAWTGLCanvasPeerInfo"/> -->
<!-- </javah> -->
<javah classpath="${lwjgl.bin}" destdir="${lwjgl.src.native}/windows/opengl" force="yes">
<class name="org.lwjgl.opengl.WindowsPbufferPeerInfo"/>
<class name="org.lwjgl.opengl.WindowsPeerInfo"/>
<class name="org.lwjgl.opengl.WindowsContextImplementation"/>
</javah>
<!-- <javah classpath="${lwjgl.bin}" destdir="${lwjgl.src.native}/windows/opengl"> -->
<!-- <class name="org.lwjgl.opengl.WindowsPbufferPeerInfo"/> -->
<!-- <class name="org.lwjgl.opengl.WindowsPeerInfo"/> -->
<!-- <class name="org.lwjgl.opengl.WindowsContextImplementation"/> -->
<!-- </javah> -->
<javah classpath="${lwjgl.bin}" destdir="${lwjgl.src.native}/windows/opengles" force="yes">
<class name="org.lwjgl.opengl.WindowsPeerInfo"/>
</javah>
<!-- <javah classpath="${lwjgl.bin}" destdir="${lwjgl.src.native}/windows/opengles"> -->
<!-- <class name="org.lwjgl.opengl.WindowsPeerInfo"/> -->
<!-- </javah> -->
<javah classpath="${lwjgl.bin}" destdir="${lwjgl.src.native}/macosx" force="yes">
<class name="org.lwjgl.MacOSXSysImplementation" />
<class name="org.lwjgl.opengl.MacOSXMouseEventQueue" />
<class name="org.lwjgl.opengl.MacOSXCanvasPeerInfo" />
<class name="org.lwjgl.opengl.MacOSXPeerInfo" />
<class name="org.lwjgl.opengl.MacOSXPbufferPeerInfo" />
<class name="org.lwjgl.opengl.MacOSXDisplay" />
<class name="org.lwjgl.opengl.MacOSXContextImplementation" />
</javah>
<echo>lwjgl.src.headers = ${lwjgl.src.headers}</echo>
<javah classpath="${lwjgl.bin}" destdir="${lwjgl.src.headers}" force="yes">
<class name="org.lwjgl.opengl.AWTSurfaceLock" />
<class name="org.lwjgl.DefaultSysImplementation" />
<class name="org.lwjgl.input.Cursor" />
<class name="org.lwjgl.input.Keyboard" />
<class name="org.lwjgl.input.Mouse" />
<class name="org.lwjgl.openal.AL" />
<class name="org.lwjgl.opencl.CL" />
<class name="org.lwjgl.opencl.CallbackUtil" />
<class name="org.lwjgl.BufferUtils" />
</javah>
<javac classpath="${lwjgl.bin}" srcdir="${lwjgl.src}" nativeheaderdir="${lwjgl.src.native}/macosx">
<compilerarg line="-h ${lwjgl.src.native}/macosx" />
<include name="java/org/lwjgl/MacOSXSysImplementation.java" />
<include name="java/org/lwjgl/opengl/MacOSXCanvasPeerInfo.java" />
<include name="java/org/lwjgl/opengl/MacOSXPeerInfo.java" />
<include name="java/org/lwjgl/opengl/MacOSXPbufferPeerInfo.java" />
<include name="java/org/lwjgl/opengl/MacOSXDisplay.java" />
<include name="java/org/lwjgl/opengl/MacOSXContextImplementation.java" />
<include name="java/org/lwjgl/opengl/MacOSXNativeKeyboard.java" />
<include name="java/org/lwjgl/opengl/MacOSXNativeMouse.java" />
<include name="java/org/lwjgl/opengl/MacOSXMouseEventQueue.java" />
</javac>
<javah classpath="${lwjgl.bin}" destdir="${lwjgl.src.headers}/opengl" force="yes">
<class name="org.lwjgl.opengl.GLContext"/>
<class name="org.lwjgl.opengl.Pbuffer"/>
<class name="org.lwjgl.opengl.CallbackUtil"/>
<class name="org.lwjgl.opengl.NVPresentVideoUtil"/>
<class name="org.lwjgl.opengl.NVVideoCaptureUtil"/>
</javah>
<javac classpath="${lwjgl.bin}" srcdir="${lwjgl.src}" nativeheaderdir="${lwjgl.src.headers}">
<compilerarg line="-h ${lwjgl.src.headers}" />
<include name="java/org/lwjgl/opengl/AWTSurfaceLock.java" />
<include name="java/org/lwjgl/DefaultSysImplementation.java" />
<include name="java/org/lwjgl/input/Cursor.java" />
<include name="java/org/lwjgl/input/Keyboard.java" />
<include name="java/org/lwjgl/input/Mouse.java" />
<include name="java/org/lwjgl/openal/AL.java" />
<include name="java/org/lwjgl/opencl/CL.java" />
<include name="java/org/lwjgl/opencl/CallbackUtil.java" />
<include name="java/org/lwjgl/BufferUtils.java" />
</javac>
<javah classpath="${lwjgl.bin}" destdir="${lwjgl.src.headers}/opengles" force="yes">
<class name="org.lwjgl.opengles.EGL"/>
<class name="org.lwjgl.opengles.EGLKHRFenceSync"/>
<class name="org.lwjgl.opengles.EGLKHRReusableSync"/>
<class name="org.lwjgl.opengles.EGLNVSync"/>
<class name="org.lwjgl.opengles.GLContext"/>
<class name="org.lwjgl.opengles.CallbackUtil"/>
</javah>
<javac classpath="${lwjgl.bin}" srcdir="${lwjgl.src}" nativeheaderdir="${lwjgl.src.headers}/opengl">
<compilerarg line="-h ${lwjgl.src.headers}/opengl" />
<include name="java/org/lwjgl/opengl/GLContext.java"/>
<include name="java/org/lwjgl/opengl/Pbuffer.java"/>
<include name="java/org/lwjgl/opengl/CallbackUtil.java"/>
<include name="java/org/lwjgl/opengl/NVPresentVideoUtil.java"/>
<include name="java/org/lwjgl/opengl/NVVideoCaptureUtil.java"/>
</javac>
<javac classpath="${lwjgl.bin}" srcdir="${lwjgl.src}" nativeheaderdir="${lwjgl.src.headers}/opengles">
<compilerarg line="-h ${lwjgl.src.headers}/opengles" />
<include name="java/org/lwjgl/opengles/EGL.java"/>
<include name="java/org/lwjgl/opengles/EGLKHRFenceSync.java"/>
<include name="java/org/lwjgl/opengles/EGLKHRReusableSync.java"/>
<include name="java/org/lwjgl/opengles/EGLNVSync.java"/>
<include name="java/org/lwjgl/opengles/GLContext.java"/>
<include name="java/org/lwjgl/opengles/CallbackUtil.java"/>
</javac>
</target>
<target name="touch-version">
@ -361,56 +386,60 @@
</target>
<target name="version-mismatch">
<loadfile srcfile="${lwjgl.src}/java/org/lwjgl/WindowsSysImplementation.java" property="lwjgl.java.windows.version">
<filterchain>
<tokenfilter>
<containsstring contains="JNI_VERSION ="/>
</tokenfilter>
</filterchain>
</loadfile>
<loadfile srcfile="${lwjgl.src}/java/org/lwjgl/LinuxSysImplementation.java" property="lwjgl.java.linux.version">
<filterchain>
<tokenfilter>
<containsstring contains="JNI_VERSION ="/>
</tokenfilter>
</filterchain>
</loadfile>
<loadfile srcfile="${lwjgl.src}/java/org/lwjgl/MacOSXSysImplementation.java" property="lwjgl.java.macosx.version">
<filterchain>
<tokenfilter>
<containsstring contains="JNI_VERSION ="/>
</tokenfilter>
</filterchain>
</loadfile>
<loadfile srcfile="${lwjgl.src.native}/windows/org_lwjgl_WindowsSysImplementation.h" property="lwjgl.native.windows.version">
<filterchain>
<tokenfilter>
<containsstring contains="#define org_lwjgl_WindowsSysImplementation_JNI_VERSION"/>
</tokenfilter>
</filterchain>
</loadfile>
<loadfile srcfile="${lwjgl.src.native}/linux/org_lwjgl_LinuxSysImplementation.h" property="lwjgl.native.linux.version">
<filterchain>
<tokenfilter>
<containsstring contains="#define org_lwjgl_LinuxSysImplementation_JNI_VERSION"/>
</tokenfilter>
</filterchain>
</loadfile>
<loadfile srcfile="${lwjgl.src.native}/macosx/org_lwjgl_MacOSXSysImplementation.h" property="lwjgl.native.macosx.version">
<filterchain>
<tokenfilter>
<containsstring contains="#define org_lwjgl_MacOSXSysImplementation_JNI_VERSION"/>
</tokenfilter>
</filterchain>
</loadfile>
<echo>
lwjgl.java.windows.version = ${lwjgl.java.windows.version}
lwjgl.native.windows.version = ${lwjgl.native.windows.version}
lwjgl.java.linux.version = ${lwjgl.java.linux.version}
lwjgl.native.linux.version = ${lwjgl.native.linux.version}
lwjgl.java.macosx.version = ${lwjgl.java.macosx.version}
lwjgl.native.macosx.version = ${lwjgl.native.macosx.version}
</echo>
<!-- <loadfile srcfile="${lwjgl.src}/java/org/lwjgl/WindowsSysImplementation.java" property="lwjgl.java.windows.version"> -->
<!-- <filterchain> -->
<!-- <tokenfilter> -->
<!-- <containsstring contains="JNI_VERSION ="/> -->
<!-- </tokenfilter> -->
<!-- </filterchain> -->
<!-- </loadfile> -->
<!-- <loadfile srcfile="${lwjgl.src}/java/org/lwjgl/LinuxSysImplementation.java" property="lwjgl.java.linux.version"> -->
<!-- <filterchain> -->
<!-- <tokenfilter> -->
<!-- <containsstring contains="JNI_VERSION ="/> -->
<!-- </tokenfilter> -->
<!-- </filterchain> -->
<!-- </loadfile> -->
<!-- <loadfile srcfile="${lwjgl.src}/java/org/lwjgl/MacOSXSysImplementation.java" property="lwjgl.java.macosx.version"> -->
<!-- <filterchain> -->
<!-- <tokenfilter> -->
<!-- <containsstring contains="JNI_VERSION ="/> -->
<!-- </tokenfilter> -->
<!-- </filterchain> -->
<!-- </loadfile> -->
<!-- <loadfile srcfile="${lwjgl.src.native}/windows/org_lwjgl_WindowsSysImplementation.h" property="lwjgl.native.windows.version"> -->
<!-- <filterchain> -->
<!-- <tokenfilter> -->
<!-- <containsstring contains="#define org_lwjgl_WindowsSysImplementation_JNI_VERSION"/> -->
<!-- </tokenfilter> -->
<!-- </filterchain> -->
<!-- </loadfile> -->
<!-- <loadfile srcfile="${lwjgl.src.native}/linux/org_lwjgl_LinuxSysImplementation.h" property="lwjgl.native.linux.version"> -->
<!-- <filterchain> -->
<!-- <tokenfilter> -->
<!-- <containsstring contains="#define org_lwjgl_LinuxSysImplementation_JNI_VERSION"/> -->
<!-- </tokenfilter> -->
<!-- </filterchain> -->
<!-- </loadfile> -->
<!-- <loadfile srcfile="${lwjgl.src.native}/macosx/org_lwjgl_MacOSXSysImplementation.h" property="lwjgl.native.macosx.version"> -->
<!-- <filterchain> -->
<!-- <tokenfilter> -->
<!-- <containsstring contains="#define org_lwjgl_MacOSXSysImplementation_JNI_VERSION"/> -->
<!-- </tokenfilter> -->
<!-- </filterchain> -->
<!-- </loadfile> -->
<!-- <echo> -->
<!-- lwjgl.java.windows.version = ${lwjgl.java.windows.version} -->
<!-- lwjgl.native.windows.version = ${lwjgl.native.windows.version} -->
<!-- lwjgl.java.linux.version = ${lwjgl.java.linux.version} -->
<!-- lwjgl.native.linux.version = ${lwjgl.native.linux.version} -->
<!-- lwjgl.java.freebsd.version = ${lwjgl.java.linux.version} -->
<!-- lwjgl.native.freebsd.version = ${lwjgl.native.linux.version} -->
<!-- lwjgl.java.openbsd.version = ${lwjgl.java.linux.version} -->
<!-- lwjgl.native.openbsd.version = ${lwjgl.native.linux.version} -->
<!-- lwjgl.java.macosx.version = ${lwjgl.java.macosx.version} -->
<!-- lwjgl.native.macosx.version = ${lwjgl.native.macosx.version} -->
<!-- </echo> -->
</target>
<macrodef name="version-check">
@ -439,7 +468,7 @@
<!-- Compiles the Java source code -->
<target name="compile" description="Compiles the java source code" depends="-initialize">
<javac debug="yes" destdir="${lwjgl.bin}" source="1.5" target="1.5" classpath="${lwjgl.lib}/jinput.jar:${lwjgl.lib}/AppleJavaExtensions.jar:${lwjgl.lib}/asm-debug-all.jar" taskname="core">
<javac debug="yes" destdir="${lwjgl.bin}" source="1.7" target="1.7" classpath="${lwjgl.lib}/jinput.jar:${lwjgl.lib}/AppleJavaExtensions.jar:${lwjgl.lib}/asm-debug-all.jar" taskname="core">
<!--<compilerarg value="-Xlint:unchecked"/>-->
<src path="${lwjgl.src}/java/"/>
<src path="${lwjgl.src}/generated/"/>
@ -452,8 +481,8 @@
<include name="org/lwjgl/util/**"/>
<exclude name="org/lwjgl/util/generator/**"/>
</javac>
<javac debug="yes" srcdir="${lwjgl.src}/java/" destdir="${lwjgl.bin}" includes="org/lwjgl/test/**" source="1.5" target="1.5" taskname="test" />
<javac debug="yes" srcdir="${lwjgl.src}/java/" destdir="${lwjgl.bin}" includes="org/lwjgl/examples/**" source="1.5" target="1.5" taskname="examples" />
<javac debug="yes" srcdir="${lwjgl.src}/java/" destdir="${lwjgl.bin}" includes="org/lwjgl/test/**" source="1.7" target="1.7" taskname="test" />
<javac debug="yes" srcdir="${lwjgl.src}/java/" destdir="${lwjgl.bin}" includes="org/lwjgl/examples/**" source="1.7" target="1.7" taskname="examples" />
</target>
<target name="compile_native" depends="-initialize, headers, touch-version, version-mismatch" description="Compiles the native files">
@ -467,6 +496,16 @@
</condition>
<antcall target="-compile_native_linux" />
<condition property="lwjgl.platform.freebsd">
<os name="FreeBSD" />
</condition>
<antcall target="-compile_native_freebsd" />
<condition property="lwjgl.platform.openbsd">
<os name="OpenBSD" />
</condition>
<antcall target="-compile_native_openbsd" />
<condition property="lwjgl.platform.solaris">
<os name="SunOS" />
</condition>
@ -496,6 +535,23 @@
<!-- headless issues <version-check platform="linux"/> -->
</target>
<!-- Compiles LWJGL on FreeBSD platforms -->
<target name="-compile_native_freebsd" if="lwjgl.platform.freebsd">
<ant antfile="platform_build/bsd_ant/build.xml" inheritAll="false"/>
<copy todir="${lwjgl.lib}/freebsd">
<fileset dir="${lwjgl.bin}/lwjgl" includes="liblwjgl*.so"/>
</copy>
</target>
<!-- Compiles LWJGL on OpenBSD platforms -->
<target name="-compile_native_openbsd" if="lwjgl.platform.openbsd">
<ant antfile="platform_build/bsd_ant/build.xml" inheritAll="false"/>
<copy todir="${lwjgl.lib}/openbsd">
<fileset dir="${lwjgl.bin}/lwjgl" includes="liblwjgl*.so"/>
</copy>
</target>
<!-- Compiles LWJGL on solaris platforms -->
<target name="-compile_native_solaris" if="lwjgl.platform.solaris">
<!-- Reusing the linux ant task, but copy the output to solaris -->
@ -509,8 +565,8 @@
<!-- Compiles LWJGL on Mac platforms -->
<target name="-compile_native_macosx" if="lwjgl.platform.macosx">
<ant antfile="platform_build/macosx_ant/build.xml" inheritAll="false"/>
<copy file="${lwjgl.bin}/lwjgl/liblwjgl.jnilib" todir="${lwjgl.lib}/macosx"/>
<version-check platform="macosx"/>
<copy file="${lwjgl.bin}/lwjgl/liblwjgl.dylib" todir="${lwjgl.lib}/macosx"/>
<!-- <version-check platform="macosx"/> -->
</target>
<target name="compile_native_es" depends="-initialize, headers, touch-version, version-mismatch" description="Compiles the native files">
@ -631,7 +687,7 @@
<!-- get and copy nightly binaries into libs folder -->
<target name="copy-nightly-binaries" depends="-initialize" description="Copies latest successful nightly binaries into appropriate libs folder">
<delete file="${lwjgl.temp}/lwjgl-${lwjgl.version}.zip" failonerror="false"/>
<get src="http://www.newdawnsoftware.com/jenkins/view/LWJGL/job/LWJGL/lastSuccessfulBuild/artifact/dist/lwjgl-${lwjgl.version}.zip" dest="${lwjgl.temp}" verbose="true"/>
<get src="http://ci.newdawnsoftware.com/job/LWJGL-git-dist/lastBuild/artifact/dist/lwjgl-${lwjgl.version}.zip" dest="${lwjgl.temp}" verbose="true"/>
<unzip src="${lwjgl.temp}/lwjgl-${lwjgl.version}.zip" dest="${lwjgl.lib}" overwrite="true">
<patternset>
<include name="**/native/**/*lwjgl*"/>

View file

@ -22,4 +22,7 @@ org.lwjgl.opengl.Window.undecorated
Whether to create an undecorated window (no title bar)
org.lwjgl.input.Mouse.allowNegativeMouseCoords
Usually mouse is clamped to 0,0 - setting this to true will cause you to get negative values if dragging outside and below or left of window
Usually mouse is clamped to 0,0 - setting this to true will cause you to get negative values if dragging outside and below or left of window
org.lwjgl.opengl.Display.enableHighDPI
Enable high DPI mode where available

Binary file not shown.

BIN
libs/linux/libopenal64.so Executable file → Normal file

Binary file not shown.

Binary file not shown.

BIN
libs/macosx/openal.dylib Normal file → Executable file

Binary file not shown.

BIN
libs/solaris/libopenal.so Executable file → Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1,147 @@
<?xml version="1.0"?>
<project name="lwjgl native code, bsd" basedir="../../bin/lwjgl" default="compile">
<property name="native" location="../../src/native"/>
<property name="libname32" value="liblwjgl.so"/>
<property name="libname64" value="liblwjgl64.so"/>
<property name="libs32" value="-L/usr/X11R6/lib -L/usr/local/lib -lm -lX11 -lXext -lXcursor -lXrandr -pthread -L${java.home}/lib/i386 -ljawt" />
<property name="libs64" value="-L/usr/X11R6/lib -L/usr/local/lib -lm -lX11 -lXext -lXcursor -lXrandr -lXxf86vm -pthread -L${java.home}/lib/amd64 -ljawt" />
<property name="cflags32" value="-O2 -Wall -c -fPIC -std=c99 -Wunused"/>
<target name="clean">
<delete>
<fileset dir="x32"/>
<fileset dir="x64"/>
<fileset dir="." includes="*.o"/>
<fileset dir="." includes="*.so"/>
</delete>
</target>
<target name="compile">
<exec executable="uname" outputproperty="hwplatform">
<arg value="-m"/>
</exec>
<condition property="xf86vm_lib" value="-lXxf86vm" else="-Wl,-static,-lXxf86vm,-call_shared">
<os name="SunOS" />
</condition>
<condition property="cflags_pthread" value="-pthreads" else="-pthread">
<os name="SunOS" />
</condition>
<condition property="version_script_flags32" value="" else="-Wl,--version-script='${native}/linux/lwjgl.map'">
<os name="SunOS" />
</condition>
<condition property="version_script_flags64" value="-m64" else="-Wl,--version-script='${native}/linux/lwjgl.map'">
<and>
<os name="SunOS" />
</and>
</condition>
<condition property="cflags64" value="-O2 -m64 -Wall -c -fPIC -std=c99 -Wunused" else="-O2 -Wall -c -fPIC -std=c99 -Wunused">
<os name="SunOS" />
</condition>
<property name="linker_flags32" value="${version_script_flags32} -shared -O2 -Wall -o ${libname32} ${libs32} ${xf86vm_lib}"/>
<property name="linker_flags64" value="${version_script_flags64} -shared -O2 -Wall -o ${libname64} ${libs64} ${xf86vm_lib}"/>
<condition property="build.32bit.only">
<and>
<os name="FreeBSD"/>
<equals arg1="${hwplatform}" arg2="i386"/>
</and>
</condition>
<condition property="build.32bit.only">
<and>
<os name="OpenBSD"/>
<equals arg1="${hwplatform}" arg2="i386"/>
</and>
</condition>
<!-- On freebsd, the 64 bit jre doesn't have the 32 bit libs -->
<condition property="build.64bit.only">
<and>
<os name="FreeBSD"/>
<equals arg1="${hwplatform}" arg2="amd64"/>
</and>
</condition>
<condition property="build.64bit.only">
<and>
<os name="OpenBSD"/>
<equals arg1="${hwplatform}" arg2="amd64"/>
</and>
</condition>
<antcall target="compile32"/>
<antcall target="compile64"/>
</target>
<target name="compile32" unless="build.64bit.only">
<mkdir dir="x32"/>
<apply dir="x32" executable="cc" skipemptyfilesets="true" failonerror="true">
<arg line="${cflags32} ${cflags_pthread}"/>
<arg value="-I${java.home}/include"/>
<arg value="-I${java.home}/include/freebsd"/>
<arg value="-I${java.home}/include/openbsd"/>
<arg value="-I${java.home}/../include"/>
<arg value="-I${java.home}/../include/freebsd"/>
<arg value="-I${java.home}/../include/openbsd"/>
<arg value="-I/usr/local/include"/>
<arg value="-I/usr/X11R6/include"/>
<arg value="-I${native}/common"/>
<arg value="-I${native}/common/opengl"/>
<arg value="-I${native}/linux"/>
<arg value="-I${native}/linux/opengl"/>
<mapper type="glob" from="*.c" to="*.o"/>
<fileset dir="${native}/common" includes="*.c"/>
<fileset dir="${native}/common/opengl" includes="*.c"/>
<fileset dir="${native}/generated/openal" includes="*.c"/>
<fileset dir="${native}/generated/opencl" includes="*.c"/>
<fileset dir="${native}/generated/opengl" includes="*.c"/>
<fileset dir="${native}/linux" includes="*.c"/>
<fileset dir="${native}/linux/opengl" includes="*.c"/>
</apply>
<apply dir="." parallel="true" executable="cc" failonerror="true">
<srcfile/>
<arg line="${linker_flags32}"/>
<fileset dir="x32" includes="*.o"/>
</apply>
<apply dir="." parallel="true" executable="strip" failonerror="true">
<fileset file="${libname32}"/>
</apply>
</target>
<target name="compile64" unless="build.32bit.only">
<mkdir dir="x64"/>
<apply dir="x64" executable="cc" skipemptyfilesets="true" failonerror="true">
<arg line="${cflags64} ${cflags_pthread}"/>
<arg value="-I${java.home}/include"/>
<arg value="-I${java.home}/include/freebsd"/>
<arg value="-I${java.home}/include/openbsd"/>
<arg value="-I${java.home}/../include"/>
<arg value="-I${java.home}/../include/freebsd"/>
<arg value="-I${java.home}/../include/openbsd"/>
<arg value="-I/usr/local/include"/>
<arg value="-I/usr/X11R6/include"/>
<arg value="-I${native}/common"/>
<arg value="-I${native}/common/opengl"/>
<arg value="-I${native}/linux"/>
<arg value="-I${native}/linux/opengl"/>
<mapper type="glob" from="*.c" to="*.o"/>
<fileset dir="${native}/common" includes="*.c"/>
<fileset dir="${native}/common/opengl" includes="*.c"/>
<fileset dir="${native}/generated/openal" includes="*.c"/>
<fileset dir="${native}/generated/opencl" includes="*.c"/>
<fileset dir="${native}/generated/opengl" includes="*.c"/>
<fileset dir="${native}/linux" includes="*.c"/>
<fileset dir="${native}/linux/opengl" includes="*.c"/>
</apply>
<apply dir="." parallel="true" executable="cc" failonerror="true">
<srcfile/>
<arg line="${linker_flags64}"/>
<fileset dir="x64" includes="*.o"/>
</apply>
<apply dir="." parallel="true" executable="strip" failonerror="true">
<fileset file="${libname64}"/>
</apply>
</target>
</project>

View file

@ -12,7 +12,7 @@
<property name="lwjgl.docs" location="doc" />
<property name="lwjgl.temp" location="temp" />
<property name="lwjgl.res" location="res" />
<property name="lwjgl.version" value="2.8.5" />
<property name="lwjgl.version" value="2.9.4" />
<property name="lwjgl.web" location="www" />
<property name="lwjgl.src.templates.al" location="${lwjgl.src.templates}/org/lwjgl/openal"/>
@ -147,12 +147,12 @@
<!-- Files to include in mac os x package -->
<patternset id="lwjgl-macosx.fileset">
<patternset id="lwjgl-macosx-lwjgl.fileset">
<include name="liblwjgl.jnilib" />
<include name="liblwjgl.dylib" />
<include name="openal.dylib" />
</patternset>
<patternset id="lwjgl-macosx-jinput.fileset">
<include name="libjinput-osx.jnilib" />
<include name="libjinput-osx-legacy.jnilib" />
<include name="libjinput-osx.dylib" />
<include name="libjinput-osx-legacy.dylib" />
</patternset>
</patternset>

View file

@ -1,5 +1,7 @@
<project name="generator">
<import file="build-definitions.xml"/>
<!-- clean the generated files -->
<target name="clean-generated" description="Deletes the generated java source">
<delete quiet="true" failonerror="false">
@ -14,16 +16,24 @@
</target>
<!-- Compiles the Java generator source code -->
<target name="generators" description="Compiles the native method generators">
<javac debug="yes" srcdir="${lwjgl.src}/java/" destdir="${lwjgl.bin}" includes="org/lwjgl/util/generator/**.java" source="1.5" target="1.5" taskname="generator">
<target name="generators" description="Compiles the native method generators">
<mkdir dir="${lwjgl.src}/generated/"/>
<mkdir dir="${lwjgl.src.native}/generated/openal"/>
<mkdir dir="${lwjgl.src.native}/generated/opengl"/>
<mkdir dir="${lwjgl.src.native}/generated/opengles"/>
<mkdir dir="${lwjgl.src.native}/generated/opencl"/>
<mkdir dir="${lwjgl.bin}"/>
<javac debug="yes" srcdir="${lwjgl.src}/java/" destdir="${lwjgl.bin}" source="1.7" target="1.7" includes="org/lwjgl/util/generator/**.java" taskname="generator">
<include name="org/lwjgl/util/generator/openal/**.java"/>
<include name="org/lwjgl/util/generator/opengl/**.java"/>
<include name="org/lwjgl/util/generator/opengles/**.java"/>
<include name="org/lwjgl/util/generator/opencl/**.java"/>
<compilerarg value="-Xlint:all"/>
<compilerarg value="-Xlint:none"/>
</javac>
<!-- Compile helper classes used by the templates -->
<javac debug="yes" srcdir="${lwjgl.src}/java/" destdir="${lwjgl.bin}" source="1.5" target="1.5" taskname="generator">
<!-- Compile helper classes used by the templates -->
<javac debug="yes" srcdir="${lwjgl.src}/java/" destdir="${lwjgl.bin}" source="1.7" target="1.7" taskname="generator">
<include name="org/lwjgl/PointerWrapper.java"/>
<include name="org/lwjgl/PointerBuffer.java"/>
<!-- OpenGL -->
@ -58,40 +68,48 @@
**************************************************************************** -->
<!-- Generate OpenAL -->
<target name="generate-openal" depends="generators" description="Generates java and native source for AL">
<apply executable="apt" parallel="true" dir="${lwjgl.src.templates.al}" relative="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.GeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<arg value="-d"/>
<arg path="${lwjgl.src.native}/generated/openal"/>
<arg value="-Abinpath=${lwjgl.bin}"/>
<arg value="-Atypemap=org.lwjgl.util.generator.openal.ALTypeMap"/>
<fileset dir="${lwjgl.src.templates.al}" includes="${openal-template-pattern}"/>
</apply>
<target name="generate-openal" depends="generators" description="Generates java and native source for AL">
<javac destdir="${lwjgl.bin}" source="1.7" target="1.7" srcdir="${lwjgl.src.templates.al}" fork="true" taskname="processor">
<compilerarg value="-proc:only"/>
<compilerarg value="-processor"/>
<compilerarg value="org.lwjgl.util.generator.GeneratorProcessor"/>
<compilerarg value="-cp"/>
<compilerarg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<compilerarg value="-s"/>
<compilerarg path="${lwjgl.src}/generated"/>
<compilerarg value="-d"/>
<compilerarg path="${lwjgl.src.native}/generated/openal"/>
<compilerarg value="-Abinpath=${lwjgl.bin}"/>
<compilerarg value="-Atypemap=org.lwjgl.util.generator.openal.ALTypeMap"/>
<src>
<fileset dir="${lwjgl.src.templates.al}">
<include name="${openal-template-pattern}"/>
</fileset>
</src>
</javac>
</target>
<!-- Generate OpenAL [DEBUG] -->
<target name="generate-openal-debug" depends="generators" description="Generates java and native source for AL">
<apply executable="apt" parallel="true" dir="${lwjgl.src.templates.al}" relative="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.GeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<arg value="-d"/>
<arg path="${lwjgl.src.native}/generated/openal"/>
<arg value="-Abinpath=${lwjgl.bin}"/>
<arg value="-Atypemap=org.lwjgl.util.generator.openal.ALTypeMap"/>
<arg value="-Ageneratechecks"/>
<fileset dir="${lwjgl.src.templates.al}" includes="${openal-template-pattern}"/>
</apply>
<javac destdir="${lwjgl.bin}" source="1.7" target="1.7" srcdir="${lwjgl.src.templates.al}" fork="true" taskname="processor">
<compilerarg value="-proc:only"/>
<compilerarg value="-processor"/>
<compilerarg value="org.lwjgl.util.generator.GeneratorProcessor"/>
<compilerarg value="-cp"/>
<compilerarg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<compilerarg value="-s"/>
<compilerarg path="${lwjgl.src}/generated"/>
<compilerarg value="-d"/>
<compilerarg path="${lwjgl.src.native}/generated/openal"/>
<compilerarg value="-Abinpath=${lwjgl.bin}"/>
<compilerarg value="-Atypemap=org.lwjgl.util.generator.openal.ALTypeMap"/>
<compilerarg value="-Ageneratechecks"/>
<src>
<fileset dir="${lwjgl.src.templates.al}">
<include name="${openal-template-pattern}"/>
</fileset>
</src>
</javac>
</target>
<!-- ********************************************************************************
@ -102,86 +120,106 @@
<!-- Generate OpenGL -->
<target name="generate-opengl" depends="generators" description="Generates java and native source for GL">
<apply executable="apt" parallel="true" dir="${lwjgl.src.templates.gl}" relative="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.GeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<arg value="-d"/>
<arg path="${lwjgl.src.native}/generated/opengl"/>
<arg value="-Abinpath=${lwjgl.bin}"/>
<arg value="-Acontextspecific"/>
<arg value="-Atypemap=org.lwjgl.util.generator.opengl.GLTypeMap"/>
<fileset dir="${lwjgl.src.templates.gl}" includes="${opengl-template-pattern}"/>
</apply>
<javac destdir="${lwjgl.bin}" source="1.7" target="1.7" srcdir="${lwjgl.src.templates.gl}" fork="true" taskname="processorGL">
<compilerarg value="-proc:only"/>
<compilerarg value="-processor"/>
<compilerarg value="org.lwjgl.util.generator.GeneratorProcessor"/>
<compilerarg value="-cp"/>
<compilerarg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<compilerarg value="-s"/>
<compilerarg path="${lwjgl.src}/generated"/>
<compilerarg value="-d"/>
<compilerarg path="${lwjgl.src.native}/generated/opengl"/>
<compilerarg value="-Abinpath=${lwjgl.bin}"/>
<compilerarg value="-Atypemap=org.lwjgl.util.generator.opengl.GLTypeMap"/>
<compilerarg value="-Acontextspecific"/>
<src>
<fileset dir="${lwjgl.src.templates.gl}">
<include name="${opengl-template-pattern}"/>
</fileset>
</src>
</javac>
</target>
<!-- Generate OpenGL [DEBUG] -->
<target name="generate-opengl-debug" depends="generators" description="Generates debug java and native source for GL">
<apply executable="apt" parallel="true" dir="${lwjgl.src.templates.gl}" relative="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.GeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<arg value="-d"/>
<arg path="${lwjgl.src.native}/generated/opengl"/>
<arg value="-Abinpath=${lwjgl.bin}"/>
<arg value="-Ageneratechecks"/>
<arg value="-Acontextspecific"/>
<arg value="-Atypemap=org.lwjgl.util.generator.opengl.GLTypeMap"/>
<fileset dir="${lwjgl.src.templates.gl}" includes="${opengl-template-pattern}"/>
</apply>
<javac destdir="${lwjgl.bin}" source="1.7" target="1.7" srcdir="${lwjgl.src.templates.gl}" fork="true" taskname="processor">
<compilerarg value="-proc:only"/>
<compilerarg value="-processor"/>
<compilerarg value="org.lwjgl.util.generator.GeneratorProcessor"/>
<compilerarg value="-cp"/>
<compilerarg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<compilerarg value="-s"/>
<compilerarg path="${lwjgl.src}/generated"/>
<compilerarg value="-d"/>
<compilerarg path="${lwjgl.src.native}/generated/opengl"/>
<compilerarg value="-Abinpath=${lwjgl.bin}"/>
<compilerarg value="-Ageneratechecks"/>
<compilerarg value="-Acontextspecific"/>
<compilerarg value="-Atypemap=org.lwjgl.util.generator.opengl.GLTypeMap"/>
<src>
<fileset dir="${lwjgl.src.templates.gl}">
<include name="${opengl-template-pattern}"/>
</fileset>
</src>
</javac>
</target>
<!-- Generate OpenGL references -->
<target name="generate-opengl-references" depends="generators" description="Generates java and native source for GL">
<apply executable="apt" parallel="true" dir="${lwjgl.src.templates.gl}" relative="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.opengl.GLReferencesGeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<fileset dir="${lwjgl.src.templates.gl}" includes="${opengl-template-pattern}"/>
</apply>
<javac destdir="${lwjgl.bin}" source="1.7" target="1.7" srcdir="${lwjgl.src.templates.gl}" fork="true" taskname="processor">
<compilerarg value="-proc:only"/>
<compilerarg value="-processor"/>
<compilerarg value="org.lwjgl.util.generator.opengl.GLReferencesGeneratorProcessor"/>
<compilerarg value="-cp"/>
<compilerarg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<compilerarg value="-s"/>
<compilerarg path="${lwjgl.src}/generated"/>
<src>
<fileset dir="${lwjgl.src.templates.gl}">
<include name="${opengl-template-pattern}"/>
</fileset>
</src>
</javac>
</target>
<!-- Generate OpenGL context capabilities -->
<target name="generate-opengl-capabilities" depends="generators" description="Generates java and native source for GL">
<apply executable="apt" parallel="true" dir="${lwjgl.src.templates.gl}" relative="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.opengl.GLGeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<arg value="-Acontextspecific"/>
<fileset dir="${lwjgl.src.templates.gl}" includes="${opengl-template-pattern}"/>
</apply>
<javac destdir="${lwjgl.bin}" source="1.7" target="1.7" srcdir="${lwjgl.src.templates.gl}" fork="true" taskname="processor">
<compilerarg value="-proc:only"/>
<compilerarg value="-processor"/>
<compilerarg value="org.lwjgl.util.generator.opengl.GLGeneratorProcessor"/>
<compilerarg value="-cp"/>
<compilerarg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<compilerarg value="-s"/>
<compilerarg path="${lwjgl.src}/generated"/>
<compilerarg value="-Acontextspecific"/>
<src>
<fileset dir="${lwjgl.src.templates.gl}">
<include name="${opengl-template-pattern}"/>
</fileset>
</src>
</javac>
</target>
<!-- Generate OpenGL context capabilities [DEBUG] -->
<target name="generate-opengl-capabilities-debug" depends="generators" description="Generates debug java and native source for GL">
<apply executable="apt" parallel="true" dir="${lwjgl.src.templates.gl}" relative="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.opengl.GLGeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<arg value="-Ageneratechecks"/>
<arg value="-Acontextspecific"/>
<fileset dir="${lwjgl.src.templates.gl}" includes="${opengl-template-pattern}"/>
</apply>
<javac destdir="${lwjgl.bin}" source="1.7" target="1.7" srcdir="${lwjgl.src.templates.gl}" fork="true" taskname="processor">
<compilerarg value="-proc:only"/>
<compilerarg value="-processor"/>
<compilerarg value="org.lwjgl.util.generator.opengl.GLGeneratorProcessor"/>
<compilerarg value="-cp"/>
<compilerarg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<compilerarg value="-s"/>
<compilerarg path="${lwjgl.src}/generated"/>
<compilerarg value="-Ageneratechecks"/>
<compilerarg value="-Acontextspecific"/>
<src>
<fileset dir="${lwjgl.src.templates.gl}">
<include name="${opengl-template-pattern}"/>
</fileset>
</src>
</javac>
</target>
<!-- ********************************************************************************
@ -192,72 +230,88 @@
<!-- Generate OpenGL ES -->
<target name="generate-opengles" depends="generators" description="Generates java and native source for GL ES">
<apply executable="apt" parallel="true" dir="${lwjgl.src.templates.gles}" relative="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.GeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<arg value="-d"/>
<arg path="${lwjgl.src.native}/generated/opengles"/>
<arg value="-Abinpath=${lwjgl.bin}"/>
<!--<arg value="-Acontextspecific"/>-->
<arg value="-Atypemap=org.lwjgl.util.generator.opengl.GLESTypeMap"/>
<fileset dir="${lwjgl.src.templates.gles}" includes="${opengles-template-pattern}"/>
</apply>
<javac destdir="${lwjgl.bin}" source="1.7" target="1.7" srcdir="${lwjgl.src.templates.gles}" fork="true" taskname="processor">
<compilerarg value="-proc:only"/>
<compilerarg value="-processor"/>
<compilerarg value="org.lwjgl.util.generator.GeneratorProcessor"/>
<compilerarg value="-cp"/>
<compilerarg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<compilerarg value="-s"/>
<compilerarg path="${lwjgl.src}/generated"/>
<compilerarg value="-d"/>
<compilerarg path="${lwjgl.src.native}/generated/opengles"/>
<compilerarg value="-Abinpath=${lwjgl.bin}"/>
<!--<compilerarg value="-Acontextspecific"/>-->
<compilerarg value="-Atypemap=org.lwjgl.util.generator.opengl.GLESTypeMap"/>
<src>
<fileset dir="${lwjgl.src.templates.gles}">
<include name="${opengles-template-pattern}"/>
</fileset>
</src>
</javac>
</target>
<!-- Generate OpenGL ES [DEBUG] -->
<target name="generate-opengles-debug" depends="generators" description="Generates debug java and native source for GL ES">
<apply executable="apt" parallel="true" dir="${lwjgl.src.templates.gles}" relative="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.GeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<arg value="-d"/>
<arg path="${lwjgl.src.native}/generated/opengles"/>
<arg value="-Abinpath=${lwjgl.bin}"/>
<arg value="-Ageneratechecks"/>
<!--<arg value="-Acontextspecific"/>-->
<arg value="-Atypemap=org.lwjgl.util.generator.opengl.GLESTypeMap"/>
<fileset dir="${lwjgl.src.templates.gles}" includes="${opengles-template-pattern}"/>
</apply>
<javac destdir="${lwjgl.bin}" source="1.7" target="1.7" srcdir="${lwjgl.src.templates.gles}" fork="true" taskname="processor">
<compilerarg value="-proc:only"/>
<compilerarg value="-processor"/>
<compilerarg value="org.lwjgl.util.generator.GeneratorProcessor"/>
<compilerarg value="-cp"/>
<compilerarg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<compilerarg value="-s"/>
<compilerarg path="${lwjgl.src}/generated"/>
<compilerarg value="-d"/>
<compilerarg path="${lwjgl.src.native}/generated/opengles"/>
<compilerarg value="-Abinpath=${lwjgl.bin}"/>
<compilerarg value="-Ageneratechecks"/>
<!--<compilerarg value="-Acontextspecific"/>-->
<compilerarg value="-Atypemap=org.lwjgl.util.generator.opengl.GLESTypeMap"/>
<src>
<fileset dir="${lwjgl.src.templates.gles}">
<include name="${opengles-template-pattern}"/>
</fileset>
</src>
</javac>
</target>
<!-- Generate OpenGL ES context capabilities -->
<target name="generate-opengles-capabilities" depends="generators" description="Generates java and native source for GL ES">
<apply executable="apt" parallel="true" dir="${lwjgl.src.templates.gles}" relative="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.opengl.GLESGeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<!--<arg value="-Acontextspecific"/>-->
<fileset dir="${lwjgl.src.templates.gles}" includes="${opengles-template-pattern}"/>
</apply>
<javac destdir="${lwjgl.bin}" source="1.7" target="1.7" srcdir="${lwjgl.src.templates.gles}" fork="true" taskname="processor">
<compilerarg value="-proc:only"/>
<compilerarg value="-processor"/>
<compilerarg value="org.lwjgl.util.generator.opengl.GLESGeneratorProcessor"/>
<compilerarg value="-cp"/>
<compilerarg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<compilerarg value="-s"/>
<compilerarg path="${lwjgl.src}/generated"/>
<!--<compilerarg value="-Acontextspecific"/>-->
<src>
<fileset dir="${lwjgl.src.templates.gles}">
<include name="${opengles-template-pattern}"/>
</fileset>
</src>
</javac>
</target>
<!-- Generate OpenGL ES context capabilities [DEBUG] -->
<target name="generate-opengles-capabilities-debug" depends="generators" description="Generates debug java and native source for GL ES">
<apply executable="apt" parallel="true" dir="${lwjgl.src.templates.gles}" relative="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.opengl.GLESGeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<arg value="-Ageneratechecks"/>
<!--<arg value="-Acontextspecific"/>-->
<fileset dir="${lwjgl.src.templates.gles}" includes="${opengles-template-pattern}"/>
</apply>
<javac destdir="${lwjgl.bin}" source="1.7" target="1.7" srcdir="${lwjgl.src.templates.gles}" fork="true" taskname="processor">
<compilerarg value="-proc:only"/>
<compilerarg value="-processor"/>
<compilerarg value="org.lwjgl.util.generator.opengl.GLESGeneratorProcessor"/>
<compilerarg value="-cp"/>
<compilerarg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<compilerarg value="-s"/>
<compilerarg path="${lwjgl.src}/generated"/>
<compilerarg value="-Ageneratechecks"/>
<!--<compilerarg value="-Acontextspecific"/>-->
<src>
<fileset dir="${lwjgl.src.templates.gles}">
<include name="${opengles-template-pattern}"/>
</fileset>
</src>
</javac>
</target>
<!-- ********************************************************************************
@ -268,71 +322,87 @@
<!-- Generate OpenCL -->
<target name="generate-opencl" depends="generators" description="Generates java and native source for CL">
<apply executable="apt" parallel="true" dir="${lwjgl.src.templates.cl}" relative="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.GeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<arg value="-d"/>
<arg path="${lwjgl.src.native}/generated/opencl"/>
<arg value="-Abinpath=${lwjgl.bin}"/>
<arg value="-Acontextspecific"/>
<arg value="-Atypemap=org.lwjgl.util.generator.opencl.CLTypeMap"/>
<fileset dir="${lwjgl.src.templates.cl}" includes="${opencl-template-pattern}"/>
</apply>
<javac destdir="${lwjgl.bin}" source="1.7" target="1.7" srcdir="${lwjgl.src.templates.cl}" fork="true" taskname="processor">
<compilerarg value="-proc:only"/>
<compilerarg value="-processor"/>
<compilerarg value="org.lwjgl.util.generator.GeneratorProcessor"/>
<compilerarg value="-cp"/>
<compilerarg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<compilerarg value="-s"/>
<compilerarg path="${lwjgl.src}/generated"/>
<compilerarg value="-d"/>
<compilerarg path="${lwjgl.src.native}/generated/opencl"/>
<compilerarg value="-Abinpath=${lwjgl.bin}"/>
<compilerarg value="-Acontextspecific"/>
<compilerarg value="-Atypemap=org.lwjgl.util.generator.opencl.CLTypeMap"/>
<src>
<fileset dir="${lwjgl.src.templates.cl}">
<include name="${opencl-template-pattern}"/>
</fileset>
</src>
</javac>
</target>
<!-- Generate OpenCL [DEBUG] -->
<target name="generate-opencl-debug" depends="generators" description="Generates debug java and native source for CL">
<apply executable="apt" parallel="true" dir="${lwjgl.src.templates.cl}" relative="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.GeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<arg value="-d"/>
<arg path="${lwjgl.src.native}/generated/opencl"/>
<arg value="-Abinpath=${lwjgl.bin}"/>
<arg value="-Ageneratechecks"/>
<arg value="-Acontextspecific"/>
<arg value="-Atypemap=org.lwjgl.util.generator.opencl.CLTypeMap"/>
<fileset dir="${lwjgl.src.templates.cl}" includes="${opencl-template-pattern}"/>
</apply>
<javac destdir="${lwjgl.bin}" source="1.7" target="1.7" srcdir="${lwjgl.src.templates.cl}" fork="true" taskname="processor">
<compilerarg value="-proc:only"/>
<compilerarg value="-processor"/>
<compilerarg value="org.lwjgl.util.generator.GeneratorProcessor"/>
<compilerarg value="-cp"/>
<compilerarg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<compilerarg value="-s"/>
<compilerarg path="${lwjgl.src}/generated"/>
<compilerarg value="-d"/>
<compilerarg path="${lwjgl.src.native}/generated/opencl"/>
<compilerarg value="-Abinpath=${lwjgl.bin}"/>
<compilerarg value="-Ageneratechecks"/>
<compilerarg value="-Acontextspecific"/>
<compilerarg value="-Atypemap=org.lwjgl.util.generator.opencl.CLTypeMap"/>
<src>
<fileset dir="${lwjgl.src.templates.cl}">
<include name="${opencl-template-pattern}"/>
</fileset>
</src>
</javac>
</target>
<!-- Generate OpenCL capabilities -->
<target name="generate-opencl-capabilities" depends="generators" description="Generates capabilities for CL">
<apply executable="apt" parallel="true" dir="${lwjgl.src.templates.cl}" relative="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.opencl.CLGeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<arg value="-Acontextspecific"/>
<fileset dir="${lwjgl.src.templates.cl}" includes="${opencl-template-pattern}"/>
</apply>
<javac destdir="${lwjgl.bin}" source="1.7" target="1.7" srcdir="${lwjgl.src.templates.cl}" fork="true" taskname="processor">
<compilerarg value="-proc:only"/>
<compilerarg value="-processor"/>
<compilerarg value="org.lwjgl.util.generator.opencl.CLGeneratorProcessor"/>
<compilerarg value="-cp"/>
<compilerarg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<compilerarg value="-s"/>
<compilerarg path="${lwjgl.src}/generated"/>
<compilerarg value="-Acontextspecific"/>
<src>
<fileset dir="${lwjgl.src.templates.cl}">
<include name="${opencl-template-pattern}"/>
</fileset>
</src>
</javac>
</target>
<!-- Generate OpenCL capabilities [DEBUG] -->
<target name="generate-opencl-capabilities-debug" depends="generators" description="Generates debug capabilities for CL">
<apply executable="apt" parallel="true" dir="${lwjgl.src.templates.cl}" relative="true">
<arg value="-nocompile"/>
<arg value="-factory"/>
<arg value="org.lwjgl.util.generator.opencl.CLGeneratorProcessorFactory"/>
<arg value="-cp"/>
<arg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<arg value="-s"/>
<arg path="${lwjgl.src}/generated"/>
<arg value="-Ageneratechecks"/>
<arg value="-Acontextspecific"/>
<fileset dir="${lwjgl.src.templates.cl}" includes="${opencl-template-pattern}"/>
</apply>
<javac destdir="${lwjgl.bin}" source="1.7" target="1.7" srcdir="${lwjgl.src.templates.cl}" fork="true" taskname="processor">
<compilerarg value="-proc:only"/>
<compilerarg value="-processor"/>
<compilerarg value="org.lwjgl.util.generator.opencl.CLGeneratorProcessor"/>
<compilerarg value="-cp"/>
<compilerarg path="${lwjgl.src}/java:${lwjgl.src.templates}:${lwjgl.bin}:${java.class.path}"/>
<compilerarg value="-s"/>
<compilerarg path="${lwjgl.src}/generated"/>
<compilerarg value="-Ageneratechecks"/>
<compilerarg value="-Acontextspecific"/>
<src>
<fileset dir="${lwjgl.src.templates.cl}">
<include name="${opencl-template-pattern}"/>
</fileset>
</src>
</javac>
</target>
</project>

View file

@ -4,7 +4,7 @@
<property name="native" location="../../src/native"/>
<property name="libname32" value="liblwjgl.so"/>
<property name="libname64" value="liblwjgl64.so"/>
<property name="libs32" value="-L/usr/X11R6/lib -L/usr/X11/lib -lm -lX11 -lXext -lXcursor -lXrandr -lpthread -L${java.home}/lib/i386 -ljawt" />
<property name="libs32" value="-L/usr/X11R6/lib -L/usr/X11/lib -lm -lX11 -lXext -lXcursor -lXrandr -lXxf86vm -lpthread -L${java.home}/lib/i386 -ljawt" />
<property name="libs64" value="-L/usr/X11R6/lib64 -L/usr/X11/lib64 -lm -lX11 -lXext -lXcursor -lXrandr -lXxf86vm -lpthread -L${java.home}/lib/amd64 -ljawt" />
<property name="cflags32" value="-O2 -Wall -c -fPIC -std=c99 -Wunused"/>
@ -21,9 +21,6 @@
<exec executable="uname" outputproperty="hwplatform">
<arg value="-m"/>
</exec>
<condition property="xf86vm_lib" value="-lXxf86vm" else="-Wl,-static,-lXxf86vm,-call_shared">
<os name="SunOS" />
</condition>
<condition property="cflags_pthread" value="-pthreads" else="-pthread">
<os name="SunOS" />
</condition>
@ -39,8 +36,8 @@
<os name="SunOS" />
</condition>
<property name="linker_flags32" value="${version_script_flags32} -shared -O2 -Wall -o ${libname32} ${libs32} ${xf86vm_lib}"/>
<property name="linker_flags64" value="${version_script_flags64} -shared -O2 -Wall -o ${libname64} ${libs64} ${xf86vm_lib}"/>
<property name="linker_flags32" value="${version_script_flags32} -shared -O2 -Wall -o ${libname32} ${libs32}"/>
<property name="linker_flags64" value="${version_script_flags64} -shared -O2 -Wall -o ${libname64} ${libs64}"/>
<condition property="build.32bit.only">
<not>
@ -65,7 +62,7 @@
<target name="compile32" unless="build.64bit.only">
<mkdir dir="x32"/>
<apply dir="x32" executable="gcc" skipemptyfilesets="true" failonerror="true">
<apply dir="x32" executable="gcc" skipemptyfilesets="true" failonerror="true" parallel="true">
<arg line="${cflags32} ${cflags_pthread}"/>
<arg value="-I${java.home}/include"/>
<arg value="-I${java.home}/include/linux"/>
@ -97,7 +94,7 @@
<target name="compile64" unless="build.32bit.only">
<mkdir dir="x64"/>
<apply dir="x64" executable="gcc" skipemptyfilesets="true" failonerror="true">
<apply dir="x64" executable="gcc" skipemptyfilesets="true" failonerror="true" parallel="true">
<arg line="${cflags64} ${cflags_pthread}"/>
<arg value="-I${java.home}/include"/>
<arg value="-I${java.home}/include/linux"/>

View file

@ -4,7 +4,8 @@
<property name="native" location="../../src/native"/>
<property name="libname32" value="liblwjgl.so"/>
<property name="libname64" value="liblwjgl64.so"/>
<property name="libs32" value="-L/home/spasi/lwjgl/libs/linux -lEGL -L/usr/X11R6/lib -L/usr/X11/lib -lm -lX11 -lXext -lXcursor -lXrandr -lpthread -L${java.home}/lib/i386 -ljawt" />
<property name="lib_folder" value="${lwjgl.lib}/linux"/>
<property name="libs32" value="-L${lib_folder} -lEGL -L/usr/X11R6/lib -L/usr/X11/lib -lm -lX11 -lXext -lXcursor -lXrandr -lXxf86vm -lpthread -L${java.home}/lib/i386 -ljawt" />
<property name="libs64" value="-L${lib_folder}/x64 -lEGL -L/usr/X11R6/lib64 -L/usr/X11/lib64 -lm -lX11 -lXext -lXcursor -lXrandr -lXxf86vm -lpthread -L${java.home}/lib/amd64 -ljawt" />
<property name="cflags32" value="-O2 -Wall -c -fPIC -std=c99 -Wunused"/>
@ -21,9 +22,6 @@
<exec executable="uname" outputproperty="hwplatform">
<arg value="-m"/>
</exec>
<condition property="xf86vm_lib" value="-lXxf86vm" else="-Wl,-static,-lXxf86vm,-call_shared">
<os name="SunOS" />
</condition>
<condition property="cflags_pthread" value="-pthreads" else="-pthread">
<os name="SunOS" />
</condition>
@ -39,8 +37,8 @@
<os name="SunOS" />
</condition>
<property name="linker_flags32" value="${version_script_flags32} -shared -O2 -Wall -o ${libname32} ${libs32} ${xf86vm_lib}"/>
<property name="linker_flags64" value="${version_script_flags64} -shared -O2 -Wall -o ${libname64} ${libs64} ${xf86vm_lib}"/>
<property name="linker_flags32" value="${version_script_flags32} -shared -O2 -Wall -o ${libname32} ${libs32}"/>
<property name="linker_flags64" value="${version_script_flags64} -shared -O2 -Wall -o ${libname64} ${libs64}"/>
<condition property="build.32bit.only">
<not>
@ -126,4 +124,4 @@
<fileset file="${libname64}"/>
</apply>
</target>
</project>
</project>

View file

@ -1,4 +1,3 @@
#!/bin/sh
nm -g "$1"/*.o | grep "Java_" | cut -d ' ' -f3 | cut -c 1-
nm -g "$1"/*.o | grep "JNI_" | cut -d ' ' -f3 | cut -c 1-
nm -j -g "$1"/*.o | grep -E "J(ava|NI)_[^.]*$"

View file

@ -1,103 +1,220 @@
<project name="OS X Native code" basedir="../../bin/lwjgl" default="nativelibrary">
<property name="native" location="../../src/native"/>
<target name="init">
<mkdir dir="ppc"/>
<mkdir dir="i386"/>
<mkdir dir="x86_64"/>
</target>
<target name="clean">
<delete failonerror="false">
<fileset dir="i386"/>
<fileset dir="x86_64"/>
<fileset dir="ppc"/>
<fileset dir="." includes="liblwjgl.jnilib"/>
<fileset dir="." includes="lwjgl.symbols"/>
</delete>
</target>
<target name="compile">
<apply dir="${dstdir}" executable="${compiler}" os="Mac OS X" skipemptyfilesets="true" failonerror="true" dest="${dstdir}">
<arg line="${cflags} -ObjC -O2 -Wall -Wunused -c -fPIC -I/System/Library/Frameworks/JavaVM.framework/Versions/A/Headers -I${native}/common -I${native}/common/opengl -I${native}/macosx -I/System/Library/Frameworks/JavaVM.framework/Versions/A/Frameworks/JavaNativeFoundation.framework/Versions/A/Headers"/>
<!-- Map from *.m and *.c to .o -->
<mapper type="regexp" from="^(.*)\.(c|m)" to="\1.o"/>
<fileset dir="${native}/macosx" includes="*.m"/>
<fileset dir="${native}/macosx" includes="*.c"/>
<fileset dir="${native}/common" includes="*.c"/>
<fileset dir="${native}/common/opengl" includes="*.c"/>
<fileset dir="${native}/generated/openal" includes="*.c"/>
<fileset dir="${native}/generated/opencl" includes="*.c"/>
<fileset dir="${native}/generated/opengl" includes="*.c"/>
</apply>
</target>
<target name="link">
<apply dir="${objdir}" parallel="true" executable="${linker}" os="Mac OS X" failonerror="true" skipemptyfilesets="true">
<arg line="${linkerflags} -exported_symbols_list ../lwjgl.symbols -dynamiclib -o ${libname} -framework Foundation -weak_framework AppKit -framework JavaVM -framework Carbon -framework OpenGL -framework QuartzCore -framework JavaNativeFoundation -F/System/Library/Frameworks/JavaVM.framework/Frameworks"/>
<fileset dir="${objdir}" includes="*.o"/>
</apply>
<apply dir="${objdir}" executable="strip" os="Mac OS X" failonerror="true">
<arg line="-S -X"/>
<fileset dir="." file="${libname}"/>
</apply>
</target>
<target name="nativelibrary" depends="init">
<property name="universal_sdkroot" location="/Developer/SDKs/MacOSX10.6.sdk"/>
<property name="ppc_sdkroot" location="/Developer/SDKs/MacOSX10.6.sdk"/>
<property name="x86_64_sdkroot" location="/Developer/SDKs/MacOSX10.6.sdk"/>
<property name="universal_flags" value="-isysroot ${universal_sdkroot}"/>
<property name="ppc_flags" value="-isysroot ${ppc_sdkroot}"/>
<antcall target="compile">
<param name="dstdir" location="ppc"/>
<param name="compiler" value="gcc-4.2"/>
<param name="sdkroot" location="${ppc_sdkroot}"/>
<param name="cflags" value="${universal_flags} -arch ppc -mmacosx-version-min=10.3"/>
</antcall>
<antcall target="compile">
<param name="dstdir" location="i386"/>
<param name="compiler" value="gcc-4.2"/>
<param name="sdkroot" location="${universal_sdkroot}"/>
<param name="cflags" value="${universal_flags} -arch i386 -mmacosx-version-min=10.4"/>
</antcall>
<antcall target="compile">
<param name="dstdir" location="x86_64"/>
<param name="compiler" value="gcc-4.2"/>
<param name="sdkroot" location="${universal_sdkroot}"/>
<param name="cflags" value="-isysroot ${x86_64_sdkroot} -arch x86_64 -mmacosx-version-min=10.5"/>
</antcall>
<exec vmlauncher="true" executable="sh" output="lwjgl.symbols" failonerror="true">
<arg path="../../platform_build/macosx_ant/build-symbol-list"/>
<arg path="i386"/>
</exec>
<antcall target="link">
<param name="objdir" location="ppc"/>
<param name="libname" value="liblwjgl-ppc.jnilib"/>
<param name="linker" value="gcc-4.2"/>
<param name="linkerflags" value="${universal_flags} -arch ppc -mmacosx-version-min=10.3"/>
</antcall>
<antcall target="link">
<param name="objdir" location="i386"/>
<param name="libname" value="liblwjgl-i386.jnilib"/>
<param name="linker" value="gcc-4.2"/>
<param name="linkerflags" value="${universal_flags} -arch i386 -mmacosx-version-min=10.4"/>
</antcall>
<antcall target="link">
<param name="objdir" location="x86_64"/>
<param name="libname" value="liblwjgl-i86_64.jnilib"/>
<param name="linker" value="gcc-4.2"/>
<param name="linkerflags" value="-isysroot ${x86_64_sdkroot} -arch x86_64 -mmacosx-version-min=10.5"/>
</antcall>
<apply dir="." parallel="true" executable="lipo" os="Mac OS X" failonerror="true" skipemptyfilesets="true" >
<arg value="-create"/>
<srcfile/>
<arg value="-output"/>
<arg path="liblwjgl.jnilib"/>
<fileset file="ppc/liblwjgl-ppc.jnilib"/>
<fileset file="i386/liblwjgl-i386.jnilib"/>
<fileset file="x86_64/liblwjgl-i86_64.jnilib"/>
</apply>
</target>
</project>
<project name="OS X Native code" basedir="../../bin/lwjgl" default="nativelibrary">
<property name="native" location="../../src/native"/>
<target name="init">
<mkdir dir="arm64"/>
<property environment="env" />
<!-- Ask Xcode for correct path to XCode tools -->
<!-- Will fail if XCode Command Line Tools are not installed on 10.7+ (Lion) -->
<exec executable="xcode-select" outputproperty="developer_path" errorproperty="xcode-select.error" failonerror="false" failifexecutionfails="false">
<arg value="-print-path" />
</exec>
<!-- Default to /Developer if xcode-select fails -->
<condition property="developer_path" value="/Developer">
<isset property="xcode-select.error" />
</condition>
<property name="sdk_path" value="Platforms/MacOSX.platform/Developer/SDKs"/>
<property name="jvm_headers_path" value="/Library/Java/JavaVirtualMachines/zulu-8.jdk/Contents/Home/include/"/>
<property name="sdkroot" value="${developer_path}/${sdk_path}/MacOSX.sdk"/>
<!-- Choose a JavaVM.framework -->
<condition property="javavmroot" value="${developer_path}/${sdk_path}/MacOSX10.9.sdk">
<and>
<not><isset property="javavmroot"/></not>
<available file="${developer_path}/${sdk_path}/MacOSX10.9.sdk/${jvm_headers_path}" type="dir"/>
</and>
</condition>
<condition property="javavmroot" value="${developer_path}/${sdk_path}/MacOSX10.8.sdk">
<and>
<not><isset property="javavmroot"/></not>
<available file="${developer_path}/${sdk_path}/MacOSX10.8.sdk/${jvm_headers_path}" type="dir"/>
</and>
</condition>
<condition property="javavmroot" value="${developer_path}/${sdk_path}/MacOSX10.7.sdk">
<and>
<not><isset property="javavmroot"/></not>
<available file="${developer_path}/${sdk_path}/MacOSX10.7.sdk/${jvm_headers_path}" type="dir"/>
</and>
</condition>
<condition property="javavmroot" value="${developer_path}/${sdk_path}/MacOSX10.6.sdk">
<and>
<not><isset property="javavmroot"/></not>
<available file="${developer_path}/${sdk_path}/MacOSX10.6.sdk/${jvm_headers_path}" type="dir"/>
</and>
</condition>
<condition property="javavmroot" value=""> <!-- Old location -->
<and>
<not><isset property="javavmroot"/></not>
<available file="/${jvm_headers_path}" type="dir"/>
</and>
</condition>
<!-- Choose a MacOSX SDK -->
<property name="compiler" value="clang"/> <!-- Default to clang for 10.8 and up -->
<condition property="sdkroot" value="${developer_path}/${sdk_path}/MacOSX10.9.sdk">
<and>
<not><isset property="sdkroot"/></not>
<available file="${developer_path}/${sdk_path}/MacOSX10.9.sdk" type="dir"/>
</and>
</condition>
<condition property="sdkroot" value="${developer_path}/${sdk_path}/MacOSX10.8.sdk">
<and>
<not><isset property="sdkroot"/></not>
<available file="${developer_path}/${sdk_path}/MacOSX10.8.sdk" type="dir"/>
</and>
</condition>
<!-- If we're on 10.7 or lower, use gcc instead of clang -->
<condition property="compiler" value="gcc-4.2">
<and>
<not><isset property="sdkroot"/></not>
<available file="gcc-4.2" filepath="${env.PATH}"/>
</and>
</condition>
<condition property="compiler" value="gcc">
<and>
<not><isset property="sdkroot"/></not>
<not><available file="gcc-4.2" filepath="${env.PATH}"/></not>
<available file="gcc" filepath="${env.PATH}"/>
</and>
</condition>
<condition property="sdkroot" value="${developer_path}/${sdk_path}/MacOSX10.7.sdk">
<and>
<not><isset property="sdkroot"/></not>
<available file="${developer_path}/${sdk_path}/MacOSX10.7.sdk" type="dir"/>
</and>
</condition>
<condition property="sdkroot" value="${developer_path}/${sdk_path}/MacOSX10.6.sdk">
<and>
<not><isset property="sdkroot"/></not>
<available file="${developer_path}/${sdk_path}/MacOSX10.6.sdk" type="dir"/>
</and>
</condition>
<condition property="sdkroot" value="${developer_path}/SDKs/MacOSx10.6.sdk"> <!-- Old XCode location -->
<and>
<not><isset property="sdkroot"/></not>
<available file="${developer_path}/SDKs/MacOSx10.6.sdk" type="dir"/>
</and>
</condition>
</target>
<target name="clean">
<delete failonerror="false">
<fileset dir="arm64"/>
<fileset dir="." includes="liblwjgl.dylib"/>
<fileset dir="." includes="lwjgl.symbols"/>
</delete>
</target>
<target name="compile" depends="init">
<apply dir="${dstdir}" executable="${compiler}" os="Mac OS X" skipemptyfilesets="true" failonerror="true" dest="${dstdir}">
<arg line="${cflags} -ObjC -O2 -Wall -Wunused -c -fPIC -I${jvm_headers_path} -I${jvm_headers_path}/darwin -I${native}/common -I${native}/common/opengl -I${native}/macosx"/>
<!-- Map from *.m and *.c to .o -->
<mapper type="regexp" from="^(.*)\.(c|m)" to="\1.o"/>
<fileset dir="${native}/macosx" includes="*.m"/>
<fileset dir="${native}/macosx" includes="*.c"/>
<fileset dir="${native}/common" includes="*.c"/>
<fileset dir="${native}/common/opengl" includes="*.c"/>
<fileset dir="${native}/generated/openal" includes="*.c"/>
<fileset dir="${native}/generated/opencl" includes="*.c"/>
<fileset dir="${native}/generated/opengl" includes="*.c"/>
</apply>
</target>
<target name="link" depends="init">
<condition property="jdk_lib" value="${java.home}/lib">
<available file="${java.home}/lib/libjawt.dylib" type="file"/>
</condition>
<condition property="jdk_lib" value="${java.home}/../Libraries">
<not><isset property="jdk_lib"/></not>
</condition>
<apply dir="${objdir}" parallel="true" executable="${compiler}" os="Mac OS X" failonerror="true" skipemptyfilesets="true">
<arg line="${linkerflags} -exported_symbols_list ../lwjgl.symbols -dynamiclib -o ${libname} -framework Foundation -weak_framework AppKit -framework Carbon -framework OpenGL -framework QuartzCore -L${jdk_lib} -ljawt"/>
<fileset dir="${objdir}" includes="*.o"/>
</apply>
<!-- <apply dir="${objdir}" executable="strip" os="Mac OS X" failonerror="true"> -->
<!-- <arg line="-S -X"/> -->
<!-- <fileset file="${libname}"/> -->
<!-- </apply> -->
</target>
<target name="nativelibrary" depends="init">
<echo message=" Compiler: ${compiler}"/>
<echo message=" Mac OS SDK: ${sdkroot}"/>
<echo message="JavaVM.framework: ${javavmroot}"/>
<property name="build_arm64" value="1" />
<antcall target="-build"/>
</target>
<target name="-build" depends="-build_arm64"/>
<!-- <target name="-build_universal" unless="build_x86_64"> -->
<!-- <mkdir dir="i386"/> -->
<!-- <property name="universal_sdkroot" location="${sdkroot}"/> -->
<!-- <property name="x86_64_sdkroot" location="${sdkroot}"/> -->
<!-- <property name="universal_flags" value="-isysroot ${universal_sdkroot}"/> -->
<!-- <antcall target="compile"> -->
<!-- <param name="dstdir" location="i386"/> -->
<!-- <param name="sdkroot" location="${universal_sdkroot}"/> -->
<!-- <param name="cflags" value="${universal_flags} -arch i386 -mmacosx-version-min=10.5"/> -->
<!-- </antcall> -->
<!-- <antcall target="compile"> -->
<!-- <param name="dstdir" location="x86_64"/> -->
<!-- <param name="sdkroot" location="${universal_sdkroot}"/> -->
<!-- <param name="cflags" value="-isysroot ${x86_64_sdkroot} -arch x86_64 -mmacosx-version-min=10.5"/> -->
<!-- </antcall> -->
<!-- <exec vmlauncher="true" executable="sh" output="lwjgl.symbols" failonerror="true"> -->
<!-- <arg path="../../platform_build/macosx_ant/build-symbol-list"/> -->
<!-- <arg path="i386"/> -->
<!-- </exec> -->
<!-- <antcall target="link"> -->
<!-- <param name="objdir" location="i386"/> -->
<!-- <param name="libname" value="liblwjgl-i386.dylib"/> -->
<!-- <param name="linkerflags" value="${universal_flags} -arch i386 -mmacosx-version-min=10.5"/> -->
<!-- </antcall> -->
<!-- <antcall target="link"> -->
<!-- <param name="objdir" location="x86_64"/> -->
<!-- <param name="libname" value="liblwjgl-i86_64.dylib"/> -->
<!-- <param name="linkerflags" value="-isysroot ${x86_64_sdkroot} -arch x86_64 -mmacosx-version-min=10.5"/> -->
<!-- </antcall> -->
<!-- <apply dir="." parallel="true" executable="lipo" os="Mac OS X" failonerror="true" skipemptyfilesets="true"> -->
<!-- <arg value="-create"/> -->
<!-- <srcfile/> -->
<!-- <arg value="-output"/> -->
<!-- <arg path="liblwjgl.dylib"/> -->
<!-- <fileset file="i386/liblwjgl-i386.dylib"/> -->
<!-- <fileset file="x86_64/liblwjgl-i86_64.dylib"/> -->
<!-- </apply> -->
<!-- </target> -->
<target name="-build_arm64" if="build_arm64">
<antcall target="compile">
<param name="dstdir" location="arm64"/>
<param name="sdkroot" location="${sdkroot}"/>
<param name="cflags" value="-isysroot ${sdkroot} -arch arm64 -mmacosx-version-min=10.5"/>
</antcall>
<exec vmlauncher="true" executable="sh" output="lwjgl.symbols" failonerror="true">
<arg path="../../platform_build/macosx_ant/build-symbol-list"/>
<arg path="arm64"/>
</exec>
<antcall target="link">
<param name="objdir" location="arm64"/>
<param name="libname" value="liblwjgl-arm64.dylib"/>
<param name="linkerflags" value="-isysroot ${sdkroot} -arch arm64 -mmacosx-version-min=10.5"/>
</antcall>
<apply dir="." parallel="true" executable="lipo" os="Mac OS X" failonerror="true" skipemptyfilesets="true">
<arg value="-create"/>
<srcfile/>
<arg value="-output"/>
<arg path="liblwjgl.dylib"/>
<fileset file="arm64/liblwjgl-arm64.dylib"/>
</apply>
</target>
</project>

View file

@ -6,8 +6,8 @@
<property name="sdkhome" location="${env.MSSDK}"/>
<target name="compile_dir">
<apply dir="." failonerror="true" executable="cl" dest="." skipemptyfilesets="true">
<arg line="/Ox /W2 /nologo /Ox /Ob2 /Oi /Ot /Oy /FD /EHsc /MT /Gy /W2 /nologo /c"/>
<apply dir="." failonerror="true" executable="cl" dest="." skipemptyfilesets="true" parallel="true">
<arg line="/c /W2 /EHsc /Ox /Gy /MT /MP /nologo"/>
<arg value="/I${sdkhome}\include"/>
<arg value="/I${java.home}\..\include"/>
<arg value="/I${java.home}\..\include\win32"/>

View file

@ -6,8 +6,8 @@
<property name="sdkhome" location="${env.MSSDK}"/>
<target name="compile_dir">
<apply dir="." failonerror="true" executable="cl" dest="." skipemptyfilesets="true">
<arg line="/Ox /W2 /nologo /Ox /Ob2 /Oi /Ot /Oy /FD /EHsc /MT /Gy /W2 /nologo /c"/>
<apply dir="." failonerror="true" executable="cl" dest="." skipemptyfilesets="true" parallel="true">
<arg line="/c /W2 /EHsc /Ox /Gy /MT /MP /nologo"/>
<arg value="/I${sdkhome}\include"/>
<arg value="/I${java.home}\..\include"/>
<arg value="/I${java.home}\..\include\win32"/>

View file

@ -272,7 +272,7 @@ public class LWJGLUtil {
final String osName = getPrivilegedProperty("os.name");
if ( osName.startsWith("Windows") )
PLATFORM = PLATFORM_WINDOWS;
else if ( osName.startsWith("Linux") || osName.startsWith("FreeBSD") || osName.startsWith("SunOS") || osName.startsWith("Unix") )
else if ( osName.startsWith("Linux") || osName.startsWith("FreeBSD") || osName.startsWith("OpenBSD") || osName.startsWith("SunOS") || osName.startsWith("Unix") )
PLATFORM = PLATFORM_LINUX;
else if ( osName.startsWith("Mac OS X") || osName.startsWith("Darwin") )
PLATFORM = PLATFORM_MACOSX;
@ -319,6 +319,21 @@ public class LWJGLUtil {
}
}
/**
* Wraps {@link System#mapLibraryName}. On OS X with JDK 6, the .jnilib file
* extension will be replaced with .dylib.
*
* @param name the name of the library.
*
* @return a platform-dependent native library name.
*/
public static String mapLibraryName(String name) {
String libName = System.mapLibraryName(name);
return LWJGLUtil.getPlatform() == LWJGLUtil.PLATFORM_MACOSX && libName.endsWith(".jnilib")
? libName.substring(0, libName.length() - ".jnilib".length()) + ".dylib"
: libName;
}
/**
* Locates the paths required by a library.
*
@ -420,9 +435,11 @@ public class LWJGLUtil {
* @return Absolute path to library if found, otherwise null
*/
private static String getPathFromClassLoader(final String libname, final ClassLoader classloader) {
Class<?> c = null;
try {
log("getPathFromClassLoader: searching for: " + libname);
Class<?> c = classloader.getClass();
c = classloader.getClass();
while (c != null) {
final Class<?> clazz = c;
try {
@ -440,7 +457,7 @@ public class LWJGLUtil {
}
}
} catch (Exception e) {
log("Failure locating " + e + " using classloader:" + e);
log("Failure locating " + e + " using classloader:" + c);
}
return null;
}
@ -603,10 +620,10 @@ public class LWJGLUtil {
* @param field the Field to test
* @param value the integer value of the field
*
* @result true if the Field is accepted
* @return true if the Field is accepted
*/
boolean accept(Field field, int value);
}
}
}

View file

@ -71,7 +71,7 @@ final class LinuxSysImplementation extends J2SESysImplementation {
// Linux may as well resort to pure Java hackery, as there's no Linux native way of doing it
// right anyway.
String[] browsers = {"xdg-open", "firefox", "mozilla", "opera", "konqueror", "nautilus", "galeon", "netscape"};
String[] browsers = {"sensible-browser", "xdg-open", "google-chrome", "chromium", "firefox", "iceweasel", "mozilla", "opera", "konqueror", "nautilus", "galeon", "netscape"};
for ( final String browser : browsers ) {
try {

View file

@ -31,9 +31,10 @@
*/
package org.lwjgl;
import java.awt.Toolkit;
import com.apple.eio.FileManager;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import java.lang.UnsatisfiedLinkError;
/**
*
@ -42,24 +43,16 @@ import com.apple.eio.FileManager;
* $Id$
*/
final class MacOSXSysImplementation extends J2SESysImplementation {
private static final int JNI_VERSION = 23;
private static final int JNI_VERSION = 25;
static {
// Make sure AWT is properly initialized. This avoids hangs on Mac OS X 10.3
Toolkit.getDefaultToolkit();
// Manually start the AWT Application Loop
java.awt.Toolkit.getDefaultToolkit();
}
public int getRequiredJNIVersion() {
return JNI_VERSION;
}
public boolean openURL(String url) {
try {
FileManager.openURL(url);
return true;
} catch (Exception e) {
LWJGLUtil.log("Exception occurred while trying to invoke browser: " + e);
return false;
}
}
public native boolean openURL(String url);
}

View file

@ -62,10 +62,10 @@ public final class MemoryUtil {
// Depends on java.nio.Buffer#address and sun.misc.Unsafe
util = loadAccessor("org.lwjgl.MemoryUtilSun$AccessorUnsafe");
} catch (Exception e0) {
try {
// Depends on java.nio.Buffer#address and sun.reflect.FieldAccessor
util = loadAccessor("org.lwjgl.MemoryUtilSun$AccessorReflectFast");
} catch (Exception e1) {
// try {
// // Depends on java.nio.Buffer#address and sun.reflect.FieldAccessor
// util = loadAccessor("org.lwjgl.MemoryUtilSun$AccessorReflectFast");
// } catch (Exception e1) {
try {
// Depends on java.nio.Buffer#address
util = new AccessorReflect();
@ -73,7 +73,7 @@ public final class MemoryUtil {
LWJGLUtil.log("Unsupported JVM detected, this will likely result in low performance. Please inform LWJGL developers.");
util = new AccessorJNI();
}
}
// }
}
LWJGLUtil.log("MemoryUtil Accessor: " + util.getClass().getSimpleName());
@ -282,7 +282,8 @@ public final class MemoryUtil {
throw new RuntimeException(e);
}
}
out.flip();
// cast to use Buffer's implementation of flip even when compiling against versions of java that have ByteBuffer::flip
((Buffer)out).flip();
return out;
}

View file

@ -37,7 +37,7 @@ import java.lang.reflect.Modifier;
import java.nio.Buffer;
import sun.misc.Unsafe;
import sun.reflect.FieldAccessor;
// import sun.reflect.FieldAccessor;
/**
* MemoryUtil.Accessor implementations that depend on sun.misc.
@ -104,32 +104,32 @@ final class MemoryUtilSun {
}
/** Implementation using reflection on ByteBuffer, FieldAccessor is used directly. */
private static class AccessorReflectFast implements MemoryUtil.Accessor {
// private static class AccessorReflectFast implements MemoryUtil.Accessor {
private final FieldAccessor addressAccessor;
// private final FieldAccessor addressAccessor;
AccessorReflectFast() {
Field address;
try {
address = MemoryUtil.getAddressField();
} catch (NoSuchFieldException e) {
throw new UnsupportedOperationException(e);
}
address.setAccessible(true);
// AccessorReflectFast() {
// Field address;
// try {
// address = MemoryUtil.getAddressField();
// } catch (NoSuchFieldException e) {
// throw new UnsupportedOperationException(e);
// }
// address.setAccessible(true);
try {
Method m = Field.class.getDeclaredMethod("acquireFieldAccessor", boolean.class);
m.setAccessible(true);
addressAccessor = (FieldAccessor)m.invoke(address, true);
} catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
// try {
// Method m = Field.class.getDeclaredMethod("acquireFieldAccessor", boolean.class);
// m.setAccessible(true);
// addressAccessor = (FieldAccessor)m.invoke(address, true);
// } catch (Exception e) {
// throw new UnsupportedOperationException(e);
// }
// }
public long getAddress(final Buffer buffer) {
return addressAccessor.getLong(buffer);
}
// public long getAddress(final Buffer buffer) {
// return addressAccessor.getLong(buffer);
// }
}
// }
}
}

View file

@ -1,409 +0,0 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl;
import java.nio.ByteBuffer;
import java.nio.ShortBuffer;
import java.nio.IntBuffer;
import java.nio.FloatBuffer;
import java.nio.LongBuffer;
import java.nio.DoubleBuffer;
import java.nio.ByteOrder;
/**
* Utility class to cache thread local direct buffers so when we are passed a non-direct buffer,
* we can put its contents into a cached direct buffer and use that at the native side instead.
*
* Internal class, don't use.
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision: 2762 $
* $Id: BufferChecks.java 2762 2007-04-11 16:13:05Z elias_naur $
*/
public final class NondirectBufferWrapper {
private static final int INITIAL_BUFFER_SIZE = 1;
private static final ThreadLocal<CachedBuffers> thread_buffer = new ThreadLocal<CachedBuffers>() {
protected CachedBuffers initialValue() {
return new CachedBuffers(INITIAL_BUFFER_SIZE);
}
};
private static CachedBuffers getCachedBuffers(int minimum_byte_size) {
CachedBuffers buffers = thread_buffer.get();
int current_byte_size = buffers.byte_buffer.capacity();
if (minimum_byte_size > current_byte_size) {
buffers = new CachedBuffers(minimum_byte_size);
thread_buffer.set(buffers);
}
return buffers;
}
public static ByteBuffer wrapNoCopyBuffer(ByteBuffer buf, int size) {
BufferChecks.checkBufferSize(buf, size);
return wrapNoCopyDirect(buf);
}
public static ShortBuffer wrapNoCopyBuffer(ShortBuffer buf, int size) {
BufferChecks.checkBufferSize(buf, size);
return wrapNoCopyDirect(buf);
}
public static IntBuffer wrapNoCopyBuffer(IntBuffer buf, int size) {
BufferChecks.checkBufferSize(buf, size);
return wrapNoCopyDirect(buf);
}
public static LongBuffer wrapNoCopyBuffer(LongBuffer buf, int size) {
BufferChecks.checkBufferSize(buf, size);
return wrapNoCopyDirect(buf);
}
public static FloatBuffer wrapNoCopyBuffer(FloatBuffer buf, int size) {
BufferChecks.checkBufferSize(buf, size);
return wrapNoCopyDirect(buf);
}
public static DoubleBuffer wrapNoCopyBuffer(DoubleBuffer buf, int size) {
BufferChecks.checkBufferSize(buf, size);
return wrapNoCopyDirect(buf);
}
public static ByteBuffer wrapBuffer(ByteBuffer buf, int size) {
BufferChecks.checkBufferSize(buf, size);
return wrapDirect(buf);
}
public static ShortBuffer wrapBuffer(ShortBuffer buf, int size) {
BufferChecks.checkBufferSize(buf, size);
return wrapDirect(buf);
}
public static IntBuffer wrapBuffer(IntBuffer buf, int size) {
BufferChecks.checkBufferSize(buf, size);
return wrapDirect(buf);
}
public static LongBuffer wrapBuffer(LongBuffer buf, int size) {
BufferChecks.checkBufferSize(buf, size);
return wrapDirect(buf);
}
public static FloatBuffer wrapBuffer(FloatBuffer buf, int size) {
BufferChecks.checkBufferSize(buf, size);
return wrapDirect(buf);
}
public static DoubleBuffer wrapBuffer(DoubleBuffer buf, int size) {
BufferChecks.checkBufferSize(buf, size);
return wrapDirect(buf);
}
public static ByteBuffer wrapDirect(ByteBuffer buffer) {
if (!buffer.isDirect())
return doWrap(buffer);
return buffer;
}
public static ShortBuffer wrapDirect(ShortBuffer buffer) {
if (!buffer.isDirect())
return doWrap(buffer);
return buffer;
}
public static FloatBuffer wrapDirect(FloatBuffer buffer) {
if (!buffer.isDirect())
return doWrap(buffer);
return buffer;
}
public static IntBuffer wrapDirect(IntBuffer buffer) {
if (!buffer.isDirect())
return doWrap(buffer);
return buffer;
}
public static LongBuffer wrapDirect(LongBuffer buffer) {
if (!buffer.isDirect())
return doWrap(buffer);
return buffer;
}
public static DoubleBuffer wrapDirect(DoubleBuffer buffer) {
if (!buffer.isDirect())
return doWrap(buffer);
return buffer;
}
public static ByteBuffer wrapNoCopyDirect(ByteBuffer buffer) {
if (!buffer.isDirect())
return doNoCopyWrap(buffer);
return buffer;
}
public static ShortBuffer wrapNoCopyDirect(ShortBuffer buffer) {
if (!buffer.isDirect())
return doNoCopyWrap(buffer);
return buffer;
}
public static FloatBuffer wrapNoCopyDirect(FloatBuffer buffer) {
if (!buffer.isDirect())
return doNoCopyWrap(buffer);
return buffer;
}
public static IntBuffer wrapNoCopyDirect(IntBuffer buffer) {
if (!buffer.isDirect())
return doNoCopyWrap(buffer);
return buffer;
}
public static LongBuffer wrapNoCopyDirect(LongBuffer buffer) {
if (!buffer.isDirect())
return doNoCopyWrap(buffer);
return buffer;
}
public static DoubleBuffer wrapNoCopyDirect(DoubleBuffer buffer) {
if (!buffer.isDirect())
return doNoCopyWrap(buffer);
return buffer;
}
public static void copy(ByteBuffer src, ByteBuffer dst) {
if (dst != null && !dst.isDirect()) {
int saved_position = dst.position();
dst.put(src);
dst.position(saved_position);
}
}
public static void copy(ShortBuffer src, ShortBuffer dst) {
if (dst != null && !dst.isDirect()) {
int saved_position = dst.position();
dst.put(src);
dst.position(saved_position);
}
}
public static void copy(IntBuffer src, IntBuffer dst) {
if (dst != null && !dst.isDirect()) {
int saved_position = dst.position();
dst.put(src);
dst.position(saved_position);
}
}
public static void copy(FloatBuffer src, FloatBuffer dst) {
if (dst != null && !dst.isDirect()) {
int saved_position = dst.position();
dst.put(src);
dst.position(saved_position);
}
}
public static void copy(LongBuffer src, LongBuffer dst) {
if (dst != null && !dst.isDirect()) {
int saved_position = dst.position();
dst.put(src);
dst.position(saved_position);
}
}
public static void copy(DoubleBuffer src, DoubleBuffer dst) {
if (dst != null && !dst.isDirect()) {
int saved_position = dst.position();
dst.put(src);
dst.position(saved_position);
}
}
private static ByteBuffer doNoCopyWrap(ByteBuffer buffer) {
ByteBuffer direct_buffer = lookupBuffer(buffer);
direct_buffer.limit(buffer.limit());
direct_buffer.position(buffer.position());
return direct_buffer;
}
private static ShortBuffer doNoCopyWrap(ShortBuffer buffer) {
ShortBuffer direct_buffer = lookupBuffer(buffer);
direct_buffer.limit(buffer.limit());
direct_buffer.position(buffer.position());
return direct_buffer;
}
private static IntBuffer doNoCopyWrap(IntBuffer buffer) {
IntBuffer direct_buffer = lookupBuffer(buffer);
direct_buffer.limit(buffer.limit());
direct_buffer.position(buffer.position());
return direct_buffer;
}
private static FloatBuffer doNoCopyWrap(FloatBuffer buffer) {
FloatBuffer direct_buffer = lookupBuffer(buffer);
direct_buffer.limit(buffer.limit());
direct_buffer.position(buffer.position());
return direct_buffer;
}
private static LongBuffer doNoCopyWrap(LongBuffer buffer) {
LongBuffer direct_buffer = lookupBuffer(buffer);
direct_buffer.limit(buffer.limit());
direct_buffer.position(buffer.position());
return direct_buffer;
}
private static DoubleBuffer doNoCopyWrap(DoubleBuffer buffer) {
DoubleBuffer direct_buffer = lookupBuffer(buffer);
direct_buffer.limit(buffer.limit());
direct_buffer.position(buffer.position());
return direct_buffer;
}
private static ByteBuffer lookupBuffer(ByteBuffer buffer) {
return getCachedBuffers(buffer.remaining()).byte_buffer;
}
private static ByteBuffer doWrap(ByteBuffer buffer) {
ByteBuffer direct_buffer = lookupBuffer(buffer);
direct_buffer.clear();
int saved_position = buffer.position();
direct_buffer.put(buffer);
buffer.position(saved_position);
direct_buffer.flip();
return direct_buffer;
}
private static ShortBuffer lookupBuffer(ShortBuffer buffer) {
CachedBuffers buffers = getCachedBuffers(buffer.remaining()*2);
return buffer.order() == ByteOrder.LITTLE_ENDIAN ? buffers.short_buffer_little : buffers.short_buffer_big;
}
private static ShortBuffer doWrap(ShortBuffer buffer) {
ShortBuffer direct_buffer = lookupBuffer(buffer);
direct_buffer.clear();
int saved_position = buffer.position();
direct_buffer.put(buffer);
buffer.position(saved_position);
direct_buffer.flip();
return direct_buffer;
}
private static FloatBuffer lookupBuffer(FloatBuffer buffer) {
CachedBuffers buffers = getCachedBuffers(buffer.remaining()*4);
return buffer.order() == ByteOrder.LITTLE_ENDIAN ? buffers.float_buffer_little : buffers.float_buffer_big;
}
private static FloatBuffer doWrap(FloatBuffer buffer) {
FloatBuffer direct_buffer = lookupBuffer(buffer);
direct_buffer.clear();
int saved_position = buffer.position();
direct_buffer.put(buffer);
buffer.position(saved_position);
direct_buffer.flip();
return direct_buffer;
}
private static IntBuffer lookupBuffer(IntBuffer buffer) {
CachedBuffers buffers = getCachedBuffers(buffer.remaining()*4);
return buffer.order() == ByteOrder.LITTLE_ENDIAN ? buffers.int_buffer_little : buffers.int_buffer_big;
}
private static IntBuffer doWrap(IntBuffer buffer) {
IntBuffer direct_buffer = lookupBuffer(buffer);
direct_buffer.clear();
int saved_position = buffer.position();
direct_buffer.put(buffer);
buffer.position(saved_position);
direct_buffer.flip();
return direct_buffer;
}
private static LongBuffer lookupBuffer(LongBuffer buffer) {
CachedBuffers buffers = getCachedBuffers(buffer.remaining()*8);
return buffer.order() == ByteOrder.LITTLE_ENDIAN ? buffers.long_buffer_little : buffers.long_buffer_big;
}
private static LongBuffer doWrap(LongBuffer buffer) {
LongBuffer direct_buffer = lookupBuffer(buffer);
direct_buffer.clear();
int saved_position = buffer.position();
direct_buffer.put(buffer);
buffer.position(saved_position);
direct_buffer.flip();
return direct_buffer;
}
private static DoubleBuffer lookupBuffer(DoubleBuffer buffer) {
CachedBuffers buffers = getCachedBuffers(buffer.remaining()*8);
return buffer.order() == ByteOrder.LITTLE_ENDIAN ? buffers.double_buffer_little : buffers.double_buffer_big;
}
private static DoubleBuffer doWrap(DoubleBuffer buffer) {
DoubleBuffer direct_buffer = lookupBuffer(buffer);
direct_buffer.clear();
int saved_position = buffer.position();
direct_buffer.put(buffer);
buffer.position(saved_position);
direct_buffer.flip();
return direct_buffer;
}
private static final class CachedBuffers {
private final ByteBuffer byte_buffer;
private final ShortBuffer short_buffer_big;
private final IntBuffer int_buffer_big;
private final FloatBuffer float_buffer_big;
private final LongBuffer long_buffer_big;
private final DoubleBuffer double_buffer_big;
private final ShortBuffer short_buffer_little;
private final IntBuffer int_buffer_little;
private final FloatBuffer float_buffer_little;
private final LongBuffer long_buffer_little;
private final DoubleBuffer double_buffer_little;
private CachedBuffers(int size) {
this.byte_buffer = ByteBuffer.allocateDirect(size);
this.short_buffer_big = byte_buffer.asShortBuffer();
this.int_buffer_big = byte_buffer.asIntBuffer();
this.float_buffer_big = byte_buffer.asFloatBuffer();
this.long_buffer_big = byte_buffer.asLongBuffer();
this.double_buffer_big = byte_buffer.asDoubleBuffer();
this.byte_buffer.order(ByteOrder.LITTLE_ENDIAN);
this.short_buffer_little = byte_buffer.asShortBuffer();
this.int_buffer_little = byte_buffer.asIntBuffer();
this.float_buffer_little = byte_buffer.asFloatBuffer();
this.long_buffer_little = byte_buffer.asLongBuffer();
this.double_buffer_little = byte_buffer.asDoubleBuffer();
}
}
}

View file

@ -550,9 +550,9 @@ public class PointerBuffer implements Comparable {
*/
public static void put(final ByteBuffer target, int index, long l) {
if ( is64Bit )
target.putLong(index * 8, l);
target.putLong(index, l);
else
target.putInt(index * 4, (int)l);
target.putInt(index, (int)l);
}
// -- Bulk get operations --

View file

@ -54,7 +54,7 @@ public final class Sys {
private static final String JNI_LIBRARY_NAME = "lwjgl";
/** Current version of library */
private static final String VERSION = "2.8.5";
private static final String VERSION = "2.9.4";
private static final String POSTFIX64BIT = "64";
@ -67,8 +67,7 @@ public final class Sys {
public Object run() {
String library_path = System.getProperty("org.lwjgl.librarypath");
if (library_path != null) {
System.load(library_path + File.separator +
System.mapLibraryName(lib_name));
System.load(library_path + File.separator + LWJGLUtil.mapLibraryName(lib_name));
} else {
System.loadLibrary(lib_name);
}
@ -80,13 +79,15 @@ public final class Sys {
private static void loadLibrary(final String lib_name) {
// actively try to load 64bit libs on 64bit architectures first
String osArch = System.getProperty("os.arch");
boolean is64bit = "amd64".equals(osArch) || "x86_64".equals(osArch);
if(is64bit) {
boolean try64First = LWJGLUtil.getPlatform() != LWJGLUtil.PLATFORM_MACOSX && ("amd64".equals(osArch) || "x86_64".equals(osArch));
Error err = null;
if ( try64First ) {
try {
doLoadLibrary(lib_name + POSTFIX64BIT);
return;
} catch (UnsatisfiedLinkError e) {
LWJGLUtil.log("Failed to load 64 bit library: " + e.getMessage());
err = e;
}
}
@ -94,6 +95,9 @@ public final class Sys {
try {
doLoadLibrary(lib_name);
} catch (UnsatisfiedLinkError e) {
if ( try64First )
throw err;
if (implementation.has64Bit()) {
try {
doLoadLibrary(lib_name + POSTFIX64BIT);
@ -102,6 +106,7 @@ public final class Sys {
LWJGLUtil.log("Failed to load 64 bit library: " + e2.getMessage());
}
}
// Throw original error
throw e;
}

View file

@ -52,12 +52,18 @@ class ControllerEvent {
private int index;
/** Type of control that generated the event */
private int type;
/** True when a button is pressed, if this event was caused by the button */
private boolean buttonState;
/** True if this event was caused by the x axis */
private boolean xaxis;
/** True if this event was caused by the y axis */
private boolean yaxis;
/** The time stamp of this event */
private long timeStamp;
/** The value on a specified axis, if this event was caused by the x-axis */
private float xaxisValue;
/** The value on a specified axis, if this event was caused by the y-axis */
private float yaxisValue;
/**
* Create a new event
@ -70,12 +76,32 @@ class ControllerEvent {
* @param yaxis True if this event was caused by the y-axis
*/
ControllerEvent(Controller source,long timeStamp, int type,int index,boolean xaxis,boolean yaxis) {
this(source, timeStamp, type, index, false, xaxis, yaxis, 0, 0);
}
/**
* Create a new event
*
* @param source The source of the event
* @param timeStamp The time stamp given for this event
* @param type The type of control generating this event
* @param index The index of the input that generated the event
* @param buttonState True when a button is pressed, if this event was caused by the button
* @param xaxis True if this event was caused by the x-axis
* @param yaxis True if this event was caused by the y-axis
* @param xaxisValue The value on a specified axis, if this event was caused by the x-axis
* @param yaxisValue The value on a specified axis, if this event was caused by the y-axis
*/
ControllerEvent(Controller source,long timeStamp, int type,int index,boolean buttonState,boolean xaxis,boolean yaxis,float xaxisValue,float yaxisValue) {
this.source = source;
this.timeStamp = timeStamp;
this.type = type;
this.index = index;
this.buttonState = buttonState;
this.xaxis = xaxis;
this.yaxis = yaxis;
this.xaxisValue = xaxisValue;
this.yaxisValue = yaxisValue;
}
/**
@ -115,6 +141,15 @@ class ControllerEvent {
return type == BUTTON;
}
/**
* Check the button is pressed or not, when this event was caused
*
* @return True when a button is pressed, if this event was caused by the button
*/
public boolean getButtonState() {
return buttonState;
}
/**
* Check if this event was generated by a axis
*
@ -159,6 +194,24 @@ class ControllerEvent {
public boolean isYAxis() {
return yaxis;
}
/**
* Get the value on an X axis when this event was caused
*
* @return The value on a specified axis, if this event was caused by the x-axis
*/
public float getXAxisValue() {
return xaxisValue;
}
/**
* Get the value on an Y axis when this event was caused
*
* @return The value on a specified axis, if this event was caused by the y-axis
*/
public float getYAxisValue() {
return yaxisValue;
}
/*
* @see java.lang.Object#toString()

View file

@ -262,12 +262,39 @@ public class Controllers {
/**
* Get the timestamp assigned to the current event
*
* @return The timestamp assigned ot the current event
* @return The timestamp assigned to the current event
*/
public static long getEventNanoseconds() {
return event.getTimeStamp();
}
/**
* Gets the state of the button that generated the current event
*
* @return True if button was down, or false if released
*/
public static boolean getEventButtonState() {
return event.getButtonState();
}
/**
* Get the value on an X axis of the current event
*
* @return The value on a x axis of the current event
*/
public static float getEventXAxisValue() {
return event.getXAxisValue();
}
/**
* Get the value on an Y axis of the current event
*
* @return The value on a y axis of the current event
*/
public static float getEventYAxisValue() {
return event.getYAxisValue();
}
/**
* Add an event to the stack of events that have been caused
*

View file

@ -33,10 +33,10 @@ package org.lwjgl.input;
import java.nio.IntBuffer;
import org.lwjgl.BufferChecks;
import org.lwjgl.BufferUtils;
import org.lwjgl.LWJGLException;
import org.lwjgl.LWJGLUtil;
import org.lwjgl.NondirectBufferWrapper;
import org.lwjgl.Sys;
/**
@ -86,9 +86,9 @@ public class Cursor {
synchronized (OpenGLPackageAccess.global_lock) {
if ((getCapabilities() & CURSOR_ONE_BIT_TRANSPARENCY) == 0)
throw new LWJGLException("Native cursors not supported");
images = NondirectBufferWrapper.wrapBuffer(images, width*height*numImages);
BufferChecks.checkBufferSize(images, width*height*numImages);
if (delays != null)
delays = NondirectBufferWrapper.wrapBuffer(delays, numImages);
BufferChecks.checkBufferSize(delays, numImages);
if (!Mouse.isCreated())
throw new IllegalStateException("Mouse must be created before creating cursor objects");
if (width*height*numImages > images.remaining())
@ -163,17 +163,32 @@ public class Cursor {
IntBuffer images_copy = BufferUtils.createIntBuffer(images.remaining());
flipImages(width, height, numImages, images, images_copy);
// Win32 doesn't (afaik) allow for animation based cursors, except when they're
// in the .ani format, which we don't support.
// Mac and Windows doesn't (afaik) allow for animation based cursors, except in the .ani
// format on Windows, which we don't support.
// The cursor animation was therefor developed using java side time tracking.
// unfortunately X flickers when changing cursor. We therefore check for either
// Win32 or X and do accordingly. This hasn't been implemented on Mac, but we
// might want to split it into a X/Win/Mac cursor if it gets too cluttered
// Windows, Mac or X and do accordingly.
// we might want to split it into a X/Win/Mac cursor if it gets too cluttered
CursorElement[] cursors;
switch (LWJGLUtil.getPlatform()) {
case LWJGLUtil.PLATFORM_MACOSX:
/* Fall through */
// OS X requires the image format to be in ABGR format
convertARGBtoABGR(images_copy);
// create our cursor elements
cursors = new CursorElement[numImages];
for(int i=0; i<numImages; i++) {
Object handle = Mouse.getImplementation().createCursor(width, height, xHotspot, yHotspot, 1, images_copy, null);
long delay = (delays != null) ? delays.get(i) : 0;
long timeout = System.currentTimeMillis();
cursors[i] = new CursorElement(handle, delay, timeout);
// offset to next image
images_copy.position(width*height*(i+1));
}
break;
case LWJGLUtil.PLATFORM_WINDOWS:
// create our cursor elements
cursors = new CursorElement[numImages];
@ -209,6 +224,26 @@ public class Cursor {
}
return cursors;
}
/**
* Convert an IntBuffer image of ARGB format into ABGR
*
* @param imageBuffer image to convert
*/
private static void convertARGBtoABGR(IntBuffer imageBuffer) {
for (int i = 0; i < imageBuffer.limit(); i++) {
int argbColor = imageBuffer.get(i);
byte alpha = (byte)(argbColor >>> 24);
byte blue = (byte)(argbColor >>> 16);
byte green = (byte)(argbColor >>> 8);
byte red = (byte)argbColor;
int abgrColor = ((alpha & 0xff) << 24 ) + ((red & 0xff) << 16 ) + ((green & 0xff) << 8 ) + ((blue & 0xff) );
imageBuffer.put(i, abgrColor);
}
}
/**
* Flips the images so they're oriented according to opengl

View file

@ -208,7 +208,8 @@ class JInputController implements Controller {
buttonState[buttonIndex] = event.getValue() != 0;
// fire button pressed event
Controllers.addEvent(new ControllerEvent(this,event.getNanos(),ControllerEvent.BUTTON,buttonIndex,false,false));
Controllers.addEvent(new ControllerEvent(this,event.getNanos(),ControllerEvent.BUTTON,buttonIndex,
buttonState[buttonIndex],false,false,0,0));
}
// handle pov events
@ -232,6 +233,8 @@ class JInputController implements Controller {
Component axis = event.getComponent();
int axisIndex = axes.indexOf(axis);
float value = axis.getPollData();
float xaxisValue = 0;
float yaxisValue = 0;
// fixed dead zone since most axis don't report it :(
if (Math.abs(value) < deadZones[axisIndex]) {
@ -246,9 +249,17 @@ class JInputController implements Controller {
// normalize the value based on maximum value read in the past
value /= axesMax[axisIndex];
if (axisIndex == xaxis) {
xaxisValue = value;
}
if (axisIndex == yaxis) {
yaxisValue = value;
}
// fire event
Controllers.addEvent(new ControllerEvent(this,event.getNanos(),ControllerEvent.AXIS,axisIndex,
axisIndex == xaxis,axisIndex == yaxis));
Controllers.addEvent(new ControllerEvent(this,event.getNanos(),ControllerEvent.AXIS,axisIndex,false,
axisIndex == xaxis,axisIndex == yaxis,xaxisValue,yaxisValue));
axesValue[axisIndex] = value;
}
}

View file

@ -33,6 +33,7 @@ package org.lwjgl.input;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
@ -158,7 +159,11 @@ public class Keyboard {
public static final int KEY_F13 = 0x64; /* (NEC PC98) */
public static final int KEY_F14 = 0x65; /* (NEC PC98) */
public static final int KEY_F15 = 0x66; /* (NEC PC98) */
public static final int KEY_F16 = 0x67; /* Extended Function keys - (Mac) */
public static final int KEY_F17 = 0x68;
public static final int KEY_F18 = 0x69;
public static final int KEY_KANA = 0x70; /* (Japanese keyboard) */
public static final int KEY_F19 = 0x71; /* Extended Function keys - (Mac) */
public static final int KEY_CONVERT = 0x79; /* (Japanese keyboard) */
public static final int KEY_NOCONVERT = 0x7B; /* (Japanese keyboard) */
public static final int KEY_YEN = 0x7D; /* (Japanese keyboard) */
@ -173,10 +178,12 @@ public class Keyboard {
public static final int KEY_UNLABELED = 0x97; /* (J3100) */
public static final int KEY_NUMPADENTER = 0x9C; /* Enter on numeric keypad */
public static final int KEY_RCONTROL = 0x9D;
public static final int KEY_SECTION = 0xA7; /* Section symbol (Mac) */
public static final int KEY_NUMPADCOMMA = 0xB3; /* , on numeric keypad (NEC PC98) */
public static final int KEY_DIVIDE = 0xB5; /* / on numeric keypad */
public static final int KEY_SYSRQ = 0xB7;
public static final int KEY_RMENU = 0xB8; /* right Alt */
public static final int KEY_FUNCTION = 0xC4; /* Function (Mac) */
public static final int KEY_PAUSE = 0xC5; /* Pause */
public static final int KEY_HOME = 0xC7; /* Home on arrow keypad */
public static final int KEY_UP = 0xC8; /* UpArrow on arrow keypad */
@ -188,7 +195,8 @@ public class Keyboard {
public static final int KEY_NEXT = 0xD1; /* PgDn on arrow keypad */
public static final int KEY_INSERT = 0xD2; /* Insert on arrow keypad */
public static final int KEY_DELETE = 0xD3; /* Delete on arrow keypad */
public static final int KEY_LMETA = 0xDB; /* Left Windows/Option key */
public static final int KEY_CLEAR = 0xDA; /* Clear key (Mac) */
public static final int KEY_LMETA = 0xDB; /* Left Windows/Option key */
/**
* The left windows key, mapped to KEY_LMETA
*
@ -229,7 +237,8 @@ public class Keyboard {
&& Modifier.isPublic(field.getModifiers())
&& Modifier.isFinal(field.getModifiers())
&& field.getType().equals(int.class)
&& field.getName().startsWith("KEY_") ) {
&& field.getName().startsWith("KEY_")
&& !field.getName().endsWith("WIN") ) { /* Don't use deprecated names */
int key = field.getInt(null);
String name = field.getName().substring(4);
@ -323,7 +332,7 @@ public class Keyboard {
}
private static void reset() {
readBuffer.limit(0);
((Buffer)readBuffer).limit(0);
for (int i = 0; i < keyDownBuffer.remaining(); i++)
keyDownBuffer.put(i, (byte)0);
current_event.reset();
@ -384,7 +393,7 @@ public class Keyboard {
private static void read() {
readBuffer.compact();
implementation.readKeyboard(readBuffer);
readBuffer.flip();
((Buffer)readBuffer).flip();
}
/**
@ -445,7 +454,7 @@ public class Keyboard {
int num_events = 0;
while (readNext(tmp_event) && (!tmp_event.repeat || repeat_enabled))
num_events++;
readBuffer.position(old_position);
((Buffer)readBuffer).position(old_position);
return num_events;
}
}

View file

@ -31,6 +31,7 @@
*/
package org.lwjgl.input;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.security.AccessController;
@ -249,7 +250,7 @@ public class Mouse {
private static void resetMouse() {
dx = dy = dwheel = 0;
readBuffer.position(readBuffer.limit());
((Buffer)readBuffer).position(readBuffer.limit());
}
static InputImplementation getImplementation() {
@ -279,7 +280,7 @@ public class Mouse {
if (currentCursor != null && implementation.getNativeCursorCapabilities() != 0)
setNativeCursor(currentCursor);
readBuffer = ByteBuffer.allocate(EVENT_SIZE * BUFFER_SIZE);
readBuffer.limit(0);
((Buffer)readBuffer).limit(0);
setGrabbed(isGrabbed);
}
@ -383,7 +384,7 @@ public class Mouse {
private static void read() {
readBuffer.compact();
implementation.readMouse(readBuffer);
readBuffer.flip();
((Buffer)readBuffer).flip();
}
/**
@ -433,8 +434,8 @@ public class Mouse {
/**
* Gets the next mouse event. You can query which button caused the event by using
* <code>getEventButton()</code> (if any). To get the state of that key, for that event, use
* <code>getEventButtonState</code>. To get the current mouse delta values use <code>getEventDX()</code>,
* <code>getEventDY()</code> and <code>getEventDZ()</code>.
* <code>getEventButtonState</code>. To get the current mouse delta values use <code>getEventDX()</code>
* and <code>getEventDY()</code>.
* @see org.lwjgl.input.Mouse#getEventButton()
* @see org.lwjgl.input.Mouse#getEventButtonState()
* @return true if a mouse event was read, false otherwise

View file

@ -115,8 +115,13 @@ public final class AL {
String[] library_names;
switch (LWJGLUtil.getPlatform()) {
case LWJGLUtil.PLATFORM_WINDOWS:
libname = "OpenAL32";
library_names = new String[]{"OpenAL64.dll", "OpenAL32.dll"};
if ( Sys.is64Bit() ) {
libname = "OpenAL64";
library_names = new String[]{"OpenAL64.dll"};
} else {
libname = "OpenAL32";
library_names = new String[]{"OpenAL32.dll"};
}
break;
case LWJGLUtil.PLATFORM_LINUX:
libname = "openal";

View file

@ -31,6 +31,7 @@
*/
package org.lwjgl.openal;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
@ -177,7 +178,7 @@ public final class ALC11 {
try {
IntBuffer ib = BufferUtils.createIntBuffer(2);
ALC10.alcGetInteger(AL.getDevice(), ALC10.ALC_MAJOR_VERSION, ib);
ib.position(1);
((Buffer)ib).position(1);
ALC10.alcGetInteger(AL.getDevice(), ALC10.ALC_MINOR_VERSION, ib);
int major = ib.get(0);

View file

@ -82,7 +82,7 @@ public final class ALCcontext {
* @param contextFrequency Frequency to add
* @param contextRefresh Refresh rate to add
* @param contextSynchronized Whether to synchronize the context
* @return
* @return attribute list
*/
static IntBuffer createAttributeList(int contextFrequency, int contextRefresh, int contextSynchronized) {
IntBuffer attribList = BufferUtils.createIntBuffer(7);

View file

@ -31,9 +31,11 @@
*/
package org.lwjgl.opencl;
import org.lwjgl.BufferUtils;
import org.lwjgl.LWJGLUtil;
import org.lwjgl.PointerBuffer;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import static org.lwjgl.opencl.CL10.*;
@ -137,7 +139,7 @@ final class CLChecks {
*
* @return the 2D image size in bytes
*/
static int calculateImage2DSize(final ByteBuffer format, final long w, final long h, long row_pitch) {
static int calculateImage2DSize(final Buffer host_ptr, final ByteBuffer format, final long w, final long h, long row_pitch) {
if ( !LWJGLUtil.CHECKS )
return 0;
@ -151,7 +153,7 @@ final class CLChecks {
else if ( LWJGLUtil.DEBUG && ((row_pitch < w * elementSize) || (row_pitch % elementSize != 0)) )
throw new IllegalArgumentException("Invalid image_row_pitch specified: " + row_pitch);
return (int)(row_pitch * h);
return (int)(row_pitch * h) >> BufferUtils.getElementSizeExponent(host_ptr);
}
/**
@ -166,7 +168,7 @@ final class CLChecks {
*
* @return the 3D image size in bytes
*/
static int calculateImage3DSize(final ByteBuffer format, final long w, final long h, final long d, long row_pitch, long slice_pitch) {
static int calculateImage3DSize(final Buffer host_ptr, final ByteBuffer format, final long w, final long h, final long d, long row_pitch, long slice_pitch) {
if ( !LWJGLUtil.CHECKS )
return 0;
@ -185,7 +187,7 @@ final class CLChecks {
else if ( LWJGLUtil.DEBUG && ((row_pitch < row_pitch * h) || (slice_pitch % row_pitch != 0)) )
throw new IllegalArgumentException("Invalid image_slice_pitch specified: " + row_pitch);
return (int)(slice_pitch * d);
return (int)(slice_pitch * d) >> BufferUtils.getElementSizeExponent(host_ptr);
}
/**

View file

@ -305,7 +305,7 @@ final class InfoUtilFactory {
errcode_ret = APIUtil.getBufferInt();
CLMem __result = new CLMem(nclCreateImage2D(context.getPointer(), flags, MemoryUtil.getAddress(formatBuffer, 0), image_width, image_height, image_row_pitch, MemoryUtil.getAddress0Safe(host_ptr) +
(host_ptr != null ? BufferChecks.checkBuffer(host_ptr, CLChecks.calculateImage2DSize(formatBuffer, image_width, image_height, image_row_pitch)) : 0),
(host_ptr != null ? BufferChecks.checkBuffer(host_ptr, CLChecks.calculateImage2DSize(host_ptr, formatBuffer, image_width, image_height, image_row_pitch)) : 0),
MemoryUtil.getAddressSafe(errcode_ret), function_pointer), context);
if ( LWJGLUtil.DEBUG )
Util.checkCLError(errcode_ret.get(0));
@ -325,7 +325,7 @@ final class InfoUtilFactory {
errcode_ret = APIUtil.getBufferInt();
CLMem __result = new CLMem(nclCreateImage3D(context.getPointer(), flags, MemoryUtil.getAddress(formatBuffer, 0), image_width, image_height, image_depth, image_row_pitch, image_slice_pitch, MemoryUtil.getAddress0Safe(host_ptr) +
(host_ptr != null ? BufferChecks.checkBuffer(host_ptr, CLChecks.calculateImage3DSize(formatBuffer, image_width, image_height, image_depth, image_row_pitch, image_slice_pitch)) : 0),
(host_ptr != null ? BufferChecks.checkBuffer(host_ptr, CLChecks.calculateImage3DSize(host_ptr, formatBuffer, image_width, image_height, image_depth, image_row_pitch, image_slice_pitch)) : 0),
MemoryUtil.getAddressSafe(errcode_ret), function_pointer), context);
if ( LWJGLUtil.DEBUG )
Util.checkCLError(errcode_ret.get(0));
@ -547,7 +547,7 @@ final class InfoUtilFactory {
target = new ByteBuffer[sizes.remaining()];
for ( int i = 0; i < sizes.remaining(); i++ )
target[i] = BufferUtils.createByteBuffer((int)sizes.get(0));
target[i] = BufferUtils.createByteBuffer((int)sizes.get(i));
} else if ( LWJGLUtil.DEBUG ) {
final PointerBuffer sizes = getSizesBuffer(program, CL_PROGRAM_BINARY_SIZES);
@ -603,4 +603,4 @@ final class InfoUtilFactory {
}
};
}
}

View file

@ -110,7 +110,7 @@ public final class AMDDebugOutputCallback extends PointerWrapperAbstract {
description = "OTHER";
break;
default:
description = "Unknown (" + Integer.toHexString(category) + ")";
description = printUnknownToken(category);
}
System.err.println("\tCategory: " + description);
@ -125,12 +125,16 @@ public final class AMDDebugOutputCallback extends PointerWrapperAbstract {
description = "LOW";
break;
default:
description = "Unknown (" + Integer.toHexString(category) + ")";
description = printUnknownToken(severity);
}
System.err.println("\tSeverity: " + description);
System.err.println("\tMessage: " + message);
}
private String printUnknownToken(final int token) {
return "Unknown (0x" + Integer.toHexString(token).toUpperCase() + ")";
}
});
}

View file

@ -97,7 +97,7 @@ final class APIUtil {
buffer = BufferUtils.createByteBuffer(size);
caps.util.buffer = buffer;
} else
buffer.clear();
((Buffer)buffer).clear();
return buffer;
}
@ -114,8 +114,8 @@ final class APIUtil {
bufferNew.put(buffer);
caps.util.buffer = (buffer = bufferNew);
} else {
buffer.position(buffer.limit());
buffer.limit(buffer.capacity());
((Buffer)buffer).position(buffer.limit());
((Buffer)buffer).limit(buffer.capacity());
}
return buffer;
@ -193,7 +193,7 @@ final class APIUtil {
*/
static long getBuffer(final ContextCapabilities caps, final CharSequence string) {
final ByteBuffer buffer = encode(getBufferByte(caps, string.length()), string);
buffer.flip();
((Buffer)buffer).flip();
return MemoryUtil.getAddress0(buffer);
}
@ -206,7 +206,7 @@ final class APIUtil {
*/
static long getBuffer(final ContextCapabilities caps, final CharSequence string, final int offset) {
final ByteBuffer buffer = encode(getBufferByteOffset(caps, offset + string.length()), string);
buffer.flip();
((Buffer)buffer).flip();
return MemoryUtil.getAddress(buffer);
}
@ -220,7 +220,7 @@ final class APIUtil {
static long getBufferNT(final ContextCapabilities caps, final CharSequence string) {
final ByteBuffer buffer = encode(getBufferByte(caps, string.length() + 1), string);
buffer.put((byte)0);
buffer.flip();
((Buffer)buffer).flip();
return MemoryUtil.getAddress0(buffer);
}
@ -245,7 +245,7 @@ final class APIUtil {
for ( CharSequence string : strings )
encode(buffer, string);
buffer.flip();
((Buffer)buffer).flip();
return MemoryUtil.getAddress0(buffer);
}
@ -264,7 +264,7 @@ final class APIUtil {
buffer.put((byte)0);
}
buffer.flip();
((Buffer)buffer).flip();
return MemoryUtil.getAddress0(buffer);
}
@ -281,7 +281,7 @@ final class APIUtil {
for ( CharSequence string : strings )
buffer.put(string.length());
buffer.flip();
((Buffer)buffer).flip();
return MemoryUtil.getAddress0(buffer);
}
@ -293,4 +293,4 @@ final class APIUtil {
return MemoryUtil.getAddress0(getBufferByte(caps, 0));
}
}
}

View file

@ -113,7 +113,7 @@ public final class ARBDebugOutputCallback extends PointerWrapperAbstract {
description = "OTHER";
break;
default:
description = "Unknown (" + Integer.toHexString(source) + ")";
description = printUnknownToken(source);
}
System.err.println("\tSource: " + description);
@ -137,7 +137,7 @@ public final class ARBDebugOutputCallback extends PointerWrapperAbstract {
description = "OTHER";
break;
default:
description = "Unknown (" + Integer.toHexString(source) + ")";
description = printUnknownToken(type);
}
System.err.println("\tType: " + description);
@ -152,12 +152,16 @@ public final class ARBDebugOutputCallback extends PointerWrapperAbstract {
description = "LOW";
break;
default:
description = "Unknown (" + Integer.toHexString(source) + ")";
description = printUnknownToken(severity);
}
System.err.println("\tSeverity: " + description);
System.err.println("\tMessage: " + message);
}
private String printUnknownToken(final int token) {
return "Unknown (0x" + Integer.toHexString(token).toUpperCase() + ")";
}
});
}
@ -184,9 +188,9 @@ public final class ARBDebugOutputCallback extends PointerWrapperAbstract {
/**
* This method will be called when an ARB_debug_output message is generated.
*
* @param id the message ID
* @param source the message source
* @param type the message type
* @param id the message ID
* @param severity the message severity
* @param message the string representation of the message.
*/

View file

@ -82,16 +82,13 @@ final class AWTSurfaceLock {
// It is only needed on first call, so we avoid it on all subsequent calls
// due to performance..
// Allow the use of a Core Animation Layer only when using non fullscreen Display.setParent() or AWTGLCanvas
final boolean allowCALayer = ((Display.getParent() != null && !Display.isFullscreen()) || component instanceof AWTGLCanvas) && isApplet(component) && LWJGLUtil.isMacOSXEqualsOrBetterThan(10, 6);
if (firstLockSucceeded)
return lockAndInitHandle(lock_buffer, component, allowCALayer);
return lockAndInitHandle(lock_buffer, component);
else
try {
firstLockSucceeded = AccessController.doPrivileged(new PrivilegedExceptionAction<Boolean>() {
public Boolean run() throws LWJGLException {
return lockAndInitHandle(lock_buffer, component, allowCALayer);
return lockAndInitHandle(lock_buffer, component);
}
});
return firstLockSucceeded;
@ -100,29 +97,11 @@ final class AWTSurfaceLock {
}
}
private static native boolean lockAndInitHandle(ByteBuffer lock_buffer, Canvas component, boolean allowCALayer) throws LWJGLException;
private static native boolean lockAndInitHandle(ByteBuffer lock_buffer, Canvas component) throws LWJGLException;
void unlock() throws LWJGLException {
nUnlock(lock_buffer);
}
private static native void nUnlock(ByteBuffer lock_buffer) throws LWJGLException;
/**
* This method will return true if the component is running in an applet
*/
public boolean isApplet(Canvas component) {
Component parent = component.getParent();
while (parent != null) {
if (parent instanceof Applet) {
return true;
}
parent = parent.getParent();
}
// not an applet
return false;
}
}

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* Copyright (c) 2002-2014 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@ -35,291 +35,399 @@ import org.lwjgl.BufferUtils;
import org.lwjgl.LWJGLUtil;
import java.nio.IntBuffer;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
/**
* This class represents the context attributes passed to CreateContextAttribs of the ARB_create_context and
* ARB_create_context_profile extensions.
* These attributes can be used to indicate at context creation which OpenGL interface will be used. This includes the
* OpenGL version, the layer plane on which rendering takes place and also optional debug and forward combatibility modes.
* (read the ARB_create_context spec for details)
* This class represents the context attributes passed to CreateContextAttribs of the ARB_create_context extension.
* <p/>
* The attributes supported are described in the following extensions:<br>
* <ul>
* <li><a href="http://www.opengl.org/registry/specs/ARB/wgl_create_context.txt">WGL_ARB_create_context(_profile)</a> and <a href="http://www.opengl.org/registry/specs/ARB/glx_create_context.txt">GLX_ARB_create_context(_profile)</a></li>
* <li><a href="http://www.opengl.org/registry/specs/ARB/wgl_create_context_robustness.txt">WGL_ARB_create_context_robustness</a> and <a href="http://www.opengl.org/registry/specs/ARB/glx_create_context_robustness.txt">GLX_ARB_create_context_robustness</a></li>
* <li><a href="http://www.opengl.org/registry/specs/ARB/wgl_robustness_isolation.txt">WGL_ARB_robustness_isolation</a> and <a href="http://www.opengl.org/registry/specs/ARB/glx_robustness_isolation.txt">GLX_ARB_robustness_isolation</a></li>
* <li><a href="http://www.opengl.org/registry/specs/ARB/wgl_create_context_es2_profile.txt">WGL_EXT_create_context_es2_profile</a> and <a href="http://www.opengl.org/registry/specs/ARB/glx_create_context_es2_profile.txt">GLX_EXT_create_context_es2_profile</a></li>
* <li><a href="http://www.opengl.org/registry/specs/ARB/context_flush_control.txt">KHR_context_flush_control</a></li>
* </ul>
* <p/>
* Use of this class is optional. If an OpenGL context is created without passing an instance of this class
* (or ARB_create_context is not supported), the old context creation code will be used. Support for debug and forward
* compatible mobes is not guaranteed by the OpenGL implementation. Developers may encounter debug contexts being the same
* as non-debug contexts or forward compatible contexts having support for deprecated functionality.
* <p/>
* If the forwardCompatible
* attribute is used, LWJGL will not load the deprecated functionality (as defined in the OpenGL 3.0 specification). This
* means that developers can start working on cleaning up their applications without an OpenGL 3.0 complaint driver.
* If the {@link #CONTEXT_FORWARD_COMPATIBLE_BIT_ARB} flag is used, LWJGL will not load the deprecated functionality (as defined in the OpenGL 3.0
* specification), even if the driver exposes the corresponding entry points.
* <p/>
* This extension is not supported on MacOS X. However, in order to enable the GL 3.2 context on MacOS X 10.7 or newer, an
* instance of this class must be passed to LWJGL. The only valid configuration is <code>new ContextAttribs(3, 2).withProfileCore()</code>,
* anything else will be ignored.
* This extension is not supported on MacOS X. However, in order to enable the GL 3.2 context on MacOS X 10.7 or newer, an instance of this class must be passed
* to LWJGL. The only valid configuration is <code>ContextAttribs(3, 2, CONTEXT_CORE_PROFILE_BIT_ARB)</code>, anything else will be ignored.
*
* @author spasi <spasi@users.sourceforge.net>
*/
public final class ContextAttribs {
// Same values for GLX & WGL
private static final int CONTEXT_ES2_PROFILE_BIT_EXT = 0x00000004;
// ATTRIBUTES
private static final int CONTEXT_ROBUST_ACCESS_BIT_ARB = 0x00000004;
private static final int CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB = 0x8256;
private static final int
NO_RESET_NOTIFICATION_ARB = 0x8261,
LOSE_CONTEXT_ON_RESET_ARB = 0x8252;
public static final int CONTEXT_MAJOR_VERSION_ARB = 0x2091;
public static final int CONTEXT_MINOR_VERSION_ARB = 0x2092;
private static final int CONTEXT_RESET_ISOLATION_BIT_ARB = 0x00000008;
public static final int CONTEXT_PROFILE_MASK_ARB = 0x9126,
CONTEXT_CORE_PROFILE_BIT_ARB = 0x00000001,
CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB = 0x00000002,
CONTEXT_ES2_PROFILE_BIT_EXT = 0x00000004;
public static final int CONTEXT_FLAGS_ARB = 0x2094,
CONTEXT_DEBUG_BIT_ARB = 0x0001,
CONTEXT_FORWARD_COMPATIBLE_BIT_ARB = 0x0002,
CONTEXT_ROBUST_ACCESS_BIT_ARB = 0x00000004,
CONTEXT_RESET_ISOLATION_BIT_ARB = 0x00000008;
public static final int CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB = 0x8256,
NO_RESET_NOTIFICATION_ARB = 0x8261,
LOSE_CONTEXT_ON_RESET_ARB = 0x8252;
public static final int CONTEXT_RELEASE_BEHABIOR_ARB = 0x2097,
CONTEXT_RELEASE_BEHAVIOR_NONE_ARB = 0x0000,
CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB = 0x2098;
public static final int CONTEXT_LAYER_PLANE_ARB = 0x2093; // WGL-only
// STATE
private int majorVersion;
private int minorVersion;
private int profileMask;
private int contextFlags;
private int contextResetNotificationStrategy = NO_RESET_NOTIFICATION_ARB;
private int contextReleaseBehavior = CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB;
private int layerPlane;
private boolean debug;
private boolean forwardCompatible;
private boolean robustAccess;
private boolean profileCore;
private boolean profileCompatibility;
private boolean profileES;
private boolean loseContextOnReset;
private boolean contextResetIsolation;
// CONSTRUCTORS
/** Creates the default ContextAttribs instance. No special attributes will be used when creating the OpenGL context. */
public ContextAttribs() {
this(1, 0);
}
public ContextAttribs(final int majorVersion, final int minorVersion) {
/** Creates a ContextAttribs instance for the given OpenGL version. */
public ContextAttribs(int majorVersion, int minorVersion) {
this(majorVersion, minorVersion, 0, 0);
}
/**
* Creates a new ContextAttribs instance with the given attributes.
*
* @param majorVersion the major OpenGL version
* @param minorVersion the minor OpenGL version
* @param profileMask the context profile mask. One of:<br>{@link #CONTEXT_CORE_PROFILE_BIT_ARB}, {@link #CONTEXT_FORWARD_COMPATIBLE_BIT_ARB}, {@link #CONTEXT_ES2_PROFILE_BIT_EXT}
*/
public ContextAttribs(int majorVersion, int minorVersion, int profileMask) {
this(majorVersion, minorVersion, 0, profileMask);
}
/**
* Creates a new ContextAttribs instance with the given attributes.
*
* @param majorVersion the major OpenGL version
* @param minorVersion the minor OpenGL version
* @param profileMask the context profile mask. One of:<br>{@link #CONTEXT_CORE_PROFILE_BIT_ARB}, {@link #CONTEXT_FORWARD_COMPATIBLE_BIT_ARB}, {@link #CONTEXT_ES2_PROFILE_BIT_EXT}
* @param contextFlags the context flags, a bitfield value. One or more of:<br>{@link #CONTEXT_DEBUG_BIT_ARB}, {@link #CONTEXT_FORWARD_COMPATIBLE_BIT_ARB}, {@link #CONTEXT_ROBUST_ACCESS_BIT_ARB}, {@link #CONTEXT_RESET_ISOLATION_BIT_ARB}
*/
public ContextAttribs(int majorVersion, int minorVersion, int profileMask, int contextFlags) {
if ( majorVersion < 0 || 4 < majorVersion ||
minorVersion < 0 ||
(majorVersion == 4 && 3 < minorVersion) ||
(majorVersion == 4 && 5 < minorVersion) ||
(majorVersion == 3 && 3 < minorVersion) ||
(majorVersion == 2 && 1 < minorVersion) ||
(majorVersion == 1 && 5 < minorVersion) )
throw new IllegalArgumentException("Invalid OpenGL version specified: " + majorVersion + '.' + minorVersion);
if ( LWJGLUtil.CHECKS ) {
if ( 1 < Integer.bitCount(profileMask) || CONTEXT_ES2_PROFILE_BIT_EXT < profileMask )
throw new IllegalArgumentException("Invalid profile mask specified: " + Integer.toBinaryString(profileMask));
if ( 0xF < contextFlags )
throw new IllegalArgumentException("Invalid context flags specified: " + Integer.toBinaryString(profileMask));
}
this.majorVersion = majorVersion;
this.minorVersion = minorVersion;
this.profileMask = profileMask;
this.contextFlags = contextFlags;
}
private ContextAttribs(final ContextAttribs attribs) {
this.majorVersion = attribs.majorVersion;
this.minorVersion = attribs.minorVersion;
// Copy constructor
private ContextAttribs(ContextAttribs other) {
this.majorVersion = other.majorVersion;
this.minorVersion = other.minorVersion;
this.layerPlane = attribs.layerPlane;
this.profileMask = other.profileMask;
this.contextFlags = other.contextFlags;
this.debug = attribs.debug;
this.forwardCompatible = attribs.forwardCompatible;
this.robustAccess = attribs.robustAccess;
this.contextResetNotificationStrategy = other.contextResetNotificationStrategy;
this.contextReleaseBehavior = other.contextReleaseBehavior;
this.profileCore = attribs.profileCore;
this.profileCompatibility = attribs.profileCompatibility;
this.profileES = attribs.profileES;
this.loseContextOnReset = attribs.loseContextOnReset;
this.layerPlane = other.layerPlane;
}
// GETTERS
/** Returns the {@link #CONTEXT_MAJOR_VERSION_ARB} value. */
public int getMajorVersion() {
return majorVersion;
}
/** Returns the {@link #CONTEXT_MINOR_VERSION_ARB} value. */
public int getMinorVersion() {
return minorVersion;
}
/** Returns the {@link #CONTEXT_PROFILE_MASK_ARB} value. */
public int getProfileMask() {
return profileMask;
}
private boolean hasMask(int mask) {
return profileMask == mask;
}
/** Returns true if the {@link #CONTEXT_CORE_PROFILE_BIT_ARB} has been set. */
public boolean isProfileCore() {
return hasMask(CONTEXT_CORE_PROFILE_BIT_ARB);
}
/** Returns true if the {@link #CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB} has been set. */
public boolean isProfileCompatibility() {
return hasMask(CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB);
}
/** Returns true if the {@link #CONTEXT_ES2_PROFILE_BIT_EXT} has been set. */
public boolean isProfileES() {
return hasMask(CONTEXT_ES2_PROFILE_BIT_EXT);
}
/** Returns the {@link #CONTEXT_FLAGS_ARB} value. */
public int getContextFlags() {
return contextFlags;
}
private boolean hasFlag(int flag) {
return (contextFlags & flag) != 0;
}
/** Returns true if the {@link #CONTEXT_DEBUG_BIT_ARB} has been set. */
public boolean isDebug() {
return hasFlag(CONTEXT_DEBUG_BIT_ARB);
}
/** Returns true if the {@link #CONTEXT_FORWARD_COMPATIBLE_BIT_ARB} has been set. */
public boolean isForwardCompatible() {
return hasFlag(CONTEXT_FORWARD_COMPATIBLE_BIT_ARB);
}
/** Returns true if the {@link #CONTEXT_ROBUST_ACCESS_BIT_ARB} has been set. */
public boolean isRobustAccess() { return hasFlag(CONTEXT_ROBUST_ACCESS_BIT_ARB); }
/** Returns true if the {@link #CONTEXT_RESET_ISOLATION_BIT_ARB} has been set. */
public boolean isContextResetIsolation() {
return hasFlag(CONTEXT_RESET_ISOLATION_BIT_ARB);
}
/** Returns the {@link #CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB} value. */
public int getContextResetNotificationStrategy() {
return contextResetNotificationStrategy;
}
/**
* Returns true if the {@link #CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB} has been set to {@link #LOSE_CONTEXT_ON_RESET_ARB}.
*
* @deprecated use {@link #getContextResetNotificationStrategy} instead
*/
public boolean isLoseContextOnReset() { return contextResetNotificationStrategy == LOSE_CONTEXT_ON_RESET_ARB; }
/** Returns the {@link #CONTEXT_RELEASE_BEHABIOR_ARB} value. */
public int getContextReleaseBehavior() {
return contextReleaseBehavior;
}
/** Returns the {@link #CONTEXT_LAYER_PLANE_ARB} value. */
public int getLayerPlane() {
return layerPlane;
}
public boolean isDebug() {
return debug;
}
// CHAIN CONFIGURATION PATTERN
public boolean isForwardCompatible() {
return forwardCompatible;
}
public boolean isProfileCore() {
return profileCore;
}
public boolean isProfileCompatibility() {
return profileCompatibility;
}
public boolean isProfileES() {
return profileES;
}
public ContextAttribs withLayer(final int layerPlane) {
if ( layerPlane < 0 )
throw new IllegalArgumentException("Invalid layer plane specified: " + layerPlane);
if ( layerPlane == this.layerPlane )
private ContextAttribs toggleMask(int mask, boolean value) {
if ( value == hasMask(mask) )
return this;
final ContextAttribs attribs = new ContextAttribs(this);
attribs.layerPlane = layerPlane;
return attribs;
}
public ContextAttribs withDebug(final boolean debug) {
if ( debug == this.debug )
return this;
final ContextAttribs attribs = new ContextAttribs(this);
attribs.debug = debug;
return attribs;
}
public ContextAttribs withForwardCompatible(final boolean forwardCompatible) {
if ( forwardCompatible == this.forwardCompatible )
return this;
final ContextAttribs attribs = new ContextAttribs(this);
attribs.forwardCompatible = forwardCompatible;
return attribs;
}
public ContextAttribs withProfileCore(final boolean profileCore) {
if ( majorVersion < 3 || (majorVersion == 3 && minorVersion < 2) )
throw new IllegalArgumentException("Profiles are only supported on OpenGL version 3.2 or higher.");
if ( profileCore == this.profileCore )
return this;
final ContextAttribs attribs = new ContextAttribs(this);
attribs.profileCore = profileCore;
if ( profileCore )
attribs.profileCompatibility = false;
return attribs;
}
public ContextAttribs withProfileCompatibility(final boolean profileCompatibility) {
if ( majorVersion < 3 || (majorVersion == 3 && minorVersion < 2) )
throw new IllegalArgumentException("Profiles are only supported on OpenGL version 3.2 or higher.");
if ( profileCompatibility == this.profileCompatibility )
return this;
final ContextAttribs attribs = new ContextAttribs(this);
attribs.profileCompatibility = profileCompatibility;
if ( profileCompatibility )
attribs.profileCore = false;
return attribs;
}
public ContextAttribs withProfileES(final boolean profileES) {
if ( !(majorVersion == 2 && minorVersion == 0) )
throw new IllegalArgumentException("The OpenGL ES profiles is only supported for OpenGL version 2.0.");
if ( profileES == this.profileES )
return this;
final ContextAttribs attribs = new ContextAttribs(this);
attribs.profileES = profileES;
ContextAttribs attribs = new ContextAttribs(this);
attribs.profileMask = value ? mask : 0;
return attribs;
}
/**
* Returns a ContextAttribs instance with CONTEXT_RESET_NOTIFICATION_STRATEGY set
* to LOSE_CONTEXT_ON_RESET if the parameter is true or to NO_RESET_NOTIFICATION
* if the parameter is false.
* Returns a new {@code ContextAttribs} instance with the {@link #CONTEXT_CORE_PROFILE_BIT_ARB} bit in {@link #CONTEXT_PROFILE_MASK_ARB} set to the given value.
* If {@code profileCore} is true, all other bits in the mask are cleared.
*/
public ContextAttribs withProfileCore(boolean profileCore) {
if ( majorVersion < 3 || (majorVersion == 3 && minorVersion < 2) )
throw new IllegalArgumentException("Profiles are only supported on OpenGL version 3.2 or higher.");
return toggleMask(CONTEXT_CORE_PROFILE_BIT_ARB, profileCore);
}
/**
* Returns a new {@code ContextAttribs} instance with the {@link #CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB} bit in {@link #CONTEXT_PROFILE_MASK_ARB} set to the given value.
* If {@code profileCompatibility} is true, all other bits in the mask are cleared.
*/
public ContextAttribs withProfileCompatibility(boolean profileCompatibility) {
if ( majorVersion < 3 || (majorVersion == 3 && minorVersion < 2) )
throw new IllegalArgumentException("Profiles are only supported on OpenGL version 3.2 or higher.");
return toggleMask(CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB, profileCompatibility);
}
/**
* Returns a new {@code ContextAttribs} instance with the {@link #CONTEXT_ES2_PROFILE_BIT_EXT} bit in {@link #CONTEXT_PROFILE_MASK_ARB} set to the given value.
* If {@code profileES} is true, all other bits in the mask are cleared.
*/
public ContextAttribs withProfileES(boolean profileES) {
if ( !(majorVersion == 2 && minorVersion == 0) )
throw new IllegalArgumentException("The OpenGL ES profile is only supported on OpenGL version 2.0.");
return toggleMask(CONTEXT_ES2_PROFILE_BIT_EXT, profileES);
}
private ContextAttribs toggleFlag(int flag, boolean value) {
if ( value == hasFlag(flag) )
return this;
ContextAttribs attribs = new ContextAttribs(this);
attribs.contextFlags ^= flag; // toggle bit
return attribs;
}
/** Returns a new {@code ContextAttribs} instance with the {@link #CONTEXT_DEBUG_BIT_ARB} bit in {@link #CONTEXT_FLAGS_ARB} set to the given value. */
public ContextAttribs withDebug(boolean debug) { return toggleFlag(CONTEXT_DEBUG_BIT_ARB, debug); }
/** Returns a new {@code ContextAttribs} instance with the {@link #CONTEXT_FORWARD_COMPATIBLE_BIT_ARB} bit in {@link #CONTEXT_FLAGS_ARB} set to the given value. */
public ContextAttribs withForwardCompatible(boolean forwardCompatible) { return toggleFlag(CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, forwardCompatible); }
/** Returns a new {@code ContextAttribs} instance with the {@link #CONTEXT_ROBUST_ACCESS_BIT_ARB} bit in {@link #CONTEXT_FLAGS_ARB} set to the given value. */
public ContextAttribs withRobustAccess(boolean robustAccess) { return toggleFlag(CONTEXT_ROBUST_ACCESS_BIT_ARB, robustAccess); }
/** Returns a new {@code ContextAttribs} instance with the {@link #CONTEXT_RESET_ISOLATION_BIT_ARB} bit in {@link #CONTEXT_FLAGS_ARB} set to the given value. */
public ContextAttribs withContextResetIsolation(boolean contextResetIsolation) { return toggleFlag(CONTEXT_RESET_ISOLATION_BIT_ARB, contextResetIsolation); }
/**
* Returns a ContextAttribs instance with {@link #CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB} set to the given strategy. The default context reset notification
* strategy is {@link #NO_RESET_NOTIFICATION_ARB}.
*
* @param loseContextOnReset
* @param strategy the context reset notification strategy. One of:<br>{@link #NO_RESET_NOTIFICATION_ARB}, {@link #LOSE_CONTEXT_ON_RESET_ARB}
*
* @return the new ContextAttribs
*/
public ContextAttribs withLoseContextOnReset(final boolean loseContextOnReset) {
if ( loseContextOnReset == this.loseContextOnReset )
public ContextAttribs withResetNotificationStrategy(int strategy) {
if ( strategy == contextResetNotificationStrategy )
return this;
final ContextAttribs attribs = new ContextAttribs(this);
attribs.loseContextOnReset = loseContextOnReset;
if ( LWJGLUtil.CHECKS && !(strategy == NO_RESET_NOTIFICATION_ARB || strategy == LOSE_CONTEXT_ON_RESET_ARB) )
throw new IllegalArgumentException("Invalid context reset notification strategy specified: 0x" + LWJGLUtil.toHexString(strategy));
ContextAttribs attribs = new ContextAttribs(this);
attribs.contextResetNotificationStrategy = strategy;
return attribs;
}
public ContextAttribs withContextResetIsolation(final boolean contextResetIsolation) {
if ( contextResetIsolation == this.contextResetIsolation )
/**
* Returns a ContextAttribs instance with {@link #CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB} set to {@link #LOSE_CONTEXT_ON_RESET_ARB} if the parameter is
* true or to {@link #NO_RESET_NOTIFICATION_ARB} if the parameter is false.
*
* @param loseContextOnReset the context reset notification strategy
*
* @return the new ContextAttribs
*
* @deprecated use {@link #withResetNotificationStrategy} instead
*/
public ContextAttribs withLoseContextOnReset(boolean loseContextOnReset) {
return withResetNotificationStrategy(loseContextOnReset ? LOSE_CONTEXT_ON_RESET_ARB : NO_RESET_NOTIFICATION_ARB);
}
/**
* Returns a ContextAttribs instance with {@link #CONTEXT_RELEASE_BEHABIOR_ARB} set to the given behavior. The default context release behavior is
* {@link #CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB}.
*
* @param behavior the context release behavior. One of:<br>{@link #CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB}, {@link #CONTEXT_RELEASE_BEHAVIOR_NONE_ARB}
*
* @return the new ContextAttribs
*/
public ContextAttribs withContextReleaseBehavior(int behavior) {
if ( behavior == contextReleaseBehavior )
return this;
final ContextAttribs attribs = new ContextAttribs(this);
attribs.contextResetIsolation = contextResetIsolation;
if ( LWJGLUtil.CHECKS && !(behavior == CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB || behavior == CONTEXT_RELEASE_BEHAVIOR_NONE_ARB) )
throw new IllegalArgumentException("Invalid context release behavior specified: 0x" + LWJGLUtil.toHexString(behavior));
ContextAttribs attribs = new ContextAttribs(this);
attribs.contextReleaseBehavior = behavior;
return attribs;
}
private static ContextAttribsImplementation getImplementation() {
switch ( LWJGLUtil.getPlatform() ) {
case LWJGLUtil.PLATFORM_LINUX:
return new LinuxContextAttribs();
case LWJGLUtil.PLATFORM_WINDOWS:
return new WindowsContextAttribs();
default:
throw new IllegalStateException("Unsupported platform");
}
/** Returns a new {@code ContextAttribs} instance with {@link #CONTEXT_LAYER_PLANE_ARB} set to the given value. */
public ContextAttribs withLayer(int layerPlane) {
if ( LWJGLUtil.getPlatform() != LWJGLUtil.PLATFORM_WINDOWS )
throw new IllegalArgumentException("The CONTEXT_LAYER_PLANE_ARB attribute is supported only on the Windows platform.");
if ( layerPlane == this.layerPlane )
return this;
if ( layerPlane < 0 )
throw new IllegalArgumentException("Invalid layer plane specified: " + layerPlane);
ContextAttribs attribs = new ContextAttribs(this);
attribs.layerPlane = layerPlane;
return attribs;
}
IntBuffer getAttribList() {
if ( LWJGLUtil.getPlatform() == LWJGLUtil.PLATFORM_MACOSX )
return null;
ContextAttribsImplementation implementation = getImplementation();
int attribCount = 0;
if ( !(majorVersion == 1 && minorVersion == 0) )
attribCount += 2;
if ( 0 < layerPlane )
attribCount++;
int flags = 0;
if ( debug )
flags |= implementation.getDebugBit();
if ( forwardCompatible )
flags |= implementation.getForwardCompatibleBit();
if ( robustAccess )
flags |= CONTEXT_ROBUST_ACCESS_BIT_ARB;
if ( contextResetIsolation )
flags |= CONTEXT_RESET_ISOLATION_BIT_ARB;
if ( 0 < flags )
attribCount++;
int profileMask = 0;
if ( profileCore )
profileMask |= implementation.getProfileCoreBit();
else if ( profileCompatibility )
profileMask |= implementation.getProfileCompatibilityBit();
else if ( profileES )
profileMask |= CONTEXT_ES2_PROFILE_BIT_EXT;
if ( 0 < profileMask )
attribCount++;
if ( loseContextOnReset )
attribCount++;
if ( attribCount == 0 )
return null;
final IntBuffer attribs = BufferUtils.createIntBuffer((attribCount * 2) + 1);
LinkedHashMap<Integer, Integer> map = new LinkedHashMap<Integer, Integer>(8);
if ( !(majorVersion == 1 && minorVersion == 0) ) {
attribs.put(implementation.getMajorVersionAttrib()).put(majorVersion);
attribs.put(implementation.getMinorVersionAttrib()).put(minorVersion);
map.put(CONTEXT_MAJOR_VERSION_ARB, majorVersion);
map.put(CONTEXT_MINOR_VERSION_ARB, minorVersion);
}
if ( 0 < layerPlane )
attribs.put(implementation.getLayerPlaneAttrib()).put(layerPlane);
if ( 0 < flags )
attribs.put(implementation.getFlagsAttrib()).put(flags);
if ( 0 < profileMask )
attribs.put(implementation.getProfileMaskAttrib()).put(profileMask);
if ( loseContextOnReset )
attribs.put(CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB).put(LOSE_CONTEXT_ON_RESET_ARB);
if ( contextFlags != 0 )
map.put(CONTEXT_FLAGS_ARB, contextFlags);
if ( profileMask != 0 )
map.put(CONTEXT_PROFILE_MASK_ARB, profileMask);
if ( contextResetNotificationStrategy != NO_RESET_NOTIFICATION_ARB )
map.put(CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB, contextResetNotificationStrategy);
if ( contextReleaseBehavior != CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB )
map.put(CONTEXT_RELEASE_BEHABIOR_ARB, contextReleaseBehavior);
if ( layerPlane != 0 )
map.put(CONTEXT_LAYER_PLANE_ARB, layerPlane);
if ( map.isEmpty() )
return null;
IntBuffer attribs = BufferUtils.createIntBuffer((map.size() * 2) + 1);
for ( Entry<Integer, Integer> attrib : map.entrySet() ) {
attribs
.put(attrib.getKey())
.put(attrib.getValue());
}
attribs.put(0);
attribs.rewind();
return attribs;
@ -330,19 +438,37 @@ public final class ContextAttribs {
sb.append("ContextAttribs:");
sb.append(" Version=").append(majorVersion).append('.').append(minorVersion);
sb.append(" - Layer=").append(layerPlane);
sb.append(" - Debug=").append(debug);
sb.append(" - ForwardCompatible=").append(forwardCompatible);
sb.append(" - RobustAccess=").append(robustAccess);
if ( robustAccess )
sb.append(" (").append(loseContextOnReset ? "LOSE_CONTEXT_ON_RESET" : "NO_RESET_NOTIFICATION");
sb.append(" - Profile=");
if ( profileCore )
sb.append("Core");
else if ( profileCompatibility )
sb.append("Compatibility");
else
sb.append("None");
if ( profileMask != 0 ) {
sb.append(", Profile=");
if ( hasMask(CONTEXT_CORE_PROFILE_BIT_ARB) )
sb.append("CORE");
else if ( hasMask(CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB) )
sb.append("COMPATIBLITY");
else if ( hasMask(CONTEXT_ES2_PROFILE_BIT_EXT) )
sb.append("ES2");
else
sb.append("*unknown*");
}
if ( contextFlags != 0 ) {
if ( hasFlag(CONTEXT_DEBUG_BIT_ARB) )
sb.append(", DEBUG");
if ( hasFlag(CONTEXT_FORWARD_COMPATIBLE_BIT_ARB) )
sb.append(", FORWARD_COMPATIBLE");
if ( hasFlag(CONTEXT_ROBUST_ACCESS_BIT_ARB) )
sb.append(", ROBUST_ACCESS");
if ( hasFlag(CONTEXT_RESET_ISOLATION_BIT_ARB) )
sb.append(", RESET_ISOLATION");
}
if ( contextResetNotificationStrategy != NO_RESET_NOTIFICATION_ARB )
sb.append(", LOSE_CONTEXT_ON_RESET");
if ( contextReleaseBehavior != CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB )
sb.append(", RELEASE_BEHAVIOR_NONE");
if ( layerPlane != 0 )
sb.append(", Layer=").append(layerPlane);
return sb.toString();
}

View file

@ -253,8 +253,12 @@ final class ContextGL implements Context {
boolean was_current = isCurrent();
int error = GL_NO_ERROR;
if ( was_current ) {
if ( GLContext.getCapabilities() != null && GLContext.getCapabilities().OpenGL11 )
try {
// May fail on GLContext.getCapabilities()
error = glGetError();
} catch (Exception e) {
// ignore
}
releaseCurrent();
}
checkDestroy();

View file

@ -43,7 +43,10 @@ package org.lwjgl.opengl;
* @author foo
*/
import org.lwjgl.*;
import org.lwjgl.BufferUtils;
import org.lwjgl.LWJGLException;
import org.lwjgl.LWJGLUtil;
import org.lwjgl.Sys;
import org.lwjgl.input.Controllers;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
@ -52,6 +55,7 @@ import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.security.AccessController;
@ -236,21 +240,21 @@ public final class Display {
throw new NullPointerException("mode must be non-null");
boolean was_fullscreen = isFullscreen();
current_mode = mode;
if ( isCreated() ) {
destroyWindow();
// If mode is not fullscreen capable, make sure we are in windowed mode
try {
if ( was_fullscreen && !isFullscreen() )
display_impl.resetDisplayMode();
else if ( isFullscreen() )
switchDisplayMode();
createWindow();
makeCurrentAndSetSwapInterval();
} catch (LWJGLException e) {
drawable.destroy();
if ( !isCreated() || parent != null )
return;
destroyWindow();
// If mode is not fullscreen capable, make sure we are in windowed mode
try {
if ( was_fullscreen && !isFullscreen() )
display_impl.resetDisplayMode();
throw e;
}
else if ( isFullscreen() )
switchDisplayMode();
createWindow();
makeCurrentAndSetSwapInterval();
} catch (LWJGLException e) {
drawable.destroy();
display_impl.resetDisplayMode();
throw e;
}
}
}
@ -401,7 +405,7 @@ public final class Display {
/**
* An accurate sync method that will attempt to run at a constant frame rate.
* It should be called once every frame.
*
*
* @param fps - the desired frame rate, in frames per second
*/
public static void sync(int fps) {
@ -1045,6 +1049,15 @@ public final class Display {
}
});
}
/** Gets a string property as a privileged action. */
static String getPrivilegedString(final String property_name) {
return AccessController.doPrivileged(new PrivilegedAction<String>() {
public String run() {
return System.getProperty(property_name);
}
});
}
private static void initControls() {
// Automatically create mouse, keyboard and controller
@ -1190,7 +1203,7 @@ public final class Display {
* <li>Linux (and similar platforms) expect one 32x32 icon.</li>
* <li>Mac OS X should be supplied one 128x128 icon</li>
* </ul>
* The implementation will use the supplied ByteBuffers with image data in RGBA and perform any conversions nescesarry for the specific platform.
* The implementation will use the supplied ByteBuffers with image data in RGBA (size must be a power of two) and perform any conversions nescesarry for the specific platform.
* <p/>
* <b>NOTE:</b> The display will make a deep copy of the supplied byte buffer array, for the purpose
* of recreating the icons when you go back and forth fullscreen mode. You therefore only need to
@ -1210,8 +1223,8 @@ public final class Display {
cached_icons[i] = BufferUtils.createByteBuffer(icons[i].capacity());
int old_position = icons[i].position();
cached_icons[i].put(icons[i]);
icons[i].position(old_position);
cached_icons[i].flip();
((Buffer)icons[i]).position(old_position);
((Buffer)cached_icons[i]).flip();
}
}
@ -1257,7 +1270,7 @@ public final class Display {
* @return this method will return the x position (top-left) of the Display window.
*
* If running in fullscreen mode it will return 0.
* If Display.setParent(Canvas parent) is being used, the x position of
* If Display.setParent(Canvas parent) is being used, the x position of
* the parent will be returned.
*/
public static int getX() {
@ -1272,12 +1285,12 @@ public final class Display {
return display_impl.getX();
}
/**
* @return this method will return the y position (top-left) of the Display window.
*
* If running in fullscreen mode it will return 0.
* If Display.setParent(Canvas parent) is being used, the y position of
* If Display.setParent(Canvas parent) is being used, the y position of
* the parent will be returned.
*/
public static int getY() {
@ -1292,7 +1305,7 @@ public final class Display {
return display_impl.getY();
}
/**
* @return this method will return the width of the Display window.
*
@ -1336,4 +1349,28 @@ public final class Display {
return height;
}
/**
* @return this method will return the pixel scale factor of the Display window.
*
* This method should be used when running in high DPI mode. In such modes Operating
* Systems will scale the Display window to avoid the window shrinking due to high
* resolutions. The OpenGL frame buffer will however use the higher resolution and
* not be scaled to match the Display window size.
*
* OpenGL methods that require pixel dependent values e.g. glViewport, glTexImage2D,
* glReadPixels, glScissor, glLineWidth, glRenderbufferStorage, etc can convert the
* scaled Display and Mouse coordinates to the correct high resolution value by
* multiplying them by the pixel scale factor.
*
* e.g. Display.getWidth() * Display.getPixelScaleFactor() will return the high DPI
* width of the OpenGL frame buffer. Whereas Display.getWidth() will be the same as
* the OpenGL frame buffer in non high DPI mode.
*
* Where high DPI mode is not available this method will just return 1.0f therefore
* not have any effect on values that are multiplied by it.
*/
public static float getPixelScaleFactor() {
return display_impl.getPixelScaleFactor();
}
}

View file

@ -192,4 +192,9 @@ interface DisplayImplementation extends InputImplementation {
* @return this method will return the top-left y position of the Display window.
*/
int getY();
/**
* @return this method will return the pixel scale factor of the Display window useful for high resolution modes.
*/
float getPixelScaleFactor();
}

View file

@ -75,7 +75,7 @@ public final class DisplayMode {
this.fullscreen = fullscreen;
}
/** True iff this instance can be used for fullscreen modes */
/** True if this instance can be used for fullscreen modes */
public boolean isFullscreenCapable() {
return fullscreen;
}

View file

@ -36,6 +36,7 @@ package org.lwjgl.opengl;
* @author elias_naur
*/
import java.nio.Buffer;
import java.nio.ByteBuffer;
class EventQueue {
@ -58,12 +59,12 @@ class EventQueue {
* Copy available events into the specified buffer.
*/
public synchronized void copyEvents(ByteBuffer dest) {
queue.flip();
((Buffer)queue).flip();
int old_limit = queue.limit();
if (dest.remaining() < queue.remaining())
queue.limit(dest.remaining() + queue.position());
((Buffer)queue).limit(dest.remaining() + queue.position());
dest.put(queue);
queue.limit(old_limit);
((Buffer)queue).limit(old_limit);
queue.compact();
}

View file

@ -43,6 +43,7 @@ import static org.lwjgl.opengl.EXTAbgr.*;
import static org.lwjgl.opengl.EXTBgra.*;
import static org.lwjgl.opengl.EXTDirectStateAccess.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL13.*;
import static org.lwjgl.opengl.GL15.*;
import static org.lwjgl.opengl.NVPathRendering.*;
@ -65,22 +66,6 @@ class GLChecks {
private GLChecks() {
}
static int getBufferObjectSize(ContextCapabilities caps, int buffer_enum) {
return glGetBufferParameteri(buffer_enum, GL_BUFFER_SIZE);
}
static int getBufferObjectSizeARB(ContextCapabilities caps, int buffer_enum) {
return glGetBufferParameteriARB(buffer_enum, GL_BUFFER_SIZE_ARB);
}
static int getBufferObjectSizeATI(ContextCapabilities caps, int buffer) {
return glGetObjectBufferiATI(buffer, GL_OBJECT_BUFFER_SIZE_ATI);
}
static int getNamedBufferObjectSize(ContextCapabilities caps, int buffer) {
return glGetNamedBufferParameterEXT(buffer, GL_BUFFER_SIZE);
}
/** Helper method to ensure that array buffer objects are disabled. If they are enabled, we'll throw an OpenGLException */
static void ensureArrayVBOdisabled(ContextCapabilities caps) {
if ( LWJGLUtil.CHECKS && StateTracker.getReferences(caps).arrayBuffer != 0 )
@ -310,37 +295,36 @@ class GLChecks {
}
}
static int calculatePathColorGenCoeffsCount(int genMode, int colorFormat) {
final int coeffsPerComponent = calculatePathGenCoeffsPerComponent(genMode);
switch ( colorFormat ) {
case GL_RGB:
return 3 * coeffsPerComponent;
case GL_RGBA:
return 4 * coeffsPerComponent;
default:
return coeffsPerComponent;
}
}
static int calculatePathTextGenCoeffsPerComponent(FloatBuffer coeffs, int genMode) {
if ( genMode == GL_NONE )
return 0;
return coeffs.remaining() / calculatePathGenCoeffsPerComponent(genMode);
}
private static int calculatePathGenCoeffsPerComponent(int genMode) {
static int calculatePathColorGenModeElements(int genMode) {
switch ( genMode ) {
case GL_NONE:
return 0;
case GL_CONSTANT:
return 1;
case GL_OBJECT_LINEAR:
case GL_PATH_OBJECT_BOUNDING_BOX_NV:
return 3;
case GL_EYE_LINEAR:
return 4;
default:
throw new IllegalArgumentException("Unsupported gen mode: " + genMode);
throw new IllegalArgumentException(String.format("Unsupported genMode specified: 0x%X", genMode));
}
}
static int calculatePathColorGenFormatComponents(int colorFormat) {
switch ( colorFormat ) {
case GL_LUMINANCE:
case GL_INTENSITY:
case GL_ALPHA:
return 1;
case GL_LUMINANCE_ALPHA:
return 2;
case GL_RGB:
return 3;
case GL_RGBA:
return 4;
default:
throw new IllegalArgumentException(String.format("Unsupported colorFormat specified: 0x%X", colorFormat));
}
}

View file

@ -243,10 +243,10 @@ public final class GLContext {
}
final int[][] GL_VERSIONS = {
{ 1, 2, 3, 4, 5 }, // OpenGL 1
{ 0, 1 }, // OpenGL 2
{ 0, 1, 2, 3 }, // OpenGL 3
{ 0, 1, 2 }, // OpenGL 4
{ 1, 2, 3, 4, 5 }, // OpenGL 1
{ 0, 1 }, // OpenGL 2
{ 0, 1, 2, 3 }, // OpenGL 3
{ 0, 1, 2, 3, 4, 5 }, // OpenGL 4
};
for ( int major = 1; major <= GL_VERSIONS.length; major++ ) {

View file

@ -69,7 +69,7 @@ public interface InputImplementation {
void pollMouse(IntBuffer coord_buffer, ByteBuffer buttons);
/**
* Method to read the keyboard buffer
* Method to read the mouse buffer
*/
void readMouse(ByteBuffer buffer);

View file

@ -115,7 +115,7 @@ public final class KHRDebugCallback extends PointerWrapperAbstract {
description = "OTHER";
break;
default:
description = "Unknown (" + Integer.toHexString(source) + ")";
description = printUnknownToken(source);
}
System.err.println("\tSource: " + description);
@ -142,7 +142,7 @@ public final class KHRDebugCallback extends PointerWrapperAbstract {
description = "MARKER";
break;
default:
description = "Unknown (" + Integer.toHexString(source) + ")";
description = printUnknownToken(type);
}
System.err.println("\tType: " + description);
@ -160,12 +160,16 @@ public final class KHRDebugCallback extends PointerWrapperAbstract {
description = "NOTIFICATION";
break;
default:
description = "Unknown (" + Integer.toHexString(source) + ")";
description = printUnknownToken(severity);
}
System.err.println("\tSeverity: " + description);
System.err.println("\tMessage: " + message);
}
private String printUnknownToken(final int token) {
return "Unknown (0x" + Integer.toHexString(token).toUpperCase() + ")";
}
});
}
@ -192,9 +196,9 @@ public final class KHRDebugCallback extends PointerWrapperAbstract {
/**
* This method will be called when an ARB_debug_output message is generated.
*
* @param id the message ID
* @param source the message source
* @param type the message type
* @param id the message ID
* @param severity the message severity
* @param message the string representation of the message.
*/

View file

@ -143,10 +143,12 @@ final class LinuxContextImplementation implements ContextImplementation {
public void setSwapInterval(int value) {
ContextGL current_context = ContextGL.getCurrentContext();
PeerInfo peer_info = current_context.getPeerInfo();
if ( current_context == null )
throw new IllegalStateException("No context is current");
PeerInfo peer_info = current_context.getPeerInfo();
synchronized ( current_context ) {
LinuxDisplay.lockAWT();
try {

View file

@ -45,6 +45,7 @@ import java.awt.event.FocusEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.ByteOrder;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
@ -128,7 +129,6 @@ final class LinuxDisplay implements DisplayImplementation {
private DisplayMode saved_mode;
private DisplayMode current_mode;
private Screen[] savedXrandrConfig;
private boolean keyboard_grabbed;
private boolean pointer_grabbed;
@ -159,6 +159,8 @@ final class LinuxDisplay implements DisplayImplementation {
private LinuxKeyboard keyboard;
private LinuxMouse mouse;
private String wm_class;
private final FocusListener focus_listener = new FocusListener() {
public void focusGained(FocusEvent e) {
@ -460,15 +462,18 @@ final class LinuxDisplay implements DisplayImplementation {
ByteBuffer handle = peer_info.lockAndGetHandle();
try {
current_window_mode = getWindowMode(Display.isFullscreen());
// Try to enable Lecagy FullScreen Support in Compiz, else
// we may have trouble with stuff overlapping our fullscreen window.
if ( current_window_mode != WINDOWED )
Compiz.setLegacyFullscreenSupport(true);
// Setting _MOTIF_WM_HINTS in fullscreen mode is problematic for certain window
// managers. We do not set MWM_HINTS_DECORATIONS in fullscreen mode anymore,
// unless org.lwjgl.opengl.Window.undecorated_fs has been specified.
// See native/linux/org_lwjgl_opengl_Display.c, createWindow function.
boolean undecorated = Display.getPrivilegedBoolean("org.lwjgl.opengl.Window.undecorated") || (current_window_mode != WINDOWED && Display.getPrivilegedBoolean("org.lwjgl.opengl.Window.undecorated_fs"));
this.parent = parent;
parent_window = parent != null ? getHandle(parent) : getRootWindow(getDisplay(), getDefaultScreen());
resizable = Display.isResizable();
@ -477,7 +482,23 @@ final class LinuxDisplay implements DisplayImplementation {
window_y = y;
window_width = mode.getWidth();
window_height = mode.getHeight();
// overwrite arguments x and y - superclass always uses 0,0 for fullscreen windows
// use the coordinates of XRandRs primary screen instead
// this is required to let the fullscreen window appear on the primary screen
if (mode.isFullscreenCapable() && current_displaymode_extension == XRANDR) {
Screen primaryScreen = XRandR.DisplayModetoScreen(Display.getDisplayMode());
x = primaryScreen.xPos;
y = primaryScreen.yPos;
}
current_window = nCreateWindow(getDisplay(), getDefaultScreen(), handle, mode, current_window_mode, x, y, undecorated, parent_window, resizable);
// Set the WM_CLASS hint which is needed by some WM's e.g. Gnome Shell
wm_class = Display.getPrivilegedString("LWJGL_WM_CLASS");
if (wm_class == null) wm_class = Display.getTitle();
setClassHint(Display.getTitle(), wm_class);
mapRaised(getDisplay(), current_window);
xembedded = parent != null && isAncestorXEmbedded(parent_window);
blank_cursor = createBlankCursor();
@ -590,12 +611,17 @@ final class LinuxDisplay implements DisplayImplementation {
}
private void switchDisplayModeOnTmpDisplay(DisplayMode mode) throws LWJGLException {
incDisplay();
try {
nSwitchDisplayMode(getDisplay(), getDefaultScreen(), current_displaymode_extension, mode);
} finally {
decDisplay();
}
if (current_displaymode_extension == XRANDR) {
// let Xrandr set the display mode
XRandR.setConfiguration(false, XRandR.DisplayModetoScreen(mode));
} else {
incDisplay();
try {
nSwitchDisplayMode(getDisplay(), getDefaultScreen(), current_displaymode_extension, mode);
} finally {
decDisplay();
}
}
}
private static native void nSwitchDisplayMode(long display, int screen, int extension, DisplayMode mode) throws LWJGLException;
@ -612,11 +638,11 @@ final class LinuxDisplay implements DisplayImplementation {
public void resetDisplayMode() {
lockAWT();
try {
if( current_displaymode_extension == XRANDR && savedXrandrConfig.length > 0 )
if( current_displaymode_extension == XRANDR )
{
AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
XRandR.setConfiguration( savedXrandrConfig );
XRandR.restoreConfiguration();
return null;
}
});
@ -714,12 +740,11 @@ final class LinuxDisplay implements DisplayImplementation {
throw new LWJGLException("No modes available");
switch (current_displaymode_extension) {
case XRANDR:
savedXrandrConfig = AccessController.doPrivileged(new PrivilegedAction<Screen[]>() {
public Screen[] run() {
return XRandR.getConfiguration();
saved_mode = AccessController.doPrivileged(new PrivilegedAction<DisplayMode>() {
public DisplayMode run() {
return XRandR.ScreentoDisplayMode(XRandR.getConfiguration());
}
});
saved_mode = getCurrentXRandrMode();
break;
case XF86VIDMODE:
saved_mode = modes[0];
@ -763,6 +788,20 @@ final class LinuxDisplay implements DisplayImplementation {
}
}
private static native void nSetTitle(long display, long window, long title, int len);
/** the WM_CLASS hint is needed by some WM's e.g. gnome shell */
private void setClassHint(String wm_name, String wm_class) {
lockAWT();
try {
final ByteBuffer nameText = MemoryUtil.encodeUTF8(wm_name);
final ByteBuffer classText = MemoryUtil.encodeUTF8(wm_class);
nSetClassHint(getDisplay(), getWindow(), MemoryUtil.getAddress(nameText), MemoryUtil.getAddress(classText));
} finally {
unlockAWT();
}
}
private static native void nSetClassHint(long display, long window, long wm_name, long wm_class);
public boolean isCloseRequested() {
boolean result = close_requested;
@ -899,13 +938,29 @@ final class LinuxDisplay implements DisplayImplementation {
public DisplayMode[] getAvailableDisplayModes() throws LWJGLException {
lockAWT();
try {
incDisplay();
try {
DisplayMode[] modes = nGetAvailableDisplayModes(getDisplay(), getDefaultScreen(), current_displaymode_extension);
return modes;
} finally {
decDisplay();
}
incDisplay();
if (current_displaymode_extension == XRANDR) {
// nGetAvailableDisplayModes cannot be trusted. Use it only for bitsPerPixel
DisplayMode[] nDisplayModes = nGetAvailableDisplayModes(getDisplay(), getDefaultScreen(), current_displaymode_extension);
int bpp = 24;
if (nDisplayModes.length > 0) {
bpp = nDisplayModes[0].getBitsPerPixel();
}
// get the resolutions and frequencys from XRandR
Screen[] resolutions = XRandR.getResolutions(XRandR.getScreenNames()[0]);
DisplayMode[] modes = new DisplayMode[resolutions.length];
for (int i = 0; i < modes.length; i++) {
modes[i] = new DisplayMode(resolutions[i].width, resolutions[i].height, bpp, resolutions[i].freq);
}
return modes;
} else {
try {
DisplayMode[] modes = nGetAvailableDisplayModes(getDisplay(), getDefaultScreen(), current_displaymode_extension);
return modes;
} finally {
decDisplay();
}
}
} finally {
unlockAWT();
}
@ -1066,16 +1121,18 @@ final class LinuxDisplay implements DisplayImplementation {
private void releaseInput() {
if (isLegacyFullscreen() || input_released)
return;
if ( keyboard != null )
keyboard.releaseAll();
input_released = true;
updateInputGrab();
if (current_window_mode == FULLSCREEN_NETWM) {
nIconifyWindow(getDisplay(), getWindow(), getDefaultScreen());
try {
if( current_displaymode_extension == XRANDR && savedXrandrConfig.length > 0 )
if( current_displaymode_extension == XRANDR )
{
AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
XRandR.setConfiguration( savedXrandrConfig );
XRandR.restoreConfiguration();
return null;
}
});
@ -1302,50 +1359,58 @@ final class LinuxDisplay implements DisplayImplementation {
public void releaseTexImageFromPbuffer(PeerInfo handle, int buffer) {
throw new UnsupportedOperationException();
}
private static ByteBuffer convertIcon(ByteBuffer icon, int width, int height) {
ByteBuffer icon_rgb = BufferUtils.createByteBuffer(icon.capacity());
int x;
int y;
byte r,g,b;
int depth = 4;
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
r = icon.get((x*4)+(y*width*4));
g = icon.get((x*4)+(y*width*4)+1);
b = icon.get((x*4)+(y*width*4)+2);
icon_rgb.put((x*depth)+(y*width*depth), b); // blue
icon_rgb.put((x*depth)+(y*width*depth)+1, g); // green
icon_rgb.put((x*depth)+(y*width*depth)+2, r);
/**
* This method will convert icon bytebuffers into a single bytebuffer
* as the icon format required by _NET_WM_ICON should be in a cardinal
* 32 bit ARGB format i.e. all icons in a single buffer the data starting
* with 32 bit width & height followed by the color data as 32bit ARGB.
*
* @param icons Array of icons in RGBA format
*/
private static ByteBuffer convertIcons(ByteBuffer[] icons) {
int bufferSize = 0;
// calculate size of bytebuffer
for ( ByteBuffer icon : icons ) {
int size = icon.limit() / 4;
int dimension = (int)Math.sqrt(size);
if ( dimension > 0 ) {
bufferSize += 2 * 4; // add 32 bit width & height, 4 bytes each
bufferSize += dimension * dimension * 4;
}
}
return icon_rgb;
}
private static ByteBuffer convertIconMask(ByteBuffer icon, int width, int height) {
ByteBuffer icon_mask = BufferUtils.createByteBuffer((icon.capacity()/4)/8);
int x;
int y;
byte a;
int depth = 4;
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
a = icon.get((x*4)+(y*width*4)+3);
int mask_index = x + y*width;
int mask_byte_index = mask_index/8;
int mask_bit_index = mask_index%8;
byte bit = (((int)a) & 0xff) >= 127 ? (byte)1 : (byte)0;
byte new_byte = (byte)((icon_mask.get(mask_byte_index) | (bit<<mask_bit_index)) & 0xff);
icon_mask.put(mask_byte_index, new_byte);
if (bufferSize == 0) return null;
ByteBuffer icon_argb = BufferUtils.createByteBuffer(bufferSize);//icon.capacity()+(2*4));
icon_argb.order(ByteOrder.BIG_ENDIAN);
for ( ByteBuffer icon : icons ) {
int size = icon.limit() / 4;
int dimension = (int)Math.sqrt(size);
icon_argb.putInt(dimension); // width
icon_argb.putInt(dimension); // height
for (int y = 0; y < dimension; y++) {
for (int x = 0; x < dimension; x++) {
byte r = icon.get((x*4)+(y*dimension*4));
byte g = icon.get((x*4)+(y*dimension*4)+1);
byte b = icon.get((x*4)+(y*dimension*4)+2);
byte a = icon.get((x*4)+(y*dimension*4)+3);
icon_argb.put(a);
icon_argb.put(r);
icon_argb.put(g);
icon_argb.put(b);
}
}
}
return icon_mask;
return icon_argb;
}
/**
@ -1365,17 +1430,11 @@ final class LinuxDisplay implements DisplayImplementation {
try {
incDisplay();
try {
for ( ByteBuffer icon : icons ) {
int size = icon.limit() / 4;
int dimension = (int)Math.sqrt(size);
if ( dimension > 0 ) {
ByteBuffer icon_rgb = convertIcon(icon, dimension, dimension);
ByteBuffer icon_mask = convertIconMask(icon, dimension, dimension);
nSetWindowIcon(getDisplay(), getWindow(), icon_rgb, icon_rgb.capacity(), icon_mask, icon_mask.capacity(), dimension, dimension);
return 1;
}
}
return 0;
// get icons as cardinal ARGB format
ByteBuffer icons_data = convertIcons(icons);
if (icons_data == null) return 0;
nSetWindowIcon(getDisplay(), getWindow(), icons_data, icons_data.capacity());//, icon_mask, icon_mask.capacity(), dimension, dimension);
return icons.length;
} finally {
decDisplay();
}
@ -1387,7 +1446,7 @@ final class LinuxDisplay implements DisplayImplementation {
}
}
private static native void nSetWindowIcon(long display, long window, ByteBuffer icon_rgb, int icon_rgb_size, ByteBuffer icon_mask, int icon_mask_size, int width, int height);
private static native void nSetWindowIcon(long display, long window, ByteBuffer icons_data, int icons_size);
public int getX() {
return window_x;
@ -1427,6 +1486,10 @@ final class LinuxDisplay implements DisplayImplementation {
return false;
}
public float getPixelScaleFactor() {
return 1f;
}
/**
* Helper class for managing Compiz's workarounds. We need this to enable Legacy
* Fullscreen Support in Compiz, else we'll have trouble with fullscreen windows

View file

@ -257,46 +257,22 @@ final class LinuxKeyboard {
private static native long lookupKeysym(long event_ptr, int index);
private static native long toUpper(long keysym);
private long mapEventToKeySym(long event_ptr, int event_state) {
int group;
long keysym;
if ((event_state & modeswitch_mask) != 0)
group = 1;
else
group = 0;
if ((event_state & numlock_mask) != 0 && isKeypadKeysym(keysym = getKeySym(event_ptr, group, 1))) {
if ((event_state & (ShiftMask | shift_lock_mask)) != 0) {
return getKeySym(event_ptr, group, 0);
} else {
return keysym;
}
} else if ((event_state & (ShiftMask | LockMask)) == 0) {
return getKeySym(event_ptr, group, 0);
} else if ((event_state & ShiftMask) == 0) {
keysym = getKeySym(event_ptr, group, 0);
if ((event_state & caps_lock_mask) != 0)
keysym = toUpper(keysym);
return keysym;
} else {
keysym = getKeySym(event_ptr, group, 1);
if ((event_state & caps_lock_mask) != 0)
keysym = toUpper(keysym);
return keysym;
}
}
private int getKeycode(long event_ptr, int event_state) {
long keysym = mapEventToKeySym(event_ptr, event_state);
int keycode = LinuxKeycodes.mapKeySymToLWJGLKeyCode(keysym);
if (keycode == Keyboard.KEY_NONE) {
// Try unshifted keysym mapping
keysym = lookupKeysym(event_ptr, 0);
keycode = LinuxKeycodes.mapKeySymToLWJGLKeyCode(keysym);
boolean shift = (event_state & (ShiftMask | shift_lock_mask)) != 0;
int group = (event_state & modeswitch_mask) != 0 ? 1 : 0;
long keysym;
if ((event_state & numlock_mask) != 0 && isKeypadKeysym(keysym = getKeySym(event_ptr, group, 1))) {
if ( shift )
keysym = getKeySym(event_ptr, group, 0);
} else {
keysym = getKeySym(event_ptr, group, 0);
if ( shift ^ ((event_state & caps_lock_mask) != 0) )
keysym = toUpper(keysym);
}
return keycode;
return LinuxKeycodes.mapKeySymToLWJGLKeyCode(keysym);
}
private byte getKeyState(int event_type) {
private static byte getKeyState(int event_type) {
switch (event_type) {
case LinuxEvent.KeyPress:
return 1;
@ -307,10 +283,22 @@ final class LinuxKeyboard {
}
}
/** This is called when the window loses focus: we release all currently pressed keys. */
void releaseAll() {
for ( int i = 0; i < key_down_buffer.length; i++ ) {
if ( key_down_buffer[i] != 0 ) {
key_down_buffer[i] = 0;
putKeyboardEvent(i, (byte)0, 0, 0L, false);
}
}
}
private void handleKeyEvent(long event_ptr, long millis, int event_type, int event_keycode, int event_state) {
int keycode = getKeycode(event_ptr, event_state);
byte key_state = getKeyState(event_type);
boolean repeat = key_state == key_down_buffer[keycode];
if ( repeat && event_type == LinuxEvent.KeyRelease ) // This can happen for modifier keys after losing and regaining focus.
return;
key_down_buffer[keycode] = key_state;
long nanos = millis*1000000;
if (event_type == LinuxEvent.KeyPress) {

View file

@ -32,33 +32,151 @@
package org.lwjgl.opengl;
import java.awt.Canvas;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.Insets;
import java.awt.Container;
import java.awt.Component;
import java.awt.Point;
import java.awt.Window;
import java.nio.ByteBuffer;
import javax.swing.SwingUtilities;
import org.lwjgl.LWJGLException;
import org.lwjgl.LWJGLUtil;
/**
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @author kappaOne <one.kappa@gmail.com>
* @version $Revision$
* $Id$
*/
abstract class MacOSXCanvasPeerInfo extends MacOSXPeerInfo {
private final AWTSurfaceLock awt_surface = new AWTSurfaceLock();
public ByteBuffer window_handle;
protected MacOSXCanvasPeerInfo(PixelFormat pixel_format, ContextAttribs attribs, boolean support_pbuffer) throws LWJGLException {
super(pixel_format, attribs, true, true, support_pbuffer, true);
}
protected void initHandle(Canvas component) throws LWJGLException {
// Allow the use of a Core Animation Layer only when using non fullscreen Display.setParent() or AWTGLCanvas
final boolean allowCALayer = ((Display.getParent() != null && !Display.isFullscreen()) || component instanceof AWTGLCanvas) && awt_surface.isApplet(component) && LWJGLUtil.isMacOSXEqualsOrBetterThan(10, 6);
boolean forceCALayer = true;
boolean autoResizable = true; // set the CALayer to autoResize
nInitHandle(awt_surface.lockAndGetHandle(component), getHandle(), allowCALayer);
String javaVersion = System.getProperty("java.version");
if (javaVersion.startsWith("1.5") || javaVersion.startsWith("1.6")) {
// On Java 7 and newer CALayer mode is the only way to use OpenGL with AWT
// therefore force it on all JVM's except for the older Java 5 and Java 6
// where the older cocoaViewRef NSView method maybe be available.
forceCALayer = false;
}
else if (javaVersion.startsWith("1.7")) {
autoResizable = false;
}
Insets insets = getInsets(component);
int top = insets != null ? insets.top : 0;
int left = insets != null ? insets.left : 0;
window_handle = nInitHandle(awt_surface.lockAndGetHandle(component), getHandle(), window_handle, forceCALayer, autoResizable, component.getX()-left, component.getY()-top);
if (javaVersion.startsWith("1.7")) {
// fix for CALayer position not covering Canvas due to a Java 7 bug
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7172187
addComponentListener(component);
reSetLayerBounds(component, getHandle());
}
}
private static native void nInitHandle(ByteBuffer surface_buffer, ByteBuffer peer_info_handle, boolean allowCALayer) throws LWJGLException;
private void addComponentListener(final Canvas component) {
ComponentListener[] components = component.getComponentListeners();
// avoid adding duplicate listners by checking if one has already been added
for (int i = 0; i < components.length; i++) {
ComponentListener c = components[i];
if (c.toString() == "CanvasPeerInfoListener") {
return; // already contains the listner below return without adding
}
}
ComponentListener comp = new ComponentListener() {
public void componentHidden(ComponentEvent e) {
}
public void componentMoved(ComponentEvent e) {
//nSetLayerPosition(getHandle(), component.getX() - left, component.getY() - top);
reSetLayerBounds(component, getHandle());
}
public void componentResized(ComponentEvent e) {
//nSetLayerPosition(getHandle(), component.getX() - left, component.getY() - top);
reSetLayerBounds(component, getHandle());
}
public void componentShown(ComponentEvent e) {
}
public String toString() {
return "CanvasPeerInfoListener";
}
};
component.addComponentListener(comp);
}
private static native ByteBuffer nInitHandle(ByteBuffer surface_buffer, ByteBuffer peer_info_handle, ByteBuffer window_handle, boolean forceCALayer, boolean autoResizable, int x, int y) throws LWJGLException;
private static native void nSetLayerPosition(ByteBuffer peer_info_handle, int x, int y);
private static native void nSetLayerBounds(ByteBuffer peer_info_handle, int x, int y, int width, int height);
/**
* fix for CALayer position not covering Canvas due to a Java 7 bug
* {@link http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7172187}
* @param component
* @param peer_info_handle
*/
private static void reSetLayerBounds(Canvas component, ByteBuffer peer_info_handle) {
// report the root parent (peer).
Component peer = SwingUtilities.getRoot(component);
Point rtLoc = SwingUtilities.convertPoint(component.getParent(), component.getLocation(), peer);
int x = (int) rtLoc.getX(), y = (int) rtLoc.getY();
Insets insets = getInsets(component);
x -= insets != null ? insets.left : 0;
y -= insets != null ? insets.top : 0;
// http://hg.openjdk.java.net/jdk8/awt/jdk/rev/65d874d16d59
y = (int) peer.getHeight() - y - (int) component.getHeight();
nSetLayerBounds(peer_info_handle, x, y, component.getWidth(), component.getHeight());
}
protected void doUnlock() throws LWJGLException {
awt_surface.unlock();
}
/**
* @return rootpane insets (peer insets) values.
*/
private static Insets getInsets(Canvas component) {
Container c = SwingUtilities.getRootPane(component);
if(c != null) {
return c.getInsets();
} else {
return new Insets(0, 0, 0, 0);
}
}
}

View file

@ -35,11 +35,13 @@ package org.lwjgl.opengl;
* This is the Display implementation interface. Display delegates
* to implementors of this interface. There is one DisplayImplementation
* for each supported platform.
* @author elias_naur
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @author mojang
* @author kappaOne <one.kappa@gmail.com>
*/
import java.awt.Canvas;
import java.awt.Cursor;
import java.awt.Robot;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
@ -50,96 +52,171 @@ import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.List;
import org.lwjgl.input.Cursor;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.BufferUtils;
import org.lwjgl.MemoryUtil;
import org.lwjgl.LWJGLException;
import org.lwjgl.LWJGLUtil;
import com.apple.eawt.Application;
import com.apple.eawt.ApplicationAdapter;
import com.apple.eawt.ApplicationEvent;
import static org.lwjgl.opengl.GL11.*;
final class MacOSXDisplay implements DisplayImplementation {
private static final int PBUFFER_HANDLE_SIZE = 24;
private static final int GAMMA_LENGTH = 256;
private MacOSXCanvasListener canvas_listener;
private MacOSXFrame frame;
//private MacOSXCanvasListener canvas_listener;
private Canvas canvas;
private Robot robot;
private MacOSXMouseEventQueue mouse_queue;
private KeyboardEventQueue keyboard_queue;
private java.awt.DisplayMode requested_mode;
/* States */
private DisplayMode requested_mode;
/* Members for native window use */
private MacOSXNativeMouse mouse;
private MacOSXNativeKeyboard keyboard;
private ByteBuffer window;
private ByteBuffer context;
private boolean skipViewportValue = false;
private static final IntBuffer current_viewport = BufferUtils.createIntBuffer(16);
private boolean mouseInsideWindow;
private boolean close_requested;
private boolean native_mode = true;
private boolean updateNativeCursor = false;
private long currentNativeCursor = 0;
private boolean enableHighDPI = false;
private float scaleFactor = 1.0f;
MacOSXDisplay() {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
public Object run() throws Exception {
Application.getApplication().addApplicationListener(new ApplicationAdapter() {
public void handleQuit(ApplicationEvent event) {
doHandleQuit();
}
});
return null;
}
});
} catch (Throwable e) {
/**
* In an applet environment, referencing com.apple.eawt.Application can fail with
* a native exception. So log any exceptions instead of re-throwing.
*/
LWJGLUtil.log("Failed to register quit handler: " + e.getMessage());
}
}
private native ByteBuffer nCreateWindow(int x, int y, int width, int height, boolean fullscreen, boolean undecorated, boolean resizable, boolean parented, boolean enableFullscreenModeAPI, boolean enableHighDPI, ByteBuffer peer_info_handle, ByteBuffer window_handle) throws LWJGLException;
private native Object nGetCurrentDisplayMode();
private native void nGetDisplayModes(Object modesList);
private native boolean nIsMiniaturized(ByteBuffer window_handle);
private native boolean nIsFocused(ByteBuffer window_handle);
private native void nSetResizable(ByteBuffer window_handle, boolean resizable);
private native void nResizeWindow(ByteBuffer window_handle, int x, int y, int width, int height);
private native boolean nWasResized(ByteBuffer window_handle);
private native int nGetX(ByteBuffer window_handle);
private native int nGetY(ByteBuffer window_handle);
private native int nGetWidth(ByteBuffer window_handle);
private native int nGetHeight(ByteBuffer window_handle);
private native boolean nIsNativeMode(ByteBuffer peer_info_handle);
private static boolean isUndecorated() {
return Display.getPrivilegedBoolean("org.lwjgl.opengl.Window.undecorated");
}
public void createWindow(final DrawableLWJGL drawable, DisplayMode mode, Canvas parent, int x, int y) throws LWJGLException {
boolean fullscreen = Display.isFullscreen();
hideUI(fullscreen);
boolean resizable = Display.isResizable();
boolean parented = (parent != null) && !fullscreen;
// OS X fullscreen mode API is only available on OS X 10.7+
boolean enableFullscreenModeAPI = LWJGLUtil.isMacOSXEqualsOrBetterThan(10, 7) && parent == null &&
!Display.getPrivilegedBoolean("org.lwjgl.opengl.Display.disableOSXFullscreenModeAPI");
// OS X high DPI mode is only available on OS X 10.7+
enableHighDPI = LWJGLUtil.isMacOSXEqualsOrBetterThan(10, 7) && parent == null &&
(Display.getPrivilegedBoolean("org.lwjgl.opengl.Display.enableHighDPI") || fullscreen);
if (parented) this.canvas = parent;
else this.canvas = null;
close_requested = false;
DrawableGL gl_drawable = (DrawableGL)Display.getDrawable();
PeerInfo peer_info = gl_drawable.peer_info;
ByteBuffer peer_handle = peer_info.lockAndGetHandle();
ByteBuffer window_handle = parented ? ((MacOSXCanvasPeerInfo)peer_info).window_handle : window;
try {
if (parent == null) {
frame = new MacOSXFrame(mode, requested_mode, fullscreen, x, y);
canvas = frame.getCanvas();
} else {
frame = null;
canvas = parent;
window = nCreateWindow(x, y, mode.getWidth(), mode.getHeight(),
fullscreen, isUndecorated(), resizable,
parented, enableFullscreenModeAPI, enableHighDPI, peer_handle, window_handle);
if (fullscreen) {
// when going to fullscreen viewport is set to screen size by Cocoa, ignore this value
skipViewportValue = true;
// if starting in fullscreen then set initial viewport to displaymode size
current_viewport.put(2, mode.getWidth());
current_viewport.put(3, mode.getHeight());
}
canvas_listener = new MacOSXCanvasListener(canvas);
robot = AWTUtil.createRobot(canvas);
native_mode = nIsNativeMode(peer_handle);
if (!native_mode) {
robot = AWTUtil.createRobot(canvas);
}
} catch (LWJGLException e) {
destroyWindow();
throw e;
} finally {
peer_info.unlock();
}
}
private void doHandleQuit() {
public void doHandleQuit() {
synchronized (this) {
close_requested = true;
}
}
public void mouseInsideWindow(boolean inside) {
synchronized (this) {
mouseInsideWindow = inside;
}
updateNativeCursor = true;
}
public void setScaleFactor(float scale) {
synchronized (this) {
scaleFactor = scale;
}
}
public native void nDestroyCALayer(ByteBuffer peer_info_handle);
public native void nDestroyWindow(ByteBuffer window_handle);
public void destroyWindow() {
if (canvas_listener != null) {
canvas_listener.disableListeners();
canvas_listener = null;
if (!native_mode) {
DrawableGL gl_drawable = (DrawableGL)Display.getDrawable();
PeerInfo peer_info = gl_drawable.peer_info;
if (peer_info != null) {
ByteBuffer peer_handle = peer_info.getHandle();
nDestroyCALayer(peer_handle);
}
robot = null;
}
if (frame != null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
if (MacOSXFrame.getDevice().getFullScreenWindow() == frame)
MacOSXFrame.getDevice().setFullScreenWindow(null);
return null;
}
});
if (frame.isDisplayable())
frame.dispose();
frame = null;
}
hideUI(false);
nDestroyWindow(window);
}
public int getGammaRampLength() {
@ -155,81 +232,80 @@ final class MacOSXDisplay implements DisplayImplementation {
public String getVersion() {
return null;
}
private static boolean equals(java.awt.DisplayMode awt_mode, DisplayMode mode) {
return awt_mode.getWidth() == mode.getWidth() && awt_mode.getHeight() == mode.getHeight()
&& awt_mode.getBitDepth() == mode.getBitsPerPixel() && awt_mode.getRefreshRate() == mode.getFrequency();
private static boolean equals(DisplayMode mode1, DisplayMode mode2) {
return mode1.getWidth() == mode2.getWidth() && mode1.getHeight() == mode2.getHeight()
&& mode1.getBitsPerPixel() == mode2.getBitsPerPixel() && mode1.getFrequency() == mode2.getFrequency();
}
public void switchDisplayMode(DisplayMode mode) throws LWJGLException {
java.awt.DisplayMode[] awt_modes = MacOSXFrame.getDevice().getDisplayModes();
for ( java.awt.DisplayMode awt_mode : awt_modes ) {
if (equals(awt_mode, mode)) {
requested_mode = awt_mode;
DisplayMode[] modes = getAvailableDisplayModes();
for (DisplayMode available_mode : modes) {
if (equals(available_mode, mode)) {
requested_mode = available_mode;
return;
}
}
throw new LWJGLException(mode + " is not supported");
}
public void resetDisplayMode() {
if (MacOSXFrame.getDevice().getFullScreenWindow() != null)
MacOSXFrame.getDevice().setFullScreenWindow(null);
requested_mode = null;
requested_mode = null;
restoreGamma();
}
private native void restoreGamma();
private static DisplayMode createLWJGLDisplayMode(java.awt.DisplayMode awt_mode) {
int bit_depth;
int refresh_rate;
int awt_bit_depth = awt_mode.getBitDepth();
int awt_refresh_rate = awt_mode.getRefreshRate();
if (awt_bit_depth != java.awt.DisplayMode.BIT_DEPTH_MULTI)
bit_depth = awt_bit_depth;
else
bit_depth = 32; // Assume the best bit depth
if (awt_refresh_rate != java.awt.DisplayMode.REFRESH_RATE_UNKNOWN)
refresh_rate = awt_refresh_rate;
else
refresh_rate = 0;
return new DisplayMode(awt_mode.getWidth(), awt_mode.getHeight(), bit_depth, refresh_rate);
public Object createDisplayMode(int width, int height, int bitsPerPixel, int refreshRate) {
return new DisplayMode(width, height, bitsPerPixel, refreshRate);
}
public DisplayMode init() throws LWJGLException {
return createLWJGLDisplayMode(MacOSXFrame.getDevice().getDisplayMode());
return (DisplayMode) nGetCurrentDisplayMode();
}
public void addDisplayMode(Object modesList, int width, int height, int bitsPerPixel, int refreshRate) {
List<DisplayMode> modes = (List<DisplayMode>) modesList;
DisplayMode displayMode = new DisplayMode(width, height, bitsPerPixel, refreshRate);
modes.add(displayMode);
}
public DisplayMode[] getAvailableDisplayModes() throws LWJGLException {
java.awt.DisplayMode[] awt_modes = MacOSXFrame.getDevice().getDisplayModes();
List<DisplayMode> modes = new ArrayList<DisplayMode>();
for ( java.awt.DisplayMode awt_mode : awt_modes )
if ( awt_mode.getBitDepth() >= 16 )
modes.add(createLWJGLDisplayMode(awt_mode));
nGetDisplayModes(modes); // will populate the above list
modes.add(Display.getDesktopDisplayMode()); // add desktop resolution as scaled resolutions do not appear
return modes.toArray(new DisplayMode[modes.size()]);
}
private native void nSetTitle(ByteBuffer window_handle, ByteBuffer title_buffer);
public void setTitle(String title) {
if (frame != null)
frame.setTitle(title);
ByteBuffer buffer = MemoryUtil.encodeUTF8(title);
nSetTitle(window, buffer);
}
public boolean isCloseRequested() {
boolean result;
synchronized (this) {
result = close_requested || (frame != null && frame.syncIsCloseRequested());
result = close_requested;
close_requested = false;
}
return result;
}
public boolean isVisible() {
return frame == null || frame.syncIsVisible();
return true;
}
public boolean isActive() {
return canvas.isFocusOwner();
if (native_mode) {
return nIsFocused(window);
}
else {
return Display.getParent().hasFocus();
}
}
public Canvas getCanvas() {
@ -237,7 +313,7 @@ final class MacOSXDisplay implements DisplayImplementation {
}
public boolean isDirty() {
return frame != null && frame.getCanvas().syncIsDirty();
return false;
}
public PeerInfo createPeerInfo(PixelFormat pixel_format, ContextAttribs attribs) throws LWJGLException {
@ -248,71 +324,37 @@ final class MacOSXDisplay implements DisplayImplementation {
}
}
private static final IntBuffer current_viewport = BufferUtils.createIntBuffer(16);
public void update() {
boolean should_update = canvas_listener.syncShouldUpdateContext();
/*
* Workaround for the "white screen in fullscreen mode" problem
*
* Sometimes, switching from windowed mode to fullscreen or simply creating the Display
* in fullscreen mode will result in the context not being bound to the window correctly.
* The program runs fine, but the canvas background (white) is shown instead of the context
* front buffer.
*
* I've discovered that re-binding the context with another setView() won't fix the problem, while a
* clearDrawable() followed by a setView() does work. A straightforward workaround would be
* to simply run the combination at every update(). This is not sufficient, since the clearDrawable()
* call makes the the background appear shortly, causing visual artifacts.
* What we really need is a way to detect that a setView() failed, and then do the magic combo. I've not
* been able to find such a detection so alternatively I'm triggering the combo if the display is fullscreen
* (I've not seen the white screen problem in windowed mode) and if the canvas has gotten a paint message or
* if its update flag was set.
*
* My testing seems to indicate that the workaround works, since I've not seen the problem after the fix.
*
* - elias
*/
boolean should_update = true;
DrawableGL drawable = (DrawableGL)Display.getDrawable();
if (Display.isFullscreen() && (frame != null && frame.getCanvas().syncCanvasPainted() || should_update)) {
try {
MacOSXContextImplementation.resetView(drawable.peer_info, drawable.context);
} catch (LWJGLException e) {
LWJGLUtil.log("Failed to reset context: " + e);
}
}
if (should_update) {
// Save the current viewport size as cocoa will automatically
// set the viewport size to the window size on context update
if (skipViewportValue) skipViewportValue = false;
else glGetInteger(GL_VIEWPORT, current_viewport);
drawable.context.update();
/* This is necessary to make sure the context won't "forget" about the view size */
glGetInteger(GL_VIEWPORT, current_viewport);
// restore the original viewport size that was set before the update
glViewport(current_viewport.get(0), current_viewport.get(1), current_viewport.get(2), current_viewport.get(3));
}
if (frame != null && mouse_queue != null) {
if (frame.syncShouldReleaseCursor())
MacOSXMouseEventQueue.nGrabMouse(false);
if (frame.syncShouldWarpCursor())
mouse_queue.warpCursor();
if (native_mode && updateNativeCursor) {
updateNativeCursor = false;
try {
setNativeCursor(currentNativeCursor);
} catch (LWJGLException e) {
e.printStackTrace();
}
}
}
/**
* This is an interface to the native Carbon call
* SetSystemUIMode. It is used to hide the dock in a way
* that will prevent AWT from shifting the fullscreen window
*
* The workaround is not necessary on 10.4, and since 10.4 shows
* instability problems calling SetSystemUIMode, we'll only call it
* when the OS version is 10.3 or lower.
*/
private void hideUI(boolean hide) {
if (!LWJGLUtil.isMacOSXEqualsOrBetterThan(10, 4))
nHideUI(hide);
}
private native void nHideUI(boolean hide);
public void reshape(int x, int y, int width, int height) {
if (frame != null)
frame.resize(x, y, width, height);
//if (native_mode) {
// nResizeWindow(window, x, y, width, height);
//}
}
/* Mouse */
@ -325,109 +367,180 @@ final class MacOSXDisplay implements DisplayImplementation {
}
public void createMouse() throws LWJGLException {
this.mouse_queue = new MacOSXMouseEventQueue(canvas);
mouse_queue.register();
if (native_mode) {
mouse = new MacOSXNativeMouse(this, window);
mouse.register();
}
else {
this.mouse_queue = new MacOSXMouseEventQueue(canvas);
mouse_queue.register();
}
}
public void destroyMouse() {
if (mouse_queue != null) {
MacOSXMouseEventQueue.nGrabMouse(false);
mouse_queue.unregister();
if (native_mode) {
// restore default native cursor
try {
MacOSXNativeMouse.setCursor(0);
} catch (LWJGLException e) {};
// release any mouse grab
grabMouse(false);
if (mouse != null) {
mouse.unregister();
}
mouse = null;
}
else {
if (mouse_queue != null) {
MacOSXMouseEventQueue.nGrabMouse(false);
mouse_queue.unregister();
}
this.mouse_queue = null;
}
this.mouse_queue = null;
}
public void pollMouse(IntBuffer coord_buffer, ByteBuffer buttons_buffer) {
mouse_queue.poll(coord_buffer, buttons_buffer);
if (native_mode) {
mouse.poll(coord_buffer, buttons_buffer);
}
else {
mouse_queue.poll(coord_buffer, buttons_buffer);
}
}
public void readMouse(ByteBuffer buffer) {
mouse_queue.copyEvents(buffer);
if (native_mode) {
mouse.copyEvents(buffer);
}
else {
mouse_queue.copyEvents(buffer);
}
}
public void grabMouse(boolean grab) {
mouse_queue.setGrabbed(grab);
if (native_mode) {
mouse.setGrabbed(grab);
}
else {
mouse_queue.setGrabbed(grab);
}
}
public int getNativeCursorCapabilities() {
if (native_mode) {
return Cursor.CURSOR_ONE_BIT_TRANSPARENCY | Cursor.CURSOR_8_BIT_ALPHA | Cursor.CURSOR_ANIMATION;
}
return AWTUtil.getNativeCursorCapabilities();
}
public void setCursorPosition(int x, int y) {
AWTUtil.setCursorPosition(canvas, robot, x, y);
if (native_mode) {
if (mouse != null) {
mouse.setCursorPosition(x, y);
}
}
//else {
//MacOSXMouseEventQueue.nWarpCursor(x, y);
//}
}
public void setNativeCursor(Object handle) throws LWJGLException {
Cursor awt_cursor = (Cursor)handle;
if (frame != null)
frame.setCursor(awt_cursor);
if (native_mode) {
currentNativeCursor = getCursorHandle(handle);
if (Display.isCreated()) {
if (mouseInsideWindow) MacOSXNativeMouse.setCursor(currentNativeCursor);
else MacOSXNativeMouse.setCursor(0); // restore default cursor if outside Display
}
}
}
public int getMinCursorSize() {
return AWTUtil.getMinCursorSize();
return 1;
}
public int getMaxCursorSize() {
return AWTUtil.getMaxCursorSize();
// as there is no max cursor size limit on OS X
// return the max cursor size as half the screen resolution
DisplayMode dm = Display.getDesktopDisplayMode();
return Math.min(dm.getWidth(), dm.getHeight()) / 2;
}
/* Keyboard */
public void createKeyboard() throws LWJGLException {
this.keyboard_queue = new KeyboardEventQueue(canvas);
keyboard_queue.register();
if (native_mode) {
this.keyboard = new MacOSXNativeKeyboard(window);
keyboard.register();
}
else {
this.keyboard_queue = new KeyboardEventQueue(canvas);
keyboard_queue.register();
}
}
public void destroyKeyboard() {
if (keyboard_queue != null)
keyboard_queue.unregister();
this.keyboard_queue = null;
if (native_mode) {
if (keyboard != null) {
keyboard.unregister();
}
keyboard = null;
}
else {
if (keyboard_queue != null) {
keyboard_queue.unregister();
}
this.keyboard_queue = null;
}
}
public void pollKeyboard(ByteBuffer keyDownBuffer) {
keyboard_queue.poll(keyDownBuffer);
if (native_mode) {
keyboard.poll(keyDownBuffer);
}
else {
keyboard_queue.poll(keyDownBuffer);
}
}
public void readKeyboard(ByteBuffer buffer) {
keyboard_queue.copyEvents(buffer);
}
/* public int isStateKeySet(int key) {
int awt_key;
switch (key) {
case Keyboard.KEY_CAPITAL:
awt_key = KeyEvent.VK_CAPS_LOCK;
break;
case Keyboard.KEY_NUMLOCK:
awt_key = KeyEvent.VK_NUM_LOCK;
break;
case Keyboard.KEY_SYSRQ:
awt_key = KeyEvent.VK_SCROLL_LOCK;
break;
default:
return Keyboard.STATE_UNKNOWN;
if (native_mode) {
keyboard.copyEvents(buffer);
}
try {
boolean state = Toolkit.getDefaultToolkit().getLockingKeyState(awt_key);
return state ? Keyboard.STATE_ON : Keyboard.STATE_OFF;
} catch (Exception e) {
LWJGLUtil.log("Failed to query key state: " + e);
return Keyboard.STATE_UNKNOWN;
else {
keyboard_queue.copyEvents(buffer);
}
}
*/
/** Native cursor handles */
public Object createCursor(int width, int height, int xHotspot, int yHotspot, int numImages, IntBuffer images, IntBuffer delays) throws LWJGLException {
return AWTUtil.createCursor(width, height, xHotspot, yHotspot, numImages, images, delays);
if (native_mode) {
long cursor = MacOSXNativeMouse.createCursor(width, height, xHotspot, yHotspot, numImages, images, delays);
return cursor;
}
else {
return AWTUtil.createCursor(width, height, xHotspot, yHotspot, numImages, images, delays);
}
}
public void destroyCursor(Object cursor_handle) {
long handle = getCursorHandle(cursor_handle);
// reset current cursor if same
if (currentNativeCursor == handle) {
currentNativeCursor = 0;
}
MacOSXNativeMouse.destroyCursor(handle);
}
private static long getCursorHandle(Object cursor_handle) {
return cursor_handle != null ? (Long)cursor_handle : 0;
}
public int getPbufferCapabilities() {
if (LWJGLUtil.isMacOSXEqualsOrBetterThan(10, 3))
return Pbuffer.PBUFFER_SUPPORTED;
else
return 0;
return Pbuffer.PBUFFER_SUPPORTED;
}
public boolean isBufferLost(PeerInfo handle) {
@ -465,7 +578,7 @@ final class MacOSXDisplay implements DisplayImplementation {
* @return number of icons used.
*/
public int setIcon(ByteBuffer[] icons) {
/* int size = 0;
/*int size = 0;
int biggest = -1;
for (int i=0;i<icons.length;i++) {
@ -497,31 +610,35 @@ final class MacOSXDisplay implements DisplayImplementation {
}
public int getX() {
return frame.getX();
return nGetX(window);
}
public int getY() {
return frame.getY();
return nGetY(window);
}
public int getWidth() {
return frame.getWidth();
return nGetWidth(window);
}
public int getHeight() {
return frame.getHeight();
return nGetHeight(window);
}
public boolean isInsideWindow() {
return true;
}
public boolean isInsideWindow() {
return mouseInsideWindow;
}
public void setResizable(boolean resizable) {
frame.setResizable(resizable);
public void setResizable(boolean resizable) {
nSetResizable(window, resizable);
}
public boolean wasResized() {
return canvas_listener.wasResized();
return nWasResized(window);
}
public float getPixelScaleFactor() {
return (enableHighDPI && !Display.isFullscreen()) ? scaleFactor : 1f;
}
}

View file

@ -1,238 +0,0 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opengl;
/**
* This is the Mac OS X AWT Frame. It contains thread safe
* methods to manipulateit from non-AWT threads
* @author elias_naur
*/
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import org.lwjgl.LWJGLException;
final class MacOSXFrame extends Frame implements WindowListener, ComponentListener {
private static final long serialVersionUID = -5823294716668988777L;
private final MacOSXGLCanvas canvas;
private boolean close_requested;
/* States */
private Rectangle bounds;
private boolean active;
private boolean minimized;
private boolean should_warp_cursor;
private boolean should_release_cursor;
MacOSXFrame(DisplayMode mode, final java.awt.DisplayMode requested_mode, boolean fullscreen, int x, int y) throws LWJGLException {
setResizable(Display.isResizable());
addWindowListener(this);
addComponentListener(this);
canvas = new MacOSXGLCanvas();
canvas.setFocusTraversalKeysEnabled(false);
add(canvas, BorderLayout.CENTER);
boolean undecorated = Display.getPrivilegedBoolean("org.lwjgl.opengl.Window.undecorated");
setUndecorated(fullscreen || undecorated);
if ( fullscreen ) {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
public Object run() throws Exception {
getDevice().setFullScreenWindow(MacOSXFrame.this);
getDevice().setDisplayMode(requested_mode);
java.awt.DisplayMode real_mode = getDevice().getDisplayMode();
/** For some strange reason, the display mode is sometimes silently capped even though the mode is reported as supported */
if ( requested_mode.getWidth() != real_mode.getWidth() || requested_mode.getHeight() != real_mode.getHeight() ) {
getDevice().setFullScreenWindow(null);
if (isDisplayable())
dispose();
throw new LWJGLException("AWT capped mode: requested mode = " + requested_mode.getWidth() + "x" + requested_mode.getHeight() +
" but got " + real_mode.getWidth() + " " + real_mode.getHeight());
}
return null;
}
});
} catch (PrivilegedActionException e) {
throw new LWJGLException(e);
}
}
pack();
resize(x, y, mode.getWidth(), mode.getHeight());
setVisible(true);
requestFocus();
canvas.requestFocus();
updateBounds();
}
public void resize(int x, int y, int width, int height) {
Insets insets = getInsets();
setBounds(x, y, width + insets.left + insets.right, height + insets.top + insets.bottom);
}
public int getWidth() {
Insets insets = getInsets();
return super.getWidth() - insets.left - insets.right;
}
public int getHeight() {
Insets insets = getInsets();
return super.getHeight() - insets.top - insets.bottom;
}
public Rectangle syncGetBounds() {
synchronized ( this ) {
return bounds;
}
}
public void componentShown(ComponentEvent e) {
}
public void componentHidden(ComponentEvent e) {
}
private void updateBounds() {
synchronized ( this ) {
bounds = getBounds();
}
}
public void componentResized(ComponentEvent e) {
updateBounds();
}
public void componentMoved(ComponentEvent e) {
updateBounds();
}
public static GraphicsDevice getDevice() {
GraphicsEnvironment g_env = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice device = g_env.getDefaultScreenDevice();
return device;
}
public void windowIconified(WindowEvent e) {
synchronized ( this ) {
minimized = true;
}
}
public void windowDeiconified(WindowEvent e) {
synchronized ( this ) {
minimized = false;
}
}
public void windowOpened(WindowEvent e) {
}
public void windowClosed(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
synchronized ( this ) {
close_requested = true;
}
}
public void windowDeactivated(WindowEvent e) {
synchronized ( this ) {
active = false;
should_release_cursor = true;
should_warp_cursor = false;
}
}
public void windowActivated(WindowEvent e) {
synchronized ( this ) {
active = true;
should_warp_cursor = true;
should_release_cursor = false;
}
}
public boolean syncIsCloseRequested() {
boolean result;
synchronized ( this ) {
result = close_requested;
close_requested = false;
}
return result;
}
public boolean syncIsVisible() {
synchronized ( this ) {
return !minimized;
}
}
public boolean syncIsActive() {
synchronized ( this ) {
return active;
}
}
public MacOSXGLCanvas getCanvas() {
return canvas;
}
public boolean syncShouldReleaseCursor() {
boolean result;
synchronized ( this ) {
result = should_release_cursor;
should_release_cursor = false;
}
return result;
}
public boolean syncShouldWarpCursor() {
boolean result;
synchronized ( this ) {
result = should_warp_cursor;
should_warp_cursor = false;
}
return result;
}
}

View file

@ -96,13 +96,13 @@ final class MacOSXMouseEventQueue extends MouseEventQueue {
// If we're going to warp the cursor position, we'll skip the next event to avoid bogus delta values
skip_event = isGrabbed();
}
/* if (isGrabbed()) {
if (isGrabbed()) {
Rectangle bounds = getComponent().getBounds();
Point location_on_screen = getComponent().getLocationOnScreen();
int x = location_on_screen.x + bounds.width/2;
int y = location_on_screen.y + bounds.height/2;
nWarpCursor(x, y);
}*/
}
}
private static native void getMouseDeltas(IntBuffer delta_buffer);
@ -110,4 +110,4 @@ final class MacOSXMouseEventQueue extends MouseEventQueue {
private static native void nWarpCursor(int x, int y);
static native void nGrabMouse(boolean grab);
}
}

View file

@ -0,0 +1,297 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opengl;
/**
* A native implementation of a LWJGL compatible Keyboard event queue.
* @author elias_naur
* @author mojang
*/
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import org.lwjgl.input.Keyboard;
final class MacOSXNativeKeyboard extends EventQueue {
private final byte[] key_states = new byte[Keyboard.KEYBOARD_SIZE];
/** Event scratch array */
private final ByteBuffer event = ByteBuffer.allocate(Keyboard.EVENT_SIZE);
private ByteBuffer window_handle;
private boolean has_deferred_event;
private long deferred_nanos;
private int deferred_key_code;
private byte deferred_key_state;
private int deferred_character;
private HashMap<Short, Integer> nativeToLwjglMap;
MacOSXNativeKeyboard(ByteBuffer window_handle) {
super(Keyboard.EVENT_SIZE);
nativeToLwjglMap = new HashMap<Short, Integer>();
initKeyboardMappings();
this.window_handle = window_handle;
}
private native void nRegisterKeyListener(ByteBuffer window_handle);
private native void nUnregisterKeyListener(ByteBuffer window_handle);
// These are from: <HIToolbox/Events.h>
private void initKeyboardMappings() {
nativeToLwjglMap.put((short)0x1D, Keyboard.KEY_0);
nativeToLwjglMap.put((short)0x12, Keyboard.KEY_1);
nativeToLwjglMap.put((short)0x13, Keyboard.KEY_2);
nativeToLwjglMap.put((short)0x14, Keyboard.KEY_3);
nativeToLwjglMap.put((short)0x15, Keyboard.KEY_4);
nativeToLwjglMap.put((short)0x17, Keyboard.KEY_5);
nativeToLwjglMap.put((short)0x16, Keyboard.KEY_6);
nativeToLwjglMap.put((short)0x1A, Keyboard.KEY_7);
nativeToLwjglMap.put((short)0x1C, Keyboard.KEY_8);
nativeToLwjglMap.put((short)0x19, Keyboard.KEY_9);
nativeToLwjglMap.put((short)0x00, Keyboard.KEY_A);
nativeToLwjglMap.put((short)0x0B, Keyboard.KEY_B);
nativeToLwjglMap.put((short)0x08, Keyboard.KEY_C);
nativeToLwjglMap.put((short)0x02, Keyboard.KEY_D);
nativeToLwjglMap.put((short)0x0E, Keyboard.KEY_E);
nativeToLwjglMap.put((short)0x03, Keyboard.KEY_F);
nativeToLwjglMap.put((short)0x05, Keyboard.KEY_G);
nativeToLwjglMap.put((short)0x04, Keyboard.KEY_H);
nativeToLwjglMap.put((short)0x22, Keyboard.KEY_I);
nativeToLwjglMap.put((short)0x26, Keyboard.KEY_J);
nativeToLwjglMap.put((short)0x28, Keyboard.KEY_K);
nativeToLwjglMap.put((short)0x25, Keyboard.KEY_L);
nativeToLwjglMap.put((short)0x2E, Keyboard.KEY_M);
nativeToLwjglMap.put((short)0x2D, Keyboard.KEY_N);
nativeToLwjglMap.put((short)0x1F, Keyboard.KEY_O);
nativeToLwjglMap.put((short)0x23, Keyboard.KEY_P);
nativeToLwjglMap.put((short)0x0C, Keyboard.KEY_Q);
nativeToLwjglMap.put((short)0x0F, Keyboard.KEY_R);
nativeToLwjglMap.put((short)0x01, Keyboard.KEY_S);
nativeToLwjglMap.put((short)0x11, Keyboard.KEY_T);
nativeToLwjglMap.put((short)0x20, Keyboard.KEY_U);
nativeToLwjglMap.put((short)0x09, Keyboard.KEY_V);
nativeToLwjglMap.put((short)0x0D, Keyboard.KEY_W);
nativeToLwjglMap.put((short)0x07, Keyboard.KEY_X);
nativeToLwjglMap.put((short)0x10, Keyboard.KEY_Y);
nativeToLwjglMap.put((short)0x06, Keyboard.KEY_Z);
nativeToLwjglMap.put((short)0x2A, Keyboard.KEY_BACKSLASH);
nativeToLwjglMap.put((short)0x2B, Keyboard.KEY_COMMA);
nativeToLwjglMap.put((short)0x18, Keyboard.KEY_EQUALS);
nativeToLwjglMap.put((short)0x21, Keyboard.KEY_LBRACKET);
nativeToLwjglMap.put((short)0x1B, Keyboard.KEY_MINUS);
nativeToLwjglMap.put((short)0x27, Keyboard.KEY_APOSTROPHE);
nativeToLwjglMap.put((short)0x1E, Keyboard.KEY_RBRACKET);
nativeToLwjglMap.put((short)0x29, Keyboard.KEY_SEMICOLON);
nativeToLwjglMap.put((short)0x2C, Keyboard.KEY_SLASH);
nativeToLwjglMap.put((short)0x2F, Keyboard.KEY_PERIOD);
nativeToLwjglMap.put((short)0x32, Keyboard.KEY_GRAVE);
nativeToLwjglMap.put((short)0x41, Keyboard.KEY_DECIMAL);
nativeToLwjglMap.put((short)0x43, Keyboard.KEY_MULTIPLY);
nativeToLwjglMap.put((short)0x45, Keyboard.KEY_ADD);
nativeToLwjglMap.put((short)0x47, Keyboard.KEY_CLEAR);
nativeToLwjglMap.put((short)0x4B, Keyboard.KEY_DIVIDE);
nativeToLwjglMap.put((short)0x4C, Keyboard.KEY_NUMPADENTER);
nativeToLwjglMap.put((short)0x4E, Keyboard.KEY_SUBTRACT);
nativeToLwjglMap.put((short)0x51, Keyboard.KEY_NUMPADEQUALS);
nativeToLwjglMap.put((short)0x52, Keyboard.KEY_NUMPAD0);
nativeToLwjglMap.put((short)0x53, Keyboard.KEY_NUMPAD1);
nativeToLwjglMap.put((short)0x54, Keyboard.KEY_NUMPAD2);
nativeToLwjglMap.put((short)0x55, Keyboard.KEY_NUMPAD3);
nativeToLwjglMap.put((short)0x56, Keyboard.KEY_NUMPAD4);
nativeToLwjglMap.put((short)0x57, Keyboard.KEY_NUMPAD5);
nativeToLwjglMap.put((short)0x58, Keyboard.KEY_NUMPAD6);
nativeToLwjglMap.put((short)0x59, Keyboard.KEY_NUMPAD7);
nativeToLwjglMap.put((short)0x5B, Keyboard.KEY_NUMPAD8);
nativeToLwjglMap.put((short)0x5C, Keyboard.KEY_NUMPAD9);
nativeToLwjglMap.put((short)0x24, Keyboard.KEY_RETURN);
nativeToLwjglMap.put((short)0x30, Keyboard.KEY_TAB);
nativeToLwjglMap.put((short)0x31, Keyboard.KEY_SPACE);
nativeToLwjglMap.put((short)0x33, Keyboard.KEY_BACK);
nativeToLwjglMap.put((short)0x35, Keyboard.KEY_ESCAPE);
nativeToLwjglMap.put((short)0x36, Keyboard.KEY_RMETA); // not in Events.h - works on MBP
nativeToLwjglMap.put((short)0x37, Keyboard.KEY_LMETA);
nativeToLwjglMap.put((short)0x38, Keyboard.KEY_LSHIFT);
nativeToLwjglMap.put((short)0x39, Keyboard.KEY_CAPITAL);
nativeToLwjglMap.put((short)0x3A, Keyboard.KEY_LMENU);
nativeToLwjglMap.put((short)0x3B, Keyboard.KEY_LCONTROL);
nativeToLwjglMap.put((short)0x3C, Keyboard.KEY_RSHIFT);
nativeToLwjglMap.put((short)0x3D, Keyboard.KEY_RMENU);
nativeToLwjglMap.put((short)0x3E, Keyboard.KEY_RCONTROL);
nativeToLwjglMap.put((short)0x3F, Keyboard.KEY_FUNCTION);
nativeToLwjglMap.put((short)0x77, Keyboard.KEY_END);
nativeToLwjglMap.put((short)0x7A, Keyboard.KEY_F1);
nativeToLwjglMap.put((short)0x78, Keyboard.KEY_F2);
nativeToLwjglMap.put((short)0x63, Keyboard.KEY_F3);
nativeToLwjglMap.put((short)0x76, Keyboard.KEY_F4);
nativeToLwjglMap.put((short)0x60, Keyboard.KEY_F5);
nativeToLwjglMap.put((short)0x61, Keyboard.KEY_F6);
nativeToLwjglMap.put((short)0x62, Keyboard.KEY_F7);
nativeToLwjglMap.put((short)0x64, Keyboard.KEY_F8);
nativeToLwjglMap.put((short)0x65, Keyboard.KEY_F9);
nativeToLwjglMap.put((short)0x6D, Keyboard.KEY_F10);
nativeToLwjglMap.put((short)0x67, Keyboard.KEY_F11);
nativeToLwjglMap.put((short)0x6F, Keyboard.KEY_F12);
nativeToLwjglMap.put((short)0x69, Keyboard.KEY_F13);
nativeToLwjglMap.put((short)0x6B, Keyboard.KEY_F14);
nativeToLwjglMap.put((short)0x71, Keyboard.KEY_F15);
nativeToLwjglMap.put((short)0x6A, Keyboard.KEY_F16);
nativeToLwjglMap.put((short)0x40, Keyboard.KEY_F17);
nativeToLwjglMap.put((short)0x4F, Keyboard.KEY_F18);
nativeToLwjglMap.put((short)0x50, Keyboard.KEY_F19);
// nativeToLwjglMap.put((short)0x5A, Keyboard.KEY_F20);
nativeToLwjglMap.put((short)0x75, Keyboard.KEY_DELETE);
nativeToLwjglMap.put((short)0x72, Keyboard.KEY_INSERT); // 'Help' in Events.h
nativeToLwjglMap.put((short)0x73, Keyboard.KEY_HOME);
// nativeToLwjglMap.put((short)0xA4, Keyboard.KEY_MUTE);
nativeToLwjglMap.put((short)0x79, Keyboard.KEY_NEXT);
nativeToLwjglMap.put((short)0x74, Keyboard.KEY_PRIOR);
// nativeToLwjglMap.put((short)0x49, Keyboard.KEY_VOLUMEDOWN);
// nativeToLwjglMap.put((short)0x48, Keyboard.KEY_VOLUMEUP);
nativeToLwjglMap.put((short)0x7B, Keyboard.KEY_LEFT);
nativeToLwjglMap.put((short)0x7C, Keyboard.KEY_RIGHT);
nativeToLwjglMap.put((short)0x7D, Keyboard.KEY_DOWN);
nativeToLwjglMap.put((short)0x7E, Keyboard.KEY_UP);
nativeToLwjglMap.put((short)0x0A, Keyboard.KEY_SECTION);
nativeToLwjglMap.put((short)0x6E, Keyboard.KEY_APPS); // not in Events.h
nativeToLwjglMap.put((short)0x129, Keyboard.KEY_COLON); // not in Events.h -- do we need it?
}
public void register() {
nRegisterKeyListener(window_handle);
}
public void unregister() {
nUnregisterKeyListener(window_handle);
}
public void putKeyboardEvent(int key_code, byte state, int character, long nanos, boolean repeat) {
((Buffer)event).clear();
event.putInt(key_code).put(state).putInt(character).putLong(nanos).put(repeat ? (byte)1 : (byte)0);
((Buffer)event).flip();
putEvent(event);
}
public synchronized void poll(ByteBuffer key_down_buffer) {
flushDeferredEvent();
int old_position = key_down_buffer.position();
key_down_buffer.put(key_states);
((Buffer)key_down_buffer).position(old_position);
}
public synchronized void copyEvents(ByteBuffer dest) {
flushDeferredEvent();
super.copyEvents(dest);
}
private synchronized void handleKey(int key_code, byte state, int character, long nanos) {
if (character == KeyEvent.CHAR_UNDEFINED)
character = Keyboard.CHAR_NONE;
if (state == 1) {
boolean repeat = false;
if (has_deferred_event) {
if ((nanos == deferred_nanos && deferred_key_code == key_code)) {
has_deferred_event = false;
repeat = true; // Repeat event
} else
flushDeferredEvent();
}
putKeyEvent(key_code, state, character, nanos, repeat);
} else {
flushDeferredEvent();
has_deferred_event = true;
deferred_nanos = nanos;
deferred_key_code = key_code;
deferred_key_state = state;
deferred_character = character;
}
}
private void flushDeferredEvent() {
if (has_deferred_event) {
putKeyEvent(deferred_key_code, deferred_key_state, deferred_character, deferred_nanos, false);
has_deferred_event = false;
}
}
public void putKeyEvent(int key_code, byte state, int character, long nanos, boolean repeat) {
/* Ignore repeating presses */
int mapped_code = getMappedKeyCode((short)key_code);
if (mapped_code < 0) {
System.out.println("Unrecognized keycode: " + key_code);
/* Unrecognized / unmapped code, do nothing */
return;
}
if ( key_states[mapped_code] == state )
repeat = true;
key_states[mapped_code] = state;
int key_int_char = character & 0xffff;
putKeyboardEvent(mapped_code, state, key_int_char, nanos, repeat);
}
private int getMappedKeyCode(short key_code) {
if (nativeToLwjglMap.containsKey(key_code)) {
return nativeToLwjglMap.get(key_code);
}
return -1;
}
public void keyPressed(int key_code, String chars, long nanos) {
// use only first character of chars returned for key press
int character = (chars == null || chars.length() == 0) ? 0 : (int)chars.charAt(0);
handleKey(key_code, (byte)1, character, nanos);
}
public void keyReleased(int key_code, String chars, long nanos) {
// use only first character of chars returned for key release
int character = (chars == null || chars.length() == 0) ? 0 : (int)chars.charAt(0);
handleKey(key_code, (byte)0, character, nanos);
}
public void keyTyped(KeyEvent e) {
}
}

View file

@ -0,0 +1,229 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opengl;
/**
* A Cocoa implementation of a LWJGL compatible Mouse.
* @author mojang
* @author kappaOne <one.kappa@gmail.com>
*/
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import org.lwjgl.input.Mouse;
import org.lwjgl.LWJGLException;
import java.lang.reflect.*;
import java.lang.Integer;
import java.lang.Long;
import org.lwjgl.BufferUtils;
final class MacOSXNativeMouse extends EventQueue {
private static final int WHEEL_SCALE = 120;
private static final int NUM_BUTTONS = 3;
private ByteBuffer window_handle;
private MacOSXDisplay display;
private boolean grabbed;
/** The accumulated mouse deltas returned by poll() */
private float accum_dx;
private float accum_dy;
private int accum_dz;
/** The last mouse position */
private float last_x;
private float last_y;
/** Saved control key state for ctrl-click right button emulation */
private boolean saved_control_state;
private final ByteBuffer event = ByteBuffer.allocate(Mouse.EVENT_SIZE);
private IntBuffer delta_buffer = BufferUtils.createIntBuffer(2);
private int skip_event;
private final byte[] buttons = new byte[NUM_BUTTONS];
MacOSXNativeMouse(MacOSXDisplay display, ByteBuffer window_handle) {
super(Mouse.EVENT_SIZE);
this.display = display;
this.window_handle = window_handle;
}
private native void nSetCursorPosition(ByteBuffer window_handle, int x, int y);
public static native void nGrabMouse(boolean grab);
private native void nRegisterMouseListener(ByteBuffer window_handle);
private native void nUnregisterMouseListener(ByteBuffer window_handle);
private static native long nCreateCursor(int width, int height, int xHotspot, int yHotspot, int numImages, IntBuffer images, int images_offset, IntBuffer delays, int delays_offset) throws LWJGLException;
private static native void nDestroyCursor(long cursor_handle);
private static native void nSetCursor(long cursor_handle) throws LWJGLException;
public synchronized void register() {
nRegisterMouseListener(window_handle);
}
public static long createCursor(int width, int height, int xHotspot, int yHotspot, int numImages, IntBuffer images, IntBuffer delays) throws LWJGLException {
try {
return nCreateCursor(width, height, xHotspot, yHotspot, numImages, images, images.position(), delays, delays != null ? delays.position() : -1);
} catch (LWJGLException e) {
throw e;
}
}
public static void destroyCursor(long cursor_handle) {
nDestroyCursor(cursor_handle);
}
public static void setCursor(long cursor_handle) throws LWJGLException {
try {
nSetCursor(cursor_handle);
} catch (LWJGLException e) {
throw e;
}
}
public synchronized void setCursorPosition(int x, int y) {
nSetCursorPosition(window_handle, x, y);
}
public synchronized void unregister() {
nUnregisterMouseListener(window_handle);
}
public synchronized void setGrabbed(boolean grabbed) {
this.grabbed = grabbed;
nGrabMouse(grabbed);
skip_event = 1;
accum_dx = accum_dy = 0;
}
public synchronized boolean isGrabbed() {
return grabbed;
}
protected void resetCursorToCenter() {
clearEvents();
accum_dx = accum_dy = 0;
if (display != null) {
last_x = display.getWidth() / 2;
last_y = display.getHeight() / 2;
}
}
private void putMouseEvent(byte button, byte state, int dz, long nanos) {
if (grabbed)
putMouseEventWithCoords(button, state, 0, 0, dz, nanos);
else
putMouseEventWithCoords(button, state, (int)last_x, (int)last_y, dz, nanos);
}
protected void putMouseEventWithCoords(byte button, byte state, int coord1, int coord2, int dz, long nanos) {
((Buffer)event).clear();
event.put(button).put(state).putInt(coord1).putInt(coord2).putInt(dz).putLong(nanos);
((Buffer)event).flip();
putEvent(event);
}
public synchronized void poll(IntBuffer coord_buffer, ByteBuffer buttons_buffer) {
if (grabbed) {
coord_buffer.put(0, (int)accum_dx);
coord_buffer.put(1, (int)accum_dy);
} else {
coord_buffer.put(0, (int)last_x);
coord_buffer.put(1, (int)last_y);
}
coord_buffer.put(2, accum_dz);
accum_dx = accum_dy = accum_dz = 0;
int old_position = buttons_buffer.position();
buttons_buffer.put(buttons, 0, buttons.length);
((Buffer)buttons_buffer).position(old_position);
}
private void setCursorPos(float x, float y, long nanos) {
if ( grabbed )
return;
float dx = x - last_x;
float dy = y - last_y;
addDelta(dx, dy);
last_x = x;
last_y = y;
putMouseEventWithCoords((byte)-1, (byte)0, (int)x, (int)y, 0, nanos);
}
protected void addDelta(float dx, float dy) {
accum_dx += dx;
accum_dy += -dy;
}
public synchronized void setButton(int button, int state, long nanos) {
buttons[button] = (byte)state;
putMouseEvent((byte)button, (byte)state, 0, nanos);
}
public synchronized void mouseMoved(float x, float y, float dx, float dy, float dz, long nanos) {
if (skip_event > 0) {
skip_event--;
if (skip_event == 0) {
last_x = x;
last_y = y;
}
return;
}
if ( dz != 0 ) { // if scroll wheel event
// if no vertical wheel events, then map the horizontal wheel event to it
if (dy == 0) dy = dx;
int wheel_amount = (int)(dy * WHEEL_SCALE);
accum_dz += wheel_amount;
putMouseEvent((byte)-1, (byte)0, wheel_amount, nanos);
}
else if (grabbed) {
if ( dx != 0 || dy != 0 ) {
putMouseEventWithCoords((byte)-1, (byte)0, (int)dx, (int)-dy, 0, nanos);
addDelta(dx, dy);
}
} else {
setCursorPos(x, y, nanos);
}
}
}

View file

@ -45,12 +45,10 @@ import org.lwjgl.LWJGLUtil;
abstract class MacOSXPeerInfo extends PeerInfo {
MacOSXPeerInfo(PixelFormat pixel_format, ContextAttribs attribs, boolean use_display_bpp, boolean support_window, boolean support_pbuffer, boolean double_buffered) throws LWJGLException {
super(createHandle());
if (pixel_format.isFloatingPoint() && !LWJGLUtil.isMacOSXEqualsOrBetterThan(10, 4))
throw new LWJGLException("Floating point pixel format requested, but it requires MacOS X 10.4 or newer");
boolean gl32 = attribs != null && attribs.getMajorVersion() == 3 && attribs.getMinorVersion() == 2 && attribs.isProfileCore();
boolean gl32 = attribs != null && (3 < attribs.getMajorVersion() || (attribs.getMajorVersion() == 3 && 2 <= attribs.getMinorVersion())) && attribs.isProfileCore();
if ( gl32 && !LWJGLUtil.isMacOSXEqualsOrBetterThan(10, 7) )
throw new LWJGLException("OpenGL 3.2 requested, but it requires MacOS X 10.7 or newer");
throw new LWJGLException("OpenGL 3.2+ requested, but it requires MacOS X 10.7 or newer");
choosePixelFormat(pixel_format, gl32, use_display_bpp, support_window, support_pbuffer, double_buffered);
}

View file

@ -81,15 +81,19 @@ class MouseEventQueue extends EventQueue implements MouseListener, MouseMotionLi
public synchronized void register() {
resetCursorToCenter();
component.addMouseListener(this);
component.addMouseMotionListener(this);
component.addMouseWheelListener(this);
if (component != null) {
component.addMouseListener(this);
component.addMouseMotionListener(this);
component.addMouseWheelListener(this);
}
}
public synchronized void unregister() {
component.removeMouseListener(this);
component.removeMouseMotionListener(this);
component.removeMouseWheelListener(this);
if (component != null) {
component.removeMouseListener(this);
component.removeMouseMotionListener(this);
component.removeMouseWheelListener(this);
}
}
protected Component getComponent() {
@ -105,18 +109,23 @@ class MouseEventQueue extends EventQueue implements MouseListener, MouseMotionLi
return grabbed;
}
private int transformY(int y) {
return component.getHeight() - 1 - y;
protected int transformY(int y) {
if (component != null) {
return component.getHeight() - 1 - y;
}
return y;
}
protected void resetCursorToCenter() {
clearEvents();
accum_dx = accum_dy = 0;
Point cursor_location = AWTUtil.getCursorPosition(component);
if (cursor_location != null) {
last_x = cursor_location.x;
last_y = cursor_location.y;
}
if (component != null) {
Point cursor_location = AWTUtil.getCursorPosition(component);
if (cursor_location != null) {
last_x = cursor_location.x;
last_y = cursor_location.y;
}
}
}
private void putMouseEvent(byte button, byte state, int dz, long nanos) {

View file

@ -1,92 +0,0 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opengl;
/**
* An implementation of ContextAttribs using WGL_create_context.
*
* @author spasi <spasi@users.sourceforge.net>
*/
final class WindowsContextAttribs implements ContextAttribsImplementation {
private static final int WGL_CONTEXT_MAJOR_VERSION_ARB = 0x2091;
private static final int WGL_CONTEXT_MINOR_VERSION_ARB = 0x2092;
private static final int WGL_CONTEXT_LAYER_PLANE_ARB = 0x2093;
private static final int WGL_CONTEXT_FLAGS_ARB = 0x2094;
private static final int WGL_CONTEXT_PROFILE_MASK_ARB = 0x9126;
private static final int WGL_CONTEXT_DEBUG_BIT_ARB = 0x0001;
private static final int WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB = 0x0002;
private static final int WGL_CONTEXT_CORE_PROFILE_BIT_ARB = 0x00000001;
private static final int WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB = 0x00000002;
WindowsContextAttribs() {
}
public int getMajorVersionAttrib() {
return WGL_CONTEXT_MAJOR_VERSION_ARB;
}
public int getMinorVersionAttrib() {
return WGL_CONTEXT_MINOR_VERSION_ARB;
}
public int getLayerPlaneAttrib() {
return WGL_CONTEXT_LAYER_PLANE_ARB;
}
public int getFlagsAttrib() {
return WGL_CONTEXT_FLAGS_ARB;
}
public int getDebugBit() {
return WGL_CONTEXT_DEBUG_BIT_ARB;
}
public int getForwardCompatibleBit() {
return WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
}
public int getProfileMaskAttrib() {
return WGL_CONTEXT_PROFILE_MASK_ARB;
}
public int getProfileCoreBit() {
return WGL_CONTEXT_CORE_PROFILE_BIT_ARB;
}
public int getProfileCompatibilityBit() {
return WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB;
}
}

View file

@ -38,8 +38,12 @@ package org.lwjgl.opengl;
* @author elias_naur
*/
import java.awt.*;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.lang.reflect.Method;
import java.nio.*;
import java.awt.Canvas;
import java.util.concurrent.atomic.AtomicBoolean;
import org.lwjgl.LWJGLException;
import org.lwjgl.LWJGLUtil;
@ -49,6 +53,8 @@ import org.lwjgl.input.Cursor;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengles.EGL;
import javax.swing.*;
final class WindowsDisplay implements DisplayImplementation {
private static final int GAMMA_LENGTH = 256;
@ -80,8 +86,10 @@ final class WindowsDisplay implements DisplayImplementation {
private static final int WM_SYSKEYDOWN = 260;
private static final int WM_SYSCHAR = 262;
private static final int WM_CHAR = 258;
private static final int WM_GETICON = 0x007F;
private static final int WM_SETICON = 0x0080;
private static final int WM_SETCURSOR = 0x0020;
private static final int WM_MOUSEACTIVATE = 0x0021;
private static final int WM_QUIT = 0x0012;
private static final int WM_SYSCOMMAND = 0x0112;
@ -150,9 +158,9 @@ final class WindowsDisplay implements DisplayImplementation {
private static final int WS_THICKFRAME = 0x00040000;
private static final int WS_MAXIMIZEBOX = 0x00010000;
private static final int HTCLIENT = 0x01;
private static final int MK_XBUTTON1 = 0x0020;
private static final int MK_XBUTTON2 = 0x0040;
private static final int XBUTTON1 = 0x0001;
@ -163,9 +171,14 @@ final class WindowsDisplay implements DisplayImplementation {
private static boolean cursor_clipped;
private WindowsDisplayPeerInfo peer_info;
private Object current_cursor;
private Canvas parent;
private static boolean hasParent;
private Canvas parent;
private long parent_hwnd;
private FocusAdapter parent_focus_tracker;
private AtomicBoolean parent_focused;
private WindowsKeyboard keyboard;
private WindowsMouse mouse;
@ -183,7 +196,6 @@ final class WindowsDisplay implements DisplayImplementation {
private boolean inAppActivate;
private boolean resized;
private boolean resizable;
private boolean maximized;
private int x;
private int y;
private int width;
@ -194,27 +206,33 @@ final class WindowsDisplay implements DisplayImplementation {
private long small_icon;
private long large_icon;
private boolean iconsLoaded;
private int captureMouse = -1;
private boolean trackingMouse;
private boolean mouseInside;
static {
try {
Method windowProc = WindowsDisplay.class.getDeclaredMethod("handleMessage", long.class, int.class, long.class, long.class, long.class);
setWindowProc(windowProc);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
WindowsDisplay() {
current_display = this;
}
public void createWindow(DrawableLWJGL drawable, DisplayMode mode, Canvas parent, int x, int y) throws LWJGLException {
close_requested = false;
is_dirty = false;
isMinimized = false;
isFocused = false;
redoMakeContextCurrent = false;
maximized = false;
this.parent = parent;
hasParent = parent != null;
long parent_hwnd = parent != null ? getHwnd(parent) : 0;
parent_hwnd = parent != null ? getHwnd(parent) : 0;
this.hwnd = nCreateWindow(x, y, mode.getWidth(), mode.getHeight(), Display.isFullscreen() || isUndecorated(), parent != null, parent_hwnd);
this.resizable=false;
if ( Display.isResizable() && parent == null ) {
setResizable(true);
}
if (hwnd == 0) {
throw new LWJGLException("Failed to create window");
}
@ -238,12 +256,22 @@ final class WindowsDisplay implements DisplayImplementation {
updateWidthAndHeight();
if ( parent == null ) {
if(Display.isResizable()) {
setResizable(true);
}
setForegroundWindow(getHwnd());
setFocus(getHwnd());
} else {
parent_focused = new AtomicBoolean(false);
parent.addFocusListener(parent_focus_tracker = new FocusAdapter() {
public void focusGained(FocusEvent e) {
parent_focused.set(true);
clearAWTFocus();
}
});
SwingUtilities.invokeLater(new Runnable() {
public void run() {
clearAWTFocus();
}
});
}
grabFocus();
} catch (LWJGLException e) {
nReleaseDC(hwnd, hdc);
nDestroyWindow(hwnd);
@ -276,11 +304,25 @@ final class WindowsDisplay implements DisplayImplementation {
}
public void destroyWindow() {
if ( parent != null ) {
parent.removeFocusListener(parent_focus_tracker);
parent_focus_tracker = null;
}
nReleaseDC(hwnd, hdc);
nDestroyWindow(hwnd);
freeLargeIcon();
freeSmallIcon();
resetCursorClipping();
// reset state
close_requested = false;
is_dirty = false;
isMinimized = false;
isFocused = false;
redoMakeContextCurrent = false;
resizable = false;
mouseInside = false;
}
private static native void nReleaseDC(long hwnd, long hdc);
private static native void nDestroyWindow(long hwnd);
@ -323,7 +365,7 @@ final class WindowsDisplay implements DisplayImplementation {
/*
* Called when the application is alt-tabbed to or from
*/
private void appActivate(boolean active) {
private void appActivate(boolean active, long millis) {
if (inAppActivate) {
return;
}
@ -334,25 +376,18 @@ final class WindowsDisplay implements DisplayImplementation {
restoreDisplayMode();
}
if (parent == null) {
if(maximized) {
showWindow(getHwnd(), SW_MAXIMIZE);
} else {
showWindow(getHwnd(), SW_RESTORE);
}
setForegroundWindow(getHwnd());
setFocus(getHwnd());
}
setFocus(getHwnd());
redoMakeContextCurrent = true;
if (Display.isFullscreen())
updateClipping();
} else {
if ( keyboard != null )
keyboard.fireLostKeyEvents();
} else if (Display.isFullscreen()) {
showWindow(getHwnd(), SW_SHOWMINNOACTIVE);
resetDisplayMode();
} else
updateClipping();
keyboard.releaseAll(millis);
if ( Display.isFullscreen() ) {
showWindow(getHwnd(), SW_SHOWMINNOACTIVE);
resetDisplayMode();
}
}
updateCursor();
inAppActivate = false;
}
@ -360,6 +395,26 @@ final class WindowsDisplay implements DisplayImplementation {
private static native void setForegroundWindow(long hwnd);
private static native void setFocus(long hwnd);
private void clearAWTFocus() {
// This is needed so that the last focused component AWT remembers is NOT our Canvas
WindowsDisplay.this.parent.setFocusable(false);
WindowsDisplay.this.parent.setFocusable(true);
// Clear AWT focus owner
KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner();
}
private void grabFocus() {
if ( parent == null )
setFocus(getHwnd());
else
SwingUtilities.invokeLater(new Runnable() {
public void run() {
parent.requestFocus();
}
});
}
private void restoreDisplayMode() {
try {
doSetGammaRamp(current_gamma);
@ -496,9 +551,11 @@ final class WindowsDisplay implements DisplayImplementation {
public void update() {
nUpdate();
if (parent != null && parent.isFocusOwner()) {
if ( !isFocused && parent != null && parent_focused.compareAndSet(true, false) ) {
setFocus(getHwnd());
}
if (redoMakeContextCurrent) {
redoMakeContextCurrent = false;
/**
@ -543,7 +600,7 @@ final class WindowsDisplay implements DisplayImplementation {
}
public void pollMouse(IntBuffer coord_buffer, ByteBuffer buttons) {
mouse.poll(coord_buffer, buttons);
mouse.poll(coord_buffer, buttons, this);
}
public void readMouse(ByteBuffer buffer) {
@ -551,7 +608,7 @@ final class WindowsDisplay implements DisplayImplementation {
}
public void grabMouse(boolean grab) {
mouse.grab(grab, shouldGrab());
mouse.grab(grab);
updateCursor();
}
@ -575,13 +632,15 @@ final class WindowsDisplay implements DisplayImplementation {
private void updateCursor() {
try {
if (mouse != null && shouldGrab())
if (mouse != null && shouldGrab()) {
centerCursor(hwnd);
nSetNativeCursor(getHwnd(), mouse.getBlankCursor());
else
} else
nSetNativeCursor(getHwnd(), current_cursor);
} catch (LWJGLException e) {
LWJGLUtil.log("Failed to update cursor: " + e);
}
updateClipping();
}
static native void nSetNativeCursor(long hwnd, Object handle) throws LWJGLException;
@ -635,11 +694,10 @@ final class WindowsDisplay implements DisplayImplementation {
/* Keyboard */
public void createKeyboard() throws LWJGLException {
keyboard = new WindowsKeyboard(getHwnd());
keyboard = new WindowsKeyboard();
}
public void destroyKeyboard() {
keyboard.destroy();
keyboard = null;
}
@ -752,6 +810,23 @@ final class WindowsDisplay implements DisplayImplementation {
large_icon = large_new_icon;
used++;
done_large = true;
// Problem: The taskbar icon won't update until Windows sends a WM_GETICON to our window proc and we reply. But this method is usually called
// on init and it might take a while before the next call to nUpdate (because of resources being loaded, etc). So we wait for the next
// WM_GETICON message (usually received about 100ms after WM_SETICON) to make sure the taskbar icon has updated before we return to the user.
// (We wouldn't need to do this if the event loop was running continuously on its own thread.)
iconsLoaded = false;
// Track how long the wait takes and give up at 500ms, just in case.
long time = System.nanoTime();
long MAX_WAIT = 500L * 1000L * 1000L;
while ( true ) {
nUpdate();
if ( iconsLoaded || MAX_WAIT < System.nanoTime() - time )
break;
Thread.yield();
}
}
}
@ -780,22 +855,12 @@ final class WindowsDisplay implements DisplayImplementation {
nReleaseCapture();
}
}
if (parent != null && !isFocused) {
setFocus(getHwnd());
}
}
private boolean shouldGrab() {
return !isMinimized && isFocused && Mouse.isGrabbed();
}
private void handleMouseMoved(int x, int y, long millis) {
if (mouse != null) {
mouse.handleMouseMoved(x, y, millis, shouldGrab());
}
}
private static native long nSetCapture(long hwnd);
private static native boolean nReleaseCapture();
@ -815,14 +880,16 @@ final class WindowsDisplay implements DisplayImplementation {
}
private void handleKeyButton(long wParam, long lParam, long millis) {
if ( keyboard == null )
return;
byte previous_state = (byte)((lParam >>> 30) & 0x1);
byte state = (byte)(1 - ((lParam >>> 31) & 0x1));
boolean repeat = state == previous_state; // Repeat message
byte extended = (byte)((lParam >>> 24) & 0x1);
int scan_code = (int)((lParam >>> 16) & 0xFF);
if (keyboard != null) {
keyboard.handleKey((int)wParam, scan_code, extended != 0, state, millis, repeat);
}
keyboard.handleKey((int)wParam, scan_code, extended != 0, state, millis, repeat);
}
private static int transformY(long hwnd, int y) {
@ -833,18 +900,16 @@ final class WindowsDisplay implements DisplayImplementation {
private static native void clientToScreen(long hwnd, IntBuffer point);
private static int handleMessage(long hwnd, int msg, long wParam, long lParam, long millis) {
private static native void setWindowProc(Method windowProc);
private static long handleMessage(long hwnd, int msg, long wParam, long lParam, long millis) {
if (current_display != null)
return current_display.doHandleMessage(hwnd, msg, wParam, lParam, millis);
else
return defWindowProc(hwnd, msg, wParam, lParam);
}
private static native int defWindowProc(long hwnd, int msg, long wParam, long lParam);
private void checkCursorState() {
updateClipping();
}
private static native long defWindowProc(long hwnd, int msg, long wParam, long lParam);
private void updateClipping() {
if ((Display.isFullscreen() || (mouse != null && mouse.isGrabbed())) && !isMinimized && isFocused && (getForegroundWindow() == getHwnd() || hasParent)) {
@ -859,15 +924,37 @@ final class WindowsDisplay implements DisplayImplementation {
}
private void setMinimized(boolean m) {
isMinimized = m;
checkCursorState();
if ( m != isMinimized ) {
isMinimized = m;
updateClipping();
}
}
private int doHandleMessage(long hwnd, int msg, long wParam, long lParam, long millis) {
private long doHandleMessage(long hwnd, int msg, long wParam, long lParam, long millis) {
/*switch ( msg ) {
case 0x0:
case 0x0020:
case 0x0084:
case WM_MOUSEMOVE:
break;
default:
WindowsEventDebug.printMessage(msg, wParam, lParam);
}*/
if ( parent != null && !isFocused ) {
switch ( msg ) {
case WM_LBUTTONDOWN:
case WM_RBUTTONDOWN:
case WM_MBUTTONDOWN:
case WM_XBUTTONDOWN:
sendMessage(parent_hwnd, msg, wParam, lParam);
}
}
switch (msg) {
// disable screen saver and monitor power down messages which wreak havoc
case WM_ACTIVATE:
switch ((int)wParam) {
/*switch ((int)wParam) {
case WA_ACTIVE:
case WA_CLICKACTIVE:
appActivate(true);
@ -875,13 +962,12 @@ final class WindowsDisplay implements DisplayImplementation {
case WA_INACTIVE:
appActivate(false);
break;
}
return 0;
}*/
return 0L;
case WM_SIZE:
switch ((int)wParam) {
case SIZE_RESTORED:
case SIZE_MAXIMIZED:
maximized = ((int)wParam) == SIZE_MAXIMIZED;
resized = true;
updateWidthAndHeight();
setMinimized(false);
@ -890,63 +976,58 @@ final class WindowsDisplay implements DisplayImplementation {
setMinimized(true);
break;
}
return defWindowProc(hwnd, msg, wParam, lParam);
case WM_ENTERSIZEMOVE:
return defWindowProc(hwnd, msg, wParam, lParam);
case WM_EXITSIZEMOVE:
return defWindowProc(hwnd, msg, wParam, lParam);
break;
case WM_SIZING:
resized = true;
updateWidthAndHeight();
return defWindowProc(hwnd, msg, wParam, lParam);
case WM_SETCURSOR:
if((lParam & 0xFFFF) == HTCLIENT) {
// if the cursor is inside the client area, reset it
// to the current LWJGL-cursor
updateCursor();
return -1; //TRUE
} else {
// let Windows handle cursors outside the client area for resizing, etc.
return defWindowProc(hwnd, msg, wParam, lParam);
}
break;
case WM_KILLFOCUS:
appActivate(false);
return 0;
appActivate(false, millis);
return 0L;
case WM_SETFOCUS:
appActivate(true);
return 0;
appActivate(true, millis);
return 0L;
case WM_MOUSEACTIVATE:
if ( parent != null ) {
if ( !isFocused )
grabFocus();
return 3L; // MA_NOACTIVATE
}
break;
case WM_MOUSEMOVE:
int xPos = (int)(short)(lParam & 0xFFFF);
int yPos = transformY(getHwnd(), (int)(short)((lParam >> 16) & 0xFFFF));
handleMouseMoved(xPos, yPos, millis);
checkCursorState();
mouseInside = true;
if(!trackingMouse) {
trackingMouse = nTrackMouseEvent(hwnd);
}
return 0;
if ( mouse != null ) {
int xPos = (short)(lParam & 0xFFFF);
int yPos = transformY(getHwnd(), (short)(lParam >>> 16));
mouse.handleMouseMoved(xPos, yPos, millis);
}
if ( !mouseInside ) {
mouseInside = true;
updateCursor();
nTrackMouseEvent(hwnd);
}
return 0L;
case WM_MOUSEWHEEL:
int dwheel = (int)(short)((wParam >> 16) & 0xFFFF);
handleMouseScrolled(dwheel, millis);
return 0;
return 0L;
case WM_LBUTTONDOWN:
handleMouseButton(0, 1, millis);
return 0;
return 0L;
case WM_LBUTTONUP:
handleMouseButton(0, 0, millis);
return 0;
return 0L;
case WM_RBUTTONDOWN:
handleMouseButton(1, 1, millis);
return 0;
return 0L;
case WM_RBUTTONUP:
handleMouseButton(1, 0, millis);
return 0;
return 0L;
case WM_MBUTTONDOWN:
handleMouseButton(2, 1, millis);
return 0;
return 0L;
case WM_MBUTTONUP:
handleMouseButton(2, 0, millis);
return 0;
return 0L;
case WM_XBUTTONUP:
if((wParam >> 16) == XBUTTON1) {
handleMouseButton(3, 0, millis);
@ -964,8 +1045,13 @@ final class WindowsDisplay implements DisplayImplementation {
case WM_SYSCHAR:
case WM_CHAR:
handleChar(wParam, lParam, millis);
return 0;
return 0L;
case WM_SYSKEYUP:
// Disable WM_SYSCOMMAND/SC_KEYMENU
if ( wParam == WindowsKeycodes.VK_MENU || wParam == WindowsKeycodes.VK_F10 ) {
handleKeyButton(wParam, lParam, millis);
return 0L;
}
/* Fall through */
case WM_KEYUP:
// SysRq apparently only generates WM_KEYUP, so we'll fake a WM_KEYDOWN
@ -982,31 +1068,26 @@ final class WindowsDisplay implements DisplayImplementation {
/* Fall through */
case WM_KEYDOWN:
handleKeyButton(wParam, lParam, millis);
return defWindowProc(hwnd, msg, wParam, lParam);
break;
case WM_QUIT:
close_requested = true;
return 0;
return 0L;
case WM_SYSCOMMAND:
switch ((int)(wParam & 0xfff0)) {
case SC_KEYMENU:
case SC_MOUSEMENU:
case SC_SCREENSAVE:
case SC_MONITORPOWER:
return 0;
return 0L;
case SC_CLOSE:
close_requested = true;
return 0;
default:
break;
return 0L;
}
return defWindowProc(hwnd, msg, wParam, lParam);
break;
case WM_PAINT:
is_dirty = true;
return defWindowProc(hwnd, msg, wParam, lParam);
break;
case WM_MOUSELEAVE:
mouseInside = false;
trackingMouse = false;
return defWindowProc(hwnd, msg, wParam, lParam);
break;
case WM_CANCELMODE:
nReleaseCapture();
/* fall through */
@ -1015,21 +1096,24 @@ final class WindowsDisplay implements DisplayImplementation {
handleMouseButton(captureMouse, 0, millis);
captureMouse = -1;
}
return 0;
return 0L;
case WM_WINDOWPOSCHANGED:
if(getWindowRect(hwnd, rect_buffer)) {
rect.copyFromBuffer(rect_buffer);
x = rect.top;
y = rect.bottom;
x = rect.left;
y = rect.top;
} else {
LWJGLUtil.log("WM_WINDOWPOSCHANGED: Unable to get window rect");
}
return defWindowProc(hwnd, msg, wParam, lParam);
default:
return defWindowProc(hwnd, msg, wParam, lParam);
break;
case WM_GETICON:
iconsLoaded = true;
break;
}
return defWindowProc(hwnd, msg, wParam, lParam);
}
private native boolean getWindowRect(long hwnd, IntBuffer rectBuffer);
public int getX() {
@ -1055,34 +1139,45 @@ final class WindowsDisplay implements DisplayImplementation {
}
public void setResizable(boolean resizable) {
if(this.resizable != resizable) {
long style = getWindowLongPtr(hwnd, GWL_STYLE);
long styleex = getWindowLongPtr(hwnd, GWL_EXSTYLE);
if ( this.resizable == resizable )
return;
// update frame style
if(resizable && !Display.isFullscreen()) {
setWindowLongPtr(hwnd, GWL_STYLE, style |= (WS_THICKFRAME | WS_MAXIMIZEBOX));
} else {
setWindowLongPtr(hwnd, GWL_STYLE, style &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX));
}
// from the existing client rect, determine the new window rect
// based on the style changes - using AdjustWindowRectEx.
getClientRect(hwnd, rect_buffer);
rect.copyFromBuffer(rect_buffer);
adjustWindowRectEx(rect_buffer, style, false, styleex);
rect.copyFromBuffer(rect_buffer);
// force a frame update and resize accordingly
setWindowPos(hwnd, HWND_TOP, 0, 0, rect.right - rect.left, rect.bottom - rect.top, SWP_NOMOVE | SWP_NOZORDER | SWP_FRAMECHANGED);
updateWidthAndHeight();
resized = false;
}
this.resized = false;
this.resizable = resizable;
int style = (int)getWindowLongPtr(hwnd, GWL_STYLE);
int styleex = (int)getWindowLongPtr(hwnd, GWL_EXSTYLE);
// update frame style
setWindowLongPtr(
hwnd,
GWL_STYLE,
style = resizable && !Display.isFullscreen()
? (style | (WS_THICKFRAME | WS_MAXIMIZEBOX))
: (style & ~(WS_THICKFRAME | WS_MAXIMIZEBOX))
);
// from the existing client rect, determine the new window rect
// based on the style changes - using AdjustWindowRectEx.
getGlobalClientRect(hwnd, rect);
rect.copyToBuffer(rect_buffer);
adjustWindowRectEx(rect_buffer, style, false, styleex);
rect.copyFromBuffer(rect_buffer);
// Apply the style changes
setWindowPos(
hwnd, 0L,
rect.left,
rect.top,
rect.right - rect.left,
rect.bottom - rect.top,
SWP_NOZORDER | SWP_FRAMECHANGED
);
updateWidthAndHeight();
}
private native boolean adjustWindowRectEx(IntBuffer rectBuffer, long style, boolean menu, long styleex);
private native boolean adjustWindowRectEx(IntBuffer rectBuffer, int style, boolean menu, int styleex);
public boolean wasResized() {
if(resized) {
@ -1092,39 +1187,49 @@ final class WindowsDisplay implements DisplayImplementation {
return false;
}
public float getPixelScaleFactor() {
return 1f;
}
private static final class Rect {
public int top;
public int bottom;
public int left;
public int right;
public int
left,
top,
right,
bottom;
public void copyToBuffer(IntBuffer buffer) {
buffer.put(0, top).put(1, bottom).put(2, left).put(3, right);
buffer
.put(0, left)
.put(1, top)
.put(2, right)
.put(3, bottom);
}
public void copyFromBuffer(IntBuffer buffer) {
top = buffer.get(0);
bottom = buffer.get(1);
left = buffer.get(2);
right = buffer.get(3);
left = buffer.get(0);
top = buffer.get(1);
right = buffer.get(2);
bottom = buffer.get(3);
}
public void offset(int offset_x, int offset_y) {
left += offset_x;
right += offset_x;
top += offset_y;
right += offset_x;
bottom += offset_y;
}
public static void intersect(Rect r1, Rect r2, Rect dst) {
dst.top = Math.max(r1.top, r2.top);
dst.bottom = Math.min(r1.bottom, r2.bottom);
dst.left = Math.max(r1.left, r2.left);
dst.top = Math.max(r1.top, r2.top);
dst.right = Math.min(r1.right, r2.right);
dst.bottom = Math.min(r1.bottom, r2.bottom);
}
public String toString() {
return "Rect: top = " + top + " bottom = " + bottom + " left = " + left + " right = " + right + ", width: " + (right - left) + ", height: " + (bottom - top);
return "Rect: left = " + left + " top = " + top + " right = " + right + " bottom = " + bottom + ", width: " + (right - left) + ", height: " + (bottom - top);
}
}
}
}

View file

@ -39,23 +39,16 @@ package org.lwjgl.opengl;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import org.lwjgl.BufferUtils;
import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
final class WindowsKeyboard {
private static final int MAPVK_VK_TO_VSC = 0;
private static final int BUFFER_SIZE = 50;
private final long hwnd;
private final byte[] key_down_buffer = new byte[Keyboard.KEYBOARD_SIZE];
private final byte[] virt_key_down_buffer = new byte[Keyboard.KEYBOARD_SIZE];
private final EventQueue event_queue = new EventQueue(Keyboard.EVENT_SIZE);
private final ByteBuffer tmp_event = ByteBuffer.allocate(Keyboard.EVENT_SIZE);
private boolean grabbed;
private boolean has_retained_event; // Indicates if we're waiting for a WM_CHAR
private int retained_key_code;
private byte retained_state;
@ -63,31 +56,26 @@ final class WindowsKeyboard {
private long retained_millis;
private boolean retained_repeat;
WindowsKeyboard(long hwnd) throws LWJGLException {
this.hwnd = hwnd;
WindowsKeyboard() throws LWJGLException {
}
private static native boolean isWindowsNT();
public void destroy() {
}
private static native boolean isWindowsNT();
boolean isKeyDown(int lwjgl_keycode) {
return key_down_buffer[lwjgl_keycode] == 1;
}
public void grab(boolean grab) {
if(grab) {
if (!grabbed) {
grabbed = true;
}
} else {
if (grabbed) {
grabbed = false;
}
}
}
void poll(ByteBuffer keyDownBuffer) {
// Handle shift key release while both are pressed.
// Windows will not send an up event for the first button that was released in this case.
// There will only be one up event, for the last button only. We handle this problem
// here, using asynchronous state queries.
if ( isKeyDown(Keyboard.KEY_LSHIFT) && !isKeyPressedAsync(WindowsKeycodes.VK_LSHIFT) )
handleKey(WindowsKeycodes.VK_SHIFT, Keyboard.KEY_LSHIFT, false, (byte)0, 0L, false);
if ( isKeyDown(Keyboard.KEY_RSHIFT) && !isKeyPressedAsync(WindowsKeycodes.VK_RSHIFT) )
handleKey(WindowsKeycodes.VK_SHIFT, Keyboard.KEY_RSHIFT, false, (byte)0, 0L, false);
public void poll(ByteBuffer keyDownBuffer) {
int old_position = keyDownBuffer.position();
keyDownBuffer.put(key_down_buffer);
keyDownBuffer.position(old_position);
@ -97,8 +85,8 @@ final class WindowsKeyboard {
private static native int ToUnicode(int wVirtKey, int wScanCode, ByteBuffer lpKeyState, CharBuffer pwszBuff, int cchBuff, int flags);
private static native int ToAscii(int wVirtKey, int wScanCode, ByteBuffer lpKeyState, ByteBuffer lpChar, int flags);
private static native int GetKeyboardState(ByteBuffer lpKeyState);
private static native int GetKeyState(int virt_key);
private static native int GetAsyncKeyState(int virt_key);
private static native short GetKeyState(int virt_key);
private static native short GetAsyncKeyState(int virt_key);
private void putEvent(int keycode, byte state, int ch, long millis, boolean repeat) {
tmp_event.clear();
@ -107,33 +95,10 @@ final class WindowsKeyboard {
event_queue.putEvent(tmp_event);
}
private boolean checkShiftKey(int virt_key, byte state) {
int key_state = (GetKeyState(virt_key) >>> 15) & 0x1;
int lwjgl_code = WindowsKeycodes.mapVirtualKeyToLWJGLCode(virt_key);
return (key_down_buffer[lwjgl_code] == 1 - state) && (key_state == state);
}
private int translateShift(int scan_code, byte state) {
if (checkShiftKey(WindowsKeycodes.VK_LSHIFT, state)) {
return WindowsKeycodes.VK_LSHIFT;
} else if (checkShiftKey(WindowsKeycodes.VK_RSHIFT, state)) {
return WindowsKeycodes.VK_RSHIFT;
} else {
if (scan_code== 0x2A)
return WindowsKeycodes.VK_LSHIFT;
else {
if (scan_code == 0x36)
return WindowsKeycodes.VK_RSHIFT;
else
return WindowsKeycodes.VK_LSHIFT;
}
}
}
private int translateExtended(int virt_key, int scan_code, byte state, boolean extended) {
private static int translateExtended(int virt_key, int scan_code, boolean extended) {
switch (virt_key) {
case WindowsKeycodes.VK_SHIFT:
return translateShift(scan_code, state);
return scan_code == 0x36 ? WindowsKeycodes.VK_RSHIFT : WindowsKeycodes.VK_LSHIFT;
case WindowsKeycodes.VK_CONTROL:
return extended ? WindowsKeycodes.VK_RCONTROL : WindowsKeycodes.VK_LCONTROL;
case WindowsKeycodes.VK_MENU:
@ -154,8 +119,24 @@ final class WindowsKeyboard {
return (state & 1) == 1;
}
public void handleKey(int virt_key, int scan_code, boolean extended, byte event_state, long millis, boolean repeat) {
virt_key = translateExtended(virt_key, scan_code, event_state, extended);
private static boolean isKeyPressedAsync(int virt_key) {
return (GetAsyncKeyState(virt_key) & 0x8000) != 0;
}
/**
* This is called when the window loses focus: we release all currently pressed keys. If a key has been pressed (or hasn't been released at all), before we
* regain focus, we'll start receiving repeat press events. We'll treat the first of those as a non-repeat press.
*/
void releaseAll(long millis) {
for ( int i = 0; i < virt_key_down_buffer.length; i++ ) {
if ( isKeyPressed(virt_key_down_buffer[i]) ) {
handleKey(i, 0, false, (byte)0, millis, false);
}
}
}
void handleKey(int virt_key, int scan_code, boolean extended, byte event_state, long millis, boolean repeat) {
virt_key = translateExtended(virt_key, scan_code, extended);
if ( !repeat && isKeyPressed(event_state) == isKeyPressed(virt_key_down_buffer[virt_key]) )
return;
@ -164,6 +145,7 @@ final class WindowsKeyboard {
int keycode = WindowsKeycodes.mapVirtualKeyToLWJGLCode(virt_key);
if (keycode < key_down_buffer.length) {
key_down_buffer[keycode] = event_state;
repeat &= isKeyPressed(virt_key_down_buffer[virt_key]); // Treat the first repeat event after releaseAll() as a non-repeat press.
virt_key_down_buffer[virt_key] = event_state;
}
retained_key_code = keycode;
@ -173,15 +155,7 @@ final class WindowsKeyboard {
retained_repeat = repeat;
}
public void fireLostKeyEvents() {
for ( int i = 0; i < virt_key_down_buffer.length; i++ ) {
if ( isKeyPressed(virt_key_down_buffer[i]) && !isKeyPressed(GetAsyncKeyState(i)) )
handleKey(i, 0, false, (byte)0, System.currentTimeMillis(), false);
}
}
public void handleChar(int event_char, long millis, boolean repeat) {
void handleChar(int event_char, long millis, boolean repeat) {
if (has_retained_event && retained_char != 0)
flushRetained();
if (!has_retained_event) {
@ -190,7 +164,7 @@ final class WindowsKeyboard {
retained_char = event_char;
}
public void read(ByteBuffer buffer) {
void read(ByteBuffer buffer) {
flushRetained();
event_queue.copyEvents(buffer);
}

View file

@ -90,7 +90,7 @@ final class WindowsMouse {
return mouse_button_count;
}
public void poll(IntBuffer coord_buffer, ByteBuffer buttons) {
public void poll(IntBuffer coord_buffer, ByteBuffer buttons, WindowsDisplay display) {
for (int i = 0; i < coord_buffer.remaining(); i++)
coord_buffer.put(coord_buffer.position() + i, 0);
int num_buttons = mouse_button_count;
@ -103,6 +103,9 @@ final class WindowsMouse {
if (isGrabbed()) {
coord_buffer.put(coord_buffer.position() + 0, accum_dx);
coord_buffer.put(coord_buffer.position() + 1, accum_dy);
if ( display.isActive() && display.isVisible() && (accum_dx != 0 || accum_dy != 0) )
WindowsDisplay.centerCursor(hwnd);
} else {
coord_buffer.put(coord_buffer.position() + 0, last_x);
coord_buffer.put(coord_buffer.position() + 1, last_y);
@ -132,25 +135,8 @@ final class WindowsMouse {
return blank_cursor;
}
public void grab(boolean grab, boolean should_center) {
if (grab) {
if (!mouse_grabbed) {
mouse_grabbed = true;
if (should_center) {
try {
WindowsDisplay.setupCursorClipping(hwnd);
} catch (LWJGLException e) {
LWJGLUtil.log("Failed to setup cursor clipping: " + e);
}
centerCursor();
}
}
} else {
if (mouse_grabbed) {
mouse_grabbed = false;
WindowsDisplay.resetCursorClipping();
}
}
public void grab(boolean grab) {
mouse_grabbed = grab;
event_queue.clearEvents();
}
@ -159,10 +145,6 @@ final class WindowsMouse {
putMouseEvent((byte)-1, (byte)0, event_dwheel, millis*1000000);
}
private void centerCursor() {
WindowsDisplay.centerCursor(hwnd);
}
public void setPosition(int x, int y) {
this.last_x = x;
this.last_y = y;
@ -172,7 +154,7 @@ final class WindowsMouse {
WindowsDisplay.doDestroyCursor(blank_cursor);
}
public void handleMouseMoved(int x, int y, long millis, boolean should_center) {
public void handleMouseMoved(int x, int y, long millis) {
int dx = x - last_x;
int dy = y - last_y;
if (dx != 0 || dy != 0) {
@ -183,8 +165,6 @@ final class WindowsMouse {
long nanos = millis*1000000;
if (mouse_grabbed) {
putMouseEventWithCoords((byte)-1, (byte)0, dx, dy, 0, nanos);
if (should_center)
centerCursor();
} else {
putMouseEventWithCoords((byte)-1, (byte)0, x, y, 0, nanos);
}

View file

@ -27,126 +27,178 @@
package org.lwjgl.opengl;
import org.lwjgl.LWJGLUtil;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.lwjgl.LWJGLUtil;
/**
* Utility for working with the xrandr commmand-line utility. Assumes
* xrandr v1.2 or higher.
*
* @author ryanm
*/
public class XRandR
{
public class XRandR {
private static Screen[] current;
/**
* Either the screen marked as "primary" (if it is turned on)
* or the one with the largest (current) resolution.
*/
private static String primaryScreenIdentifier;
/**
* Used to save the configuration of all output devices to
* restore it on exit or in case of crash.
*/
private static Screen[] savedConfiguration;
private static Map<String, Screen[]> screens;
private static void populate()
{
if( screens == null )
{
screens = new HashMap<String, Screen[]>();
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
// ProcessBuilder pb = new ProcessBuilder( "xrandr", "-q" );
// pb.redirectErrorStream();
try
{
// Process p= pb.start();
Process p = Runtime.getRuntime().exec( new String[] { "xrandr", "-q" } );
private static void populate() {
if ( screens != null )
return;
List<Screen> currentList = new ArrayList<Screen>();
List<Screen> possibles = new ArrayList<Screen>();
String name = null;
screens = new HashMap<String, Screen[]>();
BufferedReader br = new BufferedReader( new InputStreamReader( p.getInputStream() ) );
String line;
while( ( line = br.readLine() ) != null )
{
line = line.trim();
String[] sa = line.split( "\\s+" );
try {
Process p = Runtime.getRuntime().exec(new String[] { "xrandr", "-q" });
if( "connected".equals(sa[1]) )
{
// found a new screen block
if( name != null )
{
screens.put( name, possibles.toArray( new Screen[ possibles.size() ] ) );
possibles.clear();
}
name = sa[ 0 ];
List<Screen> currentList = new ArrayList<Screen>();
List<Screen> possibles = new ArrayList<Screen>();
String name = null;
// saves the position of the current screen. this is specified in the header of the screen block,
// but required later when parsing the screen modelines
int[] currentScreenPosition = new int[2];
// record the current config
parseScreen( currentList, name, sa[ 2 ] );
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ( (line = br.readLine()) != null ) {
line = line.trim();
String[] sa = WHITESPACE_PATTERN.split(line);
if ( "connected".equals(sa[1]) ) {
// found a new screen block
if ( name != null ) {
screens.put(name, possibles.toArray(new Screen[possibles.size()]));
possibles.clear();
}
else if( Pattern.matches( "\\d*x\\d*", sa[ 0 ] ) )
{
name = sa[0];
// enabled?
if (sa.length > 2) {
// save position of this screen, will be used later when current modeline is parsed
if ( "primary".equals(sa[2]) ) {
parseScreenHeader(currentScreenPosition, sa[3]);
// save primary
primaryScreenIdentifier = name;
} else {
parseScreenHeader(currentScreenPosition, sa[2]);
}
} else {
// disabled screen, no position info available
currentScreenPosition[0] = 0;
currentScreenPosition[1] = 0;
}
} else if ("disconnected".equals(sa[1])) {
// previous screen block is over
if (name != null) {
screens.put(name, possibles.toArray(new Screen[possibles.size()]));
name = null;
}
} else if (name != null) { // only read modelines after a valid screen identifier
Matcher m = SCREEN_MODELINE_PATTERN.matcher(sa[0]);
if ( m.matches() ) {
// found a new mode line
parseScreen( possibles, name, sa[ 0 ] );
parseScreenModeline(
possibles, currentList, name,
Integer.parseInt(m.group(1)), Integer.parseInt(m.group(2)),
sa, currentScreenPosition
);
}
}
screens.put( name, possibles.toArray( new Screen[ possibles.size() ] ) );
current = currentList.toArray(new Screen[currentList.size()]);
}
catch( Throwable e )
{
LWJGLUtil.log( "Exception in XRandR.populate(): " + e.getMessage() );
screens.clear();
current = new Screen[ 0 ];
if (name != null) {
screens.put(name, possibles.toArray(new Screen[possibles.size()]));
}
current = currentList.toArray(new Screen[currentList.size()]);
// set primary to largest screen if not set yet
if ( primaryScreenIdentifier == null ) {
long totalPixels = Long.MIN_VALUE;
for ( Screen screen : current ) {
if ( 1l * screen.width * screen.height > totalPixels ) {
primaryScreenIdentifier = screen.name;
totalPixels = 1l * screen.width * screen.height;
}
}
}
} catch (Throwable e) {
LWJGLUtil.log("Exception in XRandR.populate(): " + e.getMessage());
screens.clear();
current = new Screen[0];
}
}
/**
* @return The current screen configuration, or an empty array if
* xrandr is not supported
* @return The current screen configuration of the primary device,
* or an empty array if xrandr is not supported
*/
public static Screen[] getConfiguration()
{
public static Screen[] getConfiguration() {
populate();
// find and return primary
for ( Screen screen : current ) {
if ( screen.name.equals(primaryScreenIdentifier) ) {
return new Screen[] { screen };
}
}
// problem with primary device, fall back to old behaviour
return current.clone();
}
/**
* @param screens
* The desired screen set, may not be <code>null</code>
* @throws IllegalArgumentException
* if no screens are specified
* @param disableOthers if screens not included in screens should be turned off (true) or left alone (false)
* @param screens The desired screen set, may not be <code>null</code>
*
* @throws IllegalArgumentException if no screens are specified
*/
public static void setConfiguration(Screen... screens)
{
if( screens.length == 0 )
throw new IllegalArgumentException( "Must specify at least one screen" );
public static void setConfiguration(boolean disableOthers, Screen... screens) {
if ( screens.length == 0 )
throw new IllegalArgumentException("Must specify at least one screen");
if ( savedConfiguration == null )
saveConfiguration();
List<String> cmd = new ArrayList<String>();
cmd.add( "xrandr" );
cmd.add("xrandr");
// switch off those in the current set not in the new set
for ( Screen screen : current ) {
boolean found = false;
for ( Screen screen1 : screens ) {
if ( screen1.name.equals(screen.name) ) {
found = true;
break;
if ( disableOthers ) {
// switch off those in the current set not in the new set
for ( Screen screen : current ) {
boolean disable = true;
for ( Screen screen1 : screens ) {
if ( screen1.name.equals(screen.name) ) {
disable = false;
break;
}
}
}
if ( !found ) {
cmd.add("--output");
cmd.add(screen.name);
cmd.add("--off");
if ( disable ) {
cmd.add("--output");
cmd.add(screen.name);
cmd.add("--off");
}
}
}
@ -154,151 +206,196 @@ public class XRandR
for ( Screen screen : screens )
screen.getArgs(cmd);
try
{
// ProcessBuilder pb = new ProcessBuilder( cmd );
// pb.redirectErrorStream();
// Process p = pb.start();
Process p =
Runtime.getRuntime().exec( cmd.toArray( new String[ cmd.size() ] ) );
try {
Process p = Runtime.getRuntime().exec(cmd.toArray(new String[cmd.size()]));
// no output is expected, but check anyway
BufferedReader br = new BufferedReader( new InputStreamReader( p.getInputStream() ) );
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while( ( line = br.readLine() ) != null )
{
LWJGLUtil.log( "Unexpected output from xrandr process: " + line );
while ( (line = br.readLine()) != null ) {
LWJGLUtil.log("Unexpected output from xrandr process: " + line);
}
current = screens;
} catch (IOException e) {
LWJGLUtil.log("XRandR exception in setConfiguration(): " + e.getMessage());
}
catch( IOException e )
{
LWJGLUtil.log( "XRandR exception in setConfiguration(): " + e.getMessage() );
}
/**
* Saves the current configuration for all connected display devices.
* This configuration can be restored on exit/crash by calling
* restoreConfiguration()
*/
private static void saveConfiguration() {
populate();
savedConfiguration = current.clone();
}
/**
* Restores the configuration for all connected display devices.
* Used on exit or in case of a crash to reset all devices.
*/
public static void restoreConfiguration() {
if ( savedConfiguration != null ) {
setConfiguration(true, savedConfiguration);
}
}
/**
* @return the name of connected screens, or an empty array if
* xrandr is not supported
* xrandr is not supported
*/
public static String[] getScreenNames()
{
public static String[] getScreenNames() {
populate();
return screens.keySet().toArray( new String[ screens.size() ] );
return screens.keySet().toArray(new String[screens.size()]);
}
/**
* @param name
*
* @return the possible resolutions of the named screen, or
* <code>null</code> if there is no such screen
* <code>null</code> if there is no such screen
*/
public static Screen[] getResolutions( String name )
{
public static Screen[] getResolutions(String name) {
populate();
// clone the array to prevent held copies being altered
return screens.get(name).clone();
}
private static final Pattern SCREEN_PATTERN1 =
Pattern.compile( "^(\\d+)x(\\d+)\\+(\\d+)\\+(\\d+)$" );
private static final Pattern SCREEN_PATTERN2 = Pattern.compile( "^(\\d+)x(\\d+)$" );
private static final Pattern SCREEN_HEADER_PATTERN = Pattern.compile("^(\\d+)x(\\d+)[+](\\d+)[+](\\d+)$");
private static final Pattern SCREEN_MODELINE_PATTERN = Pattern.compile("^(\\d+)x(\\d+)$");
private static final Pattern FREQ_PATTERN = Pattern.compile("^(\\d+[.]\\d+)(?:\\s*[*])?(?:\\s*[+])?$");
/**
* Parses a screen configuration and adds it to the list if it's
* valid.
* Parses a screen configuration and adds it to one of the lists if valid.
*
* @param list
* the list to add the Screen to if it's valid
* @param name
* the name of this screen
* @param what
* config string, format either widthxheight or
* widthxheight+xPos+yPos
* @param allModes the list to add the Screen to if it's valid
* @param current the list to add the current screen config to
* @param name the name of this screen
* @param modeLine config string
* @param screenPosition position of this screen
*/
private static void parseScreen( List<Screen> list, String name, String what )
{
Matcher m = SCREEN_PATTERN1.matcher( what );
if( !m.matches() )
{
m = SCREEN_PATTERN2.matcher( what );
if( !m.matches() )
{
LWJGLUtil.log( "Did not match: " + what );
private static void parseScreenModeline(List<Screen> allModes, List<Screen> current, String name, int width, int height, String[] modeLine, int[] screenPosition) {
for ( int i = 1; i < modeLine.length; i++ ) {
String freqS = modeLine[i];
if ( "+".equals(freqS) ) {
// previous rate was the "preferred" refresh rate
// no way to get this info to the application, so ignore it
continue;
}
Matcher m = FREQ_PATTERN.matcher(freqS);
if ( !m.matches() ) {
LWJGLUtil.log("Frequency match failed: " + Arrays.toString(modeLine));
return;
}
String freq = m.group(1);
Screen s = new Screen(name, width, height, freq, 0, 0);
if ( freqS.contains("*") ) {
// current mode, save to current list with screen position
current.add(new Screen(name, width, height, freq, screenPosition[0], screenPosition[1]));
// make sure the current mode is always first
allModes.add(0, s);
} else {
// always add to List of all modes without screen position
allModes.add(s);
}
}
int width = Integer.parseInt( m.group( 1 ) );
int height = Integer.parseInt( m.group( 2 ) );
int xpos, ypos;
if( m.groupCount() > 3 )
{
xpos = Integer.parseInt( m.group( 3 ) );
ypos = Integer.parseInt( m.group( 4 ) );
}
else
{
xpos = 0;
ypos = 0;
}
list.add( new Screen( name, width, height, xpos, ypos ) );
}
/**
* Encapsulates the configuration of a monitor. Resolution is
* fixed, position is mutable
* Parses a screen configuration header and extracts information about the position of the screen.
*
* @param screenPosition the int-array to write the position into
* @param resPos String containing resolution and position, from xrandr
*/
private static void parseScreenHeader(int[] screenPosition, String resPos) {
Matcher m = SCREEN_HEADER_PATTERN.matcher(resPos);
if ( !m.matches() ) {
// screen not active!
screenPosition[0] = 0;
screenPosition[1] = 0;
return;
}
screenPosition[0] = Integer.parseInt(m.group(3));
screenPosition[1] = Integer.parseInt(m.group(4));
}
static Screen DisplayModetoScreen(DisplayMode mode) {
populate();
Screen primary = findPrimary(current);
return new Screen(primary.name, mode.getWidth(), mode.getHeight(), Integer.toString(mode.getFrequency()), primary.xPos, primary.yPos);
}
static DisplayMode ScreentoDisplayMode(Screen... screens) {
populate();
Screen primary = findPrimary(screens);
return new DisplayMode(primary.width, primary.height, 24, primary.freq);
}
private static Screen findPrimary(Screen... screens) {
for ( Screen screen : screens ) {
if ( screen.name.equals(primaryScreenIdentifier) ) {
return screen;
}
}
// fallback
return screens[0];
}
/**
* Encapsulates the configuration of a monitor.
* Resolution and freq are fixed, position is mutable
*
* @author ryanm
*/
public static class Screen implements Cloneable
{
/**
* Name for this output
*/
public static class Screen implements Cloneable {
/** Name for this output */
public final String name;
/**
* Width in pixels
*/
/** Width in pixels */
public final int width;
/**
* Height in pixels
*/
/** Height in pixels */
public final int height;
/**
* Position on the x-axis, in pixels
*/
/** Frequency in Hz */
public final int freq;
/** Frequency in Hz, in the original decimal format */
final String freqOriginal;
/** Position on the x-axis, in pixels */
public int xPos;
/**
* Position on the y-axis, in pixels
*/
/** Position on the y-axis, in pixels */
public int yPos;
private Screen( String name, int width, int height, int xPos, int yPos )
{
Screen(String name, int width, int height, String freq, int xPos, int yPos) {
this.name = name;
this.width = width;
this.height = height;
this.freq = (int)Float.parseFloat(freq);
this.freqOriginal = freq;
this.xPos = xPos;
this.yPos = yPos;
}
private void getArgs( List<String> argList )
{
argList.add( "--output" );
argList.add( name );
argList.add( "--mode" );
argList.add( width + "x" + height );
argList.add( "--pos" );
argList.add( xPos + "x" + yPos );
private void getArgs(List<String> argList) {
argList.add("--output");
argList.add(name);
argList.add("--mode");
argList.add(width + "x" + height);
argList.add("--rate");
argList.add(freqOriginal);
argList.add("--pos");
argList.add(xPos + "x" + yPos);
}
//@Override
public String toString()
{
return name + " " + width + "x" + height + " @ " + xPos + "x" + yPos;
public String toString() {
return name + " " + width + "x" + height + " @ " + xPos + "x" + yPos + " with " + freqOriginal + "Hz";
}
}
}

View file

@ -57,11 +57,7 @@ class GLChecks {
/** Static methods only! */
private GLChecks() {
}
static int getBufferObjectSize(int buffer_enum) {
return glGetBufferParameteri(buffer_enum, GLES20.GL_BUFFER_SIZE);
}
/** Helper method to ensure that array buffer objects are disabled. If they are enabled, we'll throw an OpenGLException */
static void ensureArrayVBOdisabled() {
if ( LWJGLUtil.CHECKS && StateTracker.getTracker().arrayBuffer != 0 )

View file

@ -81,7 +81,7 @@ public class HelloOpenCL {
System.out.println(caps);
System.out.println("\t-------------------------");
System.out.println("\tCL_DEVICE_TYPE = " + device.getInfoInt(CL_DEVICE_TYPE));
System.out.println("\tCL_DEVICE_TYPE = " + device.getInfoLong(CL_DEVICE_TYPE));
System.out.println("\tCL_DEVICE_VENDOR_ID = " + device.getInfoInt(CL_DEVICE_VENDOR_ID));
System.out.println("\tCL_DEVICE_MAX_COMPUTE_UNITS = " + device.getInfoInt(CL_DEVICE_MAX_COMPUTE_UNITS));
System.out.println("\tCL_DEVICE_MAX_WORK_ITEM_DIMENSIONS = " + device.getInfoInt(CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS));

View file

@ -2,7 +2,9 @@
#ifdef AMD_FP
#pragma OPENCL EXTENSION cl_amd_fp64 : enable
#else
#pragma OPENCL EXTENSION cl_khr_fp64 : enable
#ifndef CL_VERSION_1_2
#pragma OPENCL EXTENSION cl_khr_fp64 : enable
#endif
#endif
#define varfloat double
#define _255 255.0

View file

@ -74,18 +74,26 @@ public final class VersionTest {
if ( 2 < args.length ) {
for ( int i = 2; i < args.length; i++ ) {
if ( Pattern.matches("[0-9]+", args[i]) )
ca = ca.withLayer(Integer.parseInt(args[i]));
else if ( "debug".equalsIgnoreCase(args[i]) )
ca = ca.withDebug(true);
else if ( "fc".equalsIgnoreCase(args[i]) )
ca = ca.withForwardCompatible(true);
else if ( "core".equalsIgnoreCase(args[i]) )
if ( "core".equalsIgnoreCase(args[i]) )
ca = ca.withProfileCore(true);
else if ( "compatibility".equalsIgnoreCase(args[i]) )
ca = ca.withProfileCompatibility(true);
else if ( "es".equalsIgnoreCase(args[i]) )
ca = ca.withProfileES(true);
else if ( "debug".equalsIgnoreCase(args[i]) )
ca = ca.withDebug(true);
else if ( "fc".equalsIgnoreCase(args[i]) )
ca = ca.withForwardCompatible(true);
else if ( "robust".equalsIgnoreCase(args[i]) )
ca = ca.withRobustAccess(true);
else if ( "reset_isolation".equalsIgnoreCase(args[i]) )
ca = ca.withContextResetIsolation(true);
else if ( "reset_lose".equalsIgnoreCase(args[i]) )
ca = ca.withResetNotificationStrategy(ContextAttribs.LOSE_CONTEXT_ON_RESET_ARB);
else if ( "release_none".equalsIgnoreCase(args[i]) )
ca = ca.withContextReleaseBehavior(ContextAttribs.CONTEXT_RELEASE_BEHAVIOR_NONE_ARB);
else if ( Pattern.matches("[0-9]+", args[i]) )
ca = ca.withLayer(Integer.parseInt(args[i]));
else
argsError("Unknown argument: \'" + args[i] + "\'");
}
@ -120,6 +128,7 @@ public final class VersionTest {
boolean deprecated = false;
try {
glVertex3f(0.0f, 0.0f, 0.0f);
Util.checkGLError();
deprecated = true;
} catch (Throwable t) {}
@ -235,15 +244,19 @@ public final class VersionTest {
private static void argsError(final String msg) {
System.out.println("\nInvalid arguments error: " + msg);
System.out.println("\nUsage: VersionTest <majorVersion> <minorVersion> {'core'|'compatibility', <layer>, 'debug', 'fc'}:\n");
System.out.println("majorVersion\t- Major OpenGL version.");
System.out.println("majorVersion\t- Minor OpenGL version.");
System.out.println("\nUsage: VersionTest <majorVersion> <minorVersion> {'core'|'compatibility'|'es', 'debug', 'fc', 'robust', 'reset_isolation', 'reset_lose', 'release_none', <layer>}:\n");
System.out.println("<majorVersion>\t- Major OpenGL version.");
System.out.println("<majorVersion>\t- Minor OpenGL version.");
System.out.println("core\t- Sets the Core Profile bit (optional, requires 3.2+).");
System.out.println("compatibility\t- Sets the Compatibility Profile bit (optional, requires 3.2+).");
System.out.println("ws\t- Sets the OpenGL ES Profile bit (optional, requires 2.0).");
System.out.println("layer\t- Layer plane (optional).");
System.out.println("es\t- Sets the OpenGL ES Profile bit (optional, requires 2.0).");
System.out.println("debug\t- Enables debug mode (optional).");
System.out.println("fc\t- Enables forward compatibility mode (optional, requires 3.0+).");
System.out.println("robust\t- Enables robust access (optional).");
System.out.println("reset_isolation\t- Enables reset isolation (optional).");
System.out.println("reset_lose\t- Enables lose context on reset (optional).");
System.out.println("release_none\t- Enables release behavior = none (optional).");
System.out.println("<layer>\t- Layer plane (optional).");
cleanup();
System.exit(-1);

View file

@ -40,26 +40,33 @@ package org.lwjgl.test.opengl.multithread;
import org.lwjgl.BufferUtils;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Drawable;
import org.lwjgl.opengl.GLContext;
import org.lwjgl.opengl.GLSync;
import org.lwjgl.util.Color;
import org.lwjgl.util.ReadableColor;
import java.nio.ByteBuffer;
import java.util.concurrent.locks.ReentrantLock;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL32.*;
abstract class BackgroundLoader {
private static final int WIDTH = 32;
private static final int WIDTH = 32;
private static final int HEIGHT = 32;
private static final Object lock = new Object();
// CPU synchronization
private final ReentrantLock lock = new ReentrantLock();
// GPU synchronization
private GLSync fence;
private Drawable drawable;
private boolean running;
private ByteBuffer texture;
private int texID;
private int texID;
protected BackgroundLoader() {
running = true;
@ -73,6 +80,9 @@ abstract class BackgroundLoader {
}
void start() throws LWJGLException {
// The shared context must be created on the main thread.
drawable = getDrawable();
new Thread(new Runnable() {
public void run() {
System.out.println("-- Background Thread started --");
@ -86,7 +96,7 @@ abstract class BackgroundLoader {
}
try {
drawable = getDrawable();
// Make the shared context current in the worker thread
drawable.makeCurrent();
} catch (LWJGLException e) {
throw new RuntimeException(e);
@ -94,19 +104,29 @@ abstract class BackgroundLoader {
System.out.println("** Drawable created **");
synchronized ( lock ) {
// Create a "dummy" texture while we wait for texture IO
createCheckerTexture(Color.RED, Color.WHITE, 2);
// Create a "dummy" texture while we wait for texture IO
createCheckerTexture(Color.RED, Color.WHITE, 2);
texID = glGenTextures();
glBindTexture(GL_TEXTURE_2D, texID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, WIDTH, HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, texture);
lock.lock();
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
texID = glGenTextures();
glBindTexture(GL_TEXTURE_2D, texID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, WIDTH, HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, texture);
glBindTexture(GL_TEXTURE_2D, 0);
}
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBindTexture(GL_TEXTURE_2D, 0);
// OpenGL commands from different contexts may be executed in any order. So we need a way to synchronize
final boolean useFences = GLContext.getCapabilities().OpenGL32;
if ( useFences )
fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
else
glFlush(); // Best we can do without fences. This will force rendering on the main thread to happen after we upload the texture.
lock.unlock();
System.out.println("** Dummy texture created **");
@ -129,14 +149,23 @@ abstract class BackgroundLoader {
else
createGradientTexture(Color.GREEN, Color.YELLOW);
lock.lock();
glBindTexture(GL_TEXTURE_2D, texID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, WIDTH, HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, texture);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, 0);
if ( useFences )
fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
else
glFlush();
lock.unlock();
System.out.println("** Created new gradient texture **");
lastTextureCreated = System.currentTimeMillis();
@ -151,8 +180,15 @@ abstract class BackgroundLoader {
}
int getTexID() {
synchronized ( lock ) {
lock.lock();
try {
if ( fence != null ) {
glWaitSync(fence, 0, GL_TIMEOUT_IGNORED);
fence = null;
}
return texID;
} finally {
lock.unlock();
}
}

View file

@ -129,6 +129,7 @@ public final class SpriteShootout {
//Display.create(new PixelFormat(), new ContextAttribs(4, 1).withProfileCompatibility(true).withDebug(true));
//AMDDebugOutput.glDebugMessageCallbackAMD(new AMDDebugOutputCallback());
final ContextCapabilities caps = GLContext.getCapabilities();
if ( !GLContext.getCapabilities().OpenGL20 )
throw new RuntimeException("OpenGL 2.0 is required for this demo.");
@ -167,10 +168,12 @@ public final class SpriteShootout {
glDepthMask(false);
glDisable(GL_DEPTH_TEST);
if ( caps.GL_ARB_compatibility || !caps.OpenGL31 )
glEnable(GL_POINT_SPRITE);
// Setup geometry
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
Util.checkGLError();
}
@ -412,8 +415,6 @@ public final class SpriteShootout {
glUniform1i(glGetUniformLocation(progID, "COLOR_MAP"), 0);
updateBallSize();
glEnableClientState(GL_VERTEX_ARRAY);
}
public void updateBallSize() {

View file

@ -166,10 +166,12 @@ public final class SpriteShootout2P {
glDepthFunc(GL_LESS);
glClearDepth(1.0f);
if ( caps.GL_ARB_compatibility || !caps.OpenGL31 )
glEnable(GL_POINT_SPRITE);
// Setup geometry
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
Util.checkGLError();
}

View file

@ -39,10 +39,10 @@ import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opencl.*;
import org.lwjgl.opencl.api.Filter;
import org.lwjgl.opengl.ContextCapabilities;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GLContext;
import org.lwjgl.opengl.Util;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
@ -140,19 +140,23 @@ public final class SpriteShootoutCL {
if ( platforms == null )
throw new RuntimeException("No OpenCL platforms found.");
final CLPlatform platform = platforms.get(0);
final PointerBuffer ctxProps = BufferUtils.createPointerBuffer(3);
ctxProps.put(CL_CONTEXT_PLATFORM).put(platform.getPointer()).put(0).flip();
// Find devices with GL sharing support
final Filter<CLDevice> glSharingFilter = new Filter<CLDevice>() {
public boolean accept(final CLDevice device) {
final CLDeviceCapabilities caps = CLCapabilities.getDeviceCapabilities(device);
return caps.CL_KHR_gl_sharing;
}
};
final List<CLDevice> devices = platform.getDevices(CL_DEVICE_TYPE_GPU, glSharingFilter);
CLPlatform platform = null;
List<CLDevice> devices = null;
for ( CLPlatform p : platforms ) {
// Find devices with GL sharing support
devices = p.getDevices(CL_DEVICE_TYPE_GPU, glSharingFilter);
if ( devices != null ) {
platform = p;
break;
}
}
if ( devices == null )
throw new RuntimeException("No OpenCL GPU device found.");
@ -180,7 +184,8 @@ public final class SpriteShootoutCL {
Display.setTitle("Sprite Shootout - CL");
Display.create();
if ( !GLContext.getCapabilities().OpenGL20 )
final ContextCapabilities caps = GLContext.getCapabilities();
if ( !caps.OpenGL20 )
throw new RuntimeException("OpenGL 2.0 is required for this demo.");
// Setup viewport
@ -218,9 +223,12 @@ public final class SpriteShootoutCL {
glDepthMask(false);
glDisable(GL_DEPTH_TEST);
if ( caps.GL_ARB_compatibility || !caps.OpenGL31 )
glEnable(GL_POINT_SPRITE);
// Setup geometry
Util.checkGLError();
org.lwjgl.opengl.Util.checkGLError();
}
private static int createTexture(final String path) throws IOException {
@ -541,7 +549,7 @@ public final class SpriteShootoutCL {
createProgram(vshID);
Util.checkGLError();
org.lwjgl.opengl.Util.checkGLError();
createKernel("kernel void animate(\n" +
" const int WIDTH,\n" +

View file

@ -181,7 +181,6 @@ public final class SpriteShootoutMapped {
// Setup geometry
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
Util.checkGLError();
}

View file

@ -218,7 +218,7 @@ public class WaveData {
&& total < buf.length) {
total += read;
}
buffer = convertAudioBytes(buf, audioformat.getSampleSizeInBits() == 16);
buffer = convertAudioBytes(buf, audioformat.getSampleSizeInBits() == 16, audioformat.isBigEndian() ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);
} catch (IOException ioe) {
return null;
}
@ -237,11 +237,11 @@ public class WaveData {
return wavedata;
}
private static ByteBuffer convertAudioBytes(byte[] audio_bytes, boolean two_bytes_data) {
private static ByteBuffer convertAudioBytes(byte[] audio_bytes, boolean two_bytes_data, ByteOrder order) {
ByteBuffer dest = ByteBuffer.allocateDirect(audio_bytes.length);
dest.order(ByteOrder.nativeOrder());
ByteBuffer src = ByteBuffer.wrap(audio_bytes);
src.order(ByteOrder.LITTLE_ENDIAN);
src.order(order);
if (two_bytes_data) {
ShortBuffer dest_short = dest.asShortBuffer();
ShortBuffer src_short = src.asShortBuffer();

View file

@ -31,6 +31,8 @@
*/
package org.lwjgl.util.applet;
import org.lwjgl.LWJGLUtil;
import java.applet.Applet;
import java.applet.AppletStub;
import java.awt.BorderLayout;
@ -56,7 +58,6 @@ import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.JarURLConnection;
import java.net.SocketPermission;
@ -70,7 +71,6 @@ import java.security.CodeSource;
import java.security.PermissionCollection;
import java.security.Permissions;
import java.security.PrivilegedExceptionAction;
import java.security.SecureClassLoader;
import java.security.cert.Certificate;
import java.util.Enumeration;
import java.util.HashMap;
@ -85,7 +85,6 @@ import java.util.concurrent.Future;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.jar.Pack200;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
import java.util.zip.GZIPInputStream;
@ -113,6 +112,7 @@ import java.util.zip.ZipFile;
* <li>al_mac - [String] Jar containing native files for mac.</li>
* <li>al_solaris - [String] Jar containing native files for solaris.</li>
* <li>al_freebsd - [String] Jar containing native files for freebsd.</li>
* <li>al_openbsd - [String] Jar containing native files for openbsd.</li>
* </ul>
* </p>
* <p>
@ -375,12 +375,12 @@ public class AppletLoader extends Applet implements Runnable, AppletStub {
}
// check pack200 support
try {
java.util.jar.Pack200.class.getSimpleName();
pack200Supported = true;
} catch (Throwable e) {
/* no pack200 support */
}
// try {
// java.util.jar.Pack200.class.getSimpleName();
// pack200Supported = true;
// } catch (Throwable e) {
// /* no pack200 support */
// }
}
/**
@ -777,6 +777,8 @@ public class AppletLoader extends Applet implements Runnable, AppletStub {
nativeJarList = getParameter("al_solaris");
} else if (osName.startsWith("FreeBSD")) {
nativeJarList = getParameter("al_freebsd");
} else if (osName.startsWith("OpenBSD")) {
nativeJarList = getParameter("al_openbsd");
} else {
fatalErrorOccured("OS (" + osName + ") not supported", null);
return;
@ -1189,24 +1191,16 @@ public class AppletLoader extends Applet implements Runnable, AppletStub {
PermissionCollection perms = null;
try {
// if mac, apply workaround for the multiple security dialog issue
if (isMacOS) {
// if certificates match the AppletLoader certificates then don't use SecureClassLoader to get further permissions
if (certificatesMatch(certs, codesource.getCertificates())) {
perms = new Permissions();
perms.add(new AllPermission());
return perms;
}
}
// no permissions
perms = new Permissions();
// getPermissions from original classloader is important as it checks for signed jars and shows any security dialogs needed
Method method = SecureClassLoader.class.getDeclaredMethod("getPermissions", new Class[] { CodeSource.class });
method.setAccessible(true);
perms = (PermissionCollection)method.invoke(getClass().getClassLoader(), new Object[] {codesource});
// if certificates match the AppletLoader certificates then we should be all set
if (certificatesMatch(certs, codesource.getCertificates())) {
perms.add(new AllPermission());
return perms;
}
String host = getCodeBase().getHost();
if (host != null && (host.length() > 0)) {
// add permission for downloaded jars to access host they were from
perms.add(new SocketPermission(host, "connect,accept"));
@ -1226,7 +1220,7 @@ public class AppletLoader extends Applet implements Runnable, AppletStub {
// allow non lwjgl native to be found from cache directory
protected String findLibrary (String libname) {
String libPath = path + "natives" + File.separator + System.mapLibraryName(libname);
String libPath = path + "natives" + File.separator + LWJGLUtil.mapLibraryName(libname);
if (new File(libPath).exists()) {
return libPath;
@ -1685,20 +1679,21 @@ public class AppletLoader extends Applet implements Runnable, AppletStub {
* @throws Exception if any errors occur
*/
protected void extractPack(String in, String out) throws Exception {
File f = new File(in);
FileOutputStream fostream = new FileOutputStream(out);
JarOutputStream jostream = new JarOutputStream(fostream);
throw new UnsupportedOperationException();
// File f = new File(in);
// FileOutputStream fostream = new FileOutputStream(out);
// JarOutputStream jostream = new JarOutputStream(fostream);
try {
Pack200.Unpacker unpacker = Pack200.newUnpacker();
unpacker.unpack(f, jostream);
} finally {
jostream.close();
fostream.close();
}
// try {
// Pack200.Unpacker unpacker = Pack200.newUnpacker();
// unpacker.unpack(f, jostream);
// } finally {
// jostream.close();
// fostream.close();
// }
// delete pack file as its no longer needed
f.delete();
// // delete pack file as its no longer needed
// f.delete();
}
/**
@ -1877,8 +1872,8 @@ public class AppletLoader extends Applet implements Runnable, AppletStub {
/**
* Compare two certificate chains to see if they match
*
* @param cert1 first chain of certificates
* @param cert2 second chain of certificates
* @param certs1 first chain of certificates
* @param certs2 second chain of certificates
*
* @return true if the certificate chains are the same
*/
@ -2234,7 +2229,7 @@ public class AppletLoader extends Applet implements Runnable, AppletStub {
/**
* set the state of applet loader
* @param new state of applet loader
* @param state new state of applet loader
* */
protected void setState(int state) {
this.state = state;
@ -2266,4 +2261,4 @@ public class AppletLoader extends Applet implements Runnable, AppletStub {
}
}
}
}

View file

@ -46,4 +46,7 @@ public @interface Extension {
String className() default "";
boolean isFinal() default true;
String postfix();
/** The extension name as it appears in the extension string. The default is the API prefix followed by the interface name, converted to lower-case. */
String nativeName() default "";
}

View file

@ -29,22 +29,23 @@
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator;
import java.io.PrintWriter;
import java.util.Collection;
import com.sun.mirror.declaration.FieldDeclaration;
import com.sun.mirror.declaration.Modifier;
import com.sun.mirror.type.PrimitiveType;
import com.sun.mirror.type.TypeMirror;
import java.util.Set;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.PrimitiveType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
public class FieldsGenerator {
private static void validateField(FieldDeclaration field) {
private static void validateField(VariableElement field) {
// Check if field is "public static final"
Collection<Modifier> modifiers = field.getModifiers();
Set<Modifier> modifiers = field.getModifiers();
if ( modifiers.size() != 3
|| !modifiers.contains(Modifier.PUBLIC)
|| !modifiers.contains(Modifier.STATIC)
@ -53,17 +54,17 @@ public class FieldsGenerator {
}
// Check suported types (int, long, float, String)
TypeMirror field_type = field.getType();
if ( field_type instanceof PrimitiveType ) {
TypeMirror field_type = field.asType();
if ( "java.lang.String".equals(field_type.toString()) ) {
} else if ( field_type instanceof PrimitiveType ) {
PrimitiveType field_type_prim = (PrimitiveType)field_type;
PrimitiveType.Kind field_kind = field_type_prim.getKind();
if ( field_kind != PrimitiveType.Kind.INT
&& field_kind != PrimitiveType.Kind.LONG
&& field_kind != PrimitiveType.Kind.FLOAT
&& field_kind != PrimitiveType.Kind.BYTE ) {
throw new RuntimeException("Field " + field.getSimpleName() + " is not of type 'int', 'long' or 'float'");
TypeKind field_kind = field_type_prim.getKind();
if ( field_kind != TypeKind.INT
&& field_kind != TypeKind.LONG
&& field_kind != TypeKind.FLOAT
&& field_kind != TypeKind.BYTE ) {
throw new RuntimeException("Field " + field.getSimpleName() + " is not of type 'int', 'long', 'float' or 'byte' " + field_kind.toString());
}
} else if ( "java.lang.String".equals(field_type.toString()) ) {
} else {
throw new RuntimeException("Field " + field.getSimpleName() + " is not a primitive type or String");
}
@ -74,7 +75,7 @@ public class FieldsGenerator {
}
}
private static void generateField(PrintWriter writer, FieldDeclaration field, FieldDeclaration prev_field) {
private static void generateField(PrintWriter writer, VariableElement field, VariableElement prev_field, ProcessingEnvironment env) {
validateField(field);
Object value = field.getConstantValue();
@ -94,31 +95,33 @@ public class FieldsGenerator {
throw new RuntimeException("Field is of unexpected type. This means there is a bug in validateField().");
}
boolean hadDoc = prev_field != null && prev_field.getDocComment() != null;
boolean hasDoc = field.getDocComment() != null;
boolean newBatch = prev_field == null || !prev_field.getType().equals(field.getType()) || (!hadDoc && field.getDocComment() != null) || (hadDoc && hasDoc && !prev_field.getDocComment().equals(field.getDocComment()));
boolean hadDoc = prev_field != null && env.getElementUtils().getDocComment(prev_field) != null;
boolean hasDoc = env.getElementUtils().getDocComment(field) != null;
boolean newBatch = prev_field == null || !prev_field.asType().equals(field.asType()) || (!hadDoc && env.getElementUtils().getDocComment(field) != null) || (hadDoc && hasDoc && !env.getElementUtils().getDocComment(prev_field).equals(env.getElementUtils().getDocComment(field)));
// Print field declaration
if ( newBatch ) {
if ( prev_field != null )
if ( prev_field != null ) {
writer.println(";\n");
}
Utils.printDocComment(writer, field);
writer.print("\tpublic static final " + field.getType().toString() + " " + field.getSimpleName() + " = " + field_value_string);
} else
Utils.printDocComment(writer, field, env);
writer.print("\tpublic static final " + field.asType().toString() + " " + field.getSimpleName() + " = " + field_value_string);
} else {
writer.print(",\n\t\t" + field.getSimpleName() + " = " + field_value_string);
}
}
public static void generateFields(PrintWriter writer, Collection<FieldDeclaration> fields) {
public static void generateFields(ProcessingEnvironment env, PrintWriter writer, Collection<? extends VariableElement> fields) {
if ( 0 < fields.size() ) {
writer.println();
FieldDeclaration prev_field = null;
for ( FieldDeclaration field : fields ) {
generateField(writer, field, prev_field);
VariableElement prev_field = null;
for ( VariableElement field : fields ) {
generateField(writer, field, prev_field, env);
prev_field = field;
}
writer.println(";");
}
}
}
}

View file

@ -0,0 +1,140 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator;
import java.io.File;
import java.io.FileFilter;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.ElementFilter;
import javax.tools.Diagnostic;
/**
* Generator tool for creating the java classes and native code from an
* annotated template java interface.
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision$ $Id$
*/
@SupportedAnnotationTypes({ "*" })
@SupportedSourceVersion(SourceVersion.RELEASE_7)
@SupportedOptions({ "binpath", "typemap", "generatechecks", "contextspecific" })
public class GeneratorProcessor extends AbstractProcessor {
private static boolean first_round = true;
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if ( roundEnv.processingOver() || !first_round ) {
System.exit(0);
return true;
}
Map<String, String> options = processingEnv.getOptions();
String typemap_classname = options.get("typemap");
String bin_path = options.get("binpath");
boolean generate_error_checks = options.containsKey("generatechecks");
boolean context_specific = options.containsKey("contextspecific");
if ( bin_path == null ) {
throw new RuntimeException("No path specified for the bin directory with -Abinpath=<path>");
}
if ( typemap_classname == null ) {
throw new RuntimeException("No TypeMap class name specified with -Atypemap=<class-name>");
}
Element lastFile = null;
try {
long generatorLM = getGeneratorLastModified(bin_path);
TypeMap type_map = (TypeMap)(Class.forName(typemap_classname).newInstance());
for ( Iterator<TypeElement> it = ElementFilter.typesIn(roundEnv.getRootElements()).iterator(); it.hasNext(); ) {
lastFile = it.next();
lastFile.accept(new GeneratorVisitor(processingEnv, type_map, generate_error_checks, context_specific, generatorLM), null);
}
first_round = false;
return true;
} catch (Exception e) {
if ( lastFile == null ) {
throw new RuntimeException(e);
} else {
throw new RuntimeException("\n-- Failed to process template: " + lastFile.asType().toString() + " --", e);
}
}
}
/**
* Gets the time of the latest change on the Generator classes.
*
* @return time of the latest change
*/
private static long getGeneratorLastModified(final String bin_path) {
long lastModified = getDirectoryLastModified(bin_path, "/org/lwjgl/util/generator");
lastModified = Math.max(lastModified, getDirectoryLastModified(bin_path, "/org/lwjgl/util/generator/openal"));
lastModified = Math.max(lastModified, getDirectoryLastModified(bin_path, "/org/lwjgl/util/generator/opengl"));
lastModified = Math.max(lastModified, getDirectoryLastModified(bin_path, "/org/lwjgl/util/generator/opencl"));
return lastModified;
}
private static long getDirectoryLastModified(final String bin_path, final String path) {
final File pck = new File(bin_path + path);
if ( !pck.exists() || !pck.isDirectory() ) {
return Long.MAX_VALUE;
}
final File[] classes = pck.listFiles(new FileFilter() {
public boolean accept(final File pathname) {
return pathname.isFile() && pathname.getName().endsWith(".class");
}
});
if ( classes == null || classes.length == 0 ) {
return Long.MAX_VALUE;
}
long lastModified = 0;
for ( File clazz : classes ) {
long lm = clazz.lastModified();
if ( lastModified < lm ) {
lastModified = lm;
}
}
return lastModified;
}
}

View file

@ -1,176 +0,0 @@
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator;
import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import com.sun.mirror.apt.*;
import com.sun.mirror.declaration.AnnotationTypeDeclaration;
import com.sun.mirror.declaration.TypeDeclaration;
import static com.sun.mirror.util.DeclarationVisitors.*;
import static java.util.Collections.*;
/**
* Generator tool for creating the java classes and native code
* from an annotated template java interface.
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision$
* $Id$
*/
public class GeneratorProcessorFactory implements AnnotationProcessorFactory, RoundCompleteListener {
private static boolean first_round = true;
// Process any set of annotations
private static final Collection<String> supportedAnnotations =
unmodifiableCollection(Arrays.asList("*"));
private static final Collection<String> supportedOptions =
unmodifiableCollection(Arrays.asList("-Atypemap", "-Ageneratechecks", "-Acontextspecific"));
public Collection<String> supportedAnnotationTypes() {
return supportedAnnotations;
}
public Collection<String> supportedOptions() {
return supportedOptions;
}
public void roundComplete(RoundCompleteEvent event) {
first_round = false;
}
public AnnotationProcessor getProcessorFor(Set<AnnotationTypeDeclaration> atds, AnnotationProcessorEnvironment env) {
// Only process the initial types, not the generated ones
if ( first_round ) {
env.addListener(this);
return new GeneratorProcessor(env);
} else
return AnnotationProcessors.NO_OP;
}
private static class GeneratorProcessor implements AnnotationProcessor {
private final AnnotationProcessorEnvironment env;
GeneratorProcessor(AnnotationProcessorEnvironment env) {
this.env = env;
}
public void process() {
Map<String, String> options = env.getOptions();
String typemap_classname = null;
String bin_path = null;
boolean generate_error_checks = options.containsKey("-Ageneratechecks");
boolean context_specific = options.containsKey("-Acontextspecific");
for ( String k : options.keySet() ) {
if ( !k.startsWith("-A") )
continue;
int delimiter = k.indexOf('=');
if ( delimiter != -1 ) {
if ( k.startsWith("-Atypemap") ) {
typemap_classname = k.substring(delimiter + 1);
} else if ( k.startsWith("-Abinpath") ) {
bin_path = k.substring(delimiter + 1);
}
}
}
if ( typemap_classname == null )
throw new RuntimeException("No TypeMap class name specified with -Atypemap=<class-name>");
if ( bin_path == null )
throw new RuntimeException("No path specified for the bin directory with -Abinpath=<path>");
TypeDeclaration lastFile = null;
try {
long generatorLM = getGeneratorLastModified(bin_path);
TypeMap type_map = (TypeMap)(Class.forName(typemap_classname).newInstance());
for ( TypeDeclaration typedecl : env.getSpecifiedTypeDeclarations() ) {
lastFile = typedecl;
typedecl.accept(getDeclarationScanner(new GeneratorVisitor(env, type_map, generate_error_checks, context_specific, generatorLM), NO_OP));
}
} catch (Exception e) {
if ( lastFile == null )
throw new RuntimeException(e);
else
throw new RuntimeException("\n-- Failed to process template: " + lastFile.getQualifiedName() + " --", e);
}
}
/**
* Gets the time of the latest change on the Generator classes.
*
* @return time of the latest change
*/
private static long getGeneratorLastModified(final String bin_path) {
long lastModified = getDirectoryLastModified(bin_path, "/org/lwjgl/util/generator");
lastModified = Math.max(lastModified, getDirectoryLastModified(bin_path, "/org/lwjgl/util/generator/openal"));
lastModified = Math.max(lastModified, getDirectoryLastModified(bin_path, "/org/lwjgl/util/generator/opengl"));
lastModified = Math.max(lastModified, getDirectoryLastModified(bin_path, "/org/lwjgl/util/generator/opencl"));
return lastModified;
}
private static long getDirectoryLastModified(final String bin_path, final String path) {
final File pck = new File(bin_path + path);
if ( !pck.exists() || !pck.isDirectory() )
return Long.MAX_VALUE;
final File[] classes = pck.listFiles(new FileFilter() {
public boolean accept(final File pathname) {
return pathname.isFile() && pathname.getName().endsWith(".class");
}
});
if ( classes == null || classes.length == 0 )
return Long.MAX_VALUE;
long lastModified = 0;
for ( File clazz : classes ) {
long lm = clazz.lastModified();
if ( lastModified < lm )
lastModified = lm;
}
return lastModified;
}
}
}

View file

@ -29,37 +29,43 @@
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator;
import com.sun.mirror.apt.*;
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
import com.sun.mirror.util.*;
import java.io.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.annotation.Annotation;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.*;
import java.nio.*;
import java.util.Collection;
import java.util.List;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.*;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementKindVisitor6;
import javax.tools.Diagnostic;
import javax.tools.Diagnostic.Kind;
import javax.tools.FileObject;
import javax.tools.StandardLocation;
/**
*
* Generator visitor for the generator tool
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision$
* $Id$
* @version $Revision$ $Id$
*/
public class GeneratorVisitor extends SimpleDeclarationVisitor {
private final AnnotationProcessorEnvironment env;
private final TypeMap type_map;
private final boolean generate_error_checks;
private final boolean context_specific;
private final long generatorLM;
public class GeneratorVisitor extends ElementKindVisitor6<Void, Void> {
public GeneratorVisitor(AnnotationProcessorEnvironment env, TypeMap type_map, boolean generate_error_checks, boolean context_specific, long generatorLM) {
private final ProcessingEnvironment env;
private final TypeMap type_map;
private final boolean generate_error_checks;
private final boolean context_specific;
private final long generatorLM;
public GeneratorVisitor(ProcessingEnvironment env, TypeMap type_map, boolean generate_error_checks, boolean context_specific, long generatorLM) {
this.env = env;
this.type_map = type_map;
this.generate_error_checks = generate_error_checks;
@ -67,145 +73,166 @@ public class GeneratorVisitor extends SimpleDeclarationVisitor {
this.generatorLM = generatorLM;
}
private void validateMethod(MethodDeclaration method) {
if (method.isVarArgs())
private void validateMethod(ExecutableElement method) {
if ( method.isVarArgs() ) {
throw new RuntimeException("Method " + method.getSimpleName() + " is variadic");
}
Collection<Modifier> modifiers = method.getModifiers();
if (!modifiers.contains(Modifier.PUBLIC))
if ( !modifiers.contains(Modifier.PUBLIC) ) {
throw new RuntimeException("Method " + method.getSimpleName() + " is not public");
if (method.getThrownTypes().size() > 0)
}
if ( method.getThrownTypes().size() > 0 ) {
throw new RuntimeException("Method " + method.getSimpleName() + " throws checked exceptions");
}
validateParameters(method);
StripPostfix strip_annotation = method.getAnnotation(StripPostfix.class);
if (strip_annotation != null && method.getAnnotation(Alternate.class) == null) {
if ( strip_annotation != null && method.getAnnotation(Alternate.class) == null ) {
String postfix_param_name = strip_annotation.value();
ParameterDeclaration postfix_param = Utils.findParameter(method, postfix_param_name);
if (Utils.isParameterMultiTyped(postfix_param))
VariableElement postfix_param = Utils.findParameter(method, postfix_param_name);
if ( Utils.isParameterMultiTyped(postfix_param) ) {
throw new RuntimeException("Postfix parameter can't be the same as a multityped parameter in method " + method);
if (Utils.getNIOBufferType(postfix_param.getType()) == null)
}
if ( Utils.getNIOBufferType(postfix_param.asType()) == null ) {
throw new RuntimeException("Postfix parameter type must be a nio Buffer");
}
}
if (Utils.getResultParameter(method) != null && !method.getReturnType().equals(env.getTypeUtils().getVoidType()))
if ( Utils.getResultParameter(method) != null && !method.getReturnType().equals(env.getTypeUtils().getNoType(TypeKind.VOID)) ) {
throw new RuntimeException(method + " return type is not void but a parameter is annotated with Result");
if (method.getAnnotation(CachedResult.class) != null) {
if (Utils.getNIOBufferType(Utils.getMethodReturnType(method)) == null)
}
if ( method.getAnnotation(CachedResult.class) != null ) {
if ( Utils.getNIOBufferType(Utils.getMethodReturnType(method)) == null ) {
throw new RuntimeException(method + " return type is not a Buffer, but is annotated with CachedResult");
if (method.getAnnotation(AutoSize.class) == null)
}
if ( method.getAnnotation(AutoSize.class) == null ) {
throw new RuntimeException(method + " is annotated with CachedResult but misses an AutoSize annotation");
}
}
validateTypes(method, method.getAnnotationMirrors(), method.getReturnType());
}
private void validateType(MethodDeclaration method, Class<?extends Annotation> annotation_type, Class type) {
private void validateType(ExecutableElement method, Class<? extends Annotation> annotation_type, Class type) {
Class[] valid_types = type_map.getValidAnnotationTypes(type);
for ( Class valid_type : valid_types )
if ( valid_type.equals(annotation_type) )
for ( Class valid_type : valid_types ) {
if ( valid_type.equals(annotation_type) ) {
return;
throw new RuntimeException(type + " is annotated with invalid native type " + annotation_type +
" in method " + method);
}
}
throw new RuntimeException(type + " is annotated with invalid native type " + annotation_type
+ " in method " + method);
}
private void validateTypes(MethodDeclaration method, Collection<AnnotationMirror> annotations, TypeMirror type_mirror) {
for (AnnotationMirror annotation : annotations) {
private void validateTypes(ExecutableElement method, List<? extends AnnotationMirror> annotations, TypeMirror type_mirror) {
for ( AnnotationMirror annotation : annotations ) {
NativeType native_type_annotation = NativeTypeTranslator.getAnnotation(annotation, NativeType.class);
if (native_type_annotation != null) {
if ( native_type_annotation != null ) {
Class<? extends Annotation> annotation_type = NativeTypeTranslator.getClassFromType(annotation.getAnnotationType());
Class type = Utils.getJavaType(type_mirror);
if (Buffer.class.equals(type))
if ( Buffer.class.equals(type) ) {
continue;
}
validateType(method, annotation_type, type);
}
}
}
private void validateParameters(MethodDeclaration method) {
for (ParameterDeclaration param : method.getParameters()) {
validateTypes(method, param.getAnnotationMirrors(), param.getType());
Class<?> param_type = Utils.getJavaType(param.getType());
if (Utils.getNIOBufferType(param.getType()) != null && param_type != CharSequence.class && param_type != CharSequence[].class) {
private void validateParameters(ExecutableElement method) {
for ( VariableElement param : method.getParameters() ) {
validateTypes(method, param.getAnnotationMirrors(), param.asType());
Class<?> param_type = Utils.getJavaType(param.asType());
if ( Utils.getNIOBufferType(param.asType()) != null && param_type != CharSequence.class && param_type != CharSequence[].class ) {
Check parameter_check_annotation = param.getAnnotation(Check.class);
NullTerminated null_terminated_annotation = param.getAnnotation(NullTerminated.class);
if (parameter_check_annotation == null && null_terminated_annotation == null) {
if ( parameter_check_annotation == null && null_terminated_annotation == null ) {
boolean found_auto_size_param = false;
for (ParameterDeclaration inner_param : method.getParameters()) {
for ( VariableElement inner_param : method.getParameters() ) {
AutoSize auto_size_annotation = inner_param.getAnnotation(AutoSize.class);
if (auto_size_annotation != null &&
auto_size_annotation.value().equals(param.getSimpleName())) {
if ( auto_size_annotation != null
&& auto_size_annotation.value().equals(param.getSimpleName().toString()) ) {
found_auto_size_param = true;
break;
}
}
if (!found_auto_size_param
&& param.getAnnotation(Result.class) == null
&& param.getAnnotation(Constant.class) == null
&& !Utils.isReturnParameter(method, param)
)
throw new RuntimeException(param + " has no Check, Result nor Constant annotation, is not the return parameter and no other parameter has" +
" an @AutoSize annotation on it in method " + method);
if ( !found_auto_size_param
&& param.getAnnotation(Result.class) == null
&& param.getAnnotation(Constant.class) == null
&& !Utils.isReturnParameter(method, param) ) {
throw new RuntimeException(param + " has no Check, Result nor Constant annotation, is not the return parameter and no other parameter has"
+ " an @AutoSize annotation on it in method " + method);
}
}
if (param.getAnnotation(CachedReference.class) != null && param.getAnnotation(Result.class) != null)
if ( param.getAnnotation(CachedReference.class) != null && param.getAnnotation(Result.class) != null ) {
throw new RuntimeException(param + " can't be annotated with both CachedReference and Result");
if (param.getAnnotation(BufferObject.class) != null && param.getAnnotation(Result.class) != null)
}
if ( param.getAnnotation(BufferObject.class) != null && param.getAnnotation(Result.class) != null ) {
throw new RuntimeException(param + " can't be annotated with both BufferObject and Result");
}
//if (param.getAnnotation(Constant.class) != null)
//throw new RuntimeException("Buffer parameter " + param + " cannot be Constant");
//throw new RuntimeException("Buffer parameter " + param + " cannot be Constant");
} else {
if (param.getAnnotation(BufferObject.class) != null)
if ( param.getAnnotation(BufferObject.class) != null ) {
throw new RuntimeException(param + " type is not a buffer, but annotated as a BufferObject");
if (param.getAnnotation(CachedReference.class) != null)
}
if ( param.getAnnotation(CachedReference.class) != null ) {
throw new RuntimeException(param + " type is not a buffer, but annotated as a CachedReference");
}
}
}
}
private static void generateMethodsNativePointers(PrintWriter writer, Collection<? extends MethodDeclaration> methods) {
for (MethodDeclaration method : methods) {
if ( method.getAnnotation(Alternate.class) == null )
private static void generateMethodsNativePointers(PrintWriter writer, Collection<? extends ExecutableElement> methods) {
for ( ExecutableElement method : methods ) {
if ( method.getAnnotation(Alternate.class) == null ) {
generateMethodNativePointers(writer, method);
}
}
}
private static void generateMethodNativePointers(PrintWriter writer, MethodDeclaration method) {
if ( method.getAnnotation(Extern.class) == null )
private static void generateMethodNativePointers(PrintWriter writer, ExecutableElement method) {
if ( method.getAnnotation(Extern.class) == null ) {
writer.print("static ");
}
writer.println(Utils.getTypedefName(method) + " " + method.getSimpleName() + ";");
}
private void generateJavaSource(InterfaceDeclaration d, PrintWriter java_writer) throws IOException {
private void generateJavaSource(TypeElement d, PrintWriter java_writer) throws IOException {
java_writer.println("/* MACHINE GENERATED FILE, DO NOT EDIT */");
java_writer.println();
java_writer.println("package " + d.getPackage().getQualifiedName() + ";");
java_writer.println("package " + env.getElementUtils().getPackageOf(d).getQualifiedName().toString() + ";");
java_writer.println();
java_writer.println("import org.lwjgl.*;");
java_writer.println("import java.nio.*;");
Imports imports = d.getAnnotation(Imports.class);
if ( imports != null ) {
for ( String i : imports.value() )
for ( String i : imports.value() ) {
java_writer.println("import " + i + ";");
}
}
java_writer.println();
Utils.printDocComment(java_writer, d);
if ( d.getAnnotation(Private.class) == null )
Utils.printDocComment(java_writer, d, env);
if ( d.getAnnotation(Private.class) == null ) {
java_writer.print("public ");
}
boolean is_final = Utils.isFinal(d);
if (is_final)
if ( is_final ) {
java_writer.write("final ");
}
java_writer.print("class " + Utils.getSimpleClassName(d));
Collection<InterfaceType> super_interfaces = d.getSuperinterfaces();
if (super_interfaces.size() > 1)
List<? extends TypeMirror> super_interfaces = d.getInterfaces();
if ( super_interfaces.size() > 1 ) {
throw new RuntimeException(d + " extends more than one interface");
if (super_interfaces.size() == 1) {
InterfaceDeclaration super_interface = super_interfaces.iterator().next().getDeclaration();
java_writer.print(" extends " + Utils.getSimpleClassName(super_interface));
}
if ( super_interfaces.size() == 1 ) {
TypeMirror super_interface = super_interfaces.iterator().next();
java_writer.print(" extends " + Utils.getSimpleClassName(env.getElementUtils().getTypeElement(super_interface.toString())));
}
java_writer.println(" {");
FieldsGenerator.generateFields(java_writer, d.getFields());
FieldsGenerator.generateFields(env, java_writer, Utils.getFields(d));
java_writer.println();
if (is_final) {
if ( is_final ) {
// Write private constructor to avoid instantiation
java_writer.println("\tprivate " + Utils.getSimpleClassName(d) + "() {}");
}
if (d.getMethods().size() > 0 && !context_specific) {
if ( Utils.getMethods(d).size() > 0 && !context_specific ) {
java_writer.println();
java_writer.println("\tstatic native void " + Utils.STUB_INITIALIZER_NAME + "() throws LWJGLException;");
}
@ -213,26 +240,29 @@ public class GeneratorVisitor extends SimpleDeclarationVisitor {
java_writer.println("}");
java_writer.close();
String qualified_interface_name = Utils.getQualifiedClassName(d);
env.getMessager().printNotice("Generated class " + qualified_interface_name);
env.getMessager().printMessage(Diagnostic.Kind.NOTE, "Generated class " + qualified_interface_name);
}
private void generateNativeSource(InterfaceDeclaration d) throws IOException {
private void generateNativeSource(TypeElement d) throws IOException {
if ( d.getKind().equals(ElementKind.ANNOTATION_TYPE) ) {
return;
}
String qualified_interface_name = Utils.getQualifiedClassName(d);
String qualified_native_name = Utils.getNativeQualifiedName(qualified_interface_name)+ ".c";
PrintWriter native_writer = env.getFiler().createTextFile(Filer.Location.CLASS_TREE, "", new File(qualified_native_name), "UTF-8");
String qualified_native_name = Utils.getNativeQualifiedName(qualified_interface_name) + ".c";
PrintWriter native_writer = new PrintWriter(env.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", qualified_native_name).openWriter());
native_writer.println("/* MACHINE GENERATED FILE, DO NOT EDIT */");
native_writer.println();
native_writer.println("#include <jni.h>");
type_map.printNativeIncludes(native_writer);
native_writer.println();
TypedefsGenerator.generateNativeTypedefs(type_map, native_writer, d.getMethods());
TypedefsGenerator.generateNativeTypedefs(type_map, native_writer, Utils.getMethods(d));
native_writer.println();
if (!context_specific) {
generateMethodsNativePointers(native_writer, d.getMethods());
if ( !context_specific ) {
generateMethodsNativePointers(native_writer, Utils.getMethods(d));
native_writer.println();
}
NativeMethodStubsGenerator.generateNativeMethodStubs(env, type_map, native_writer, d, generate_error_checks, context_specific);
if (!context_specific) {
if ( !context_specific ) {
native_writer.print("JNIEXPORT void JNICALL " + Utils.getQualifiedNativeMethodName(qualified_interface_name, Utils.STUB_INITIALIZER_NAME));
native_writer.println("(JNIEnv *env, jclass clazz) {");
native_writer.println("\tJavaMethodAndExtFunction functions[] = {");
@ -245,84 +275,63 @@ public class GeneratorVisitor extends SimpleDeclarationVisitor {
native_writer.println("}");
}
native_writer.close();
env.getMessager().printNotice("Generated C source " + qualified_interface_name);
env.getMessager().printMessage(Kind.NOTE, "Generated C source " + qualified_interface_name);
}
public void visitInterfaceDeclaration(InterfaceDeclaration d) {
final File input = d.getPosition().file();
final File outputJava = new File(env.getOptions().get("-s") + '/' + d.getPackage().getQualifiedName().replace('.', '/'), Utils.getSimpleClassName(d) + ".java");
@Override
public Void visitTypeAsInterface(TypeElement e, Void p) {
final File input = new File("src/templates/" + e.getQualifiedName().toString().replace('.', '/') + ".java");
final File outputJava = new File("src/generated/" + env.getElementUtils().getPackageOf(e).getQualifiedName().toString().replace('.', '/'), Utils.getSimpleClassName(e) + ".java");
PrintWriter java_writer = null;
try {
final Collection<? extends MethodDeclaration> methods = d.getMethods();
if ( methods.size() == 0 && d.getFields().size() == 0 )
return;
final Collection<? extends ExecutableElement> methods = Utils.getMethods(e);
if ( methods.isEmpty() && Utils.getFields(e).isEmpty() ) {
return DEFAULT_VALUE;
}
// Skip this class if the output exists and the input has not been modified.
if ( outputJava.exists() && Math.max(input.lastModified(), generatorLM) < outputJava.lastModified() )
return;
return DEFAULT_VALUE;
for ( final MethodDeclaration method : methods )
//env.getMessager().printMessage(Kind.NOTE, "methods count : " + Utils.getMethods(e).size() + " fields count : " + Utils.getFields(e).size(), e);
for ( final ExecutableElement method : methods ) {
validateMethod(method);
java_writer = env.getFiler().createTextFile(Filer.Location.SOURCE_TREE, d.getPackage().getQualifiedName(), new File(Utils.getSimpleClassName(d) + ".java"), null);
generateJavaSource(d, java_writer);
}
// TODO: Back-port LWJGL 3's generation file handling (generate in-memory and avoid touching files if nothing has changed)
// java_writer = new PrintWriter(env.getFiler().createSourceFile(Utils.getQualifiedClassName(e), env.getElementUtils().getPackageOf(e)).openWriter());
outputJava.getParentFile().mkdirs();
outputJava.createNewFile();
java_writer = new PrintWriter(outputJava);
generateJavaSource(e, java_writer);
if ( methods.size() > 0 ) {
boolean noNative = true;
for ( final MethodDeclaration method : methods ) {
for ( final ExecutableElement method : methods ) {
Alternate alt_annotation = method.getAnnotation(Alternate.class);
if ( (alt_annotation == null || alt_annotation.nativeAlt()) && method.getAnnotation(Reuse.class) == null ) {
noNative = false;
break;
}
}
if ( noNative )
return;
final String outputPath = env.getOptions().get("-d") + '/' + Utils.getNativeQualifiedName(Utils.getQualifiedClassName(d));
final File outputNative = new File(outputPath + ".c");
final File outputBackup = new File(outputPath + "_backup.c");
// If the native file exists, rename.
final ByteBuffer nativeBefore;
if ( outputNative.exists() ) {
nativeBefore = readFile(outputNative);
outputNative.renameTo(outputBackup);
} else
nativeBefore = null;
if ( noNative ) {
return DEFAULT_VALUE;
}
try {
generateNativeSource(d);
// If the native file did exist, compare with the new file. If they're the same,
// reset the last modified time to avoid ridiculous C compilation times.
if ( nativeBefore != null && outputNative.length() == nativeBefore.capacity() ) {
final ByteBuffer nativeAfter = readFile(outputNative);
boolean same = true;
for ( int i = nativeBefore.position(); i < nativeBefore.limit(); i++ ) {
if ( nativeBefore.get(i) != nativeAfter.get(i) ) {
same = false;
break;
}
}
if ( same ) {
outputNative.delete();
outputBackup.renameTo(outputNative);
}
}
} finally {
if ( outputBackup.exists() )
outputBackup.delete();
generateNativeSource(e);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
} catch (Exception e) {
return DEFAULT_VALUE;
} catch (Exception ex) {
// If anything goes wrong mid-gen, delete output to allow regen next time we run.
if ( java_writer != null ) java_writer.close();
if ( outputJava.exists() ) outputJava.delete();
throw new RuntimeException(e);
throw new RuntimeException(ex);
}
}

View file

@ -35,20 +35,21 @@ package org.lwjgl.util.generator;
import org.lwjgl.PointerBuffer;
import java.nio.Buffer;
import com.sun.mirror.type.*;
import com.sun.mirror.util.*;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.NoType;
import javax.lang.model.type.PrimitiveType;
import javax.lang.model.util.SimpleTypeVisitor6;
/**
*
* A TypeVisitor that translates TypeMirrors to JNI
* type strings.
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision$
* $Id$
* $Id$
*/
public class JNITypeTranslator implements TypeVisitor {
public class JNITypeTranslator extends SimpleTypeVisitor6<Void, Void> {
private final StringBuilder signature = new StringBuilder();
@ -62,11 +63,8 @@ public class JNITypeTranslator implements TypeVisitor {
return objectReturn ? "jobject" : signature.toString();
}
public void visitAnnotationType(AnnotationType t) {
throw new RuntimeException(t + " is not allowed");
}
public void visitArrayType(ArrayType t) {
@Override
public Void visitArray(ArrayType t, Void o) {
final String className = t.getComponentType().toString();
if ( "java.lang.CharSequence".equals(className) )
signature.append("jlong");
@ -76,9 +74,10 @@ public class JNITypeTranslator implements TypeVisitor {
signature.append("jobjectArray");
else
throw new RuntimeException(t + " is not allowed");
return DEFAULT_VALUE;
}
public void visitClassType(ClassType t) {
private void visitClassType(DeclaredType t) {
final Class<?> type = Utils.getJavaType(t);
if ( Buffer.class.isAssignableFrom(type) || PointerBuffer.class.isAssignableFrom(type) ) {
signature.append("jlong");
@ -87,21 +86,17 @@ public class JNITypeTranslator implements TypeVisitor {
signature.append("jobject");
}
public void visitDeclaredType(DeclaredType t) {
throw new RuntimeException(t + " is not allowed");
@Override
public Void visitDeclared(DeclaredType t, Void o) {
if ( t.asElement().getKind().isClass() )
visitClassType(t);
return DEFAULT_VALUE;
}
public void visitEnumType(EnumType t) {
throw new RuntimeException(t + " is not allowed");
}
public void visitInterfaceType(InterfaceType t) {
throw new RuntimeException(t + " is not allowed");
}
public void visitPrimitiveType(PrimitiveType t) {
@Override
public Void visitPrimitive(PrimitiveType t, Void o) {
String type;
switch (t.getKind()) {
switch ( t.getKind() ) {
case LONG:
type = "jlong";
break;
@ -127,25 +122,13 @@ public class JNITypeTranslator implements TypeVisitor {
throw new RuntimeException(t + " is not allowed");
}
signature.append(type);
return DEFAULT_VALUE;
}
public void visitReferenceType(ReferenceType t) {
throw new RuntimeException(t + " is not allowed");
}
public void visitTypeMirror(TypeMirror t) {
throw new RuntimeException(t + " is not allowed");
}
public void visitTypeVariable(TypeVariable t) {
throw new RuntimeException(t + " is not allowed");
}
public void visitVoidType(VoidType t) {
@Override
public Void visitNoType(NoType t, Void o) {
signature.append(t.toString());
return DEFAULT_VALUE;
}
public void visitWildcardType(WildcardType t) {
throw new RuntimeException(t + " is not allowed");
}
}

File diff suppressed because it is too large Load diff

View file

@ -29,54 +29,50 @@
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator;
import org.lwjgl.opencl.CLMem;
import java.nio.ByteBuffer;
import com.sun.mirror.type.*;
import com.sun.mirror.util.*;
import javax.lang.model.type.*;
import javax.lang.model.util.SimpleTypeVisitor6;
/**
* A TypeVisitor that translates (annotated) TypeMirrors to
* java types (represented by a Class)
* A TypeVisitor that translates (annotated) TypeMirrors to java types
* (represented by a Class)
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision$
* $Id$
* @version $Revision$ $Id$
*/
public class JavaTypeTranslator implements TypeVisitor {
public class JavaTypeTranslator extends SimpleTypeVisitor6<Void, Void> {
private Class type;
public Class getType() {
return type;
}
public void visitAnnotationType(AnnotationType t) {
throw new RuntimeException(t + " is not allowed");
}
public void visitArrayType(ArrayType t) {
@Override
public Void visitArray(ArrayType t, Void o) {
final TypeMirror componentType = t.getComponentType();
if ( componentType instanceof PrimitiveType ) {
type = getPrimitiveArrayClassFromKind(((PrimitiveType)componentType).getKind());
} else {
try {
final Class c = Class.forName(t.getComponentType().toString());
if ( CharSequence.class.isAssignableFrom(c) || ByteBuffer.class.isAssignableFrom(c) || org.lwjgl.PointerWrapper.class.isAssignableFrom(c) )
type = Class.forName("[L" + t.getComponentType() + ";");
else {
try {
final Class c = Class.forName(t.getComponentType().toString());
if ( CharSequence.class.isAssignableFrom(c) || ByteBuffer.class.isAssignableFrom(c) || org.lwjgl.PointerWrapper.class.isAssignableFrom(c) ) {
type = Class.forName("[L" + t.getComponentType() + ";");
}
} catch (ClassNotFoundException ex) {
type = null;
} finally {
if ( type == null ) {
if ( componentType instanceof PrimitiveType ) {
type = getPrimitiveArrayClassFromKind(componentType.getKind());
} else {
throw new RuntimeException(t + " is not allowed");
}
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
return DEFAULT_VALUE;
}
}
public static Class getPrimitiveClassFromKind(PrimitiveType.Kind kind) {
public static Class getPrimitiveClassFromKind(TypeKind kind) {
switch ( kind ) {
case LONG:
return long.class;
@ -97,7 +93,7 @@ public class JavaTypeTranslator implements TypeVisitor {
}
}
private static Class getPrimitiveArrayClassFromKind(PrimitiveType.Kind kind) {
private static Class getPrimitiveArrayClassFromKind(TypeKind kind) {
switch ( kind ) {
case LONG:
return long[].class;
@ -118,43 +114,36 @@ public class JavaTypeTranslator implements TypeVisitor {
}
}
public void visitPrimitiveType(PrimitiveType t) {
@Override
public Void visitPrimitive(PrimitiveType t, Void p) {
type = getPrimitiveClassFromKind(t.getKind());
return DEFAULT_VALUE;
}
public void visitDeclaredType(DeclaredType t) {
throw new RuntimeException(t + " is not allowed");
@Override
public Void visitDeclared(DeclaredType t, Void o) {
if ( t.asElement().getKind().isClass() ) {
visitClassType(t);
} else if ( t.asElement().getKind().isInterface() ) {
visitInterfaceType(t);
} else {
throw new RuntimeException(t.asElement().getKind() + " is not allowed");
}
return DEFAULT_VALUE;
}
public void visitEnumType(EnumType t) {
throw new RuntimeException(t + " is not allowed");
}
public void visitClassType(ClassType t) {
private void visitClassType(DeclaredType t) {
type = NativeTypeTranslator.getClassFromType(t);
}
public void visitInterfaceType(InterfaceType t) {
private void visitInterfaceType(DeclaredType t) {
type = NativeTypeTranslator.getClassFromType(t);
}
public void visitReferenceType(ReferenceType t) {
throw new RuntimeException(t + " is not allowed");
}
public void visitTypeMirror(TypeMirror t) {
throw new RuntimeException(t + " is not allowed");
}
public void visitTypeVariable(TypeVariable t) {
throw new RuntimeException(t + " is not allowed");
}
public void visitVoidType(VoidType t) {
@Override
public Void visitNoType(NoType t, Void p) {
type = void.class;
return DEFAULT_VALUE;
}
public void visitWildcardType(WildcardType t) {
throw new RuntimeException(t + " is not allowed");
}
}

View file

@ -43,33 +43,36 @@ package org.lwjgl.util.generator;
import org.lwjgl.PointerBuffer;
import com.sun.mirror.apt.*;
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
import java.io.*;
import java.util.*;
import java.nio.*;
import java.io.PrintWriter;
import java.nio.Buffer;
import java.util.List;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
public class NativeMethodStubsGenerator {
private static final String BUFFER_ADDRESS_POSTFIX = "_address";
public static final String BUFFER_POSITION_POSTFIX = "_position";
private static final String STRING_LIST_NAME = "_str";
private static final String POINTER_LIST_NAME = "_ptr";
private static final String BUFFER_ADDRESS_POSTFIX = "_address";
public static final String BUFFER_POSITION_POSTFIX = "_position";
private static final String STRING_LIST_NAME = "_str";
private static final String POINTER_LIST_NAME = "_ptr";
public static void generateNativeMethodStubs(AnnotationProcessorEnvironment env, TypeMap type_map, PrintWriter writer, InterfaceDeclaration d, boolean generate_error_checks, boolean context_specific) {
for (MethodDeclaration method : d.getMethods()) {
public static void generateNativeMethodStubs(ProcessingEnvironment env, TypeMap type_map, PrintWriter writer, TypeElement d, boolean generate_error_checks, boolean context_specific) {
for ( ExecutableElement method : Utils.getMethods(d) ) {
Alternate alt_annotation = method.getAnnotation(Alternate.class);
if ( (alt_annotation != null && (!alt_annotation.nativeAlt() || alt_annotation.skipNative())) || method.getAnnotation(Reuse.class) != null )
continue;
generateMethodStub(env, type_map, writer, Utils.getQualifiedClassName(d), method, Mode.NORMAL, generate_error_checks, context_specific);
if (Utils.hasMethodBufferObjectParameter(method))
if ( Utils.hasMethodBufferObjectParameter(method) )
generateMethodStub(env, type_map, writer, Utils.getQualifiedClassName(d), method, Mode.BUFFEROBJECT, generate_error_checks, context_specific);
}
}
private static void generateParameters(PrintWriter writer, Collection<ParameterDeclaration> params, Mode mode) {
for (ParameterDeclaration param : params) {
private static void generateParameters(PrintWriter writer, List<? extends VariableElement> params, Mode mode) {
for ( VariableElement param : params ) {
if ( param.getAnnotation(Result.class) != null || (param.getAnnotation(Helper.class) != null && !param.getAnnotation(Helper.class).passToNative()) )
continue;
final Constant constant_annotation = param.getAnnotation(Constant.class);
@ -78,20 +81,20 @@ public class NativeMethodStubsGenerator {
}
}
private static void generateParameter(PrintWriter writer, ParameterDeclaration param, Mode mode) {
private static void generateParameter(PrintWriter writer, VariableElement param, Mode mode) {
writer.print(", ");
if (mode == Mode.BUFFEROBJECT && param.getAnnotation(BufferObject.class) != null) {
if ( mode == Mode.BUFFEROBJECT && param.getAnnotation(BufferObject.class) != null ) {
writer.print("jlong " + param.getSimpleName() + Utils.BUFFER_OBJECT_PARAMETER_POSTFIX);
} else if ( param.getAnnotation(PointerWrapper.class) != null ) {
writer.print("jlong " + param.getSimpleName());
} else {
JNITypeTranslator translator = new JNITypeTranslator();
param.getType().accept(translator);
param.asType().accept(translator, null);
writer.print(translator.getSignature() + " " + param.getSimpleName());
}
}
private static void generateMethodStub(AnnotationProcessorEnvironment env, TypeMap type_map, PrintWriter writer, String interface_name, MethodDeclaration method, Mode mode, boolean generate_error_checks, boolean context_specific) {
private static void generateMethodStub(ProcessingEnvironment env, TypeMap type_map, PrintWriter writer, String interface_name, ExecutableElement method, Mode mode, boolean generate_error_checks, boolean context_specific) {
if ( !context_specific && method.getAnnotation(Alternate.class) == null )
writer.print("static ");
else
@ -105,30 +108,30 @@ public class NativeMethodStubsGenerator {
writer.print("jlong");
} else {
JNITypeTranslator translator = new JNITypeTranslator();
result_type.accept(translator);
result_type.accept(translator, null);
writer.print(translator.getReturnSignature());
}
writer.print(" JNICALL ");
writer.print(Utils.getQualifiedNativeMethodName(interface_name, method, generate_error_checks, context_specific));
if (mode == Mode.BUFFEROBJECT)
if ( mode == Mode.BUFFEROBJECT )
writer.print(Utils.BUFFER_OBJECT_METHOD_POSTFIX);
writer.print("(JNIEnv *env, jclass clazz");
generateParameters(writer, method.getParameters(), mode);
if (Utils.getNIOBufferType(result_type) != null) {
if ( Utils.getNIOBufferType(result_type) != null ) {
if ( (cached_result_annotation == null || !cached_result_annotation.isRange()) && (auto_size_annotation == null || !auto_size_annotation.isNative()) )
writer.print(", jlong " + Utils.RESULT_SIZE_NAME);
if (cached_result_annotation != null)
if ( cached_result_annotation != null )
writer.print(", jobject " + Utils.CACHED_BUFFER_NAME);
}
if (context_specific) {
if ( context_specific ) {
writer.print(", jlong " + Utils.FUNCTION_POINTER_VAR_NAME);
}
writer.println(") {");
generateBufferParameterAddresses(type_map, writer, method, mode);
Alternate alt_annotation = method.getAnnotation(Alternate.class);
if (context_specific) {
if ( context_specific ) {
String typedef_name = Utils.getTypedefName(method);
writer.print("\t" + typedef_name + " " + (alt_annotation == null ? method.getSimpleName() : alt_annotation.value()));
writer.print(" = (" + typedef_name + ")((intptr_t)");
@ -137,7 +140,7 @@ public class NativeMethodStubsGenerator {
final Code code_annotation = method.getAnnotation(Code.class);
final boolean hasResult = !result_type.equals(env.getTypeUtils().getVoidType());
final boolean hasResult = !result_type.equals(env.getTypeUtils().getNoType(TypeKind.VOID));
final boolean resultPreDeclare = hasResult && (hasPointerArrayInits(method.getParameters()) || (code_annotation != null && (code_annotation.nativeAfterVars().length() > 0 || code_annotation.nativeBeforeCall().length() > 0)));
if ( resultPreDeclare )
printResultParam(type_map, writer, method, result_type, true);
@ -164,21 +167,21 @@ public class NativeMethodStubsGenerator {
writer.println(code_annotation.nativeAfterCall());
generateStringDeallocations(writer, method.getParameters());
if (!result_type.equals(env.getTypeUtils().getVoidType())) {
if ( !result_type.equals(env.getTypeUtils().getNoType(TypeKind.VOID)) ) {
writer.print("\treturn ");
Class java_result_type = Utils.getJavaType(result_type);
if (Buffer.class.isAssignableFrom(java_result_type)) {
if (cached_result_annotation != null)
if ( Buffer.class.isAssignableFrom(java_result_type) ) {
if ( cached_result_annotation != null )
writer.print("safeNewBufferCached(env, ");
else
writer.print("safeNewBuffer(env, ");
} else if (String.class.equals(java_result_type)) {
} else if ( String.class.equals(java_result_type) ) {
writer.print("NewStringNativeUnsigned(env, ");
} else if ( method.getAnnotation(PointerWrapper.class) != null ) {
writer.print("(intptr_t)");
}
writer.print(Utils.RESULT_VAR_NAME);
if (Buffer.class.isAssignableFrom(java_result_type)) {
if ( Buffer.class.isAssignableFrom(java_result_type) ) {
final String size_parameter_name;
if ( auto_size_annotation != null && (auto_size_annotation.isNative() || (cached_result_annotation != null && cached_result_annotation.isRange())) )
size_parameter_name = auto_size_annotation.value();
@ -188,8 +191,8 @@ public class NativeMethodStubsGenerator {
writer.print(", ");
Utils.printExtraCallArguments(writer, method, size_parameter_name);
}
if (Buffer.class.isAssignableFrom(java_result_type) ||
String.class.equals(java_result_type))
if ( Buffer.class.isAssignableFrom(java_result_type) ||
String.class.equals(java_result_type) )
writer.print(")");
writer.println(";");
}
@ -197,24 +200,24 @@ public class NativeMethodStubsGenerator {
writer.println();
}
private static void printResultParam(final TypeMap type_map, final PrintWriter writer, final MethodDeclaration method, final TypeMirror result_type, final boolean preDeclare) {
final ParameterDeclaration result_param = Utils.getResultParameter(method);
final Declaration return_declaration = result_param == null ? method : result_param;
private static void printResultParam(final TypeMap type_map, final PrintWriter writer, final ExecutableElement method, final TypeMirror result_type, final boolean preDeclare) {
final VariableElement result_param = Utils.getResultParameter(method);
final Element return_declaration = result_param == null ? method : result_param;
final NativeTypeTranslator result_translator = new NativeTypeTranslator(type_map, return_declaration);
result_type.accept(result_translator);
result_type.accept(result_translator, null);
if ( preDeclare )
writer.print("\t");
writer.print(result_translator.getSignature() + " " + Utils.RESULT_VAR_NAME);
if ( preDeclare)
if ( preDeclare )
writer.println(";");
else
writer.print(result_param == null ? " = " : ";\n\t");
}
private static void generateCallParameters(PrintWriter writer, TypeMap type_map, Collection<ParameterDeclaration> params) {
if (params.size() > 0) {
private static void generateCallParameters(PrintWriter writer, TypeMap type_map, List<? extends VariableElement> params) {
if ( params.size() > 0 ) {
boolean first = true;
for ( ParameterDeclaration param : params ) {
for ( VariableElement param : params ) {
if ( param.getAnnotation(Helper.class) != null )
continue;
@ -228,7 +231,7 @@ public class NativeMethodStubsGenerator {
}
}
private static void generateCallParameter(PrintWriter writer, TypeMap type_map, ParameterDeclaration param) {
private static void generateCallParameter(PrintWriter writer, TypeMap type_map, VariableElement param) {
if ( param.getAnnotation(Helper.class) != null )
return;
@ -239,16 +242,16 @@ public class NativeMethodStubsGenerator {
}
boolean is_indirect = param.getAnnotation(Indirect.class) != null;
if (is_indirect || param.getAnnotation(PointerArray.class) != null) {
if ( is_indirect || param.getAnnotation(PointerArray.class) != null ) {
writer.print("(");
final NativeTypeTranslator translator = new NativeTypeTranslator(type_map, param);
param.getType().accept(translator);
param.asType().accept(translator, null);
writer.print(translator.getSignature());
writer.print("*)");
}
if ( param.getAnnotation(PointerWrapper.class) != null )
writer.print("(" + param.getAnnotation(PointerWrapper.class).value() + ")(intptr_t)");
if (param.getAnnotation(Result.class) != null || is_indirect)
if ( param.getAnnotation(Result.class) != null || is_indirect )
writer.print("&");
if ( param.getAnnotation(Result.class) != null ) {
@ -256,42 +259,42 @@ public class NativeMethodStubsGenerator {
} else {
writer.print(param.getSimpleName());
if ( param.getAnnotation(PointerArray.class) != null )
writer.print(getPointerArrayName(Utils.getJavaType(param.getType())));
else if ( Utils.isAddressableType(param.getType()) )
writer.print(getPointerArrayName(Utils.getJavaType(param.asType())));
else if ( Utils.isAddressableType(param.asType()) )
writer.print(BUFFER_ADDRESS_POSTFIX);
}
}
private static void generateStringDeallocations(PrintWriter writer, Collection<ParameterDeclaration> params) {
for (ParameterDeclaration param : params) {
final Class java_type = Utils.getJavaType(param.getType());
private static void generateStringDeallocations(PrintWriter writer, List<? extends VariableElement> params) {
for ( VariableElement param : params ) {
final Class java_type = Utils.getJavaType(param.asType());
if ( java_type.equals(String.class) && param.getAnnotation(Result.class) == null )
writer.println("\tfree(" + param.getSimpleName() + BUFFER_ADDRESS_POSTFIX + ");");
else if (param.getAnnotation(PointerArray.class) != null ) // Free the string array mem
else if ( param.getAnnotation(PointerArray.class) != null ) // Free the string array mem
writer.println("\tfree(" + param.getSimpleName() + getPointerArrayName(java_type) + ");");
}
}
private static void generateBufferParameterAddresses(TypeMap type_map, PrintWriter writer, MethodDeclaration method, Mode mode) {
private static void generateBufferParameterAddresses(TypeMap type_map, PrintWriter writer, ExecutableElement method, Mode mode) {
strLoopDeclared = false;
ptrLoopDeclared = false;
for ( ParameterDeclaration param : method.getParameters() ) {
for ( VariableElement param : method.getParameters() ) {
final Constant constant_annotation = param.getAnnotation(Constant.class);
if ( param.getAnnotation(Result.class) == null && (constant_annotation == null || !constant_annotation.isNative()) && Utils.isAddressableType(param.getType()))
generateBufferParameterAddress(type_map, writer, method, param, mode);
if ( param.getAnnotation(Result.class) == null && (constant_annotation == null || !constant_annotation.isNative()) && Utils.isAddressableType(param.asType()) )
generateBufferParameterAddress(type_map, writer, param, mode);
}
}
private static boolean strLoopDeclared;
private static boolean ptrLoopDeclared;
private static void generateBufferParameterAddress(TypeMap type_map, PrintWriter writer, MethodDeclaration method, ParameterDeclaration param, Mode mode) {
private static void generateBufferParameterAddress(TypeMap type_map, PrintWriter writer, VariableElement param, Mode mode) {
final Check check_annotation = param.getAnnotation(Check.class);
final PointerArray array_annotation = param.getAnnotation(PointerArray.class);
final Class java_type = Utils.getJavaType(param.getType());
final Class java_type = Utils.getJavaType(param.asType());
final NativeTypeTranslator translator = new NativeTypeTranslator(type_map, param);
param.getType().accept(translator);
param.asType().accept(translator, null);
final String native_type = translator.getSignature();
if ( !java_type.isArray() || CharSequence.class.isAssignableFrom(java_type.getComponentType()) ) {
@ -300,12 +303,12 @@ public class NativeMethodStubsGenerator {
writer.print(native_type);
writer.print(")(intptr_t)");
if (mode == Mode.BUFFEROBJECT && param.getAnnotation(BufferObject.class) != null) {
if ( mode == Mode.BUFFEROBJECT && param.getAnnotation(BufferObject.class) != null ) {
writer.print("offsetToPointer(" + param.getSimpleName() + Utils.BUFFER_OBJECT_PARAMETER_POSTFIX + ")");
} else {
if (Buffer.class.isAssignableFrom(java_type) || java_type.equals(CharSequence.class) || java_type.equals(CharSequence[].class) || PointerBuffer.class.isAssignableFrom(java_type) ) {
if ( Buffer.class.isAssignableFrom(java_type) || java_type.equals(CharSequence.class) || java_type.equals(CharSequence[].class) || PointerBuffer.class.isAssignableFrom(java_type) ) {
writer.print(param.getSimpleName());
} else if (java_type.equals(String.class)) {
} else if ( java_type.equals(String.class) ) {
writer.print("GetStringNativeChars(env, " + param.getSimpleName() + ")");
} else if ( array_annotation == null )
throw new RuntimeException("Illegal type " + java_type);
@ -317,26 +320,26 @@ public class NativeMethodStubsGenerator {
final String n = getPointerArrayName(java_type);
final String arrayType;
if ( POINTER_LIST_NAME.equals(n) ) {
if ( n.equals(param.getSimpleName()) )
if ( n.equals(param.getSimpleName().toString()) )
throw new RuntimeException("The name '" + n + "' is not valid for object array arguments annotated with PointerArray");
arrayType = translator.getSignature(true) + (org.lwjgl.PointerWrapper.class.isAssignableFrom(java_type.getComponentType()) ? " " : "");
// Declare loop counters and allocate object array
if ( !ptrLoopDeclared ) {
writer.println("\tunsigned int " + n + "_i;");
writer.println("\tint " + n + "_i;");
writer.println("\tjobject " + n + "_object;");
ptrLoopDeclared = true;
}
} else {
if ( n.equals(param.getSimpleName()) )
if ( n.equals(param.getSimpleName().toString()) )
throw new RuntimeException("The name '" + n + "' is not valid for arguments annotated with PointerArray");
arrayType = translator.getSignature(true);
// Declare loop counters and allocate string array
if ( !strLoopDeclared ) {
writer.println("\tunsigned int " + n + "_i;");
writer.println("\tint " + n + "_i;");
writer.println("\t" + arrayType + n + "_address;");
strLoopDeclared = true;
}
@ -357,8 +360,8 @@ public class NativeMethodStubsGenerator {
return STRING_LIST_NAME;
}
private static boolean hasPointerArrayInits(Collection<ParameterDeclaration> params) {
for ( ParameterDeclaration param : params ) {
private static boolean hasPointerArrayInits(List<? extends VariableElement> params) {
for ( VariableElement param : params ) {
PointerArray pointerArray_annotation = param.getAnnotation(PointerArray.class);
if ( pointerArray_annotation != null )
return true;
@ -366,14 +369,14 @@ public class NativeMethodStubsGenerator {
return false;
}
private static void generatePointerArrayInits(TypeMap type_map, PrintWriter writer, Collection<ParameterDeclaration> params) {
for ( ParameterDeclaration param : params ) {
private static void generatePointerArrayInits(TypeMap type_map, PrintWriter writer, List<? extends VariableElement> params) {
for ( VariableElement param : params ) {
PointerArray pointerArray_annotation = param.getAnnotation(PointerArray.class);
if ( pointerArray_annotation != null ) {
final Class java_type = Utils.getJavaType(param.getType());
final Class java_type = Utils.getJavaType(param.asType());
final Class<?> component_type = java_type.isArray() ? java_type.getComponentType() : null;
final NativeTypeTranslator translator = new NativeTypeTranslator(type_map, param);
param.getType().accept(translator);
param.asType().accept(translator, null);
final String n = getPointerArrayName(java_type);
if ( POINTER_LIST_NAME.equals(n) ) {
@ -381,11 +384,12 @@ public class NativeMethodStubsGenerator {
writer.println("\t" + n + "_i = 0;");
// Fill pointer array with the buffer pointers
writer.println("\twhile ( " + n + "_i < " + pointerArray_annotation.value() + " ) {");
if ( component_type.isAssignableFrom(Buffer.class) )
writer.println("\t\t" + n + "_object = (*env)->GetObjectArrayElement(env, " + param.getSimpleName() + ", " + n + "_i);");
writer.println("\t\t" + n + "_object = (*env)->GetObjectArrayElement(env, " + param.getSimpleName() + ", " + n + "_i);");
writer.print("\t\t" + param.getSimpleName() + n + "[" + n + "_i++] = (" + translator.getSignature(true) + ")");
if ( Buffer.class.isAssignableFrom(component_type) )
writer.println("(*env)->GetDirectBufferAddress(env, " + n + "_object);");
else
writer.println("\t\t" + n + "_object = (*env)->GetObjectArrayElement(env, " + param.getSimpleName() + ", " + n + "_i);");
writer.println("\t\t" + param.getSimpleName() + n + "[" + n + "_i++] = (" + translator.getSignature(true) + ")(intptr_t)getPointerWrapperAddress(env, " + n + "_object);");
writer.println("(intptr_t)getPointerWrapperAddress(env, " + n + "_object);");
writer.println("\t}");
} else {
final String lengths = pointerArray_annotation.lengths();
@ -397,7 +401,7 @@ public class NativeMethodStubsGenerator {
writer.println("\twhile ( " + n + "_i < " + pointerArray_annotation.value() + " ) {");
if ( lengths.length() == 0 ) {
writer.println("\t\t" + param.getSimpleName() + n + "[" + n + "_i++] = " + n + "_address;");
writer.println("\t\t" + n + "_address += strlen(" + n + "_address) + 1;");
writer.println("\t\t" + n + "_address += strlen((const char *)" + n + "_address) + 1;");
} else {
writer.println("\t\t" + param.getSimpleName() + n + "[" + n + "_i] = " + n + "_address;");
writer.println("\t\t" + n + "_address += " + lengths + BUFFER_ADDRESS_POSTFIX + "[" + n + "_i++];");

View file

@ -29,48 +29,44 @@
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator;
/**
*
* A TypeVisitor that translates types (and optional native type
* annotations) to the native type string.
* A TypeVisitor that translates types (and optional native type annotations) to
* the native type string.
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision$
* $Id$
* @version $Revision$ $Id$
*/
import org.lwjgl.PointerBuffer;
import java.lang.annotation.Annotation;
import java.nio.*;
import java.util.ArrayList;
import java.util.Collection;
import com.sun.mirror.declaration.AnnotationMirror;
import com.sun.mirror.declaration.Declaration;
import com.sun.mirror.type.*;
import com.sun.mirror.util.TypeVisitor;
import java.util.List;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.type.*;
import javax.lang.model.util.SimpleTypeVisitor6;
/**
* $Id$
* <p/>
* A TypeVisitor that translates (annotated) TypeMirrors to
* native types
* A TypeVisitor that translates (annotated) TypeMirrors to native types
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision$
*/
public class NativeTypeTranslator implements TypeVisitor {
public class NativeTypeTranslator extends SimpleTypeVisitor6<Void, Void> {
private Collection<Class> native_types;
private boolean is_indirect;
private final Declaration declaration;
private final TypeMap type_map;
private Collection<Class> native_types;
private boolean is_indirect;
private final Element declaration;
private final TypeMap type_map;
public NativeTypeTranslator(TypeMap type_map, Declaration declaration) {
public NativeTypeTranslator(TypeMap type_map, Element declaration) {
this.declaration = declaration;
this.type_map = type_map;
}
@ -81,8 +77,9 @@ public class NativeTypeTranslator implements TypeVisitor {
public String getSignature(final boolean skipConst) {
StringBuilder signature = new StringBuilder();
if ( !skipConst && declaration.getAnnotation(Const.class) != null )
if ( !skipConst && declaration.getAnnotation(Const.class) != null ) {
signature.append("const ");
}
if ( declaration.getAnnotation(PointerWrapper.class) != null ) {
signature.append(declaration.getAnnotation(PointerWrapper.class).value());
@ -93,23 +90,22 @@ public class NativeTypeTranslator implements TypeVisitor {
signature.append(getAnnotationType().getSimpleName());
}
if ( is_indirect )
if ( is_indirect ) {
signature.append(" *");
}
return signature.toString();
}
public Class getAnnotationType() {
if ( native_types.size() != 1 )
throw new RuntimeException("Expected only one native type for declaration " + declaration +
", but got " + native_types.size());
if ( native_types.size() != 1 ) {
throw new RuntimeException("Expected only one native type for declaration " + declaration
+ ", but got " + native_types.size());
}
return native_types.iterator().next();
}
public void visitAnnotationType(AnnotationType t) {
throw new RuntimeException(t + " is not allowed");
}
public void visitArrayType(ArrayType t) {
@Override
public Void visitArray(ArrayType t, Void o) {
final Class<?> type = Utils.getJavaType(t).getComponentType();
if ( CharSequence.class.isAssignableFrom(type) ) {
@ -122,43 +118,47 @@ public class NativeTypeTranslator implements TypeVisitor {
native_types.add(type_map.getByteBufferArrayType());
} else if ( org.lwjgl.PointerWrapper.class.isAssignableFrom(type) ) {
is_indirect = false;
} else
} else {
throw new RuntimeException(t + " is not allowed");
}
return DEFAULT_VALUE;
}
public static PrimitiveType.Kind getPrimitiveKindFromBufferClass(Class c) {
if ( IntBuffer.class.equals(c) )
return PrimitiveType.Kind.INT;
else if ( DoubleBuffer.class.equals(c) )
return PrimitiveType.Kind.DOUBLE;
else if ( ShortBuffer.class.equals(c) )
return PrimitiveType.Kind.SHORT;
else if ( ByteBuffer.class.equals(c) || PointerBuffer.class.equals(c) )
return PrimitiveType.Kind.BYTE;
else if ( FloatBuffer.class.equals(c) )
return PrimitiveType.Kind.FLOAT;
else if ( LongBuffer.class.equals(c) )
return PrimitiveType.Kind.LONG;
else
public static TypeKind getPrimitiveKindFromBufferClass(Class c) {
if ( IntBuffer.class.equals(c) ) {
return TypeKind.INT;
} else if ( DoubleBuffer.class.equals(c) ) {
return TypeKind.DOUBLE;
} else if ( ShortBuffer.class.equals(c) ) {
return TypeKind.SHORT;
} else if ( ByteBuffer.class.equals(c) || PointerBuffer.class.equals(c) ) {
return TypeKind.BYTE;
} else if ( FloatBuffer.class.equals(c) ) {
return TypeKind.FLOAT;
} else if ( LongBuffer.class.equals(c) ) {
return TypeKind.LONG;
} else {
throw new RuntimeException(c + " is not allowed");
}
}
@SuppressWarnings("unchecked")
public static Class<? extends Annotation> getClassFromType(DeclaredType t) {
try {
return (Class<? extends Annotation>)Class.forName(t.getDeclaration().getQualifiedName());
return (Class<? extends Annotation>)Class.forName(t.toString());
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
private void getNativeTypeFromAnnotatedPrimitiveType(PrimitiveType.Kind kind) {
private void getNativeTypeFromAnnotatedPrimitiveType(TypeKind kind) {
native_types = translateAnnotations();
if ( native_types.size() == 0 )
if ( native_types.isEmpty() ) {
native_types.add(type_map.getNativeTypeFromPrimitiveType(kind));
}
}
public void visitClassType(ClassType t) {
private void visitClassType(DeclaredType t) {
is_indirect = true;
Class<?> c = getClassFromType(t);
@ -168,34 +168,26 @@ public class NativeTypeTranslator implements TypeVisitor {
} else if ( Buffer.class.equals(c) ) {
native_types = new ArrayList<Class>();
native_types.add(type_map.getVoidType());
} else if ( Buffer.class.isAssignableFrom(c) ) {
PrimitiveType.Kind kind = getPrimitiveKindFromBufferClass(c);
} else if ( Buffer.class.isAssignableFrom(c) || PointerBuffer.class.isAssignableFrom(c) ) {
TypeKind kind = getPrimitiveKindFromBufferClass(c);
getNativeTypeFromAnnotatedPrimitiveType(kind);
} else if ( PointerBuffer.class.isAssignableFrom(c) ) {
native_types = new ArrayList<Class>();
native_types.add(PointerBuffer.class);
} else if ( org.lwjgl.PointerWrapper.class.isAssignableFrom(c) ) {
native_types = new ArrayList<Class>();
native_types.add(PointerWrapper.class);
is_indirect = false;
} else
} else {
throw new RuntimeException(t + " is not allowed");
}
}
public void visitPrimitiveType(PrimitiveType t) {
@Override
public Void visitPrimitive(PrimitiveType t, Void p) {
getNativeTypeFromAnnotatedPrimitiveType(t.getKind());
return DEFAULT_VALUE;
}
public void visitDeclaredType(DeclaredType t) {
throw new RuntimeException(t + " is not allowed");
}
public void visitEnumType(EnumType t) {
throw new RuntimeException(t + " is not allowed");
}
public void visitInterfaceType(InterfaceType t) {
private void visitInterfaceType(DeclaredType t) {
// See ARB_debug_label.glObjectPtrLabel
Class<?> c = getClassFromType(t);
if ( org.lwjgl.PointerWrapper.class.isAssignableFrom(c) ) {
@ -203,26 +195,39 @@ public class NativeTypeTranslator implements TypeVisitor {
native_types.add(PointerWrapper.class);
is_indirect = false;
} else
} else {
throw new RuntimeException(t + " is not allowed");
}
}
// Check if the annotation is itself annotated with a certain annotation type
@Override
public Void visitDeclared(DeclaredType t, Void p) {
if ( t.asElement().getKind().isInterface() ) {
visitInterfaceType(t);
} else if ( t.asElement().getKind().isClass() ) {
visitClassType(t);
}
return DEFAULT_VALUE;
}
/* Check if the annotation is itself annotated with a certain annotation type
* @discuss compare (DeclaredType).getAnnotation(Class) and (Element).getAnnotation(Class), they mean different Annotation's.
*/
public static <T extends Annotation> T getAnnotation(AnnotationMirror annotation, Class<T> type) {
return annotation.getAnnotationType().getDeclaration().getAnnotation(type);
return annotation.getAnnotationType().asElement().getAnnotation(type);
}
private static Class translateAnnotation(AnnotationMirror annotation) {
NativeType native_type = getAnnotation(annotation, NativeType.class);
if ( native_type != null ) {
return getClassFromType(annotation.getAnnotationType());
} else
} else {
return null;
}
}
private Collection<Class> translateAnnotations() {
Collection<Class> result = new ArrayList<Class>();
private List<Class> translateAnnotations() {
List<Class> result = new ArrayList<Class>();
for ( AnnotationMirror annotation : Utils.getSortedAnnotations(declaration.getAnnotationMirrors()) ) {
Class translated_result = translateAnnotation(annotation);
if ( translated_result != null ) {
@ -232,25 +237,13 @@ public class NativeTypeTranslator implements TypeVisitor {
return result;
}
public void visitReferenceType(ReferenceType t) {
throw new RuntimeException(t + " is not allowed");
}
public void visitTypeMirror(TypeMirror t) {
throw new RuntimeException(t + " is not allowed");
}
public void visitTypeVariable(TypeVariable t) {
throw new RuntimeException(t + " is not allowed");
}
public void visitVoidType(VoidType t) {
@Override
public Void visitNoType(NoType t, Void p) {
native_types = translateAnnotations();
if ( native_types.size() == 0 )
if ( native_types.isEmpty() ) {
native_types.add(void.class);
}
return DEFAULT_VALUE;
}
public void visitWildcardType(WildcardType t) {
throw new RuntimeException(t + " is not allowed");
}
}

View file

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

View file

@ -42,19 +42,21 @@ package org.lwjgl.util.generator;
* $Id$
*/
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
import com.sun.mirror.util.*;
import java.lang.annotation.Annotation;
import java.nio.*;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.PrimitiveType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.util.SimpleTypeVisitor6;
public class PostfixTranslator implements TypeVisitor {
public class PostfixTranslator extends SimpleTypeVisitor6<Void, Void> {
private final StringBuilder signature = new StringBuilder();
private final Declaration declaration;
private final Element declaration;
private final TypeMap type_map;
public PostfixTranslator(TypeMap type_map, Declaration declaration) {
public PostfixTranslator(TypeMap type_map, Element declaration) {
this.declaration = declaration;
this.type_map = type_map;
}
@ -63,52 +65,39 @@ public class PostfixTranslator implements TypeVisitor {
return signature.toString();
}
public void visitAnnotationType(AnnotationType t) {
throw new RuntimeException(t + " is not allowed");
}
public void visitArrayType(ArrayType t) {
throw new RuntimeException(t + " is not allowed");
}
private static PrimitiveType.Kind getPrimitiveKindFromBufferClass(Class c) {
if (IntBuffer.class.equals(c) || int.class.equals(c) )
return PrimitiveType.Kind.INT;
else if (DoubleBuffer.class.equals(c) || double.class.equals(c) )
return PrimitiveType.Kind.DOUBLE;
else if (ShortBuffer.class.equals(c) || short.class.equals(c) )
return PrimitiveType.Kind.SHORT;
else if (ByteBuffer.class.equals(c) || byte.class.equals(c) )
return PrimitiveType.Kind.BYTE;
else if (FloatBuffer.class.equals(c) || float.class.equals(c))
return PrimitiveType.Kind.FLOAT;
else if (LongBuffer.class.equals(c) || long.class.equals(c) )
return PrimitiveType.Kind.LONG;
private static TypeKind getPrimitiveKindFromBufferClass(Class c) {
if ( IntBuffer.class.equals(c) || int.class.equals(c) )
return TypeKind.INT;
else if ( DoubleBuffer.class.equals(c) || double.class.equals(c) )
return TypeKind.DOUBLE;
else if ( ShortBuffer.class.equals(c) || short.class.equals(c) )
return TypeKind.SHORT;
else if ( ByteBuffer.class.equals(c) || byte.class.equals(c) )
return TypeKind.BYTE;
else if ( FloatBuffer.class.equals(c) || float.class.equals(c) )
return TypeKind.FLOAT;
else if ( LongBuffer.class.equals(c) || long.class.equals(c) )
return TypeKind.LONG;
else
throw new RuntimeException(c + " is not allowed");
}
public void visitClassType(ClassType t) {
private void visitClassType(DeclaredType t) {
Class<?> c = NativeTypeTranslator.getClassFromType(t);
PrimitiveType.Kind kind = getPrimitiveKindFromBufferClass(c);
TypeKind kind = getPrimitiveKindFromBufferClass(c);
visitPrimitiveTypeKind(kind);
}
public void visitDeclaredType(DeclaredType t) {
throw new RuntimeException(t + " is not allowed");
}
public void visitEnumType(EnumType t) {
throw new RuntimeException(t + " is not allowed");
}
public void visitInterfaceType(InterfaceType t) {
throw new RuntimeException(t + " is not allowed");
@Override
public Void visitDeclared(DeclaredType t, Void o) {
if ( t.asElement().getKind().isClass() )
visitClassType(t);
return DEFAULT_VALUE;
}
private boolean translateAnnotation(AnnotationMirror annotation) {
NativeType native_type = NativeTypeTranslator.getAnnotation(annotation, NativeType.class);
if (native_type != null) {
if ( native_type != null ) {
Class<? extends Annotation> annotation_class = NativeTypeTranslator.getClassFromType(annotation.getAnnotationType());
signature.append(type_map.translateAnnotation(annotation_class));
return true;
@ -118,26 +107,28 @@ public class PostfixTranslator implements TypeVisitor {
private boolean translateAnnotations() {
boolean result = false;
for (AnnotationMirror annotation : Utils.getSortedAnnotations(declaration.getAnnotationMirrors()))
if (translateAnnotation(annotation)) {
if (result)
for ( AnnotationMirror annotation : Utils.getSortedAnnotations(declaration.getAnnotationMirrors()) )
if ( translateAnnotation(annotation) ) {
if ( result )
throw new RuntimeException("Multiple native types");
result = true;
}
return result;
}
public void visitPrimitiveType(PrimitiveType t) {
@Override
public Void visitPrimitive(PrimitiveType t, Void o) {
visitPrimitiveTypeKind(t.getKind());
return DEFAULT_VALUE;
}
private void visitPrimitiveTypeKind(PrimitiveType.Kind kind) {
private void visitPrimitiveTypeKind(TypeKind kind) {
boolean annotated_translation = translateAnnotations();
if (annotated_translation)
if ( annotated_translation )
return;
// No annotation type was specified, fall back to default
String type;
switch (kind) {
switch ( kind ) {
case INT:
type = "i";
break;
@ -161,23 +152,4 @@ public class PostfixTranslator implements TypeVisitor {
}
signature.append(type);
}
public void visitReferenceType(ReferenceType t) {
throw new RuntimeException(t + " is not allowed");
}
public void visitTypeMirror(TypeMirror t) {
throw new RuntimeException(t + " is not allowed");
}
public void visitTypeVariable(TypeVariable t) {
throw new RuntimeException(t + " is not allowed");
}
public void visitVoidType(VoidType t) {
}
public void visitWildcardType(WildcardType t) {
throw new RuntimeException(t + " is not allowed");
}
}

View file

@ -29,7 +29,6 @@
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator;
/**
@ -37,35 +36,41 @@ package org.lwjgl.util.generator;
* This class generates the initNatives native function.
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision$
* $Id$
* @version $Revision$ $Id$
*/
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
import java.io.*;
import java.util.*;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
public class RegisterStubsGenerator {
public static void generateMethodsNativeStubBind(PrintWriter writer, InterfaceDeclaration d, boolean generate_error_checks, boolean context_specific) {
Iterator<? extends MethodDeclaration> it = d.getMethods().iterator();
while (it.hasNext()) {
MethodDeclaration method = it.next();
public static void generateMethodsNativeStubBind(PrintWriter writer, TypeElement d, boolean generate_error_checks, boolean context_specific) {
Iterator<? extends ExecutableElement> it = Utils.getMethods(d).iterator();
while ( it.hasNext() ) {
ExecutableElement method = it.next();
Alternate alt_annotation = method.getAnnotation(Alternate.class);
if ( (alt_annotation != null && (!alt_annotation.nativeAlt() || alt_annotation.skipNative())) || method.getAnnotation(Reuse.class) != null )
if ( (alt_annotation != null && (!alt_annotation.nativeAlt() || alt_annotation.skipNative())) || method.getAnnotation(Reuse.class) != null ) {
continue;
}
EnumSet<Platform> platforms;
PlatformDependent platform_annotation = method.getAnnotation(PlatformDependent.class);
if (platform_annotation != null)
if ( platform_annotation != null ) {
platforms = EnumSet.copyOf(Arrays.asList(platform_annotation.value()));
else
} else {
platforms = EnumSet.of(Platform.ALL);
for (Platform platform : platforms) {
}
for ( Platform platform : platforms ) {
platform.printPrologue(writer);
boolean has_buffer_parameter = Utils.hasMethodBufferObjectParameter(method);
printMethodNativeStubBind(writer, d, method, platform, Mode.NORMAL, it.hasNext() || has_buffer_parameter, generate_error_checks, context_specific);
if (has_buffer_parameter) {
if ( has_buffer_parameter ) {
printMethodNativeStubBind(writer, d, method, platform, Mode.BUFFEROBJECT, it.hasNext(), generate_error_checks, context_specific);
}
platform.printEpilogue(writer);
@ -74,27 +79,30 @@ public class RegisterStubsGenerator {
writer.println();
}
private static String getTypeSignature(TypeMirror type, boolean add_position_signature) {
SignatureTranslator v = new SignatureTranslator(add_position_signature);
type.accept(v);
private static String getTypeSignature(TypeMirror type) {
SignatureTranslator v = new SignatureTranslator();
type.accept(v, null);
return v.getSignature();
}
private static String getMethodSignature(MethodDeclaration method, Mode mode) {
Collection<ParameterDeclaration> params = method.getParameters();
private static String getMethodSignature(ExecutableElement method, Mode mode) {
List<? extends VariableElement> params = method.getParameters();
String signature = "(";
for (ParameterDeclaration param : params) {
if ( param.getAnnotation(Result.class) != null || (param.getAnnotation(Helper.class) != null && !param.getAnnotation(Helper.class).passToNative()) )
for ( VariableElement param : params ) {
if ( param.getAnnotation(Result.class) != null || (param.getAnnotation(Helper.class) != null && !param.getAnnotation(Helper.class).passToNative()) ) {
continue;
}
final Constant constant_annotation = param.getAnnotation(Constant.class);
if ( constant_annotation != null && constant_annotation.isNative() )
if ( constant_annotation != null && constant_annotation.isNative() ) {
continue;
}
if (mode == Mode.BUFFEROBJECT && param.getAnnotation(BufferObject.class) != null)
if ( mode == Mode.BUFFEROBJECT && param.getAnnotation(BufferObject.class) != null ) {
signature += "J";
else
signature += getTypeSignature(param.getType(), true);
} else {
signature += getTypeSignature(param.asType());
}
}
final TypeMirror result_type = Utils.getMethodReturnType(method);
@ -102,33 +110,40 @@ public class RegisterStubsGenerator {
final AutoSize auto_size_annotation = method.getAnnotation(AutoSize.class);
final boolean isNIOBuffer = Utils.getNIOBufferType(result_type) != null;
if ( isNIOBuffer && (auto_size_annotation == null || !auto_size_annotation.isNative()) )
if ( isNIOBuffer && (auto_size_annotation == null || !auto_size_annotation.isNative()) ) {
signature += "J";
}
final String result_type_signature = isNIOBuffer ? "Ljava/nio/ByteBuffer;" : getTypeSignature(result_type, false);
if ( cached_result_annotation != null )
final String result_type_signature = isNIOBuffer ? "Ljava/nio/ByteBuffer;" : getTypeSignature(result_type);
if ( cached_result_annotation != null ) {
signature += result_type_signature;
}
signature += ")";
signature += result_type_signature;
return signature;
}
private static void printMethodNativeStubBind(PrintWriter writer, InterfaceDeclaration d, MethodDeclaration method, Platform platform, Mode mode, boolean has_more, boolean generate_error_checks, boolean context_specific) {
private static final Pattern GL_PATTERN = Pattern.compile("gl");
private static void printMethodNativeStubBind(PrintWriter writer, TypeElement d, ExecutableElement method, Platform platform, Mode mode, boolean has_more, boolean generate_error_checks, boolean context_specific) {
writer.print("\t\t{\"" + Utils.getSimpleNativeMethodName(method, generate_error_checks, context_specific));
if (mode == Mode.BUFFEROBJECT)
if ( mode == Mode.BUFFEROBJECT ) {
writer.print(Utils.BUFFER_OBJECT_METHOD_POSTFIX);
}
writer.print("\", \"" + getMethodSignature(method, mode) + "\", (void *)&");
writer.print(Utils.getQualifiedNativeMethodName(Utils.getQualifiedClassName(d), method, generate_error_checks, context_specific));
if (mode == Mode.BUFFEROBJECT)
if ( mode == Mode.BUFFEROBJECT ) {
writer.print(Utils.BUFFER_OBJECT_METHOD_POSTFIX);
}
final Alternate alt_annotation = method.getAnnotation(Alternate.class);
final String methodName = alt_annotation == null ? method.getSimpleName() : alt_annotation.value();
String opengl_handle_name = methodName.replaceFirst("gl", platform.getPrefix());
final String methodName = alt_annotation == null ? method.getSimpleName().toString() : alt_annotation.value();
String opengl_handle_name = GL_PATTERN.matcher(methodName).replaceFirst(platform.getPrefix());
writer.print(", \"" + opengl_handle_name + "\", (void *)&" + methodName + ", " + (method.getAnnotation(Optional.class) == null ? "false" : "true") + "}");
if (has_more)
if ( has_more ) {
writer.println(",");
}
}
}

View file

@ -42,55 +42,57 @@ package org.lwjgl.util.generator;
*/
import org.lwjgl.PointerBuffer;
import org.lwjgl.PointerWrapper;
import com.sun.mirror.type.*;
import com.sun.mirror.util.*;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.util.regex.Pattern;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.NoType;
import javax.lang.model.type.PrimitiveType;
import javax.lang.model.util.SimpleTypeVisitor6;
import java.nio.*;
class SignatureTranslator implements TypeVisitor {
private final boolean add_position_signature;
class SignatureTranslator extends SimpleTypeVisitor6<Void, Void> {
private final StringBuilder signature = new StringBuilder();
SignatureTranslator(boolean add_position_signature) {
this.add_position_signature = add_position_signature;
}
SignatureTranslator() {}
private static final Pattern DOT_PATTERN = Pattern.compile("\\.");
private static String getNativeNameFromClassName(String class_name) {
return class_name.replaceAll("\\.", "/");
return DOT_PATTERN.matcher(class_name).replaceAll("/");
}
public String getSignature() {
return signature.toString();
}
public void visitAnnotationType(AnnotationType t) {
throw new RuntimeException(t + " is not allowed");
}
public void visitArrayType(ArrayType t) {
@Override
public Void visitArray(ArrayType t, Void o) {
final Class type = Utils.getJavaType(t.getComponentType());
if ( CharSequence.class.isAssignableFrom(type) )
signature.append("J");
else if ( Buffer.class.isAssignableFrom(type) )
signature.append("[Ljava/nio/ByteBuffer;");
else if ( org.lwjgl.PointerWrapper.class.isAssignableFrom(type) )
else if ( PointerWrapper.class.isAssignableFrom(type) )
signature.append("[L" + getNativeNameFromClassName(type.getName()) + ";");
else
throw new RuntimeException(t + " is not allowed");
return DEFAULT_VALUE;
}
public void visitClassType(ClassType t) {
private void visitClassType(DeclaredType t) {
Class type = NativeTypeTranslator.getClassFromType(t);
if ( org.lwjgl.PointerWrapper.class.isAssignableFrom(type) || (Utils.isAddressableType(type) && !String.class.equals(type)) )
if ( PointerWrapper.class.isAssignableFrom(type) || (Utils.isAddressableType(type) && !String.class.equals(type)) )
signature.append("J");
else {
String type_name;
if ( (CharSequence.class.isAssignableFrom(type) && !String.class.equals(type)) || CharSequence[].class.isAssignableFrom(type) || PointerBuffer.class.isAssignableFrom(type) )
type_name = ByteBuffer.class.getName();
else
type_name = t.getDeclaration().getQualifiedName();
type_name = t.toString();
signature.append("L");
signature.append(getNativeNameFromClassName(type_name));
@ -98,24 +100,26 @@ class SignatureTranslator implements TypeVisitor {
}
}
public void visitDeclaredType(DeclaredType t) {
throw new RuntimeException(t + " is not allowed");
@Override
public Void visitDeclared(DeclaredType t, Void o) {
if ( t.asElement().getKind().isClass() )
visitClassType(t);
else if ( t.asElement().getKind().isInterface() )
visitInterfaceType(t);
return DEFAULT_VALUE;
}
public void visitEnumType(EnumType t) {
throw new RuntimeException(t + " is not allowed");
}
public void visitInterfaceType(InterfaceType t) {
private void visitInterfaceType(DeclaredType t) {
Class type = NativeTypeTranslator.getClassFromType(t);
if ( org.lwjgl.PointerWrapper.class.isAssignableFrom(type) )
if ( PointerWrapper.class.isAssignableFrom(type) )
signature.append("J");
else
throw new RuntimeException(t + " is not allowed");
}
public void visitPrimitiveType(PrimitiveType t) {
switch (t.getKind()) {
@Override
public Void visitPrimitive(PrimitiveType t, Void o) {
switch ( t.getKind() ) {
case BOOLEAN:
signature.append("Z");
break;
@ -140,25 +144,13 @@ class SignatureTranslator implements TypeVisitor {
default:
throw new RuntimeException("Unsupported type " + t);
}
return DEFAULT_VALUE;
}
public void visitReferenceType(ReferenceType t) {
throw new RuntimeException(t + " is not allowed");
}
public void visitTypeMirror(TypeMirror t) {
throw new RuntimeException(t + " is not allowed");
}
public void visitTypeVariable(TypeVariable t) {
throw new RuntimeException(t + " is not allowed");
}
public void visitVoidType(VoidType t) {
@Override
public Void visitNoType(NoType t, Void o) {
signature.append("V");
return DEFAULT_VALUE;
}
public void visitWildcardType(WildcardType t) {
throw new RuntimeException(t + " is not allowed");
}
}

View file

@ -33,29 +33,31 @@ package org.lwjgl.util.generator;
/**
*
* This class represent a parameter configuration. There are multiple
* TypeInfos in case of multityped parameters.
* This class represent a parameter configuration. There are multiple TypeInfos
* in case of multityped parameters.
*
* @author elias_naur <elias_naur@users.sourceforge.net>
* @version $Revision$
* $Id$
* @version $Revision$ $Id$
*/
import org.lwjgl.PointerBuffer;
import org.lwjgl.util.generator.opengl.GLvoid;
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
import java.lang.annotation.Annotation;
import java.util.*;
import java.nio.*;
import java.util.*;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
public class TypeInfo {
public static final String UNSIGNED_PARAMETER_NAME = "unsigned";
private final Signedness signedness;
private final Class type;
private final String auto_type;
private final Class type;
private final String auto_type;
private TypeInfo(Class type, Signedness signedness, String auto_type) {
this.type = type;
@ -72,14 +74,15 @@ public class TypeInfo {
}
public String getAutoType() {
if (auto_type == null)
if ( auto_type == null ) {
throw new RuntimeException("No auto type assigned");
}
return auto_type;
}
private static Class getTypeFromPrimitiveKind(PrimitiveType.Kind kind) {
private static Class getTypeFromPrimitiveKind(TypeKind kind) {
Class type;
switch (kind) {
switch ( kind ) {
case LONG:
type = long.class;
break;
@ -107,9 +110,9 @@ public class TypeInfo {
return type;
}
private static Class getBufferTypeFromPrimitiveKind(PrimitiveType.Kind kind) {
private static Class getBufferTypeFromPrimitiveKind(TypeKind kind, AnnotationMirror annotation) {
Class type;
switch (kind) {
switch ( kind ) {
case INT:
type = IntBuffer.class;
break;
@ -123,9 +126,14 @@ public class TypeInfo {
type = ShortBuffer.class;
break;
case LONG:
type = LongBuffer.class;
if ( annotation.getAnnotationType().asElement().getAnnotation(PointerType.class) != null ) {
type = PointerBuffer.class;
} else {
type = LongBuffer.class;
}
break;
case BYTE: /* fall through */
case BOOLEAN:
type = ByteBuffer.class;
break;
@ -140,33 +148,34 @@ public class TypeInfo {
return new TypeInfo(java_type, Signedness.NONE, null);
}
public static Map<ParameterDeclaration, TypeInfo> getDefaultTypeInfoMap(MethodDeclaration method) {
Map<ParameterDeclaration, TypeInfo> map = new HashMap<ParameterDeclaration, TypeInfo>();
for (ParameterDeclaration param : method.getParameters()) {
TypeInfo type_info = getDefaultTypeInfo(param.getType());
public static Map<VariableElement, TypeInfo> getDefaultTypeInfoMap(ExecutableElement method) {
Map<VariableElement, TypeInfo> map = new HashMap<VariableElement, TypeInfo>();
for ( VariableElement param : method.getParameters() ) {
TypeInfo type_info = getDefaultTypeInfo(param.asType());
map.put(param, type_info);
}
return map;
}
private static Collection<TypeInfo> getTypeInfos(TypeMap type_map, Declaration param, TypeMirror decl_type) {
Collection<AnnotationMirror> annotations = Utils.getSortedAnnotations(param.getAnnotationMirrors());
private static Collection<TypeInfo> getTypeInfos(TypeMap type_map, VariableElement param) {
List<? extends AnnotationMirror> annotations = Utils.getSortedAnnotations(param.getAnnotationMirrors());
GLvoid void_annotation = param.getAnnotation(GLvoid.class);
Map<Class, TypeInfo> types = new HashMap<Class, TypeInfo>();
Collection<TypeInfo> multityped_result = new ArrayList<TypeInfo>();
boolean add_default_type = true;
for (AnnotationMirror annotation : annotations) {
for ( AnnotationMirror annotation : annotations ) {
NativeType native_type_annotation = NativeTypeTranslator.getAnnotation(annotation, NativeType.class);
if (native_type_annotation != null) {
if ( native_type_annotation != null ) {
Class<? extends Annotation> annotation_type = NativeTypeTranslator.getClassFromType(annotation.getAnnotationType());
Signedness signedness = type_map.getSignednessFromType(annotation_type);
Class inverse_type = type_map.getInverseType(annotation_type);
String auto_type = type_map.getAutoTypeFromAnnotation(annotation);
if (inverse_type != null) {
if (types.containsKey(inverse_type)) {
if ( inverse_type != null ) {
if ( types.containsKey(inverse_type) ) {
TypeInfo inverse_type_info = types.get(inverse_type);
String inverse_auto_type = inverse_type_info.getAutoType();
auto_type = signedness == Signedness.UNSIGNED ? auto_type + " : " + inverse_auto_type :
inverse_auto_type + " : " + auto_type;
auto_type = signedness == Signedness.UNSIGNED ? auto_type + " : " + inverse_auto_type : inverse_auto_type + " : " + auto_type;
auto_type = UNSIGNED_PARAMETER_NAME + " ? " + auto_type;
signedness = Signedness.BOTH;
types.remove(inverse_type);
@ -174,59 +183,59 @@ public class TypeInfo {
}
}
Class type;
PrimitiveType.Kind kind;
GLvoid void_annotation = param.getAnnotation(GLvoid.class);
TypeKind kind;
kind = void_annotation == null ? type_map.getPrimitiveTypeFromNativeType(annotation_type) : void_annotation.value();
if (Utils.getNIOBufferType(decl_type) != null)
type = getBufferTypeFromPrimitiveKind(kind);
else
if ( Utils.getNIOBufferType(param.asType()) != null ) {
type = getBufferTypeFromPrimitiveKind(kind, annotation);
} else {
type = getTypeFromPrimitiveKind(kind);
}
TypeInfo type_info = new TypeInfo(type, signedness, auto_type);
types.put(annotation_type, type_info);
multityped_result.add(type_info);
add_default_type = false;
}
}
if (add_default_type) {
TypeInfo default_type_info = getDefaultTypeInfo(decl_type);
if ( add_default_type ) {
TypeInfo default_type_info = getDefaultTypeInfo(param.asType());
Collection<TypeInfo> result = new ArrayList<TypeInfo>();
result.add(default_type_info);
return result;
} else
} else {
return multityped_result;
}
}
private static Map<ParameterDeclaration, Collection<TypeInfo>> getTypeInfoMap(TypeMap type_map, MethodDeclaration method) {
Map<ParameterDeclaration, Collection<TypeInfo>> map = new HashMap<ParameterDeclaration, Collection<TypeInfo>>();
for (ParameterDeclaration param : method.getParameters()) {
Collection<TypeInfo> types = getTypeInfos(type_map, param, param.getType());
private static Map<VariableElement, Collection<TypeInfo>> getTypeInfoMap(TypeMap type_map, ExecutableElement method) {
Map<VariableElement, Collection<TypeInfo>> map = new HashMap<VariableElement, Collection<TypeInfo>>();
for ( VariableElement param : method.getParameters() ) {
Collection<TypeInfo> types = getTypeInfos(type_map, param);
map.put(param, types);
}
return map;
}
public static Collection<Map<ParameterDeclaration, TypeInfo>> getTypeInfoCrossProduct(TypeMap type_map, MethodDeclaration method) {
Collection<ParameterDeclaration> parameter_collection = method.getParameters();
ParameterDeclaration[] parameters = new ParameterDeclaration[parameter_collection.size()];
parameter_collection.toArray(parameters);
Collection<Map<ParameterDeclaration, TypeInfo>> cross_product = new ArrayList<Map<ParameterDeclaration, TypeInfo>>();
getCrossProductRecursive(0, parameters, getTypeInfoMap(type_map, method),
new HashMap<ParameterDeclaration, TypeInfo>(), cross_product);
public static Collection<Map<VariableElement, TypeInfo>> getTypeInfoCrossProduct(TypeMap type_map, ExecutableElement method) {
List<? extends VariableElement> parameter_collection = method.getParameters();
Collection<Map<VariableElement, TypeInfo>> cross_product = new ArrayList<Map<VariableElement, TypeInfo>>();
getCrossProductRecursive(0, parameter_collection, getTypeInfoMap(type_map, method),
new HashMap<VariableElement, TypeInfo>(), cross_product);
return cross_product;
}
private static void getCrossProductRecursive(int index, ParameterDeclaration[] parameters, Map<ParameterDeclaration,
Collection<TypeInfo>> typeinfos_map, Map<ParameterDeclaration, TypeInfo> current_instance,
Collection<Map<ParameterDeclaration, TypeInfo>> cross_product) {
if (index == parameters.length) {
private static void getCrossProductRecursive(int index, List<? extends VariableElement> parameters, Map<VariableElement, Collection<TypeInfo>> typeinfos_map, Map<VariableElement, TypeInfo> current_instance, Collection<Map<VariableElement, TypeInfo>> cross_product) {
if ( index == parameters.size() ) {
/**
* the last parameter is treated as multi-type only
*/
cross_product.add(current_instance);
return;
}
ParameterDeclaration param = parameters[index];
VariableElement param = parameters.get(index);
Collection<TypeInfo> typeinfos = typeinfos_map.get(param);
if (typeinfos != null) {
for (TypeInfo typeinfo : typeinfos) {
Map<ParameterDeclaration, TypeInfo> instance = new HashMap<ParameterDeclaration, TypeInfo>(current_instance);
if ( typeinfos != null ) {
for ( TypeInfo typeinfo : typeinfos ) {
Map<VariableElement, TypeInfo> instance = new HashMap<VariableElement, TypeInfo>(current_instance);
instance.put(param, typeinfo);
getCrossProductRecursive(index + 1, parameters, typeinfos_map, instance, cross_product);
}

View file

@ -41,19 +41,19 @@ package org.lwjgl.util.generator;
* $Id$
*/
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
import java.io.*;
import java.io.PrintWriter;
import java.lang.annotation.Annotation;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.type.TypeKind;
public interface TypeMap {
void printCapabilitiesInit(PrintWriter writer);
String getCapabilities();
String getAPIUtilParam(boolean comma);
void printErrorCheckMethod(PrintWriter writer, MethodDeclaration method, String tabs);
void printErrorCheckMethod(PrintWriter writer, ExecutableElement method, String tabs);
String getRegisterNativesFunctionName();
PrimitiveType.Kind getPrimitiveTypeFromNativeType(Class<? extends Annotation> native_type);
TypeKind getPrimitiveTypeFromNativeType(Class<? extends Annotation> native_type);
String getTypedefPostfix();
String getFunctionPrefix();
void printNativeIncludes(PrintWriter writer);
@ -63,7 +63,7 @@ public interface TypeMap {
Class[] getValidAnnotationTypes(Class type);
Class<? extends Annotation> getVoidType();
String translateAnnotation(Class<? extends Annotation> annotation_type);
Class getNativeTypeFromPrimitiveType(PrimitiveType.Kind kind);
Class getNativeTypeFromPrimitiveType(TypeKind kind);
String getAutoTypeFromAnnotation(AnnotationMirror annotation);
Class<? extends Annotation> getInverseType(Class<? extends Annotation> type);
Signedness getSignednessFromType(Class<? extends Annotation> type);

View file

@ -41,19 +41,19 @@ package org.lwjgl.util.generator;
* $Id$
*/
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
import java.io.*;
import java.util.*;
import java.io.PrintWriter;
import java.util.Collection;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
public class TypedefsGenerator {
private static void generateNativeTypedefs(TypeMap type_map, PrintWriter writer, MethodDeclaration method) {
private static void generateNativeTypedefs(TypeMap type_map, PrintWriter writer, ExecutableElement method) {
TypeMirror return_type = method.getReturnType();
writer.print("typedef ");
writer.print(type_map.getTypedefPostfix());
NativeTypeTranslator translator = new NativeTypeTranslator(type_map, method);
return_type.accept(translator);
return_type.accept(translator, null);
writer.print(translator.getSignature());
writer.print(" (");
writer.print(type_map.getFunctionPrefix());
@ -62,10 +62,10 @@ public class TypedefsGenerator {
writer.println(");");
}
private static void generateNativeTypedefsParameters(TypeMap type_map, PrintWriter writer, Collection<ParameterDeclaration> params) {
if (params.size() > 0) {
private static void generateNativeTypedefsParameters(TypeMap type_map, PrintWriter writer, Collection<? extends VariableElement> params) {
if ( params.size() > 0 ) {
boolean first = true;
for ( ParameterDeclaration param : params ) {
for ( VariableElement param : params ) {
if ( param.getAnnotation(Helper.class) != null )
continue;
@ -79,17 +79,17 @@ public class TypedefsGenerator {
}
}
private static void generateNativeTypedefsParameter(TypeMap type_map, PrintWriter writer, ParameterDeclaration param) {
private static void generateNativeTypedefsParameter(TypeMap type_map, PrintWriter writer, VariableElement param) {
NativeTypeTranslator translator = new NativeTypeTranslator(type_map, param);
param.getType().accept(translator);
param.asType().accept(translator, null);
writer.print(translator.getSignature());
if (param.getAnnotation(Result.class) != null || param.getAnnotation(Indirect.class) != null || param.getAnnotation(PointerArray.class) != null)
if ( param.getAnnotation(Result.class) != null || param.getAnnotation(Indirect.class) != null || param.getAnnotation(PointerArray.class) != null )
writer.print("*");
writer.print(" " + param.getSimpleName());
}
public static void generateNativeTypedefs(TypeMap type_map, PrintWriter writer, Collection<? extends MethodDeclaration> methods) {
for (MethodDeclaration method : methods) {
public static void generateNativeTypedefs(TypeMap type_map, PrintWriter writer, Collection<? extends ExecutableElement> methods) {
for ( ExecutableElement method : methods ) {
if ( method.getAnnotation(Alternate.class) == null && method.getAnnotation(Reuse.class) == null )
generateNativeTypedefs(type_map, writer, method);
}

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