summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorJames Cowgill <james410@cowgill.org.uk>2013-08-23 09:57:55 +0100
committerJames Cowgill <james410@cowgill.org.uk>2013-08-23 09:57:55 +0100
commit9a298ca833d9b6a3425bb30c2e52cf04e34aeb7c (patch)
treed46630a885bcea03bbea036b86c645dc6c55708d /src
parent0969839d538a385254c6eced9648acc7299876cc (diff)
Imported Upstream version 2.1+dfsg
Diffstat (limited to 'src')
-rw-r--r--[-rwxr-xr-x]src/SFML/Audio/ALCheck.cpp (renamed from src/SFML/Audio/OpenAL.hpp)241
-rw-r--r--[-rwxr-xr-x]src/SFML/Audio/ALCheck.hpp (renamed from src/SFML/Window/Template for new ports/Joystick.cpp)58
-rw-r--r--[-rwxr-xr-x]src/SFML/Audio/AudioDevice.cpp133
-rw-r--r--[-rwxr-xr-x]src/SFML/Audio/AudioDevice.hpp73
-rw-r--r--src/SFML/Audio/CMakeLists.txt53
-rw-r--r--[-rwxr-xr-x]src/SFML/Audio/Listener.cpp81
-rwxr-xr-xsrc/SFML/Audio/Makefile39
-rw-r--r--[-rwxr-xr-x]src/SFML/Audio/Music.cpp136
-rw-r--r--[-rwxr-xr-x]src/SFML/Audio/Sound.cpp334
-rw-r--r--[-rwxr-xr-x]src/SFML/Audio/SoundBuffer.cpp267
-rw-r--r--[-rwxr-xr-x]src/SFML/Audio/SoundBufferRecorder.cpp29
-rw-r--r--[-rwxr-xr-x]src/SFML/Audio/SoundFile.cpp448
-rw-r--r--[-rwxr-xr-x]src/SFML/Audio/SoundFile.hpp183
-rwxr-xr-xsrc/SFML/Audio/SoundFileDefault.cpp352
-rwxr-xr-xsrc/SFML/Audio/SoundFileDefault.hpp156
-rwxr-xr-xsrc/SFML/Audio/SoundFileOgg.cpp182
-rw-r--r--[-rwxr-xr-x]src/SFML/Audio/SoundRecorder.cpp136
-rw-r--r--src/SFML/Audio/SoundSource.cpp194
-rw-r--r--[-rwxr-xr-x]src/SFML/Audio/SoundStream.cpp311
-rwxr-xr-xsrc/SFML/Audio/stb_vorbis/stb_vorbis.c5039
-rwxr-xr-xsrc/SFML/Audio/stb_vorbis/stb_vorbis.h357
-rw-r--r--src/SFML/CMakeLists.txt45
-rw-r--r--src/SFML/Graphics/CMakeLists.txt135
-rw-r--r--src/SFML/Graphics/CircleShape.cpp84
-rw-r--r--[-rwxr-xr-x]src/SFML/Graphics/Color.cpp78
-rw-r--r--[-rwxr-xr-x]src/SFML/Graphics/ConvexShape.cpp (renamed from src/SFML/System/Unix/Mutex.cpp)137
-rwxr-xr-xsrc/SFML/Graphics/Drawable.cpp402
-rw-r--r--[-rwxr-xr-x]src/SFML/Graphics/Font.cpp591
-rwxr-xr-xsrc/SFML/Graphics/FontLoader.cpp419
-rw-r--r--src/SFML/Graphics/GLCheck.cpp130
-rw-r--r--[-rwxr-xr-x]src/SFML/Graphics/GLCheck.hpp (renamed from src/SFML/Window/Cocoa/Joystick.cpp)152
-rwxr-xr-xsrc/SFML/Graphics/GraphicsContext.cpp94
-rwxr-xr-xsrc/SFML/Graphics/GraphicsContext.hpp176
-rw-r--r--[-rwxr-xr-x]src/SFML/Graphics/Image.cpp765
-rw-r--r--[-rwxr-xr-x]src/SFML/Graphics/ImageLoader.cpp351
-rw-r--r--[-rwxr-xr-x]src/SFML/Graphics/ImageLoader.hpp90
-rwxr-xr-xsrc/SFML/Graphics/Makefile47
-rwxr-xr-xsrc/SFML/Graphics/PostFX.cpp506
-rw-r--r--src/SFML/Graphics/RectangleShape.cpp76
-rw-r--r--src/SFML/Graphics/RenderStates.cpp98
-rw-r--r--[-rwxr-xr-x]src/SFML/Graphics/RenderTarget.cpp434
-rw-r--r--src/SFML/Graphics/RenderTexture.cpp155
-rw-r--r--src/SFML/Graphics/RenderTextureImpl.cpp43
-rw-r--r--src/SFML/Graphics/RenderTextureImpl.hpp89
-rw-r--r--src/SFML/Graphics/RenderTextureImplDefault.cpp91
-rw-r--r--src/SFML/Graphics/RenderTextureImplDefault.hpp107
-rw-r--r--src/SFML/Graphics/RenderTextureImplFBO.cpp146
-rw-r--r--src/SFML/Graphics/RenderTextureImplFBO.hpp115
-rw-r--r--[-rwxr-xr-x]src/SFML/Graphics/RenderWindow.cpp120
-rw-r--r--src/SFML/Graphics/Shader.cpp593
-rw-r--r--[-rwxr-xr-x]src/SFML/Graphics/Shape.cpp426
-rw-r--r--[-rwxr-xr-x]src/SFML/Graphics/Sprite.cpp200
-rwxr-xr-xsrc/SFML/Graphics/String.cpp412
-rw-r--r--src/SFML/Graphics/Text.cpp346
-rw-r--r--src/SFML/Graphics/Texture.cpp545
-rw-r--r--[-rwxr-xr-x]src/SFML/Graphics/TextureSaver.cpp (renamed from src/SFML/Graphics/Matrix3.cpp)90
-rw-r--r--[-rwxr-xr-x]src/SFML/Graphics/TextureSaver.hpp (renamed from src/SFML/System/Win32/Platform.hpp)144
-rw-r--r--src/SFML/Graphics/Transform.cpp272
-rw-r--r--src/SFML/Graphics/Transformable.cpp219
-rw-r--r--src/SFML/Graphics/Vertex.cpp77
-rw-r--r--src/SFML/Graphics/VertexArray.cpp150
-rw-r--r--[-rwxr-xr-x]src/SFML/Graphics/View.cpp218
-rw-r--r--src/SFML/Graphics/stb_image/stb_image.h4673
-rw-r--r--src/SFML/Graphics/stb_image/stb_image_write.h511
-rw-r--r--src/SFML/Main/CMakeLists.txt21
-rw-r--r--[-rwxr-xr-x]src/SFML/Main/SFML_Main.cpp2
-rwxr-xr-xsrc/SFML/Makefile67
-rw-r--r--src/SFML/Network/CMakeLists.txt57
-rw-r--r--[-rwxr-xr-x]src/SFML/Network/Ftp.cpp532
-rw-r--r--[-rwxr-xr-x]src/SFML/Network/Http.cpp318
-rwxr-xr-xsrc/SFML/Network/IPAddress.cpp298
-rw-r--r--src/SFML/Network/IpAddress.cpp255
-rwxr-xr-xsrc/SFML/Network/Makefile34
-rw-r--r--[-rwxr-xr-x]src/SFML/Network/Packet.cpp425
-rwxr-xr-xsrc/SFML/Network/SelectorBase.cpp132
-rw-r--r--src/SFML/Network/Socket.cpp144
-rw-r--r--[-rwxr-xr-x]src/SFML/Network/SocketImpl.hpp (renamed from src/SFML/System/Platform.hpp)14
-rw-r--r--src/SFML/Network/SocketSelector.cpp141
-rwxr-xr-xsrc/SFML/Network/SocketTCP.cpp511
-rwxr-xr-xsrc/SFML/Network/SocketUDP.cpp433
-rw-r--r--src/SFML/Network/TcpListener.cpp124
-rw-r--r--src/SFML/Network/TcpSocket.cpp381
-rw-r--r--src/SFML/Network/UdpSocket.cpp193
-rw-r--r--[-rwxr-xr-x]src/SFML/Network/Unix/SocketImpl.cpp (renamed from src/SFML/Network/Unix/SocketHelper.cpp)47
-rw-r--r--src/SFML/Network/Unix/SocketImpl.hpp109
-rw-r--r--[-rwxr-xr-x]src/SFML/Network/Win32/SocketImpl.cpp (renamed from src/SFML/Network/Win32/SocketHelper.cpp)50
-rw-r--r--src/SFML/Network/Win32/SocketImpl.hpp112
-rw-r--r--src/SFML/System/CMakeLists.txt83
-rw-r--r--[-rwxr-xr-x]src/SFML/System/Clock.cpp31
-rw-r--r--src/SFML/System/Err.cpp110
-rw-r--r--[-rwxr-xr-x]src/SFML/System/Lock.cpp14
-rwxr-xr-xsrc/SFML/System/Makefile34
-rw-r--r--src/SFML/System/Mutex.cpp66
-rwxr-xr-xsrc/SFML/System/Randomizer.cpp96
-rw-r--r--[-rwxr-xr-x]src/SFML/System/Sleep.cpp17
-rw-r--r--src/SFML/System/String.cpp335
-rw-r--r--src/SFML/System/Thread.cpp86
-rw-r--r--src/SFML/System/ThreadLocal.cpp67
-rw-r--r--src/SFML/System/Time.cpp239
-rwxr-xr-xsrc/SFML/System/Unicode.cpp300
-rw-r--r--src/SFML/System/Unix/ClockImpl.cpp64
-rw-r--r--[-rwxr-xr-x]src/SFML/System/Unix/ClockImpl.hpp (renamed from src/SFML/System/Unix/Platform.hpp)130
-rwxr-xr-xsrc/SFML/System/Unix/Initializer.cpp86
-rw-r--r--[-rwxr-xr-x]src/SFML/System/Unix/MutexImpl.cpp (renamed from src/SFML/Window/Template for new ports/VideoModeSupport.cpp)33
-rw-r--r--[-rwxr-xr-x]src/SFML/System/Unix/MutexImpl.hpp (renamed from src/SFML/Window/Template for new ports/Joystick.hpp)45
-rw-r--r--src/SFML/System/Unix/SleepImpl.cpp77
-rw-r--r--src/SFML/System/Unix/SleepImpl.hpp52
-rwxr-xr-xsrc/SFML/System/Unix/Thread.cpp148
-rw-r--r--[-rwxr-xr-x]src/SFML/System/Unix/ThreadImpl.cpp (renamed from src/SFML/System/Win32/Platform.cpp)57
-rw-r--r--[-rwxr-xr-x]src/SFML/System/Unix/ThreadImpl.hpp (renamed from src/SFML/Window/Linux/Joystick.hpp)64
-rw-r--r--[-rwxr-xr-x]src/SFML/System/Unix/ThreadLocalImpl.cpp (renamed from src/SFML/System/Unix/Platform.cpp)32
-rw-r--r--src/SFML/System/Unix/ThreadLocalImpl.hpp87
-rw-r--r--src/SFML/System/Win32/ClockImpl.cpp71
-rw-r--r--src/SFML/System/Win32/ClockImpl.hpp61
-rw-r--r--src/SFML/System/Win32/MutexImpl.cpp64
-rw-r--r--[-rwxr-xr-x]src/SFML/System/Win32/MutexImpl.hpp (renamed from src/SFML/Window/Cocoa/Joystick.hpp)167
-rw-r--r--src/SFML/System/Win32/SleepImpl.cpp44
-rw-r--r--src/SFML/System/Win32/SleepImpl.hpp52
-rwxr-xr-xsrc/SFML/System/Win32/Thread.cpp146
-rw-r--r--src/SFML/System/Win32/ThreadImpl.cpp93
-rw-r--r--[-rwxr-xr-x]src/SFML/System/Win32/ThreadImpl.hpp (renamed from src/SFML/Window/Win32/Joystick.hpp)59
-rw-r--r--src/SFML/System/Win32/ThreadLocalImpl.cpp64
-rw-r--r--src/SFML/System/Win32/ThreadLocalImpl.hpp87
-rw-r--r--src/SFML/Window/CMakeLists.txt132
-rwxr-xr-xsrc/SFML/Window/Cocoa/AppController.h95
-rwxr-xr-xsrc/SFML/Window/Cocoa/AppController.mm578
-rwxr-xr-xsrc/SFML/Window/Cocoa/GLKit.h233
-rwxr-xr-xsrc/SFML/Window/Cocoa/GLKit.mm1124
-rwxr-xr-xsrc/SFML/Window/Cocoa/VideoModeSupport.cpp101
-rwxr-xr-xsrc/SFML/Window/Cocoa/WindowImplCocoa.hpp205
-rwxr-xr-xsrc/SFML/Window/Cocoa/WindowImplCocoa.mm844
-rw-r--r--[-rwxr-xr-x]src/SFML/Window/Context.cpp44
-rw-r--r--src/SFML/Window/GlContext.cpp280
-rw-r--r--src/SFML/Window/GlContext.hpp234
-rw-r--r--src/SFML/Window/GlResource.cpp85
-rwxr-xr-xsrc/SFML/Window/Input.cpp169
-rw-r--r--[-rwxr-xr-x]src/SFML/Window/InputImpl.hpp (renamed from src/SFML/Window/VideoModeSupport.hpp)21
-rw-r--r--src/SFML/Window/Joystick.cpp75
-rw-r--r--[-rwxr-xr-x]src/SFML/Window/JoystickImpl.hpp (renamed from src/SFML/Window/Win32/VideoModeSupport.cpp)163
-rw-r--r--src/SFML/Window/JoystickManager.cpp114
-rw-r--r--[-rwxr-xr-x]src/SFML/Window/JoystickManager.hpp (renamed from src/SFML/Graphics/FontLoader.hpp)250
-rw-r--r--src/SFML/Window/Keyboard.cpp40
-rw-r--r--src/SFML/Window/Linux/Display.cpp65
-rw-r--r--src/SFML/Window/Linux/Display.hpp62
-rw-r--r--src/SFML/Window/Linux/GlxContext.cpp343
-rw-r--r--src/SFML/Window/Linux/GlxContext.hpp148
-rw-r--r--src/SFML/Window/Linux/InputImpl.cpp293
-rw-r--r--src/SFML/Window/Linux/InputImpl.hpp123
-rwxr-xr-xsrc/SFML/Window/Linux/Joystick.cpp219
-rw-r--r--src/SFML/Window/Linux/JoystickImpl.cpp256
-rw-r--r--[-rwxr-xr-x]src/SFML/Window/Linux/JoystickImpl.hpp (renamed from src/SFML/Audio/SoundFileOgg.hpp)235
-rw-r--r--src/SFML/Window/Linux/VideoModeImpl.cpp176
-rwxr-xr-xsrc/SFML/Window/Linux/VideoModeSupport.cpp144
-rwxr-xr-xsrc/SFML/Window/Linux/VideoModeSupport.hpp69
-rw-r--r--[-rwxr-xr-x]src/SFML/Window/Linux/WindowImplX11.cpp2251
-rw-r--r--[-rwxr-xr-x]src/SFML/Window/Linux/WindowImplX11.hpp500
-rwxr-xr-xsrc/SFML/Window/Makefile35
-rw-r--r--[-rwxr-xr-x]src/SFML/Window/Mouse.cpp (renamed from src/SFML/System/Win32/Mutex.cpp)137
-rw-r--r--src/SFML/Window/OSX/AutoreleasePoolWrapper.h51
-rw-r--r--src/SFML/Window/OSX/AutoreleasePoolWrapper.mm239
-rw-r--r--src/SFML/Window/OSX/HIDInputManager.hpp264
-rw-r--r--src/SFML/Window/OSX/HIDInputManager.mm1027
-rw-r--r--src/SFML/Window/OSX/HIDJoystickManager.cpp151
-rw-r--r--src/SFML/Window/OSX/HIDJoystickManager.hpp128
-rw-r--r--src/SFML/Window/OSX/InputImpl.hpp124
-rw-r--r--src/SFML/Window/OSX/InputImpl.mm183
-rw-r--r--src/SFML/Window/OSX/JoystickImpl.cpp402
-rw-r--r--src/SFML/Window/OSX/JoystickImpl.hpp126
-rw-r--r--[-rwxr-xr-x]src/SFML/Window/OSX/SFApplication.h (renamed from src/SFML/Audio/AudioResource.cpp)115
-rw-r--r--src/SFML/Window/OSX/SFApplication.m64
-rw-r--r--src/SFML/Window/OSX/SFContext.hpp161
-rw-r--r--src/SFML/Window/OSX/SFContext.mm223
-rw-r--r--src/SFML/Window/OSX/SFKeyboardModifiersHelper.h61
-rw-r--r--src/SFML/Window/OSX/SFKeyboardModifiersHelper.mm247
-rw-r--r--src/SFML/Window/OSX/SFOpenGLView.h120
-rw-r--r--src/SFML/Window/OSX/SFOpenGLView.mm695
-rw-r--r--src/SFML/Window/OSX/SFSilentResponder.h41
-rw-r--r--src/SFML/Window/OSX/SFSilentResponder.m39
-rw-r--r--src/SFML/Window/OSX/SFViewController.h49
-rw-r--r--src/SFML/Window/OSX/SFViewController.mm241
-rw-r--r--src/SFML/Window/OSX/SFWindow.h48
-rw-r--r--src/SFML/Window/OSX/SFWindow.m59
-rw-r--r--src/SFML/Window/OSX/SFWindowController.h79
-rw-r--r--src/SFML/Window/OSX/SFWindowController.mm546
-rw-r--r--src/SFML/Window/OSX/VideoModeImpl.cpp118
-rw-r--r--src/SFML/Window/OSX/WindowImplCocoa.hpp343
-rw-r--r--src/SFML/Window/OSX/WindowImplCocoa.mm418
-rw-r--r--src/SFML/Window/OSX/WindowImplDelegateProtocol.h159
-rw-r--r--src/SFML/Window/OSX/cg_sf_conversion.cpp181
-rw-r--r--src/SFML/Window/OSX/cg_sf_conversion.hpp82
-rw-r--r--src/SFML/Window/OSX/cpp_objc_conversion.h39
-rw-r--r--src/SFML/Window/OSX/cpp_objc_conversion.mm58
-rwxr-xr-xsrc/SFML/Window/Template for new ports/VideoModeSupport.hpp69
-rwxr-xr-xsrc/SFML/Window/Template for new ports/WindowImplXXX.cpp231
-rwxr-xr-xsrc/SFML/Window/Template for new ports/WindowImplXXX.hpp167
-rw-r--r--[-rwxr-xr-x]src/SFML/Window/VideoMode.cpp148
-rw-r--r--[-rwxr-xr-x]src/SFML/Window/VideoModeImpl.hpp (renamed from src/SFML/Window/Cocoa/VideoModeSupport.hpp)137
-rw-r--r--src/SFML/Window/Win32/InputImpl.cpp225
-rw-r--r--src/SFML/Window/Win32/InputImpl.hpp123
-rwxr-xr-xsrc/SFML/Window/Win32/Joystick.cpp157
-rw-r--r--src/SFML/Window/Win32/JoystickImpl.cpp189
-rw-r--r--src/SFML/Window/Win32/JoystickImpl.hpp125
-rw-r--r--[-rwxr-xr-x]src/SFML/Window/Win32/VideoModeImpl.cpp (renamed from src/SFML/Window/Joystick.hpp)151
-rwxr-xr-xsrc/SFML/Window/Win32/VideoModeSupport.hpp69
-rw-r--r--src/SFML/Window/Win32/WglContext.cpp325
-rw-r--r--src/SFML/Window/Win32/WglContext.hpp136
-rw-r--r--[-rwxr-xr-x]src/SFML/Window/Win32/WindowImplWin32.cpp1259
-rw-r--r--[-rwxr-xr-x]src/SFML/Window/Win32/WindowImplWin32.hpp199
-rw-r--r--[-rwxr-xr-x]src/SFML/Window/Window.cpp433
-rw-r--r--[-rwxr-xr-x]src/SFML/Window/WindowImpl.cpp243
-rw-r--r--[-rwxr-xr-x]src/SFML/Window/WindowImpl.hpp227
-rw-r--r--src/SFML/Window/glext/glext.h11028
-rw-r--r--src/SFML/Window/glext/glxext.h993
-rw-r--r--src/SFML/Window/glext/wglext.h901
214 files changed, 42413 insertions, 22861 deletions
diff --git a/src/SFML/Audio/OpenAL.hpp b/src/SFML/Audio/ALCheck.cpp
index c1dea8c..0558f11 100755..100644
--- a/src/SFML/Audio/OpenAL.hpp
+++ b/src/SFML/Audio/ALCheck.cpp
@@ -1,132 +1,109 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-#ifndef SFML_OPENAL_HPP
-#define SFML_OPENAL_HPP
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Config.hpp>
-
-#if defined(SFML_SYSTEM_MACOS)
-#include <OpenAL/al.h>
-#include <OpenAL/alc.h>
-#else
-#include <AL/al.h>
-#include <AL/alc.h>
-#endif
-
-#include <iostream>
-#include <string>
-
-
-namespace sf
-{
-namespace priv
-{
-////////////////////////////////////////////////////////////
-/// Let's define a macro to quickly check every OpenAL
-/// API calls
-///
-////////////////////////////////////////////////////////////
-#ifdef SFML_DEBUG
-
- // If in debug mode, perform a test on every call
- #define ALCheck(Func) ((Func), priv::ALCheckError(__FILE__, __LINE__))
-
-#else
-
- // Else, we don't add any overhead
- #define ALCheck(Func) (Func)
-
-#endif
-
-
-////////////////////////////////////////////////////////////
-/// Check last OpenAL error
-///
-////////////////////////////////////////////////////////////
-inline void ALCheckError(const std::string& File, unsigned int Line)
-{
- // Get the last error
- ALenum ErrorCode = alGetError();
-
- if (ErrorCode != AL_NO_ERROR)
- {
- std::string Error, Desc;
-
- // Decode the error code
- switch (ErrorCode)
- {
- case AL_INVALID_NAME :
- {
- Error = "AL_INVALID_NAME";
- Desc = "an unacceptable name has been specified";
- break;
- }
-
- case AL_INVALID_ENUM :
- {
- Error = "AL_INVALID_ENUM";
- Desc = "an unacceptable value has been specified for an enumerated argument";
- break;
- }
-
- case AL_INVALID_VALUE :
- {
- Error = "AL_INVALID_VALUE";
- Desc = "a numeric argument is out of range";
- break;
- }
-
- case AL_INVALID_OPERATION :
- {
- Error = "AL_INVALID_OPERATION";
- Desc = "the specified operation is not allowed in the current state";
- break;
- }
-
- case AL_OUT_OF_MEMORY :
- {
- Error = "AL_OUT_OF_MEMORY";
- Desc = "there is not enough memory left to execute the command";
- break;
- }
- }
-
- // Log the error
- std::cerr << "An internal OpenAL call failed in "
- << File.substr(File.find_last_of("\\/") + 1) << " (" << Line << ") : "
- << Error << ", " << Desc
- << std::endl;
- }
-}
-
-} // namespace priv
-
-} // namespace sf
-
-
-#endif // SFML_OPENAL_HPP
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Audio/ALCheck.hpp>
+#include <SFML/Audio/AudioDevice.hpp>
+#include <SFML/System/Err.hpp>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+void alCheckError(const std::string& file, unsigned int line)
+{
+ // Get the last error
+ ALenum errorCode = alGetError();
+
+ if (errorCode != AL_NO_ERROR)
+ {
+ std::string error, description;
+
+ // Decode the error code
+ switch (errorCode)
+ {
+ case AL_INVALID_NAME :
+ {
+ error = "AL_INVALID_NAME";
+ description = "an unacceptable name has been specified";
+ break;
+ }
+
+ case AL_INVALID_ENUM :
+ {
+ error = "AL_INVALID_ENUM";
+ description = "an unacceptable value has been specified for an enumerated argument";
+ break;
+ }
+
+ case AL_INVALID_VALUE :
+ {
+ error = "AL_INVALID_VALUE";
+ description = "a numeric argument is out of range";
+ break;
+ }
+
+ case AL_INVALID_OPERATION :
+ {
+ error = "AL_INVALID_OPERATION";
+ description = "the specified operation is not allowed in the current state";
+ break;
+ }
+
+ case AL_OUT_OF_MEMORY :
+ {
+ error = "AL_OUT_OF_MEMORY";
+ description = "there is not enough memory left to execute the command";
+ break;
+ }
+ }
+
+ // Log the error
+ err() << "An internal OpenAL call failed in "
+ << file.substr(file.find_last_of("\\/") + 1) << " (" << line << ") : "
+ << error << ", " << description
+ << std::endl;
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+/// Make sure that OpenAL is initialized
+////////////////////////////////////////////////////////////
+void ensureALInit()
+{
+ // The audio device is instanciated on demand rather than at global startup,
+ // which solves a lot of weird crashes and errors.
+ // It is destroyed at global exit which is fine.
+
+ static AudioDevice globalDevice;
+}
+
+} // namespace priv
+
+} // namespace sf
diff --git a/src/SFML/Window/Template for new ports/Joystick.cpp b/src/SFML/Audio/ALCheck.hpp
index 442e329..7c7d659 100755..100644
--- a/src/SFML/Window/Template for new ports/Joystick.cpp
+++ b/src/SFML/Audio/ALCheck.hpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -22,10 +22,17 @@
//
////////////////////////////////////////////////////////////
+#ifndef SFML_ALCHECK_HPP
+#define SFML_ALCHECK_HPP
+
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
-#include <SFML/xxx/Joystick.hpp>
+#include <SFML/Config.hpp>
+#include <iostream>
+#include <string>
+#include <al.h>
+#include <alc.h>
namespace sf
@@ -33,42 +40,39 @@ namespace sf
namespace priv
{
////////////////////////////////////////////////////////////
-/// Initialize the instance and bind it to a physical joystick
+/// Let's define a macro to quickly check every OpenAL API calls
////////////////////////////////////////////////////////////
-void Joystick::Initialize(unsigned int Index)
-{
- // Reset the joystick state
-
- // Initialize the Index-th available joystick
-}
+#ifdef SFML_DEBUG
+ // If in debug mode, perform a test on every call
+ #define alCheck(Func) ((Func), priv::alCheckError(__FILE__, __LINE__))
-////////////////////////////////////////////////////////////
-/// Update the current joystick and return its new state
-////////////////////////////////////////////////////////////
-JoystickState Joystick::UpdateState()
-{
- // Fill a JoystickState instance with the current joystick state
-}
+#else
+
+ // Else, we don't add any overhead
+ #define alCheck(Func) (Func)
+
+#endif
////////////////////////////////////////////////////////////
-/// Get the number of axes supported by the joystick
+/// Check the last OpenAL error
+///
+/// \param file Source file where the call is located
+/// \param line Line number of the source file where the call is located
+///
////////////////////////////////////////////////////////////
-unsigned int Joystick::GetAxesCount() const
-{
- // Return number of supported axes
-}
-
+void alCheckError(const std::string& file, unsigned int line);
////////////////////////////////////////////////////////////
-/// Get the number of buttons supported by the joystick
+/// Make sure that OpenAL is initialized
+///
////////////////////////////////////////////////////////////
-unsigned int Joystick::GetButtonsCount() const
-{
- // Return number of supported buttons
-}
+void ensureALInit();
} // namespace priv
} // namespace sf
+
+
+#endif // SFML_ALCHECK_HPP
diff --git a/src/SFML/Audio/AudioDevice.cpp b/src/SFML/Audio/AudioDevice.cpp
index 096a163..d218b91 100755..100644
--- a/src/SFML/Audio/AudioDevice.cpp
+++ b/src/SFML/Audio/AudioDevice.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -26,143 +26,98 @@
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio/AudioDevice.hpp>
-#include <SFML/Audio/AudioResource.hpp>
+#include <SFML/Audio/ALCheck.hpp>
#include <SFML/Audio/Listener.hpp>
-#include <algorithm>
-#include <iostream>
+#include <SFML/System/Err.hpp>
+namespace
+{
+ ALCdevice* audioDevice = NULL;
+ ALCcontext* audioContext = NULL;
+}
+
namespace sf
{
namespace priv
{
////////////////////////////////////////////////////////////
-// Static member data
-////////////////////////////////////////////////////////////
-AudioDevice* AudioDevice::ourInstance;
-
-
-////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
-AudioDevice::AudioDevice() :
-myRefCount(0)
+AudioDevice::AudioDevice()
{
// Create the device
- myDevice = alcOpenDevice(NULL);
+ audioDevice = alcOpenDevice(NULL);
- if (myDevice)
+ if (audioDevice)
{
// Create the context
- myContext = alcCreateContext(myDevice, NULL);
+ audioContext = alcCreateContext(audioDevice, NULL);
- if (myContext)
+ if (audioContext)
{
// Set the context as the current one (we'll only need one)
- alcMakeContextCurrent(myContext);
-
- // Initialize the listener, located at the origin and looking along the Z axis
- Listener::SetPosition(0.f, 0.f, 0.f);
- Listener::SetTarget(0.f, 0.f, -1.f);
+ alcMakeContextCurrent(audioContext);
}
else
{
- std::cerr << "Failed to create the audio context" << std::endl;
+ err() << "Failed to create the audio context" << std::endl;
}
}
else
{
- std::cerr << "Failed to open the audio device" << std::endl;
+ err() << "Failed to open the audio device" << std::endl;
}
}
////////////////////////////////////////////////////////////
-/// Destructor
-////////////////////////////////////////////////////////////
AudioDevice::~AudioDevice()
{
// Destroy the context
alcMakeContextCurrent(NULL);
- if (myContext)
- alcDestroyContext(myContext);
-
- // Destroy the device
- if (myDevice)
- alcCloseDevice(myDevice);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the unique instance of the class
-////////////////////////////////////////////////////////////
-AudioDevice& AudioDevice::GetInstance()
-{
- // Create the audio device if it doesn't exist
- if (!ourInstance)
- ourInstance = new AudioDevice;
-
- return *ourInstance;
-}
-
+ if (audioContext)
+ alcDestroyContext(audioContext);
-////////////////////////////////////////////////////////////
-/// Add a reference to the audio device
-////////////////////////////////////////////////////////////
-void AudioDevice::AddReference()
-{
- // Create the audio device if it doesn't exist
- if (!ourInstance)
- ourInstance = new AudioDevice;
-
- // Increase the references count
- ourInstance->myRefCount++;
+ // Destroy the device
+ if (audioDevice)
+ alcCloseDevice(audioDevice);
}
////////////////////////////////////////////////////////////
-/// Remove a reference to the audio device
-////////////////////////////////////////////////////////////
-void AudioDevice::RemoveReference()
+bool AudioDevice::isExtensionSupported(const std::string& extension)
{
- // Decrease the references count
- ourInstance->myRefCount--;
+ ensureALInit();
- // Destroy the audio device if the references count reaches 0
- if (ourInstance->myRefCount == 0)
- {
- delete ourInstance;
- ourInstance = NULL;
- }
+ if ((extension.length() > 2) && (extension.substr(0, 3) == "ALC"))
+ return alcIsExtensionPresent(audioDevice, extension.c_str()) != AL_FALSE;
+ else
+ return alIsExtensionPresent(extension.c_str()) != AL_FALSE;
}
////////////////////////////////////////////////////////////
-/// Get the OpenAL audio device
-////////////////////////////////////////////////////////////
-ALCdevice* AudioDevice::GetDevice() const
+int AudioDevice::getFormatFromChannelCount(unsigned int channelCount)
{
- return myDevice;
-}
-
+ ensureALInit();
-////////////////////////////////////////////////////////////
-/// Get the OpenAL format that matches the given number of channels
-////////////////////////////////////////////////////////////
-ALenum AudioDevice::GetFormatFromChannelsCount(unsigned int ChannelsCount) const
-{
// Find the good format according to the number of channels
- switch (ChannelsCount)
+ int format = 0;
+ switch (channelCount)
{
- case 1 : return AL_FORMAT_MONO16;
- case 2 : return AL_FORMAT_STEREO16;
- case 4 : return alGetEnumValue("AL_FORMAT_QUAD16");
- case 6 : return alGetEnumValue("AL_FORMAT_51CHN16");
- case 7 : return alGetEnumValue("AL_FORMAT_61CHN16");
- case 8 : return alGetEnumValue("AL_FORMAT_71CHN16");
+ case 1 : format = AL_FORMAT_MONO16; break;
+ case 2 : format = AL_FORMAT_STEREO16; break;
+ case 4 : format = alGetEnumValue("AL_FORMAT_QUAD16"); break;
+ case 6 : format = alGetEnumValue("AL_FORMAT_51CHN16"); break;
+ case 7 : format = alGetEnumValue("AL_FORMAT_61CHN16"); break;
+ case 8 : format = alGetEnumValue("AL_FORMAT_71CHN16"); break;
+ default : format = 0; break;
}
- return 0;
+ // Fixes a bug on OS X
+ if (format == -1)
+ format = 0;
+
+ return format;
}
} // namespace priv
diff --git a/src/SFML/Audio/AudioDevice.hpp b/src/SFML/Audio/AudioDevice.hpp
index 6b47177..01c7b4c 100755..100644
--- a/src/SFML/Audio/AudioDevice.hpp
+++ b/src/SFML/Audio/AudioDevice.hpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -28,90 +28,59 @@
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
-#include <SFML/Audio/OpenAL.hpp>
#include <set>
#include <string>
namespace sf
{
-class AudioResource;
-
namespace priv
{
-
////////////////////////////////////////////////////////////
-/// AudioDevice is the high-level wrapper around the audio API,
-/// it manages creation and destruction of the audio device and context
-/// and stores the device capabilities
+/// \brief High-level wrapper around the audio API, it manages
+/// the creation and destruction of the audio device and
+/// context and stores the device capabilities
+///
////////////////////////////////////////////////////////////
class AudioDevice
{
public :
////////////////////////////////////////////////////////////
- /// Get the unique instance of the class
- ///
- /// \return Unique instance of the class
- ///
- ////////////////////////////////////////////////////////////
- static AudioDevice& GetInstance();
-
- ////////////////////////////////////////////////////////////
- /// Add a reference to the audio device
+ /// \brief Default constructor
///
////////////////////////////////////////////////////////////
- static void AddReference();
+ AudioDevice();
////////////////////////////////////////////////////////////
- /// Remove a reference to the audio device
+ /// \brief Destructor
///
////////////////////////////////////////////////////////////
- static void RemoveReference();
+ ~AudioDevice();
////////////////////////////////////////////////////////////
- /// Get the OpenAL audio device
- ///
- /// \return OpenAL device (cannot be NULL)
+ /// \brief Check if an OpenAL extension is supported
///
- ////////////////////////////////////////////////////////////
- ALCdevice* GetDevice() const;
-
- ////////////////////////////////////////////////////////////
- /// Get the OpenAL format that matches the given number of channels
+ /// This functions automatically finds whether it
+ /// is an AL or ALC extension, and calls the corresponding
+ /// function.
///
- /// \param ChannelsCount : Number of channels
+ /// \param extension Name of the extension to test
///
- /// \return OpenAL device (cannot be NULL)
+ /// \return True if the extension is supported, false if not
///
////////////////////////////////////////////////////////////
- ALenum GetFormatFromChannelsCount(unsigned int ChannelsCount) const;
-
-private :
+ static bool isExtensionSupported(const std::string& extension);
////////////////////////////////////////////////////////////
- /// Default constructor
+ /// \brief Get the OpenAL format that matches the given number of channels
///
- ////////////////////////////////////////////////////////////
- AudioDevice();
-
- ////////////////////////////////////////////////////////////
- /// Destructor
+ /// \param channelCount Number of channels
+ ///
+ /// \return Corresponding format
///
////////////////////////////////////////////////////////////
- ~AudioDevice();
-
- ////////////////////////////////////////////////////////////
- // Static member data
- ////////////////////////////////////////////////////////////
- static AudioDevice* ourInstance; ///< Unique instance of the audio device
-
- ////////////////////////////////////////////////////////////
- // Member data
- ////////////////////////////////////////////////////////////
- ALCdevice* myDevice; ///< Audio device
- ALCcontext* myContext; ///< Audio context
- unsigned int myRefCount; ///< References count
+ static int getFormatFromChannelCount(unsigned int channelCount);
};
} // namespace priv
diff --git a/src/SFML/Audio/CMakeLists.txt b/src/SFML/Audio/CMakeLists.txt
new file mode 100644
index 0000000..818b9b6
--- /dev/null
+++ b/src/SFML/Audio/CMakeLists.txt
@@ -0,0 +1,53 @@
+
+set(INCROOT ${PROJECT_SOURCE_DIR}/include/SFML/Audio)
+set(SRCROOT ${PROJECT_SOURCE_DIR}/src/SFML/Audio)
+
+# all source files
+set(SRC
+ ${SRCROOT}/ALCheck.cpp
+ ${SRCROOT}/ALCheck.hpp
+ ${SRCROOT}/AudioDevice.cpp
+ ${SRCROOT}/AudioDevice.hpp
+ ${INCROOT}/Export.hpp
+ ${SRCROOT}/Listener.cpp
+ ${INCROOT}/Listener.hpp
+ ${SRCROOT}/Music.cpp
+ ${INCROOT}/Music.hpp
+ ${SRCROOT}/Sound.cpp
+ ${INCROOT}/Sound.hpp
+ ${SRCROOT}/SoundBuffer.cpp
+ ${INCROOT}/SoundBuffer.hpp
+ ${SRCROOT}/SoundBufferRecorder.cpp
+ ${INCROOT}/SoundBufferRecorder.hpp
+ ${SRCROOT}/SoundFile.cpp
+ ${SRCROOT}/SoundFile.hpp
+ ${SRCROOT}/SoundRecorder.cpp
+ ${INCROOT}/SoundRecorder.hpp
+ ${SRCROOT}/SoundSource.cpp
+ ${INCROOT}/SoundSource.hpp
+ ${SRCROOT}/SoundStream.cpp
+ ${INCROOT}/SoundStream.hpp
+)
+source_group("" FILES ${SRC})
+
+# let CMake know about our additional audio libraries paths (on Windows and OSX)
+if(WINDOWS)
+ set(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} "${PROJECT_SOURCE_DIR}/extlibs/headers/AL")
+ set(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} "${PROJECT_SOURCE_DIR}/extlibs/headers/libsndfile/windows")
+elseif (MACOSX)
+ set(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} "${PROJECT_SOURCE_DIR}/extlibs/headers/libsndfile/osx")
+ set(CMAKE_LIBRARY_PATH ${CMAKE_LIBRARY_PATH} "${PROJECT_SOURCE_DIR}/extlibs/libs-osx/Frameworks")
+endif()
+
+# find external libraries
+find_package(OpenAL REQUIRED)
+find_package(Sndfile REQUIRED)
+
+# add include paths of external libraries
+include_directories(${OPENAL_INCLUDE_DIR} ${SNDFILE_INCLUDE_DIR})
+
+# define the sfml-audio target
+sfml_add_library(sfml-audio
+ SOURCES ${SRC}
+ DEPENDS sfml-system
+ EXTERNAL_LIBS ${OPENAL_LIBRARY} ${SNDFILE_LIBRARY})
diff --git a/src/SFML/Audio/Listener.cpp b/src/SFML/Audio/Listener.cpp
index b51b3c5..a4995ce 100755..100644
--- a/src/SFML/Audio/Listener.cpp
+++ b/src/SFML/Audio/Listener.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -26,93 +26,86 @@
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio/Listener.hpp>
-#include <SFML/Audio/OpenAL.hpp>
+#include <SFML/Audio/ALCheck.hpp>
namespace sf
{
////////////////////////////////////////////////////////////
-/// Change the global volume of all the sounds
-////////////////////////////////////////////////////////////
-void Listener::SetGlobalVolume(float Volume)
+void Listener::setGlobalVolume(float volume)
{
- ALCheck(alListenerf(AL_GAIN, Volume * 0.01f));
+ priv::ensureALInit();
+
+ alCheck(alListenerf(AL_GAIN, volume * 0.01f));
}
////////////////////////////////////////////////////////////
-/// Get the current value of the global volume of all the sounds
-////////////////////////////////////////////////////////////
-float Listener::GetGlobalVolume()
+float Listener::getGlobalVolume()
{
- float Volume = 0.f;
- ALCheck(alGetListenerf(AL_GAIN, &Volume));
+ priv::ensureALInit();
+
+ float volume = 0.f;
+ alCheck(alGetListenerf(AL_GAIN, &volume));
- return Volume;
+ return volume * 100;
}
////////////////////////////////////////////////////////////
-/// Change the position of the listener (take 3 values)
-////////////////////////////////////////////////////////////
-void Listener::SetPosition(float X, float Y, float Z)
+void Listener::setPosition(float x, float y, float z)
{
- ALCheck(alListener3f(AL_POSITION, X, Y, Z));
+ priv::ensureALInit();
+
+ alCheck(alListener3f(AL_POSITION, x, y, z));
}
////////////////////////////////////////////////////////////
-/// Change the position of the listener (take a 3D vector)
-////////////////////////////////////////////////////////////
-void Listener::SetPosition(const Vector3f& Position)
+void Listener::setPosition(const Vector3f& position)
{
- SetPosition(Position.x, Position.y, Position.z);
+ setPosition(position.x, position.y, position.z);
}
////////////////////////////////////////////////////////////
-/// Get the current position of the listener
-////////////////////////////////////////////////////////////
-Vector3f Listener::GetPosition()
+Vector3f Listener::getPosition()
{
- Vector3f Position;
- ALCheck(alGetListener3f(AL_POSITION, &Position.x, &Position.y, &Position.z));
+ priv::ensureALInit();
+
+ Vector3f position;
+ alCheck(alGetListener3f(AL_POSITION, &position.x, &position.y, &position.z));
- return Position;
+ return position;
}
////////////////////////////////////////////////////////////
-/// Change the orientation of the listener (the point
-/// he must look at) (take 3 values)
-////////////////////////////////////////////////////////////
-void Listener::SetTarget(float X, float Y, float Z)
+void Listener::setDirection(float x, float y, float z)
{
- float Orientation[] = {X, Y, Z, 0.f, 1.f, 0.f};
- ALCheck(alListenerfv(AL_ORIENTATION, Orientation));
+ priv::ensureALInit();
+
+ float orientation[] = {x, y, z, 0.f, 1.f, 0.f};
+ alCheck(alListenerfv(AL_ORIENTATION, orientation));
}
////////////////////////////////////////////////////////////
-/// Change the orientation of the listener (the point
-/// he must look at) (take a 3D vector)
-////////////////////////////////////////////////////////////
-void Listener::SetTarget(const Vector3f& Target)
+void Listener::setDirection(const Vector3f& direction)
{
- SetTarget(Target.x, Target.y, Target.z);
+ setDirection(direction.x, direction.y, direction.z);
}
////////////////////////////////////////////////////////////
-/// Get the current orientation of the listener (the point
-/// he's looking at)
-////////////////////////////////////////////////////////////
-Vector3f Listener::GetTarget()
+Vector3f Listener::getDirection()
{
- float Orientation[6];
- ALCheck(alGetListenerfv(AL_ORIENTATION, Orientation));
+ priv::ensureALInit();
+
+ float orientation[6];
+ alCheck(alGetListenerfv(AL_ORIENTATION, orientation));
- return Vector3f(Orientation[0], Orientation[1], Orientation[2]);
+ return Vector3f(orientation[0], orientation[1], orientation[2]);
}
} // namespace sf
diff --git a/src/SFML/Audio/Makefile b/src/SFML/Audio/Makefile
deleted file mode 100755
index 0215e80..0000000
--- a/src/SFML/Audio/Makefile
+++ /dev/null
@@ -1,39 +0,0 @@
-SRC = $(wildcard *.cpp)
-SRCVORBIS = $(wildcard ./stb_vorbis/*.c)
-OBJ = $(SRC:.cpp=.o)
-OBJVORBIS = $(SRCVORBIS:.c=.o)
-
-ifeq ($(STATIC), yes)
- LIB = libsfml-audio-s.a
- LIBNAME = $(LIBPATH)/$(LIB)
- INSTALL =
-else
- LIB = libsfml-audio.so
- LIBNAME = $(LIBPATH)/$(LIB).$(VERSION)
- INSTALL = && $(LN) $(LNFLAGS) $(LIB).$(VERSION) $(DESTLIBDIR)/$(LIB)
-endif
-
-all: $(LIB)
-
-libsfml-audio-s.a: $(OBJ) $(OBJVORBIS)
- $(AR) $(ARFLAGS) $(LIBNAME) $(OBJ) $(OBJVORBIS)
-
-libsfml-audio.so: $(OBJ) $(OBJVORBIS)
- $(CPP) $(LDFLAGS) -Wl,-soname,$(LIB).$(VERSION) -o $(LIBNAME) $(OBJ) $(OBJVORBIS) -lsndfile -lopenal
-
-$(OBJ): %.o: %.cpp
- $(CPP) -o $@ -c $< $(CFLAGS)
-
-$(OBJVORBIS): %.o: %.c
- $(CC) -o $@ -c $< $(CFLAGSEXT)
-
-.PHONY: clean mrproper
-
-clean:
- @rm -rf $(OBJ) $(OBJVORBIS)
-
-mrproper: clean
- @rm -rf $(LIBNAME)
-
-install:
- @($(CP) $(LIBNAME) $(DESTLIBDIR) $(INSTALL))
diff --git a/src/SFML/Audio/Music.cpp b/src/SFML/Audio/Music.cpp
index 5023ff5..ef784e4 100755..100644
--- a/src/SFML/Audio/Music.cpp
+++ b/src/SFML/Audio/Music.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -26,128 +26,126 @@
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio/Music.hpp>
-#include <SFML/Audio/OpenAL.hpp>
+#include <SFML/Audio/ALCheck.hpp>
#include <SFML/Audio/SoundFile.hpp>
+#include <SFML/System/Lock.hpp>
+#include <SFML/System/Err.hpp>
#include <fstream>
-#include <iostream>
namespace sf
{
////////////////////////////////////////////////////////////
-/// Construct the music with a buffer size
-////////////////////////////////////////////////////////////
-Music::Music(std::size_t BufferSize) :
-myFile (NULL),
-myDuration(0.f),
-mySamples (BufferSize)
+Music::Music() :
+m_file (new priv::SoundFile),
+m_duration()
{
}
////////////////////////////////////////////////////////////
-/// Destructor
-////////////////////////////////////////////////////////////
Music::~Music()
{
// We must stop before destroying the file :)
- Stop();
+ stop();
- delete myFile;
+ delete m_file;
}
////////////////////////////////////////////////////////////
-/// Open a music file (doesn't play it -- call Play() for that)
-////////////////////////////////////////////////////////////
-bool Music::OpenFromFile(const std::string& Filename)
+bool Music::openFromFile(const std::string& filename)
{
// First stop the music if it was already running
- Stop();
-
- // Create the sound file implementation, and open it in read mode
- delete myFile;
- myFile = priv::SoundFile::CreateRead(Filename);
- if (!myFile)
- {
- std::cerr << "Failed to open \"" << Filename << "\" for reading" << std::endl;
- return false;
- }
+ stop();
- // Compute the duration
- myDuration = static_cast<float>(myFile->GetSamplesCount()) / myFile->GetSampleRate() / myFile->GetChannelsCount();
+ // Open the underlying sound file
+ if (!m_file->openRead(filename))
+ return false;
- // Initialize the stream
- Initialize(myFile->GetChannelsCount(), myFile->GetSampleRate());
+ // Perform common initializations
+ initialize();
return true;
}
////////////////////////////////////////////////////////////
-/// Open a music file from memory (doesn't play it -- call Play() for that)
-////////////////////////////////////////////////////////////
-bool Music::OpenFromMemory(const char* Data, std::size_t SizeInBytes)
+bool Music::openFromMemory(const void* data, std::size_t sizeInBytes)
{
// First stop the music if it was already running
- Stop();
-
- // Create the sound file implementation, and open it in read mode
- delete myFile;
- myFile = priv::SoundFile::CreateRead(Data, SizeInBytes);
- if (!myFile)
- {
- std::cerr << "Failed to open music from memory for reading" << std::endl;
- return false;
- }
+ stop();
- // Compute the duration
- myDuration = static_cast<float>(myFile->GetSamplesCount()) / myFile->GetSampleRate();
+ // Open the underlying sound file
+ if (!m_file->openRead(data, sizeInBytes))
+ return false;
- // Initialize the stream
- Initialize(myFile->GetChannelsCount(), myFile->GetSampleRate());
+ // Perform common initializations
+ initialize();
return true;
}
////////////////////////////////////////////////////////////
-/// /see SoundStream::OnStart
-////////////////////////////////////////////////////////////
-bool Music::OnStart()
+bool Music::openFromStream(InputStream& stream)
{
- return myFile && myFile->Restart();
+ // First stop the music if it was already running
+ stop();
+
+ // Open the underlying sound file
+ if (!m_file->openRead(stream))
+ return false;
+
+ // Perform common initializations
+ initialize();
+
+ return true;
}
////////////////////////////////////////////////////////////
-/// /see SoundStream::OnGetData
+Time Music::getDuration() const
+{
+ return m_duration;
+}
+
+
////////////////////////////////////////////////////////////
-bool Music::OnGetData(SoundStream::Chunk& Data)
+bool Music::onGetData(SoundStream::Chunk& data)
{
- if (myFile)
- {
- // Fill the chunk parameters
- Data.Samples = &mySamples[0];
- Data.NbSamples = myFile->Read(&mySamples[0], mySamples.size());
-
- // Check if we have reached the end of the audio file
- return Data.NbSamples == mySamples.size();
- }
- else
- {
- return false;
- }
+ Lock lock(m_mutex);
+
+ // Fill the chunk parameters
+ data.samples = &m_samples[0];
+ data.sampleCount = m_file->read(&m_samples[0], m_samples.size());
+
+ // Check if we have reached the end of the audio file
+ return data.sampleCount == m_samples.size();
}
////////////////////////////////////////////////////////////
-/// Get the sound duration
+void Music::onSeek(Time timeOffset)
+{
+ Lock lock(m_mutex);
+
+ m_file->seek(timeOffset);
+}
+
+
////////////////////////////////////////////////////////////
-float Music::GetDuration() const
+void Music::initialize()
{
- return myDuration;
+ // Compute the music duration
+ m_duration = seconds(static_cast<float>(m_file->getSampleCount()) / m_file->getSampleRate() / m_file->getChannelCount());
+
+ // Resize the internal buffer so that it can contain 1 second of audio samples
+ m_samples.resize(m_file->getSampleRate() * m_file->getChannelCount());
+
+ // Initialize the stream
+ SoundStream::initialize(m_file->getChannelCount(), m_file->getSampleRate());
}
} // namespace sf
diff --git a/src/SFML/Audio/Sound.cpp b/src/SFML/Audio/Sound.cpp
index 84136db..8619cab 100755..100644
--- a/src/SFML/Audio/Sound.cpp
+++ b/src/SFML/Audio/Sound.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -27,378 +27,170 @@
////////////////////////////////////////////////////////////
#include <SFML/Audio/Sound.hpp>
#include <SFML/Audio/SoundBuffer.hpp>
-#include <SFML/Audio/OpenAL.hpp>
+#include <SFML/Audio/ALCheck.hpp>
namespace sf
{
////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
-Sound::Sound()
+Sound::Sound() :
+m_buffer(NULL)
{
- ALCheck(alGenSources(1, &mySource));
- ALCheck(alSourcei(mySource, AL_BUFFER, 0));
}
////////////////////////////////////////////////////////////
-/// Construct the sound from its parameters
-////////////////////////////////////////////////////////////
-Sound::Sound(const SoundBuffer& Buffer, bool Loop, float Pitch, float Volume, const Vector3f& Position) :
-myBuffer(NULL)
+Sound::Sound(const SoundBuffer& buffer) :
+m_buffer(NULL)
{
- ALCheck(alGenSources(1, &mySource));
-
- SetBuffer(Buffer);
- SetLoop(Loop);
- SetPitch(Pitch);
- SetVolume(Volume);
- SetPosition(Position);
+ setBuffer(buffer);
}
////////////////////////////////////////////////////////////
-/// Copy constructor
-////////////////////////////////////////////////////////////
-Sound::Sound(const Sound& Copy) :
-AudioResource(Copy),
-myBuffer(NULL)
+Sound::Sound(const Sound& copy) :
+SoundSource(copy),
+m_buffer (NULL)
{
- ALCheck(alGenSources(1, &mySource));
-
- if (Copy.myBuffer)
- SetBuffer(*Copy.myBuffer);
- SetLoop(Copy.GetLoop());
- SetPitch(Copy.GetPitch());
- SetVolume(Copy.GetVolume());
- SetPosition(Copy.GetPosition());
- SetRelativeToListener(Copy.IsRelativeToListener());
- SetMinDistance(Copy.GetMinDistance());
- SetAttenuation(Copy.GetAttenuation());
+ if (copy.m_buffer)
+ setBuffer(*copy.m_buffer);
+ setLoop(copy.getLoop());
}
////////////////////////////////////////////////////////////
-/// Destructor
-////////////////////////////////////////////////////////////
Sound::~Sound()
{
- if (mySource)
- {
- if (myBuffer)
- {
- Stop();
- ALCheck(alSourcei(mySource, AL_BUFFER, 0));
- myBuffer->DetachSound(this);
- }
- ALCheck(alDeleteSources(1, &mySource));
- }
+ stop();
+ if (m_buffer)
+ m_buffer->detachSound(this);
}
////////////////////////////////////////////////////////////
-/// Play the sound
-////////////////////////////////////////////////////////////
-void Sound::Play()
+void Sound::play()
{
- ALCheck(alSourcePlay(mySource));
+ alCheck(alSourcePlay(m_source));
}
////////////////////////////////////////////////////////////
-/// Pause the sound
-////////////////////////////////////////////////////////////
-void Sound::Pause()
+void Sound::pause()
{
- ALCheck(alSourcePause(mySource));
+ alCheck(alSourcePause(m_source));
}
////////////////////////////////////////////////////////////
-/// Stop the sound
-////////////////////////////////////////////////////////////
-void Sound::Stop()
+void Sound::stop()
{
- ALCheck(alSourceStop(mySource));
+ alCheck(alSourceStop(m_source));
}
////////////////////////////////////////////////////////////
-/// Set the source buffer
-////////////////////////////////////////////////////////////
-void Sound::SetBuffer(const SoundBuffer& Buffer)
+void Sound::setBuffer(const SoundBuffer& buffer)
{
// First detach from the previous buffer
- if (myBuffer)
+ if (m_buffer)
{
- Stop();
- myBuffer->DetachSound(this);
+ stop();
+ m_buffer->detachSound(this);
}
// Assign and use the new buffer
- myBuffer = &Buffer;
- myBuffer->AttachSound(this);
- ALCheck(alSourcei(mySource, AL_BUFFER, myBuffer->myBuffer));
-}
-
-
-////////////////////////////////////////////////////////////
-/// Set the sound loop state
-////////////////////////////////////////////////////////////
-void Sound::SetLoop(bool Loop)
-{
- ALCheck(alSourcei(mySource, AL_LOOPING, Loop));
-}
-
-
-////////////////////////////////////////////////////////////
-/// Set the sound pitch
-////////////////////////////////////////////////////////////
-void Sound::SetPitch(float Pitch)
-{
- ALCheck(alSourcef(mySource, AL_PITCH, Pitch));
-}
-
-
-////////////////////////////////////////////////////////////
-/// Set the sound volume
-////////////////////////////////////////////////////////////
-void Sound::SetVolume(float Volume)
-{
- ALCheck(alSourcef(mySource, AL_GAIN, Volume * 0.01f));
-}
-
-////////////////////////////////////////////////////////////
-/// Set the sound position (take 3 values).
-/// The default position is (0, 0, 0)
-////////////////////////////////////////////////////////////
-void Sound::SetPosition(float X, float Y, float Z)
-{
- ALCheck(alSource3f(mySource, AL_POSITION, X, Y, Z));
-}
-
-
-////////////////////////////////////////////////////////////
-/// Set the sound position (take a 3D vector).
-/// The default position is (0, 0, 0)
-////////////////////////////////////////////////////////////
-void Sound::SetPosition(const Vector3f& Position)
-{
- SetPosition(Position.x, Position.y, Position.z);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Make the sound's position relative to the listener's
-/// position, or absolute.
-/// The default value is false (absolute)
-////////////////////////////////////////////////////////////
-void Sound::SetRelativeToListener(bool Relative)
-{
- ALCheck(alSourcei(mySource, AL_SOURCE_RELATIVE, Relative));
-}
-
-
-////////////////////////////////////////////////////////////
-/// Set the minimum distance - closer than this distance,
-/// the listener will hear the sound at its maximum volume.
-/// The default minimum distance is 1.0
-////////////////////////////////////////////////////////////
-void Sound::SetMinDistance(float MinDistance)
-{
- ALCheck(alSourcef(mySource, AL_REFERENCE_DISTANCE, MinDistance));
-}
-
-
-////////////////////////////////////////////////////////////
-/// Set the attenuation factor - the higher the attenuation, the
-/// more the sound will be attenuated with distance from listener.
-/// The default attenuation factor 1.0
-////////////////////////////////////////////////////////////
-void Sound::SetAttenuation(float Attenuation)
-{
- ALCheck(alSourcef(mySource, AL_ROLLOFF_FACTOR, Attenuation));
+ m_buffer = &buffer;
+ m_buffer->attachSound(this);
+ alCheck(alSourcei(m_source, AL_BUFFER, m_buffer->m_buffer));
}
////////////////////////////////////////////////////////////
-/// Set the current playing position of the sound
-////////////////////////////////////////////////////////////
-void Sound::SetPlayingOffset(float TimeOffset)
+void Sound::setLoop(bool Loop)
{
- ALCheck(alSourcef(mySource, AL_SEC_OFFSET, TimeOffset));
+ alCheck(alSourcei(m_source, AL_LOOPING, Loop));
}
////////////////////////////////////////////////////////////
-/// Get the source buffer
-////////////////////////////////////////////////////////////
-const SoundBuffer* Sound::GetBuffer() const
+void Sound::setPlayingOffset(Time timeOffset)
{
- return myBuffer;
+ alCheck(alSourcef(m_source, AL_SEC_OFFSET, timeOffset.asSeconds()));
}
////////////////////////////////////////////////////////////
-/// Tell whether or not the sound is looping
-////////////////////////////////////////////////////////////
-bool Sound::GetLoop() const
+const SoundBuffer* Sound::getBuffer() const
{
- ALint Loop;
- ALCheck(alGetSourcei(mySource, AL_LOOPING, &Loop));
-
- return Loop != 0;
+ return m_buffer;
}
////////////////////////////////////////////////////////////
-/// Get the pitch
-////////////////////////////////////////////////////////////
-float Sound::GetPitch() const
+bool Sound::getLoop() const
{
- ALfloat Pitch;
- ALCheck(alGetSourcef(mySource, AL_PITCH, &Pitch));
+ ALint loop;
+ alCheck(alGetSourcei(m_source, AL_LOOPING, &loop));
- return Pitch;
+ return loop != 0;
}
////////////////////////////////////////////////////////////
-/// Get the volume
-////////////////////////////////////////////////////////////
-float Sound::GetVolume() const
+Time Sound::getPlayingOffset() const
{
- ALfloat Gain;
- ALCheck(alGetSourcef(mySource, AL_GAIN, &Gain));
+ ALfloat secs = 0.f;
+ alCheck(alGetSourcef(m_source, AL_SEC_OFFSET, &secs));
- return Gain * 100.f;
+ return seconds(secs);
}
////////////////////////////////////////////////////////////
-/// Get the sound position
-////////////////////////////////////////////////////////////
-Vector3f Sound::GetPosition() const
+Sound::Status Sound::getStatus() const
{
- Vector3f Position;
- ALCheck(alGetSource3f(mySource, AL_POSITION, &Position.x, &Position.y, &Position.z));
-
- return Position;
+ return SoundSource::getStatus();
}
////////////////////////////////////////////////////////////
-/// Tell if the sound's position is relative to the listener's
-/// position, or if it's absolute
-////////////////////////////////////////////////////////////
-bool Sound::IsRelativeToListener() const
-{
- ALint Relative;
- ALCheck(alGetSourcei(mySource, AL_SOURCE_RELATIVE, &Relative));
-
- return Relative != 0;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the minimum distance
-////////////////////////////////////////////////////////////
-float Sound::GetMinDistance() const
-{
- ALfloat MinDistance;
- ALCheck(alGetSourcef(mySource, AL_REFERENCE_DISTANCE, &MinDistance));
-
- return MinDistance;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the attenuation factor
-////////////////////////////////////////////////////////////
-float Sound::GetAttenuation() const
-{
- ALfloat Attenuation;
- ALCheck(alGetSourcef(mySource, AL_ROLLOFF_FACTOR, &Attenuation));
-
- return Attenuation;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the current playing position of the sound
-////////////////////////////////////////////////////////////
-float Sound::GetPlayingOffset() const
-{
- ALfloat Seconds = 0.f;
- ALCheck(alGetSourcef(mySource, AL_SEC_OFFSET, &Seconds));
-
- return Seconds;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the status of the sound (stopped, paused, playing)
-////////////////////////////////////////////////////////////
-Sound::Status Sound::GetStatus() const
-{
- ALint State;
- ALCheck(alGetSourcei(mySource, AL_SOURCE_STATE, &State));
-
- switch (State)
- {
- case AL_INITIAL :
- case AL_STOPPED : return Stopped;
- case AL_PAUSED : return Paused;
- case AL_PLAYING : return Playing;
- }
-
- return Stopped;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Assignment operator
-////////////////////////////////////////////////////////////
-Sound& Sound::operator =(const Sound& Other)
+Sound& Sound::operator =(const Sound& right)
{
// Here we don't use the copy-and-swap idiom, because it would mess up
// the list of sound instances contained in the buffers
// Detach the sound instance from the previous buffer (if any)
- if (myBuffer)
+ if (m_buffer)
{
- Stop();
- myBuffer->DetachSound(this);
- myBuffer = NULL;
+ stop();
+ m_buffer->detachSound(this);
+ m_buffer = NULL;
}
// Copy the sound attributes
- if (Other.myBuffer)
- SetBuffer(*Other.myBuffer);
- SetLoop(Other.GetLoop());
- SetPitch(Other.GetPitch());
- SetVolume(Other.GetVolume());
- SetPosition(Other.GetPosition());
- SetRelativeToListener(Other.IsRelativeToListener());
- SetMinDistance(Other.GetMinDistance());
- SetAttenuation(Other.GetAttenuation());
+ if (right.m_buffer)
+ setBuffer(*right.m_buffer);
+ setLoop(right.getLoop());
+ setPitch(right.getPitch());
+ setVolume(right.getVolume());
+ setPosition(right.getPosition());
+ setRelativeToListener(right.isRelativeToListener());
+ setMinDistance(right.getMinDistance());
+ setAttenuation(right.getAttenuation());
return *this;
}
////////////////////////////////////////////////////////////
-/// Reset the internal buffer
-////////////////////////////////////////////////////////////
-void Sound::ResetBuffer()
+void Sound::resetBuffer()
{
// First stop the sound in case it is playing
- Stop();
+ stop();
// Detach the buffer
- ALCheck(alSourcei(mySource, AL_BUFFER, 0));
- myBuffer = NULL;
+ alCheck(alSourcei(m_source, AL_BUFFER, 0));
+ m_buffer = NULL;
}
} // namespace sf
diff --git a/src/SFML/Audio/SoundBuffer.cpp b/src/SFML/Audio/SoundBuffer.cpp
index e726b13..406a9fe 100755..100644
--- a/src/SFML/Audio/SoundBuffer.cpp
+++ b/src/SFML/Audio/SoundBuffer.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -29,164 +29,106 @@
#include <SFML/Audio/SoundFile.hpp>
#include <SFML/Audio/Sound.hpp>
#include <SFML/Audio/AudioDevice.hpp>
-#include <SFML/Audio/OpenAL.hpp>
-#include <iostream>
+#include <SFML/Audio/ALCheck.hpp>
+#include <SFML/System/Err.hpp>
#include <memory>
namespace sf
{
////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
SoundBuffer::SoundBuffer() :
-myBuffer (0),
-myDuration(0.f)
+m_buffer (0),
+m_duration()
{
+ priv::ensureALInit();
+
// Create the buffer
- ALCheck(alGenBuffers(1, &myBuffer));
+ alCheck(alGenBuffers(1, &m_buffer));
}
////////////////////////////////////////////////////////////
-/// Copy constructor
-////////////////////////////////////////////////////////////
-SoundBuffer::SoundBuffer(const SoundBuffer& Copy) :
-AudioResource (Copy),
-Resource<SoundBuffer>(Copy),
-myBuffer (0),
-mySamples (Copy.mySamples),
-myDuration (Copy.myDuration),
-mySounds () // don't copy the attached sounds
+SoundBuffer::SoundBuffer(const SoundBuffer& copy) :
+m_buffer (0),
+m_samples (copy.m_samples),
+m_duration(copy.m_duration),
+m_sounds () // don't copy the attached sounds
{
// Create the buffer
- ALCheck(alGenBuffers(1, &myBuffer));
+ alCheck(alGenBuffers(1, &m_buffer));
// Update the internal buffer with the new samples
- Update(Copy.GetChannelsCount(), Copy.GetSampleRate());
+ update(copy.getChannelCount(), copy.getSampleRate());
}
////////////////////////////////////////////////////////////
-/// Destructor
-////////////////////////////////////////////////////////////
SoundBuffer::~SoundBuffer()
{
// First detach the buffer from the sounds that use it (to avoid OpenAL errors)
- for (SoundList::const_iterator it = mySounds.begin(); it != mySounds.end(); ++it)
- (*it)->ResetBuffer();
+ for (SoundList::const_iterator it = m_sounds.begin(); it != m_sounds.end(); ++it)
+ (*it)->resetBuffer();
// Destroy the buffer
- if (myBuffer)
- ALCheck(alDeleteBuffers(1, &myBuffer));
+ if (m_buffer)
+ alCheck(alDeleteBuffers(1, &m_buffer));
}
////////////////////////////////////////////////////////////
-/// Load the sound buffer from a file
-////////////////////////////////////////////////////////////
-bool SoundBuffer::LoadFromFile(const std::string& Filename)
+bool SoundBuffer::loadFromFile(const std::string& filename)
{
- // Create the sound file
- std::auto_ptr<priv::SoundFile> File(priv::SoundFile::CreateRead(Filename));
-
- // Open the sound file
- if (File.get())
- {
- // Get the sound parameters
- std::size_t NbSamples = File->GetSamplesCount();
- unsigned int ChannelsCount = File->GetChannelsCount();
- unsigned int SampleRate = File->GetSampleRate();
-
- // Read the samples from the opened file
- mySamples.resize(NbSamples);
- if (File->Read(&mySamples[0], NbSamples) == NbSamples)
- {
- // Update the internal buffer with the new samples
- return Update(ChannelsCount, SampleRate);
- }
- else
- {
- // Error...
- std::cerr << "Failed to read audio data from file \"" << Filename << "\"" << std::endl;
-
- return false;
- }
- }
+ priv::SoundFile file;
+ if (file.openRead(filename))
+ return initialize(file);
else
- {
- // Error...
- std::cerr << "Failed to load sound buffer from file \"" << Filename << "\"" << std::endl;
-
return false;
- }
}
////////////////////////////////////////////////////////////
-/// Load the sound buffer from a file in memory
-////////////////////////////////////////////////////////////
-bool SoundBuffer::LoadFromMemory(const char* Data, std::size_t SizeInBytes)
+bool SoundBuffer::loadFromMemory(const void* data, std::size_t sizeInBytes)
{
- // Create the sound file
- std::auto_ptr<priv::SoundFile> File(priv::SoundFile::CreateRead(Data, SizeInBytes));
-
- // Open the sound file
- if (File.get())
- {
- // Get the sound parameters
- std::size_t NbSamples = File->GetSamplesCount();
- unsigned int ChannelsCount = File->GetChannelsCount();
- unsigned int SampleRate = File->GetSampleRate();
-
- // Read the samples from the opened file
- mySamples.resize(NbSamples);
- if (File->Read(&mySamples[0], NbSamples) == NbSamples)
- {
- // Update the internal buffer with the new samples
- return Update(ChannelsCount, SampleRate);
- }
- else
- {
- // Error...
- std::cerr << "Failed to read audio data from file in memory" << std::endl;
-
- return false;
- }
- }
+ priv::SoundFile file;
+ if (file.openRead(data, sizeInBytes))
+ return initialize(file);
else
- {
- // Error...
- std::cerr << "Failed to load sound buffer from file in memory" << std::endl;
-
return false;
- }
}
////////////////////////////////////////////////////////////
-/// Load the sound buffer from an array of samples - assumed format for
-/// samples is 16 bits signed integer
+bool SoundBuffer::loadFromStream(InputStream& stream)
+{
+ priv::SoundFile file;
+ if (file.openRead(stream))
+ return initialize(file);
+ else
+ return false;
+}
+
+
////////////////////////////////////////////////////////////
-bool SoundBuffer::LoadFromSamples(const Int16* Samples, std::size_t SamplesCount, unsigned int ChannelsCount, unsigned int SampleRate)
+bool SoundBuffer::loadFromSamples(const Int16* samples, std::size_t sampleCount, unsigned int channelCount, unsigned int sampleRate)
{
- if (Samples && SamplesCount && ChannelsCount && SampleRate)
+ if (samples && sampleCount && channelCount && sampleRate)
{
// Copy the new audio samples
- mySamples.assign(Samples, Samples + SamplesCount);
+ m_samples.assign(samples, samples + sampleCount);
// Update the internal buffer with the new samples
- return Update(ChannelsCount, SampleRate);
+ return update(channelCount, sampleRate);
}
else
{
// Error...
- std::cerr << "Failed to load sound buffer from memory ("
- << "Samples : " << Samples << ", "
- << "Samples count : " << SamplesCount << ", "
- << "Channels count : " << ChannelsCount << ", "
- << "Sample rate : " << SampleRate << ")"
- << std::endl;
+ err() << "Failed to load sound buffer from samples ("
+ << "array: " << samples << ", "
+ << "count: " << sampleCount << ", "
+ << "channels: " << channelCount << ", "
+ << "samplerate: " << sampleRate << ")"
+ << std::endl;
return false;
}
@@ -194,141 +136,140 @@ bool SoundBuffer::LoadFromSamples(const Int16* Samples, std::size_t SamplesCount
////////////////////////////////////////////////////////////
-/// Save the sound buffer to a file
-////////////////////////////////////////////////////////////
-bool SoundBuffer::SaveToFile(const std::string& Filename) const
+bool SoundBuffer::saveToFile(const std::string& filename) const
{
// Create the sound file in write mode
- std::auto_ptr<priv::SoundFile> File(priv::SoundFile::CreateWrite(Filename, GetChannelsCount(), GetSampleRate()));
- if (File.get())
+ priv::SoundFile file;
+ if (file.openWrite(filename, getChannelCount(), getSampleRate()))
{
// Write the samples to the opened file
- File->Write(&mySamples[0], mySamples.size());
+ file.write(&m_samples[0], m_samples.size());
return true;
}
else
{
- // Error...
- std::cerr << "Failed to save sound buffer to file \"" << Filename << "\"" << std::endl;
-
return false;
}
}
////////////////////////////////////////////////////////////
-/// Return the sound samples
-////////////////////////////////////////////////////////////
-const Int16* SoundBuffer::GetSamples() const
+const Int16* SoundBuffer::getSamples() const
{
- return mySamples.empty() ? NULL : &mySamples[0];
+ return m_samples.empty() ? NULL : &m_samples[0];
}
////////////////////////////////////////////////////////////
-/// Return the samples count
-////////////////////////////////////////////////////////////
-std::size_t SoundBuffer::GetSamplesCount() const
+std::size_t SoundBuffer::getSampleCount() const
{
- return mySamples.size();
+ return m_samples.size();
}
////////////////////////////////////////////////////////////
-/// Get the sample rate
-////////////////////////////////////////////////////////////
-unsigned int SoundBuffer::GetSampleRate() const
+unsigned int SoundBuffer::getSampleRate() const
{
- ALint SampleRate;
- ALCheck(alGetBufferi(myBuffer, AL_FREQUENCY, &SampleRate));
+ ALint sampleRate;
+ alCheck(alGetBufferi(m_buffer, AL_FREQUENCY, &sampleRate));
- return SampleRate;
+ return sampleRate;
}
////////////////////////////////////////////////////////////
-/// Return the number of channels (1 = mono, 2 = stereo, ...)
-////////////////////////////////////////////////////////////
-unsigned int SoundBuffer::GetChannelsCount() const
+unsigned int SoundBuffer::getChannelCount() const
{
- ALint ChannelsCount;
- ALCheck(alGetBufferi(myBuffer, AL_CHANNELS, &ChannelsCount));
+ ALint channelCount;
+ alCheck(alGetBufferi(m_buffer, AL_CHANNELS, &channelCount));
- return ChannelsCount;
+ return channelCount;
}
////////////////////////////////////////////////////////////
-/// Get the sound duration
-////////////////////////////////////////////////////////////
-float SoundBuffer::GetDuration() const
+Time SoundBuffer::getDuration() const
{
- return myDuration;
+ return m_duration;
}
////////////////////////////////////////////////////////////
-/// Assignment operator
-////////////////////////////////////////////////////////////
-SoundBuffer& SoundBuffer::operator =(const SoundBuffer& Other)
+SoundBuffer& SoundBuffer::operator =(const SoundBuffer& right)
{
- SoundBuffer Temp(Other);
+ SoundBuffer temp(right);
- std::swap(mySamples, Temp.mySamples);
- std::swap(myBuffer, Temp.myBuffer);
- std::swap(myDuration, Temp.myDuration);
- std::swap(mySounds, Temp.mySounds); // swap sounds too, so that they are detached when Temp is destroyed
+ std::swap(m_samples, temp.m_samples);
+ std::swap(m_buffer, temp.m_buffer);
+ std::swap(m_duration, temp.m_duration);
+ std::swap(m_sounds, temp.m_sounds); // swap sounds too, so that they are detached when temp is destroyed
return *this;
}
////////////////////////////////////////////////////////////
-/// Update the internal buffer with the audio samples
+bool SoundBuffer::initialize(priv::SoundFile& file)
+{
+ // Retrieve the sound parameters
+ std::size_t sampleCount = file.getSampleCount();
+ unsigned int channelCount = file.getChannelCount();
+ unsigned int sampleRate = file.getSampleRate();
+
+ // Read the samples from the provided file
+ m_samples.resize(sampleCount);
+ if (file.read(&m_samples[0], sampleCount) == sampleCount)
+ {
+ // Update the internal buffer with the new samples
+ return update(channelCount, sampleRate);
+ }
+ else
+ {
+ return false;
+ }
+}
+
+
////////////////////////////////////////////////////////////
-bool SoundBuffer::Update(unsigned int ChannelsCount, unsigned int SampleRate)
+bool SoundBuffer::update(unsigned int channelCount, unsigned int sampleRate)
{
// Check parameters
- if (!SampleRate || !ChannelsCount || mySamples.empty())
+ if (!channelCount || !sampleRate || m_samples.empty())
return false;
// Find the good format according to the number of channels
- ALenum Format = priv::AudioDevice::GetInstance().GetFormatFromChannelsCount(ChannelsCount);
+ ALenum format = priv::AudioDevice::getFormatFromChannelCount(channelCount);
// Check if the format is valid
- if (Format == 0)
+ if (format == 0)
{
- std::cerr << "Unsupported number of channels (" << ChannelsCount << ")" << std::endl;
+ err() << "Failed to load sound buffer (unsupported number of channels: " << channelCount << ")" << std::endl;
return false;
}
// Fill the buffer
- ALsizei Size = static_cast<ALsizei>(mySamples.size()) * sizeof(Int16);
- ALCheck(alBufferData(myBuffer, Format, &mySamples[0], Size, SampleRate));
+ ALsizei size = static_cast<ALsizei>(m_samples.size()) * sizeof(Int16);
+ alCheck(alBufferData(m_buffer, format, &m_samples[0], size, sampleRate));
// Compute the duration
- myDuration = static_cast<float>(mySamples.size()) / SampleRate / ChannelsCount;
+ m_duration = milliseconds(1000 * m_samples.size() / sampleRate / channelCount);
return true;
}
////////////////////////////////////////////////////////////
-/// Add a sound to the list of sounds that use this buffer
-////////////////////////////////////////////////////////////
-void SoundBuffer::AttachSound(Sound* Instance) const
+void SoundBuffer::attachSound(Sound* sound) const
{
- mySounds.insert(Instance);
+ m_sounds.insert(sound);
}
////////////////////////////////////////////////////////////
-/// Remove a sound from the list of sounds that use this buffer
-////////////////////////////////////////////////////////////
-void SoundBuffer::DetachSound(Sound* Instance) const
+void SoundBuffer::detachSound(Sound* sound) const
{
- mySounds.erase(Instance);
+ m_sounds.erase(sound);
}
} // namespace sf
diff --git a/src/SFML/Audio/SoundBufferRecorder.cpp b/src/SFML/Audio/SoundBufferRecorder.cpp
index c0af7bf..a8b2993 100755..100644
--- a/src/SFML/Audio/SoundBufferRecorder.cpp
+++ b/src/SFML/Audio/SoundBufferRecorder.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -33,43 +33,36 @@
namespace sf
{
////////////////////////////////////////////////////////////
-/// /see SoundBuffer::OnStart
-////////////////////////////////////////////////////////////
-bool SoundBufferRecorder::OnStart()
+bool SoundBufferRecorder::onStart()
{
- mySamples.clear();
+ m_samples.clear();
+ m_buffer = SoundBuffer();
return true;
}
////////////////////////////////////////////////////////////
-/// /see SoundBuffer::OnProcessSamples
-////////////////////////////////////////////////////////////
-bool SoundBufferRecorder::OnProcessSamples(const Int16* Samples, std::size_t SamplesCount)
+bool SoundBufferRecorder::onProcessSamples(const Int16* samples, std::size_t sampleCount)
{
- std::copy(Samples, Samples + SamplesCount, std::back_inserter(mySamples));
+ std::copy(samples, samples + sampleCount, std::back_inserter(m_samples));
return true;
}
////////////////////////////////////////////////////////////
-/// /see SoundBuffer::OnStop
-////////////////////////////////////////////////////////////
-void SoundBufferRecorder::OnStop()
+void SoundBufferRecorder::onStop()
{
- if (!mySamples.empty())
- myBuffer.LoadFromSamples(&mySamples[0], mySamples.size(), 1, GetSampleRate());
+ if (!m_samples.empty())
+ m_buffer.loadFromSamples(&m_samples[0], m_samples.size(), 1, getSampleRate());
}
////////////////////////////////////////////////////////////
-/// Get the sound buffer containing the captured audio data
-////////////////////////////////////////////////////////////
-const SoundBuffer& SoundBufferRecorder::GetBuffer() const
+const SoundBuffer& SoundBufferRecorder::getBuffer() const
{
- return myBuffer;
+ return m_buffer;
}
} // namespace sf
diff --git a/src/SFML/Audio/SoundFile.cpp b/src/SFML/Audio/SoundFile.cpp
index 0554d8b..91db819 100755..100644
--- a/src/SFML/Audio/SoundFile.cpp
+++ b/src/SFML/Audio/SoundFile.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -26,9 +26,22 @@
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio/SoundFile.hpp>
-#include <SFML/Audio/SoundFileDefault.hpp>
-#include <SFML/Audio/SoundFileOgg.hpp>
-#include <iostream>
+#include <SFML/System/InputStream.hpp>
+#include <SFML/System/Err.hpp>
+#include <cstring>
+#include <cctype>
+
+
+namespace
+{
+ // Convert a string to lower case
+ std::string toLower(std::string str)
+ {
+ for (std::string::iterator i = str.begin(); i != str.end(); ++i)
+ *i = static_cast<char>(std::tolower(*i));
+ return str;
+ }
+}
namespace sf
@@ -36,234 +49,375 @@ namespace sf
namespace priv
{
////////////////////////////////////////////////////////////
-/// Create a new sound from a file, for reading
-////////////////////////////////////////////////////////////
-SoundFile* SoundFile::CreateRead(const std::string& Filename)
+SoundFile::SoundFile() :
+m_file (NULL),
+m_sampleCount (0),
+m_channelCount(0),
+m_sampleRate (0)
{
- // Create the file according to its type
- SoundFile* File = NULL;
- if (SoundFileOgg::IsFileSupported(Filename, true)) File = new SoundFileOgg;
- else if (SoundFileDefault::IsFileSupported(Filename, true)) File = new SoundFileDefault;
- // Open it for reading
- if (File)
- {
- std::size_t SamplesCount;
- unsigned int ChannelsCount;
- unsigned int SampleRate;
+}
- if (File->OpenRead(Filename, SamplesCount, ChannelsCount, SampleRate))
- {
- File->myFilename = Filename;
- File->myData = NULL;
- File->mySize = 0;
- File->myNbSamples = SamplesCount;
- File->myChannelsCount = ChannelsCount;
- File->mySampleRate = SampleRate;
- }
- else
- {
- delete File;
- File = NULL;
- }
- }
- return File;
+////////////////////////////////////////////////////////////
+SoundFile::~SoundFile()
+{
+ if (m_file)
+ sf_close(m_file);
}
////////////////////////////////////////////////////////////
-/// Create a new sound from a file in memory, for reading
-////////////////////////////////////////////////////////////
-SoundFile* SoundFile::CreateRead(const char* Data, std::size_t SizeInMemory)
+std::size_t SoundFile::getSampleCount() const
{
- // Create the file according to its type
- SoundFile* File = NULL;
- if (SoundFileOgg::IsFileSupported(Data, SizeInMemory)) File = new SoundFileOgg;
- else if (SoundFileDefault::IsFileSupported(Data, SizeInMemory)) File = new SoundFileDefault;
-
- // Open it for reading
- if (File)
- {
- std::size_t SamplesCount;
- unsigned int ChannelsCount;
- unsigned int SampleRate;
+ return m_sampleCount;
+}
- if (File->OpenRead(Data, SizeInMemory, SamplesCount, ChannelsCount, SampleRate))
- {
- File->myFilename = "";
- File->myData = Data;
- File->mySize = SizeInMemory;
- File->myNbSamples = SamplesCount;
- File->myChannelsCount = ChannelsCount;
- File->mySampleRate = SampleRate;
- }
- else
- {
- delete File;
- File = NULL;
- }
- }
- return File;
+////////////////////////////////////////////////////////////
+unsigned int SoundFile::getChannelCount() const
+{
+ return m_channelCount;
}
////////////////////////////////////////////////////////////
-/// Create a new sound from a file, for writing
-////////////////////////////////////////////////////////////
-SoundFile* SoundFile::CreateWrite(const std::string& Filename, unsigned int ChannelsCount, unsigned int SampleRate)
+unsigned int SoundFile::getSampleRate() const
{
- // Create the file according to its type
- SoundFile* File = NULL;
- if (SoundFileOgg::IsFileSupported(Filename, false)) File = new SoundFileOgg;
- else if (SoundFileDefault::IsFileSupported(Filename, false)) File = new SoundFileDefault;
+ return m_sampleRate;
+}
+
- // Open it for writing
- if (File)
+////////////////////////////////////////////////////////////
+bool SoundFile::openRead(const std::string& filename)
+{
+ // If the file is already opened, first close it
+ if (m_file)
+ sf_close(m_file);
+
+ // Open the sound file
+ SF_INFO fileInfo;
+ fileInfo.format = 0;
+ m_file = sf_open(filename.c_str(), SFM_READ, &fileInfo);
+ if (!m_file)
{
- if (File->OpenWrite(Filename, ChannelsCount, SampleRate))
- {
- File->myFilename = "";
- File->myData = NULL;
- File->mySize = 0;
- File->myNbSamples = 0;
- File->myChannelsCount = ChannelsCount;
- File->mySampleRate = SampleRate;
- }
- else
- {
- delete File;
- File = NULL;
- }
+ err() << "Failed to open sound file \"" << filename << "\" (" << sf_strerror(m_file) << ")" << std::endl;
+ return false;
}
- return File;
+ // Initialize the internal state from the loaded information
+ initialize(fileInfo);
+
+ return true;
}
////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
-SoundFile::SoundFile() :
-myNbSamples (0),
-myChannelsCount(0),
-mySampleRate (0)
+bool SoundFile::openRead(const void* data, std::size_t sizeInBytes)
{
+ // If the file is already opened, first close it
+ if (m_file)
+ sf_close(m_file);
+
+ // Prepare the memory I/O structure
+ SF_VIRTUAL_IO io;
+ io.get_filelen = &Memory::getLength;
+ io.read = &Memory::read;
+ io.seek = &Memory::seek;
+ io.tell = &Memory::tell;
+
+ // Initialize the memory data
+ m_memory.begin = static_cast<const char*>(data);
+ m_memory.current = m_memory.begin;
+ m_memory.size = sizeInBytes;
+
+ // Open the sound file
+ SF_INFO fileInfo;
+ fileInfo.format = 0;
+ m_file = sf_open_virtual(&io, SFM_READ, &fileInfo, &m_memory);
+ if (!m_file)
+ {
+ err() << "Failed to open sound file from memory (" << sf_strerror(m_file) << ")" << std::endl;
+ return false;
+ }
+
+ // Initialize the internal state from the loaded information
+ initialize(fileInfo);
+ return true;
}
////////////////////////////////////////////////////////////
-/// Virtual destructor
-////////////////////////////////////////////////////////////
-SoundFile::~SoundFile()
+bool SoundFile::openRead(InputStream& stream)
{
- // Nothing to do
+ // If the file is already opened, first close it
+ if (m_file)
+ sf_close(m_file);
+
+ // Prepare the memory I/O structure
+ SF_VIRTUAL_IO io;
+ io.get_filelen = &Stream::getLength;
+ io.read = &Stream::read;
+ io.seek = &Stream::seek;
+ io.tell = &Stream::tell;
+
+ // Initialize the stream data
+ m_stream.source = &stream;
+ m_stream.size = stream.getSize();
+
+ // Make sure that the stream's reading position is at the beginning
+ stream.seek(0);
+
+ // Open the sound file
+ SF_INFO fileInfo;
+ fileInfo.format = 0;
+ m_file = sf_open_virtual(&io, SFM_READ, &fileInfo, &m_stream);
+ if (!m_file)
+ {
+ err() << "Failed to open sound file from stream (" << sf_strerror(m_file) << ")" << std::endl;
+ return false;
+ }
+
+ // Initialize the internal state from the loaded information
+ initialize(fileInfo);
+
+ return true;
}
////////////////////////////////////////////////////////////
-/// Get the total number of samples in the file
-////////////////////////////////////////////////////////////
-std::size_t SoundFile::GetSamplesCount() const
+bool SoundFile::openWrite(const std::string& filename, unsigned int channelCount, unsigned int sampleRate)
{
- return myNbSamples;
+ // If the file is already opened, first close it
+ if (m_file)
+ sf_close(m_file);
+
+ // Find the right format according to the file extension
+ int format = getFormatFromFilename(filename);
+ if (format == -1)
+ {
+ // Error : unrecognized extension
+ err() << "Failed to create sound file \"" << filename << "\" (unknown format)" << std::endl;
+ return false;
+ }
+
+ // Fill the sound infos with parameters
+ SF_INFO fileInfos;
+ fileInfos.channels = channelCount;
+ fileInfos.samplerate = sampleRate;
+ fileInfos.format = format | (format == SF_FORMAT_OGG ? SF_FORMAT_VORBIS : SF_FORMAT_PCM_16);
+
+ // Open the sound file for writing
+ m_file = sf_open(filename.c_str(), SFM_WRITE, &fileInfos);
+ if (!m_file)
+ {
+ err() << "Failed to create sound file \"" << filename << "\" (" << sf_strerror(m_file) << ")" << std::endl;
+ return false;
+ }
+
+ // Set the sound parameters
+ m_channelCount = channelCount;
+ m_sampleRate = sampleRate;
+ m_sampleCount = 0;
+
+ return true;
}
////////////////////////////////////////////////////////////
-/// Get the number of channels used by the sound
-////////////////////////////////////////////////////////////
-unsigned int SoundFile::GetChannelsCount() const
+std::size_t SoundFile::read(Int16* data, std::size_t sampleCount)
{
- return myChannelsCount;
+ if (m_file && data && sampleCount)
+ return static_cast<std::size_t>(sf_read_short(m_file, data, sampleCount));
+ else
+ return 0;
}
////////////////////////////////////////////////////////////
-/// Get the sample rate of the sound
-////////////////////////////////////////////////////////////
-unsigned int SoundFile::GetSampleRate() const
+void SoundFile::write(const Int16* data, std::size_t sampleCount)
{
- return mySampleRate;
+ if (m_file && data && sampleCount)
+ {
+ // Write small chunks instead of everything at once,
+ // to avoid a stack overflow in libsndfile (happens only with OGG format)
+ while (sampleCount > 0)
+ {
+ std::size_t count = sampleCount > 10000 ? 10000 : sampleCount;
+ sf_write_short(m_file, data, count);
+ data += count;
+ sampleCount -= count;
+ }
+ }
}
////////////////////////////////////////////////////////////
-/// Restart the sound from the beginning
-////////////////////////////////////////////////////////////
-bool SoundFile::Restart()
+void SoundFile::seek(Time timeOffset)
{
- if (myData)
- {
- // Reopen from memory
- return OpenRead(myData, mySize, myNbSamples, myChannelsCount, mySampleRate);
- }
- else if (myFilename != "")
- {
- // Reopen from file
- return OpenRead(myFilename, myNbSamples, myChannelsCount, mySampleRate);
- }
- else
+ if (m_file)
{
- // Trying to reopen a file opened in write mode... error
- std::cerr << "Warning : trying to restart a sound opened in write mode, which is not allowed" << std::endl;
- return false;
+ sf_count_t frameOffset = static_cast<sf_count_t>(timeOffset.asSeconds() * m_sampleRate);
+ sf_seek(m_file, frameOffset, SEEK_SET);
}
}
////////////////////////////////////////////////////////////
-/// Open the sound file for reading
-////////////////////////////////////////////////////////////
-bool SoundFile::OpenRead(const std::string& Filename, std::size_t&, unsigned int&, unsigned int&)
+void SoundFile::initialize(SF_INFO fileInfo)
{
- std::cerr << "Failed to open sound file \"" << Filename << "\", format is not supported by SFML" << std::endl;
+ // Save the sound properties
+ m_channelCount = fileInfo.channels;
+ m_sampleRate = fileInfo.samplerate;
+ m_sampleCount = static_cast<std::size_t>(fileInfo.frames) * fileInfo.channels;
+
+ // Enable scaling for Vorbis files (float samples)
+ // @todo enable when it's faster (it currently has to iterate over the *whole* music)
+ //if (fileInfo.format & SF_FORMAT_VORBIS)
+ // sf_command(m_file, SFC_SET_SCALE_FLOAT_INT_READ, NULL, SF_TRUE);
+}
- return false;
+
+////////////////////////////////////////////////////////////
+int SoundFile::getFormatFromFilename(const std::string& filename)
+{
+ // Extract the extension
+ std::string ext = "wav";
+ std::string::size_type pos = filename.find_last_of(".");
+ if (pos != std::string::npos)
+ ext = filename.substr(pos + 1);
+
+ // Match every supported extension with its format constant
+ if (toLower(ext) == "wav" ) return SF_FORMAT_WAV;
+ if (toLower(ext) == "aif" ) return SF_FORMAT_AIFF;
+ if (toLower(ext) == "aiff" ) return SF_FORMAT_AIFF;
+ if (toLower(ext) == "au" ) return SF_FORMAT_AU;
+ if (toLower(ext) == "raw" ) return SF_FORMAT_RAW;
+ if (toLower(ext) == "paf" ) return SF_FORMAT_PAF;
+ if (toLower(ext) == "svx" ) return SF_FORMAT_SVX;
+ if (toLower(ext) == "nist" ) return SF_FORMAT_NIST;
+ if (toLower(ext) == "voc" ) return SF_FORMAT_VOC;
+ if (toLower(ext) == "sf" ) return SF_FORMAT_IRCAM;
+ if (toLower(ext) == "w64" ) return SF_FORMAT_W64;
+ if (toLower(ext) == "mat4" ) return SF_FORMAT_MAT4;
+ if (toLower(ext) == "mat5" ) return SF_FORMAT_MAT5;
+ if (toLower(ext) == "pvf" ) return SF_FORMAT_PVF;
+ if (toLower(ext) == "xi" ) return SF_FORMAT_XI;
+ if (toLower(ext) == "htk" ) return SF_FORMAT_HTK;
+ if (toLower(ext) == "sds" ) return SF_FORMAT_SDS;
+ if (toLower(ext) == "avr" ) return SF_FORMAT_AVR;
+ if (toLower(ext) == "sd2" ) return SF_FORMAT_SD2;
+ if (toLower(ext) == "flac" ) return SF_FORMAT_FLAC;
+ if (toLower(ext) == "caf" ) return SF_FORMAT_CAF;
+ if (toLower(ext) == "wve" ) return SF_FORMAT_WVE;
+ if (toLower(ext) == "ogg" ) return SF_FORMAT_OGG;
+ if (toLower(ext) == "mpc2k") return SF_FORMAT_MPC2K;
+ if (toLower(ext) == "rf64" ) return SF_FORMAT_RF64;
+
+ return -1;
}
////////////////////////////////////////////////////////////
-/// Open the sound file in memory for reading
+sf_count_t SoundFile::Memory::getLength(void* user)
+{
+ Memory* memory = static_cast<Memory*>(user);
+ return memory->size;
+}
+
+
////////////////////////////////////////////////////////////
-bool SoundFile::OpenRead(const char*, std::size_t, std::size_t&, unsigned int&, unsigned int&)
+sf_count_t SoundFile::Memory::read(void* ptr, sf_count_t count, void* user)
{
- std::cerr << "Failed to open sound file from memory, format is not supported by SFML" << std::endl;
+ Memory* memory = static_cast<Memory*>(user);
- return false;
+ sf_count_t position = tell(user);
+ if (position + count >= memory->size)
+ count = memory->size - position;
+
+ std::memcpy(ptr, memory->current, static_cast<std::size_t>(count));
+ memory->current += count;
+ return count;
}
////////////////////////////////////////////////////////////
-/// Open the sound file for writing
-////////////////////////////////////////////////////////////
-bool SoundFile::OpenWrite(const std::string& Filename, unsigned int, unsigned int)
+sf_count_t SoundFile::Memory::seek(sf_count_t offset, int whence, void* user)
{
- std::cerr << "Failed to open sound file \"" << Filename << "\", format is not supported by SFML" << std::endl;
+ Memory* memory = static_cast<Memory*>(user);
+ sf_count_t position = 0;
+ switch (whence)
+ {
+ case SEEK_SET : position = offset; break;
+ case SEEK_CUR : position = memory->current - memory->begin + offset; break;
+ case SEEK_END : position = memory->size - offset; break;
+ default : position = 0; break;
+ }
+
+ if (position >= memory->size)
+ position = memory->size - 1;
+ else if (position < 0)
+ position = 0;
- return false;
+ memory->current = memory->begin + position;
+ return position;
}
////////////////////////////////////////////////////////////
-/// Read samples from the loaded sound
+sf_count_t SoundFile::Memory::tell(void* user)
+{
+ Memory* memory = static_cast<Memory*>(user);
+ return memory->current - memory->begin;
+}
+
+
////////////////////////////////////////////////////////////
-std::size_t SoundFile::Read(Int16*, std::size_t)
+sf_count_t SoundFile::Stream::getLength(void* userData)
{
- std::cerr << "Failed to read from sound file (not supported)" << std::endl;
+ Stream* stream = static_cast<Stream*>(userData);
+ return stream->size;
+}
- return 0;
+
+////////////////////////////////////////////////////////////
+sf_count_t SoundFile::Stream::read(void* ptr, sf_count_t count, void* userData)
+{
+ Stream* stream = static_cast<Stream*>(userData);
+ Int64 position = stream->source->tell();
+ if (position != -1)
+ {
+ if (count > stream->size - position)
+ count = stream->size - position;
+ return stream->source->read(reinterpret_cast<char*>(ptr), count);
+ }
+ else
+ {
+ return -1;
+ }
}
////////////////////////////////////////////////////////////
-/// Write samples to the file
+sf_count_t SoundFile::Stream::seek(sf_count_t offset, int whence, void* userData)
+{
+ Stream* stream = static_cast<Stream*>(userData);
+ switch (whence)
+ {
+ case SEEK_SET : return stream->source->seek(offset);
+ case SEEK_CUR : return stream->source->seek(stream->source->tell() + offset);
+ case SEEK_END : return stream->source->seek(stream->size - offset);
+ default : return stream->source->seek(0);
+ }
+}
+
+
////////////////////////////////////////////////////////////
-void SoundFile::Write(const Int16*, std::size_t)
+sf_count_t SoundFile::Stream::tell(void* userData)
{
- std::cerr << "Failed to write to sound file (not supported)" << std::endl;
+ Stream* stream = static_cast<Stream*>(userData);
+ return stream->source->tell();
}
} // namespace priv
diff --git a/src/SFML/Audio/SoundFile.hpp b/src/SFML/Audio/SoundFile.hpp
index fb36bdd..105a951 100755..100644
--- a/src/SFML/Audio/SoundFile.hpp
+++ b/src/SFML/Audio/SoundFile.hpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -29,176 +29,195 @@
// Headers
////////////////////////////////////////////////////////////
#include <SFML/System/NonCopyable.hpp>
+#include <SFML/System/Time.hpp>
+#include <sndfile.h>
#include <string>
namespace sf
{
+class InputStream;
+
namespace priv
{
////////////////////////////////////////////////////////////
-/// SoundFile is the abstract base class for loading
-/// and saving different sound file formats
+/// \brief Provide read and write access to sound files
+///
////////////////////////////////////////////////////////////
class SoundFile : NonCopyable
{
public :
////////////////////////////////////////////////////////////
- /// Create a new sound from a file, for reading
- ///
- /// \param Filename : Path of sound file
- /// \param NbSamples : Number of samples in the file
- /// \param ChannelsCount : Number of channels in the loaded sound
- /// \param SampleRate : Sample rate of the loaded sound
- ///
- /// \return Pointer to the new sound file (NULL if failed)
+ /// \brief Default constructor
///
////////////////////////////////////////////////////////////
- static SoundFile* CreateRead(const std::string& Filename);
+ SoundFile();
////////////////////////////////////////////////////////////
- /// Create a new sound from a file in memory, for reading
+ /// \brief Destructor
///
- /// \param Data : Pointer to the file data in memory
- /// \param SizeInBytes : Size of the data to load, in bytes
- /// \param NbSamples : Number of samples in the file
- /// \param ChannelsCount : Number of channels in the loaded sound
- /// \param SampleRate : Sample rate of the loaded sound
+ ////////////////////////////////////////////////////////////
+ ~SoundFile();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Get the total number of audio samples in the file
///
- /// \return Pointer to the new sound file (NULL if failed)
+ /// \return Number of samples
///
////////////////////////////////////////////////////////////
- static SoundFile* CreateRead(const char* Data, std::size_t SizeInBytes);
+ std::size_t getSampleCount() const;
////////////////////////////////////////////////////////////
- /// Create a new sound from a file, for writing
- ///
- /// \param Filename : Path of sound file
- /// \param ChannelsCount : Number of channels in the sound
- /// \param SampleRate : Sample rate of the sound
+ /// \brief Get the number of channels used by the sound
///
- /// \return Pointer to the new sound file (NULL if failed)
+ /// \return Number of channels (1 = mono, 2 = stereo)
///
////////////////////////////////////////////////////////////
- static SoundFile* CreateWrite(const std::string& Filename, unsigned int ChannelsCount, unsigned int SampleRate);
+ unsigned int getChannelCount() const;
////////////////////////////////////////////////////////////
- /// Virtual destructor
+ /// \brief Get the sample rate of the sound
+ ///
+ /// \return Sample rate, in samples per second
///
////////////////////////////////////////////////////////////
- virtual ~SoundFile();
+ unsigned int getSampleRate() const;
////////////////////////////////////////////////////////////
- /// Get the total number of samples in the file
+ /// \brief Open a sound file for reading
///
- /// \return Number of samples
+ /// \param filename Path of the sound file to load
+ ///
+ /// \return True if the file was successfully opened
///
////////////////////////////////////////////////////////////
- std::size_t GetSamplesCount() const;
+ bool openRead(const std::string& filename);
////////////////////////////////////////////////////////////
- /// Get the number of channels used by the sound
+ /// \brief Open a sound file in memory for reading
///
- /// \return Number of channels (1 = mono, 2 = stereo)
+ /// \param data Pointer to the file data in memory
+ /// \param sizeInBytes Size of the data to load, in bytes
+ ///
+ /// \return True if the file was successfully opened
///
////////////////////////////////////////////////////////////
- unsigned int GetChannelsCount() const;
+ bool openRead(const void* data, std::size_t sizeInBytes);
////////////////////////////////////////////////////////////
- /// Get the sample rate of the sound
+ /// \brief Open a sound file from a custom stream for reading
///
- /// \return Sample rate, in samples / sec
+ /// \param stream Source stream to read from
+ ///
+ /// \return True if the file was successfully opened
///
////////////////////////////////////////////////////////////
- unsigned int GetSampleRate() const;
+ bool openRead(InputStream& stream);
////////////////////////////////////////////////////////////
- /// Restart the sound from the beginning
+ /// \brief a the sound file for writing
///
- /// \return True if restart was successful
+ /// \param filename Path of the sound file to write
+ /// \param channelCount Number of channels in the sound
+ /// \param sampleRate Sample rate of the sound
+ ///
+ /// \return True if the file was successfully opened
///
////////////////////////////////////////////////////////////
- bool Restart();
+ bool openWrite(const std::string& filename, unsigned int channelCount, unsigned int sampleRate);
////////////////////////////////////////////////////////////
- /// Read samples from the loaded sound
+ /// \brief Read audio samples from the loaded sound
///
- /// \param Data : Pointer to the samples array to fill
- /// \param NbSamples : Number of samples to read
+ /// \param data Pointer to the sample array to fill
+ /// \param sampleCount Number of samples to read
///
- /// \return Number of samples read
+ /// \return Number of samples actually read (may be less than \a sampleCount)
///
////////////////////////////////////////////////////////////
- virtual std::size_t Read(Int16* Data, std::size_t NbSamples);
+ std::size_t read(Int16* data, std::size_t sampleCount);
////////////////////////////////////////////////////////////
- /// Write samples to the file
+ /// \brief Write audio samples to the file
///
- /// \param Data : Pointer to the samples array to write
- /// \param NbSamples : Number of samples to write
+ /// \param data Pointer to the sample array to write
+ /// \param sampleCount Number of samples to write
///
////////////////////////////////////////////////////////////
- virtual void Write(const Int16* Data, std::size_t NbSamples);
-
-protected :
+ void write(const Int16* data, std::size_t sampleCount);
////////////////////////////////////////////////////////////
- /// Default constructor
+ /// \brief Change the current read position in the file
+ ///
+ /// \param timeOffset New playing position, from the beginning of the file
///
////////////////////////////////////////////////////////////
- SoundFile();
+ void seek(Time timeOffset);
private :
////////////////////////////////////////////////////////////
- /// Open the sound file for reading
+ /// \brief Initialize the internal state of the sound file
///
- /// \param Filename : Path of sound file to load
- /// \param NbSamples : Number of samples in the file
- /// \param ChannelsCount : Number of channels in the loaded sound
- /// \param SampleRate : Sample rate of the loaded sound
+ /// This function is called by all the openRead functions.
///
- /// \return True if the file was successfully opened
+ /// \param fileInfo Information about the loaded sound file
///
////////////////////////////////////////////////////////////
- virtual bool OpenRead(const std::string& Filename, std::size_t& NbSamples, unsigned int& ChannelsCount, unsigned int& SampleRate);
+ void initialize(SF_INFO fileInfo);
////////////////////////////////////////////////////////////
- /// Open the sound file in memory for reading
+ /// \brief Get the internal format of an audio file according to
+ /// its filename extension
///
- /// \param Data : Pointer to the file data in memory
- /// \param SizeInBytes : Size of the data to load, in bytes
- /// \param NbSamples : Number of samples in the file
- /// \param ChannelsCount : Number of channels in the loaded sound
- /// \param SampleRate : Sample rate of the loaded sound
+ /// \param filename Filename to check
///
- /// \return True if the file was successfully opened
+ /// \return Internal format matching the filename (-1 if no match)
///
////////////////////////////////////////////////////////////
- virtual bool OpenRead(const char* Data, std::size_t SizeInBytes, std::size_t& NbSamples, unsigned int& ChannelsCount, unsigned int& SampleRate);
+ static int getFormatFromFilename(const std::string& filename);
////////////////////////////////////////////////////////////
- /// Open the sound file for writing
- ///
- /// \param Filename : Path of sound file to write
- /// \param ChannelsCount : Number of channels in the sound
- /// \param SampleRate : Sample rate of the sound
+ /// \brief Data and callbacks for opening from memory
///
- /// \return True if the file was successfully opened
+ ////////////////////////////////////////////////////////////
+ struct Memory
+ {
+ const char* begin;
+ const char* current;
+ sf_count_t size;
+
+ static sf_count_t getLength(void* user);
+ static sf_count_t read(void* ptr, sf_count_t count, void* user);
+ static sf_count_t seek(sf_count_t offset, int whence, void* user);
+ static sf_count_t tell(void* user);
+ };
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Data and callbacks for opening from stream
///
////////////////////////////////////////////////////////////
- virtual bool OpenWrite(const std::string& Filename, unsigned int ChannelsCount, unsigned int SampleRate);
+ struct Stream
+ {
+ InputStream* source;
+ Int64 size;
+
+ static sf_count_t getLength(void* user);
+ static sf_count_t read(void* ptr, sf_count_t count, void* user);
+ static sf_count_t seek(sf_count_t offset, int whence, void* user);
+ static sf_count_t tell(void* user);
+ };
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
- std::size_t myNbSamples; ///< Total number of samples in the file
- unsigned int myChannelsCount; ///< Number of channels used by the sound
- unsigned int mySampleRate; ///< Number of samples per second
- std::string myFilename; ///< Path of the file (valid if loaded from a file)
- const char* myData; ///< Pointer to the file in memory (valid if loaded from memory)
- std::size_t mySize; ///< Size of the file in memory (valid if loaded from memory)
+ SNDFILE* m_file; ///< File descriptor
+ Memory m_memory; ///< Memory reading info
+ Stream m_stream; ///< Stream reading info
+ std::size_t m_sampleCount; ///< Total number of samples in the file
+ unsigned int m_channelCount; ///< Number of channels used by the sound
+ unsigned int m_sampleRate; ///< Number of samples per second
};
} // namespace priv
diff --git a/src/SFML/Audio/SoundFileDefault.cpp b/src/SFML/Audio/SoundFileDefault.cpp
deleted file mode 100755
index 4413f6b..0000000
--- a/src/SFML/Audio/SoundFileDefault.cpp
+++ /dev/null
@@ -1,352 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Audio/SoundFileDefault.hpp>
-#include <iostream>
-#include <string.h>
-
-
-namespace sf
-{
-namespace priv
-{
-////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
-SoundFileDefault::SoundFileDefault() :
-myFile(NULL)
-{
-
-}
-
-
-////////////////////////////////////////////////////////////
-/// Destructor
-////////////////////////////////////////////////////////////
-SoundFileDefault::~SoundFileDefault()
-{
- if (myFile)
- sf_close(myFile);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Check if a given file is supported by this loader
-////////////////////////////////////////////////////////////
-bool SoundFileDefault::IsFileSupported(const std::string& Filename, bool Read)
-{
- if (Read)
- {
- // Open the sound file
- SF_INFO FileInfos;
- SNDFILE* File = sf_open(Filename.c_str(), SFM_READ, &FileInfos);
-
- if (File)
- {
- sf_close(File);
- return true;
- }
- else
- {
- return false;
- }
- }
- else
- {
- // Check the extension
- return GetFormatFromFilename(Filename) != -1;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Check if a given file in memory is supported by this loader
-////////////////////////////////////////////////////////////
-bool SoundFileDefault::IsFileSupported(const char* Data, std::size_t SizeInBytes)
-{
- // Define the I/O custom functions for reading from memory
- SF_VIRTUAL_IO VirtualIO;
- VirtualIO.get_filelen = &SoundFileDefault::MemoryGetLength;
- VirtualIO.read = &SoundFileDefault::MemoryRead;
- VirtualIO.seek = &SoundFileDefault::MemorySeek;
- VirtualIO.tell = &SoundFileDefault::MemoryTell;
- VirtualIO.write = &SoundFileDefault::MemoryWrite;
-
- // Initialize the memory data
- MemoryInfos Memory;
- Memory.DataStart = Data;
- Memory.DataPtr = Data;
- Memory.TotalSize = SizeInBytes;
-
- // Open the sound file
- SF_INFO FileInfos;
- SNDFILE* File = sf_open_virtual(&VirtualIO, SFM_READ, &FileInfos, &Memory);
-
- if (File)
- {
- sf_close(File);
- return true;
- }
- else
- {
- return false;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Open the sound file for reading
-////////////////////////////////////////////////////////////
-bool SoundFileDefault::OpenRead(const std::string& Filename, std::size_t& NbSamples, unsigned int& ChannelsCount, unsigned int& SampleRate)
-{
- // If the file is already opened, first close it
- if (myFile)
- sf_close(myFile);
-
- // Open the sound file
- SF_INFO FileInfos;
- myFile = sf_open(Filename.c_str(), SFM_READ, &FileInfos);
- if (!myFile)
- {
- std::cerr << "Failed to read sound file \"" << Filename << "\"" << std::endl;
- return false;
- }
-
- // Set the sound parameters
- ChannelsCount = FileInfos.channels;
- SampleRate = FileInfos.samplerate;
- NbSamples = static_cast<std::size_t>(FileInfos.frames) * ChannelsCount;
-
- return true;
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see sf::SoundFile::OpenRead
-////////////////////////////////////////////////////////////
-bool SoundFileDefault::OpenRead(const char* Data, std::size_t SizeInBytes, std::size_t& NbSamples, unsigned int& ChannelsCount, unsigned int& SampleRate)
-{
- // If the file is already opened, first close it
- if (myFile)
- sf_close(myFile);
-
- // Define the I/O custom functions for reading from memory
- SF_VIRTUAL_IO VirtualIO;
- VirtualIO.get_filelen = &SoundFileDefault::MemoryGetLength;
- VirtualIO.read = &SoundFileDefault::MemoryRead;
- VirtualIO.seek = &SoundFileDefault::MemorySeek;
- VirtualIO.tell = &SoundFileDefault::MemoryTell;
- VirtualIO.write = &SoundFileDefault::MemoryWrite;
-
- // Initialize the memory data
- myMemory.DataStart = Data;
- myMemory.DataPtr = Data;
- myMemory.TotalSize = SizeInBytes;
-
- // Open the sound file
- SF_INFO FileInfos;
- myFile = sf_open_virtual(&VirtualIO, SFM_READ, &FileInfos, &myMemory);
- if (!myFile)
- {
- std::cerr << "Failed to read sound file from memory" << std::endl;
- return false;
- }
-
- // Set the sound parameters
- ChannelsCount = FileInfos.channels;
- SampleRate = FileInfos.samplerate;
- NbSamples = static_cast<std::size_t>(FileInfos.frames) * ChannelsCount;
-
- return true;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Open the sound file for writing
-////////////////////////////////////////////////////////////
-bool SoundFileDefault::OpenWrite(const std::string& Filename, unsigned int ChannelsCount, unsigned int SampleRate)
-{
- // If the file is already opened, first close it
- if (myFile)
- sf_close(myFile);
-
- // Find the right format according to the file extension
- int Format = GetFormatFromFilename(Filename);
- if (Format == -1)
- {
- // Error : unrecognized extension
- std::cerr << "Failed to create sound file \"" << Filename << "\" : unknown format" << std::endl;
- return false;
- }
-
- // Fill the sound infos with parameters
- SF_INFO FileInfos;
- FileInfos.channels = ChannelsCount;
- FileInfos.samplerate = SampleRate;
- FileInfos.format = Format | SF_FORMAT_PCM_16;
-
- // Open the sound file for writing
- myFile = sf_open(Filename.c_str(), SFM_WRITE, &FileInfos);
- if (!myFile)
- {
- std::cerr << "Failed to create sound file \"" << Filename << "\"" << std::endl;
- return false;
- }
-
- return true;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Read samples from the loaded sound
-////////////////////////////////////////////////////////////
-std::size_t SoundFileDefault::Read(Int16* Data, std::size_t NbSamples)
-{
- if (myFile && Data && NbSamples)
- return static_cast<std::size_t>(sf_read_short(myFile, Data, NbSamples));
- else
- return 0;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Write samples to the file
-////////////////////////////////////////////////////////////
-void SoundFileDefault::Write(const Int16* Data, std::size_t NbSamples)
-{
- if (myFile && Data && NbSamples)
- sf_write_short(myFile, Data, NbSamples);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the internal format of an audio file according to
-/// its filename extension
-////////////////////////////////////////////////////////////
-int SoundFileDefault::GetFormatFromFilename(const std::string& Filename)
-{
- // Extract the extension
- std::string Ext = "wav";
- std::string::size_type Pos = Filename.find_last_of(".");
- if (Pos != std::string::npos)
- Ext = Filename.substr(Pos + 1);
-
- // Match every supported extension with its format constant
- if (Ext == "wav" || Ext == "WAV" ) return SF_FORMAT_WAV;
- if (Ext == "aif" || Ext == "AIF" ) return SF_FORMAT_AIFF;
- if (Ext == "aiff" || Ext == "AIFF") return SF_FORMAT_AIFF;
- if (Ext == "au" || Ext == "AU" ) return SF_FORMAT_AU;
- if (Ext == "raw" || Ext == "RAW" ) return SF_FORMAT_RAW;
- if (Ext == "paf" || Ext == "PAF" ) return SF_FORMAT_PAF;
- if (Ext == "svx" || Ext == "SVX" ) return SF_FORMAT_SVX;
- if (Ext == "voc" || Ext == "VOC" ) return SF_FORMAT_VOC;
- if (Ext == "sf" || Ext == "SF" ) return SF_FORMAT_IRCAM;
- if (Ext == "w64" || Ext == "W64" ) return SF_FORMAT_W64;
- if (Ext == "mat4" || Ext == "MAT4") return SF_FORMAT_MAT4;
- if (Ext == "mat5" || Ext == "MAT5") return SF_FORMAT_MAT5;
- if (Ext == "pvf" || Ext == "PVF" ) return SF_FORMAT_PVF;
- if (Ext == "htk" || Ext == "HTK" ) return SF_FORMAT_HTK;
- if (Ext == "caf" || Ext == "CAF" ) return SF_FORMAT_CAF;
- if (Ext == "nist" || Ext == "NIST") return SF_FORMAT_NIST; // SUPPORTED ?
- if (Ext == "sds" || Ext == "SDS" ) return SF_FORMAT_SDS; // SUPPORTED ?
- if (Ext == "avr" || Ext == "AVR" ) return SF_FORMAT_AVR; // SUPPORTED ?
- if (Ext == "sd2" || Ext == "SD2" ) return SF_FORMAT_SD2; // SUPPORTED ?
- if (Ext == "flac" || Ext == "FLAC") return SF_FORMAT_FLAC; // SUPPORTED ?
-
- return -1;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Functions for implementing custom read and write to memory files
-///
-////////////////////////////////////////////////////////////
-sf_count_t SoundFileDefault::MemoryGetLength(void* UserData)
-{
- MemoryInfos* Memory = static_cast<MemoryInfos*>(UserData);
-
- return Memory->TotalSize;
-}
-sf_count_t SoundFileDefault::MemoryRead(void* Ptr, sf_count_t Count, void* UserData)
-{
- MemoryInfos* Memory = static_cast<MemoryInfos*>(UserData);
-
- sf_count_t Position = Memory->DataPtr - Memory->DataStart;
- if (Position + Count >= Memory->TotalSize)
- Count = Memory->TotalSize - Position;
-
- memcpy(Ptr, Memory->DataPtr, static_cast<std::size_t>(Count));
-
- Memory->DataPtr += Count;
-
- return Count;
-}
-sf_count_t SoundFileDefault::MemorySeek(sf_count_t Offset, int Whence, void* UserData)
-{
- MemoryInfos* Memory = static_cast<MemoryInfos*>(UserData);
-
- sf_count_t Position = 0;
- switch (Whence)
- {
- case SEEK_SET :
- Position = Offset;
- break;
- case SEEK_CUR :
- Position = Memory->DataPtr - Memory->DataStart + Offset;
- break;
- case SEEK_END :
- Position = Memory->TotalSize - Offset;
- break;
- default :
- Position = 0;
- break;
- }
-
- if (Position >= Memory->TotalSize)
- Position = Memory->TotalSize - 1;
- else if (Position < 0)
- Position = 0;
-
- Memory->DataPtr = Memory->DataStart + Position;
-
- return Position;
-}
-sf_count_t SoundFileDefault::MemoryTell(void* UserData)
-{
- MemoryInfos* Memory = static_cast<MemoryInfos*>(UserData);
-
- return Memory->DataPtr - Memory->DataStart;
-}
-sf_count_t SoundFileDefault::MemoryWrite(const void*, sf_count_t, void*)
-{
- return 0;
-}
-
-
-} // namespace priv
-
-} // namespace sf
diff --git a/src/SFML/Audio/SoundFileDefault.hpp b/src/SFML/Audio/SoundFileDefault.hpp
deleted file mode 100755
index 8317d54..0000000
--- a/src/SFML/Audio/SoundFileDefault.hpp
+++ /dev/null
@@ -1,156 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-#ifndef SFML_SOUNDFILEDEFAULT_HPP
-#define SFML_SOUNDFILEDEFAULT_HPP
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Audio/SoundFile.hpp>
-#include <sndfile.h>
-
-
-namespace sf
-{
-namespace priv
-{
-////////////////////////////////////////////////////////////
-/// Specialization of SoundFile that can handle a lot of
-/// sound formats (see libsndfile homepage for a complete list)
-////////////////////////////////////////////////////////////
-class SoundFileDefault : public SoundFile
-{
-public :
-
- ////////////////////////////////////////////////////////////
- /// Default constructor
- ///
- ////////////////////////////////////////////////////////////
- SoundFileDefault();
-
- ////////////////////////////////////////////////////////////
- /// Destructor
- ///
- ////////////////////////////////////////////////////////////
- ~SoundFileDefault();
-
- ////////////////////////////////////////////////////////////
- /// Check if a given file is supported by this loader
- ///
- /// \param Filename : Path of the file to check
- /// \param Read : Is the file opened for reading or writing ?
- ///
- /// \param return True if the loader can handle this file
- ///
- ////////////////////////////////////////////////////////////
- static bool IsFileSupported(const std::string& Filename, bool Read);
-
- ////////////////////////////////////////////////////////////
- /// Check if a given file in memory is supported by this loader
- ///
- /// \param Data : Pointer to the file data in memory
- /// \param SizeInBytes : Size of the data to load, in bytes
- ///
- /// \param return True if the loader can handle this file
- ///
- ////////////////////////////////////////////////////////////
- static bool IsFileSupported(const char* Data, std::size_t SizeInBytes);
-
- ////////////////////////////////////////////////////////////
- /// /see sf::SoundFile::Read
- ///
- ////////////////////////////////////////////////////////////
- virtual std::size_t Read(Int16* Data, std::size_t NbSamples);
-
- ////////////////////////////////////////////////////////////
- /// /see sf::SoundFile::Write
- ///
- ////////////////////////////////////////////////////////////
- virtual void Write(const Int16* Data, std::size_t NbSamples);
-
-private :
-
- ////////////////////////////////////////////////////////////
- /// /see sf::SoundFile::OpenRead
- ///
- ////////////////////////////////////////////////////////////
- virtual bool OpenRead(const std::string& Filename, std::size_t& NbSamples, unsigned int& ChannelsCount, unsigned int& SampleRate);
-
- ////////////////////////////////////////////////////////////
- /// /see sf::SoundFile::OpenRead
- ///
- ////////////////////////////////////////////////////////////
- virtual bool OpenRead(const char* Data, std::size_t SizeInBytes, std::size_t& NbSamples, unsigned int& ChannelsCount, unsigned int& SampleRate);
-
- ////////////////////////////////////////////////////////////
- /// /see sf::SoundFile::OpenWrite
- ///
- ////////////////////////////////////////////////////////////
- virtual bool OpenWrite(const std::string& Filename, unsigned int ChannelsCount, unsigned int SampleRate);
-
- ////////////////////////////////////////////////////////////
- /// Get the internal format of an audio file according to
- /// its filename extension
- ///
- /// \param Filename : Filename to check
- ///
- /// \return Internal format matching the filename (-1 if no match)
- ///
- ////////////////////////////////////////////////////////////
- static int GetFormatFromFilename(const std::string& Filename);
-
- ////////////////////////////////////////////////////////////
- /// Functions for implementing custom read and write to memory files
- ///
- ////////////////////////////////////////////////////////////
- static sf_count_t MemoryGetLength(void* UserData);
- static sf_count_t MemoryRead(void* Ptr, sf_count_t Count, void* UserData);
- static sf_count_t MemorySeek(sf_count_t Offset, int Whence, void* UserData);
- static sf_count_t MemoryTell(void* UserData);
- static sf_count_t MemoryWrite(const void* Ptr, sf_count_t Count, void* UserData);
-
- ////////////////////////////////////////////////////////////
- /// Structure holding data related to memory operations
- ////////////////////////////////////////////////////////////
- struct MemoryInfos
- {
- const char* DataStart; ///< Pointer to the begining of the data
- const char* DataPtr; ///< Pointer to the current read / write position
- sf_count_t TotalSize; ///< Total size of the data, in bytes
- };
-
- ////////////////////////////////////////////////////////////
- // Member data
- ////////////////////////////////////////////////////////////
- SNDFILE* myFile; ///< File descriptor
- MemoryInfos myMemory; ///< Memory read / write data
-};
-
-} // namespace priv
-
-} // namespace sf
-
-
-#endif // SFML_SOUNDFILEDEFAULT_HPP
diff --git a/src/SFML/Audio/SoundFileOgg.cpp b/src/SFML/Audio/SoundFileOgg.cpp
deleted file mode 100755
index 8aa94f8..0000000
--- a/src/SFML/Audio/SoundFileOgg.cpp
+++ /dev/null
@@ -1,182 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Audio/SoundFileOgg.hpp>
-#include <SFML/Audio/stb_vorbis/stb_vorbis.h>
-#include <iostream>
-
-
-namespace sf
-{
-namespace priv
-{
-////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
-SoundFileOgg::SoundFileOgg() :
-myStream (NULL),
-myChannelsCount(0)
-{
-
-}
-
-
-////////////////////////////////////////////////////////////
-/// Destructor
-////////////////////////////////////////////////////////////
-SoundFileOgg::~SoundFileOgg()
-{
- if (myStream)
- stb_vorbis_close(myStream);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Check if a given file is supported by this loader
-////////////////////////////////////////////////////////////
-bool SoundFileOgg::IsFileSupported(const std::string& Filename, bool Read)
-{
- if (Read)
- {
- // Open the vorbis stream
- stb_vorbis* Stream = stb_vorbis_open_filename(const_cast<char*>(Filename.c_str()), NULL, NULL);
-
- if (Stream)
- {
- stb_vorbis_close(Stream);
- return true;
- }
- else
- {
- return false;
- }
- }
- else
- {
- // No support for writing ogg files yet...
- return false;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Check if a given file in memory is supported by this loader
-////////////////////////////////////////////////////////////
-bool SoundFileOgg::IsFileSupported(const char* Data, std::size_t SizeInBytes)
-{
- // Open the vorbis stream
- unsigned char* Buffer = reinterpret_cast<unsigned char*>(const_cast<char*>(Data));
- int Length = static_cast<int>(SizeInBytes);
- stb_vorbis* Stream = stb_vorbis_open_memory(Buffer, Length, NULL, NULL);
-
- if (Stream)
- {
- stb_vorbis_close(Stream);
- return true;
- }
- else
- {
- return false;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Open the sound file for reading
-////////////////////////////////////////////////////////////
-bool SoundFileOgg::OpenRead(const std::string& Filename, std::size_t& NbSamples, unsigned int& ChannelsCount, unsigned int& SampleRate)
-{
- // Close the file if already opened
- if (myStream)
- stb_vorbis_close(myStream);
-
- // Open the vorbis stream
- myStream = stb_vorbis_open_filename(const_cast<char*>(Filename.c_str()), NULL, NULL);
- if (myStream == NULL)
- {
- std::cerr << "Failed to read sound file \"" << Filename << "\" (cannot open the file)" << std::endl;
- return false;
- }
-
- // Get the music parameters
- stb_vorbis_info Infos = stb_vorbis_get_info(myStream);
- ChannelsCount = myChannelsCount = Infos.channels;
- SampleRate = Infos.sample_rate;
- NbSamples = static_cast<std::size_t>(stb_vorbis_stream_length_in_samples(myStream) * ChannelsCount);
-
- return true;
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see sf::SoundFile::OpenRead
-////////////////////////////////////////////////////////////
-bool SoundFileOgg::OpenRead(const char* Data, std::size_t SizeInBytes, std::size_t& NbSamples, unsigned int& ChannelsCount, unsigned int& SampleRate)
-{
- // Close the file if already opened
- if (myStream)
- stb_vorbis_close(myStream);
-
- // Open the vorbis stream
- unsigned char* Buffer = reinterpret_cast<unsigned char*>(const_cast<char*>(Data));
- int Length = static_cast<int>(SizeInBytes);
- myStream = stb_vorbis_open_memory(Buffer, Length, NULL, NULL);
- if (myStream == NULL)
- {
- std::cerr << "Failed to read sound file from memory (cannot open the file)" << std::endl;
- return false;
- }
-
- // Get the music parameters
- stb_vorbis_info Infos = stb_vorbis_get_info(myStream);
- ChannelsCount = myChannelsCount = Infos.channels;
- SampleRate = Infos.sample_rate;
- NbSamples = static_cast<std::size_t>(stb_vorbis_stream_length_in_samples(myStream) * ChannelsCount);
-
- return true;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Read samples from the loaded sound
-////////////////////////////////////////////////////////////
-std::size_t SoundFileOgg::Read(Int16* Data, std::size_t NbSamples)
-{
- if (myStream && Data && NbSamples)
- {
- int Read = stb_vorbis_get_samples_short_interleaved(myStream, myChannelsCount, Data, static_cast<int>(NbSamples));
- return static_cast<std::size_t>(Read * myChannelsCount);
- }
- else
- {
- return 0;
- }
-}
-
-} // namespace priv
-
-} // namespace sf
diff --git a/src/SFML/Audio/SoundRecorder.cpp b/src/SFML/Audio/SoundRecorder.cpp
index c12a49d..bf7b03f 100755..100644
--- a/src/SFML/Audio/SoundRecorder.cpp
+++ b/src/SFML/Audio/SoundRecorder.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -27,35 +27,33 @@
////////////////////////////////////////////////////////////
#include <SFML/Audio/SoundRecorder.hpp>
#include <SFML/Audio/AudioDevice.hpp>
-#include <SFML/Audio/OpenAL.hpp>
+#include <SFML/Audio/ALCheck.hpp>
#include <SFML/System/Sleep.hpp>
-#include <iostream>
+#include <SFML/System/Err.hpp>
+
+#ifdef _MSC_VER
+ #pragma warning(disable : 4355) // 'this' used in base member initializer list
+#endif
-////////////////////////////////////////////////////////////
-// Private data
-////////////////////////////////////////////////////////////
namespace
{
- ALCdevice* CaptureDevice = NULL;
+ ALCdevice* captureDevice = NULL;
}
namespace sf
{
////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
SoundRecorder::SoundRecorder() :
-mySampleRate (0),
-myIsCapturing(false)
+m_thread (&SoundRecorder::record, this),
+m_sampleRate (0),
+m_isCapturing(false)
{
-
+ priv::ensureALInit();
}
////////////////////////////////////////////////////////////
-/// Virtual destructor
-////////////////////////////////////////////////////////////
SoundRecorder::~SoundRecorder()
{
// Nothing to do
@@ -63,89 +61,75 @@ SoundRecorder::~SoundRecorder()
////////////////////////////////////////////////////////////
-/// Start the capture.
-/// Warning : only one capture can happen at the same time
-////////////////////////////////////////////////////////////
-void SoundRecorder::Start(unsigned int SampleRate)
+void SoundRecorder::start(unsigned int sampleRate)
{
// Check if the device can do audio capture
- if (!CanCapture())
+ if (!isAvailable())
{
- std::cerr << "Failed to start capture : your system cannot capture audio data (call SoundRecorder::CanCapture to check it)" << std::endl;
+ err() << "Failed to start capture : your system cannot capture audio data (call SoundRecorder::IsAvailable to check it)" << std::endl;
return;
}
// Check that another capture is not already running
- if (CaptureDevice)
+ if (captureDevice)
{
- std::cerr << "Trying to start audio capture, but another capture is already running" << std::endl;
+ err() << "Trying to start audio capture, but another capture is already running" << std::endl;
return;
}
// Open the capture device for capturing 16 bits mono samples
- CaptureDevice = alcCaptureOpenDevice(NULL, SampleRate, AL_FORMAT_MONO16, SampleRate);
- if (!CaptureDevice)
+ captureDevice = alcCaptureOpenDevice(NULL, sampleRate, AL_FORMAT_MONO16, sampleRate);
+ if (!captureDevice)
{
- std::cerr << "Failed to open the audio capture device" << std::endl;
+ err() << "Failed to open the audio capture device" << std::endl;
return;
}
- // Clear the sample array
- mySamples.clear();
+ // Clear the array of samples
+ m_samples.clear();
// Store the sample rate
- mySampleRate = SampleRate;
+ m_sampleRate = sampleRate;
// Notify derived class
- if (OnStart())
+ if (onStart())
{
// Start the capture
- alcCaptureStart(CaptureDevice);
+ alcCaptureStart(captureDevice);
// Start the capture in a new thread, to avoid blocking the main thread
- myIsCapturing = true;
- Launch();
+ m_isCapturing = true;
+ m_thread.launch();
}
}
////////////////////////////////////////////////////////////
-/// Stop the capture
-////////////////////////////////////////////////////////////
-void SoundRecorder::Stop()
+void SoundRecorder::stop()
{
// Stop the capturing thread
- myIsCapturing = false;
- Wait();
+ m_isCapturing = false;
+ m_thread.wait();
}
////////////////////////////////////////////////////////////
-/// Get the sample rate
-////////////////////////////////////////////////////////////
-unsigned int SoundRecorder::GetSampleRate() const
+unsigned int SoundRecorder::getSampleRate() const
{
- return mySampleRate;
+ return m_sampleRate;
}
////////////////////////////////////////////////////////////
-/// Tell if the system supports sound capture.
-/// If not, this class won't be usable
-////////////////////////////////////////////////////////////
-bool SoundRecorder::CanCapture()
+bool SoundRecorder::isAvailable()
{
- ALCdevice* Device = priv::AudioDevice::GetInstance().GetDevice();
-
- return (alcIsExtensionPresent(Device, "ALC_EXT_CAPTURE") != AL_FALSE) ||
- (alcIsExtensionPresent(Device, "ALC_EXT_capture") != AL_FALSE); // "bug" in Mac OS X 10.5 and 10.6
+ return (priv::AudioDevice::isExtensionSupported("ALC_EXT_CAPTURE") != AL_FALSE) ||
+ (priv::AudioDevice::isExtensionSupported("ALC_EXT_capture") != AL_FALSE); // "bug" in Mac OS X 10.5 and 10.6
}
////////////////////////////////////////////////////////////
-/// Start recording audio data
-////////////////////////////////////////////////////////////
-bool SoundRecorder::OnStart()
+bool SoundRecorder::onStart()
{
// Nothing to do
return true;
@@ -153,75 +137,67 @@ bool SoundRecorder::OnStart()
////////////////////////////////////////////////////////////
-/// Stop recording audio data
-////////////////////////////////////////////////////////////
-void SoundRecorder::OnStop()
+void SoundRecorder::onStop()
{
// Nothing to do
}
////////////////////////////////////////////////////////////
-/// /see Thread::Run
-////////////////////////////////////////////////////////////
-void SoundRecorder::Run()
+void SoundRecorder::record()
{
- while (myIsCapturing)
+ while (m_isCapturing)
{
// Process available samples
- ProcessCapturedSamples();
+ processCapturedSamples();
// Don't bother the CPU while waiting for more captured data
- Sleep(0.1f);
+ sleep(milliseconds(100));
}
// Capture is finished : clean up everything
- CleanUp();
+ cleanup();
// Notify derived class
- OnStop();
+ onStop();
}
////////////////////////////////////////////////////////////
-/// Get available captured samples and process them
-////////////////////////////////////////////////////////////
-void SoundRecorder::ProcessCapturedSamples()
+void SoundRecorder::processCapturedSamples()
{
// Get the number of samples available
- ALCint SamplesAvailable;
- alcGetIntegerv(CaptureDevice, ALC_CAPTURE_SAMPLES, 1, &SamplesAvailable);
+ ALCint samplesAvailable;
+ alcGetIntegerv(captureDevice, ALC_CAPTURE_SAMPLES, 1, &samplesAvailable);
- if (SamplesAvailable > 0)
+ if (samplesAvailable > 0)
{
// Get the recorded samples
- mySamples.resize(SamplesAvailable);
- alcCaptureSamples(CaptureDevice, &mySamples[0], SamplesAvailable);
+ m_samples.resize(samplesAvailable);
+ alcCaptureSamples(captureDevice, &m_samples[0], samplesAvailable);
// Forward them to the derived class
- if (!OnProcessSamples(&mySamples[0], mySamples.size()))
+ if (!onProcessSamples(&m_samples[0], m_samples.size()))
{
// The user wants to stop the capture
- myIsCapturing = false;
+ m_isCapturing = false;
}
}
}
////////////////////////////////////////////////////////////
-/// Clean up recorder internal resources
-////////////////////////////////////////////////////////////
-void SoundRecorder::CleanUp()
+void SoundRecorder::cleanup()
{
// Stop the capture
- alcCaptureStop(CaptureDevice);
+ alcCaptureStop(captureDevice);
// Get the samples left in the buffer
- ProcessCapturedSamples();
+ processCapturedSamples();
// Close the device
- alcCaptureCloseDevice(CaptureDevice);
- CaptureDevice = NULL;
+ alcCaptureCloseDevice(captureDevice);
+ captureDevice = NULL;
}
} // namespace sf
diff --git a/src/SFML/Audio/SoundSource.cpp b/src/SFML/Audio/SoundSource.cpp
new file mode 100644
index 0000000..c5a6524
--- /dev/null
+++ b/src/SFML/Audio/SoundSource.cpp
@@ -0,0 +1,194 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Audio/SoundSource.hpp>
+#include <SFML/Audio/ALCheck.hpp>
+
+
+namespace sf
+{
+////////////////////////////////////////////////////////////
+SoundSource::SoundSource()
+{
+ priv::ensureALInit();
+
+ alCheck(alGenSources(1, &m_source));
+ alCheck(alSourcei(m_source, AL_BUFFER, 0));
+}
+
+
+////////////////////////////////////////////////////////////
+SoundSource::SoundSource(const SoundSource& copy)
+{
+ priv::ensureALInit();
+
+ alCheck(alGenSources(1, &m_source));
+ alCheck(alSourcei(m_source, AL_BUFFER, 0));
+
+ setPitch(copy.getPitch());
+ setVolume(copy.getVolume());
+ setPosition(copy.getPosition());
+ setRelativeToListener(copy.isRelativeToListener());
+ setMinDistance(copy.getMinDistance());
+ setAttenuation(copy.getAttenuation());
+}
+
+
+////////////////////////////////////////////////////////////
+SoundSource::~SoundSource()
+{
+ alCheck(alSourcei(m_source, AL_BUFFER, 0));
+ alCheck(alDeleteSources(1, &m_source));
+}
+
+
+////////////////////////////////////////////////////////////
+void SoundSource::setPitch(float pitch)
+{
+ alCheck(alSourcef(m_source, AL_PITCH, pitch));
+}
+
+
+////////////////////////////////////////////////////////////
+void SoundSource::setVolume(float volume)
+{
+ alCheck(alSourcef(m_source, AL_GAIN, volume * 0.01f));
+}
+
+////////////////////////////////////////////////////////////
+void SoundSource::setPosition(float x, float y, float z)
+{
+ alCheck(alSource3f(m_source, AL_POSITION, x, y, z));
+}
+
+
+////////////////////////////////////////////////////////////
+void SoundSource::setPosition(const Vector3f& position)
+{
+ setPosition(position.x, position.y, position.z);
+}
+
+
+////////////////////////////////////////////////////////////
+void SoundSource::setRelativeToListener(bool relative)
+{
+ alCheck(alSourcei(m_source, AL_SOURCE_RELATIVE, relative));
+}
+
+
+////////////////////////////////////////////////////////////
+void SoundSource::setMinDistance(float distance)
+{
+ alCheck(alSourcef(m_source, AL_REFERENCE_DISTANCE, distance));
+}
+
+
+////////////////////////////////////////////////////////////
+void SoundSource::setAttenuation(float attenuation)
+{
+ alCheck(alSourcef(m_source, AL_ROLLOFF_FACTOR, attenuation));
+}
+
+
+////////////////////////////////////////////////////////////
+float SoundSource::getPitch() const
+{
+ ALfloat pitch;
+ alCheck(alGetSourcef(m_source, AL_PITCH, &pitch));
+
+ return pitch;
+}
+
+
+////////////////////////////////////////////////////////////
+float SoundSource::getVolume() const
+{
+ ALfloat gain;
+ alCheck(alGetSourcef(m_source, AL_GAIN, &gain));
+
+ return gain * 100.f;
+}
+
+
+////////////////////////////////////////////////////////////
+Vector3f SoundSource::getPosition() const
+{
+ Vector3f position;
+ alCheck(alGetSource3f(m_source, AL_POSITION, &position.x, &position.y, &position.z));
+
+ return position;
+}
+
+
+////////////////////////////////////////////////////////////
+bool SoundSource::isRelativeToListener() const
+{
+ ALint relative;
+ alCheck(alGetSourcei(m_source, AL_SOURCE_RELATIVE, &relative));
+
+ return relative != 0;
+}
+
+
+////////////////////////////////////////////////////////////
+float SoundSource::getMinDistance() const
+{
+ ALfloat distance;
+ alCheck(alGetSourcef(m_source, AL_REFERENCE_DISTANCE, &distance));
+
+ return distance;
+}
+
+
+////////////////////////////////////////////////////////////
+float SoundSource::getAttenuation() const
+{
+ ALfloat attenuation;
+ alCheck(alGetSourcef(m_source, AL_ROLLOFF_FACTOR, &attenuation));
+
+ return attenuation;
+}
+
+
+////////////////////////////////////////////////////////////
+SoundSource::Status SoundSource::getStatus() const
+{
+ ALint status;
+ alCheck(alGetSourcei(m_source, AL_SOURCE_STATE, &status));
+
+ switch (status)
+ {
+ case AL_INITIAL :
+ case AL_STOPPED : return Stopped;
+ case AL_PAUSED : return Paused;
+ case AL_PLAYING : return Playing;
+ }
+
+ return Stopped;
+}
+
+} // namespace sf
diff --git a/src/SFML/Audio/SoundStream.cpp b/src/SFML/Audio/SoundStream.cpp
index 9530d78..31df188 100755..100644
--- a/src/SFML/Audio/SoundStream.cpp
+++ b/src/SFML/Audio/SoundStream.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -27,342 +27,339 @@
////////////////////////////////////////////////////////////
#include <SFML/Audio/SoundStream.hpp>
#include <SFML/Audio/AudioDevice.hpp>
-#include <SFML/Audio/OpenAL.hpp>
+#include <SFML/Audio/ALCheck.hpp>
#include <SFML/System/Sleep.hpp>
+#include <SFML/System/Err.hpp>
+
+#ifdef _MSC_VER
+ #pragma warning(disable : 4355) // 'this' used in base member initializer list
+#endif
namespace sf
{
////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
SoundStream::SoundStream() :
-myIsStreaming (false),
-myChannelsCount (0),
-mySampleRate (0),
-myFormat (0),
-myLoop (false),
-mySamplesProcessed(0)
+m_thread (&SoundStream::streamData, this),
+m_isStreaming (false),
+m_channelCount (0),
+m_sampleRate (0),
+m_format (0),
+m_loop (false),
+m_samplesProcessed(0)
{
}
////////////////////////////////////////////////////////////
-/// Virtual destructor
-////////////////////////////////////////////////////////////
SoundStream::~SoundStream()
{
// Stop the sound if it was playing
- Stop();
+ stop();
}
////////////////////////////////////////////////////////////
-/// Set the audio stream parameters, you must call it before Play()
-////////////////////////////////////////////////////////////
-void SoundStream::Initialize(unsigned int ChannelsCount, unsigned int SampleRate)
+void SoundStream::initialize(unsigned int channelCount, unsigned int sampleRate)
{
- myChannelsCount = ChannelsCount;
- mySampleRate = SampleRate;
+ m_channelCount = channelCount;
+ m_sampleRate = sampleRate;
// Deduce the format from the number of channels
- myFormat = priv::AudioDevice::GetInstance().GetFormatFromChannelsCount(ChannelsCount);
+ m_format = priv::AudioDevice::getFormatFromChannelCount(channelCount);
// Check if the format is valid
- if (myFormat == 0)
+ if (m_format == 0)
{
- myChannelsCount = 0;
- mySampleRate = 0;
- std::cerr << "Unsupported number of channels (" << myChannelsCount << ")" << std::endl;
+ m_channelCount = 0;
+ m_sampleRate = 0;
+ err() << "Unsupported number of channels (" << m_channelCount << ")" << std::endl;
}
}
////////////////////////////////////////////////////////////
-/// Start playing the audio stream
-////////////////////////////////////////////////////////////
-void SoundStream::Play()
+void SoundStream::play()
{
// Check if the sound parameters have been set
- if (myFormat == 0)
+ if (m_format == 0)
{
- std::cerr << "Failed to play audio stream : sound parameters have not been initialized (call Initialize first)" << std::endl;
+ err() << "Failed to play audio stream: sound parameters have not been initialized (call Initialize first)" << std::endl;
return;
}
// If the sound is already playing (probably paused), just resume it
- if (myIsStreaming)
+ if (m_isStreaming)
{
- Sound::Play();
+ alCheck(alSourcePlay(m_source));
return;
}
- // Notify the derived class
- if (OnStart())
- {
- // Start updating the stream in a separate thread to avoid blocking the application
- mySamplesProcessed = 0;
- myIsStreaming = true;
- Launch();
- }
+ // Move to the beginning
+ onSeek(Time::Zero);
+
+ // Start updating the stream in a separate thread to avoid blocking the application
+ m_samplesProcessed = 0;
+ m_isStreaming = true;
+ m_thread.launch();
}
////////////////////////////////////////////////////////////
-/// Stop playing the audio stream
+void SoundStream::pause()
+{
+ alCheck(alSourcePause(m_source));
+}
+
+
////////////////////////////////////////////////////////////
-void SoundStream::Stop()
+void SoundStream::stop()
{
// Wait for the thread to terminate
- myIsStreaming = false;
- Wait();
+ m_isStreaming = false;
+ m_thread.wait();
}
////////////////////////////////////////////////////////////
-/// Return the number of channels (1 = mono, 2 = stereo, ...)
-////////////////////////////////////////////////////////////
-unsigned int SoundStream::GetChannelsCount() const
+unsigned int SoundStream::getChannelCount() const
{
- return myChannelsCount;
+ return m_channelCount;
}
////////////////////////////////////////////////////////////
-/// Get the sound frequency (sample rate)
-////////////////////////////////////////////////////////////
-unsigned int SoundStream::GetSampleRate() const
+unsigned int SoundStream::getSampleRate() const
{
- return mySampleRate;
+ return m_sampleRate;
}
////////////////////////////////////////////////////////////
-/// Get the status of the sound (stopped, paused, playing)
-////////////////////////////////////////////////////////////
-Sound::Status SoundStream::GetStatus() const
+SoundStream::Status SoundStream::getStatus() const
{
- Status Status = Sound::GetStatus();
+ Status status = SoundSource::getStatus();
- // To compensate for the lag between Play() and alSourcePlay()
- if ((Status == Stopped) && myIsStreaming)
- Status = Playing;
+ // To compensate for the lag between play() and alSourceplay()
+ if ((status == Stopped) && m_isStreaming)
+ status = Playing;
- return Status;
+ return status;
}
////////////////////////////////////////////////////////////
-/// Get the current playing position of the stream
-///
-/// \return Current playing position, expressed in seconds
-///
-////////////////////////////////////////////////////////////
-float SoundStream::GetPlayingOffset() const
+void SoundStream::setPlayingOffset(Time timeOffset)
{
- return Sound::GetPlayingOffset() + static_cast<float>(mySamplesProcessed) / mySampleRate / myChannelsCount;
+ // Stop the stream
+ stop();
+
+ // Let the derived class update the current position
+ onSeek(timeOffset);
+
+ // Restart streaming
+ m_samplesProcessed = static_cast<Uint64>(timeOffset.asSeconds() * m_sampleRate * m_channelCount);
+ m_isStreaming = true;
+ m_thread.launch();
}
////////////////////////////////////////////////////////////
-/// Set the music loop state
-////////////////////////////////////////////////////////////
-void SoundStream::SetLoop(bool Loop)
+Time SoundStream::getPlayingOffset() const
{
- myLoop = Loop;
+ if (m_sampleRate && m_channelCount)
+ {
+ ALfloat secs = 0.f;
+ alCheck(alGetSourcef(m_source, AL_SEC_OFFSET, &secs));
+
+ return seconds(secs + static_cast<float>(m_samplesProcessed) / m_sampleRate / m_channelCount);
+ }
+ else
+ {
+ return Time::Zero;
+ }
}
////////////////////////////////////////////////////////////
-/// Tell whether or not the music is looping
-////////////////////////////////////////////////////////////
-bool SoundStream::GetLoop() const
+void SoundStream::setLoop(bool loop)
{
- return myLoop;
+ m_loop = loop;
}
////////////////////////////////////////////////////////////
-/// /see Thread::Run
+bool SoundStream::getLoop() const
+{
+ return m_loop;
+}
+
+
////////////////////////////////////////////////////////////
-void SoundStream::Run()
+void SoundStream::streamData()
{
// Create the buffers
- ALCheck(alGenBuffers(BuffersCount, myBuffers));
- for (int i = 0; i < BuffersCount; ++i)
- myEndBuffers[i] = false;
+ alCheck(alGenBuffers(BufferCount, m_buffers));
+ for (int i = 0; i < BufferCount; ++i)
+ m_endBuffers[i] = false;
// Fill the queue
- bool RequestStop = FillQueue();
+ bool requestStop = fillQueue();
// Play the sound
- Sound::Play();
+ alCheck(alSourcePlay(m_source));
- while (myIsStreaming)
+ while (m_isStreaming)
{
- // The stream has been interrupted !
- if (Sound::GetStatus() == Stopped)
+ // The stream has been interrupted!
+ if (SoundSource::getStatus() == Stopped)
{
- if (!RequestStop)
+ if (!requestStop)
{
// Just continue
- Sound::Play();
+ alCheck(alSourcePlay(m_source));
}
else
{
// End streaming
- myIsStreaming = false;
+ m_isStreaming = false;
}
}
// Get the number of buffers that have been processed (ie. ready for reuse)
- ALint NbProcessed;
- ALCheck(alGetSourcei(Sound::mySource, AL_BUFFERS_PROCESSED, &NbProcessed));
+ ALint nbProcessed = 0;
+ alCheck(alGetSourcei(m_source, AL_BUFFERS_PROCESSED, &nbProcessed));
- while (NbProcessed--)
+ while (nbProcessed--)
{
// Pop the first unused buffer from the queue
- ALuint Buffer;
- ALCheck(alSourceUnqueueBuffers(Sound::mySource, 1, &Buffer));
+ ALuint buffer;
+ alCheck(alSourceUnqueueBuffers(m_source, 1, &buffer));
// Find its number
- unsigned int BufferNum = 0;
- for (int i = 0; i < BuffersCount; ++i)
- if (myBuffers[i] == Buffer)
+ unsigned int bufferNum = 0;
+ for (int i = 0; i < BufferCount; ++i)
+ if (m_buffers[i] == buffer)
{
- BufferNum = i;
+ bufferNum = i;
break;
}
// Retrieve its size and add it to the samples count
- if (myEndBuffers[BufferNum])
+ if (m_endBuffers[bufferNum])
{
// This was the last buffer: reset the sample count
- mySamplesProcessed = 0;
- myEndBuffers[BufferNum] = false;
+ m_samplesProcessed = 0;
+ m_endBuffers[bufferNum] = false;
}
else
{
- ALint Size;
- ALCheck(alGetBufferi(Buffer, AL_SIZE, &Size));
- mySamplesProcessed += Size / sizeof(Int16);
+ ALint size, bits;
+ alCheck(alGetBufferi(buffer, AL_SIZE, &size));
+ alCheck(alGetBufferi(buffer, AL_BITS, &bits));
+ m_samplesProcessed += size / (bits / 8);
}
// Fill it and push it back into the playing queue
- if (!RequestStop)
+ if (!requestStop)
{
- if (FillAndPushBuffer(BufferNum))
- RequestStop = true;
+ if (fillAndPushBuffer(bufferNum))
+ requestStop = true;
}
}
// Leave some time for the other threads if the stream is still playing
- if (Sound::GetStatus() != Stopped)
- Sleep(0.1f);
+ if (SoundSource::getStatus() != Stopped)
+ sleep(milliseconds(10));
}
// Stop the playback
- Sound::Stop();
+ alCheck(alSourceStop(m_source));
// Unqueue any buffer left in the queue
- ClearQueue();
+ clearQueue();
// Delete the buffers
- ALCheck(alSourcei(Sound::mySource, AL_BUFFER, 0));
- ALCheck(alDeleteBuffers(BuffersCount, myBuffers));
+ alCheck(alSourcei(m_source, AL_BUFFER, 0));
+ alCheck(alDeleteBuffers(BufferCount, m_buffers));
}
////////////////////////////////////////////////////////////
-/// Fill a new buffer with audio data, and push it to the
-/// playing queue
-////////////////////////////////////////////////////////////
-bool SoundStream::FillAndPushBuffer(unsigned int BufferNum)
+bool SoundStream::fillAndPushBuffer(unsigned int bufferNum)
{
- bool RequestStop = false;
+ bool requestStop = false;
// Acquire audio data
- Chunk Data = {NULL, 0};
- if (!OnGetData(Data))
+ Chunk data = {NULL, 0};
+ if (!onGetData(data))
{
// Mark the buffer as the last one (so that we know when to reset the playing position)
- myEndBuffers[BufferNum] = true;
+ m_endBuffers[bufferNum] = true;
// Check if the stream must loop or stop
- if (myLoop && OnStart())
+ if (m_loop)
{
- // If we succeeded to restart and we previously had no data, try to fill the buffer once again
- if (!Data.Samples || (Data.NbSamples == 0))
+ // Return to the beginning of the stream source
+ onSeek(Time::Zero);
+
+ // If we previously had no data, try to fill the buffer once again
+ if (!data.samples || (data.sampleCount == 0))
{
- return FillAndPushBuffer(BufferNum);
+ return fillAndPushBuffer(bufferNum);
}
}
else
{
- // Not looping or restart failed: request stop
- RequestStop = true;
+ // Not looping: request stop
+ requestStop = true;
}
}
// Fill the buffer if some data was returned
- if (Data.Samples && Data.NbSamples)
+ if (data.samples && data.sampleCount)
{
- unsigned int Buffer = myBuffers[BufferNum];
+ unsigned int buffer = m_buffers[bufferNum];
// Fill the buffer
- ALsizei Size = static_cast<ALsizei>(Data.NbSamples) * sizeof(Int16);
- ALCheck(alBufferData(Buffer, myFormat, Data.Samples, Size, mySampleRate));
+ ALsizei size = static_cast<ALsizei>(data.sampleCount) * sizeof(Int16);
+ alCheck(alBufferData(buffer, m_format, data.samples, size, m_sampleRate));
// Push it into the sound queue
- ALCheck(alSourceQueueBuffers(Sound::mySource, 1, &Buffer));
+ alCheck(alSourceQueueBuffers(m_source, 1, &buffer));
}
- return RequestStop;
+ return requestStop;
}
////////////////////////////////////////////////////////////
-/// Fill the buffers queue with all available buffers
-////////////////////////////////////////////////////////////
-bool SoundStream::FillQueue()
+bool SoundStream::fillQueue()
{
// Fill and enqueue all the available buffers
- bool RequestStop = false;
- for (int i = 0; (i < BuffersCount) && !RequestStop; ++i)
+ bool requestStop = false;
+ for (int i = 0; (i < BufferCount) && !requestStop; ++i)
{
- if (FillAndPushBuffer(i))
- RequestStop = true;
+ if (fillAndPushBuffer(i))
+ requestStop = true;
}
- return RequestStop;
+ return requestStop;
}
////////////////////////////////////////////////////////////
-/// Clear the queue of any remaining buffers
-////////////////////////////////////////////////////////////
-void SoundStream::ClearQueue()
+void SoundStream::clearQueue()
{
// Get the number of buffers still in the queue
- ALint NbQueued;
- ALCheck(alGetSourcei(Sound::mySource, AL_BUFFERS_QUEUED, &NbQueued));
+ ALint nbQueued;
+ alCheck(alGetSourcei(m_source, AL_BUFFERS_QUEUED, &nbQueued));
// Unqueue them all
- ALuint Buffer;
- for (ALint i = 0; i < NbQueued; ++i)
- ALCheck(alSourceUnqueueBuffers(Sound::mySource, 1, &Buffer));
-}
-
-
-////////////////////////////////////////////////////////////
-/// Called when the sound restarts
-////////////////////////////////////////////////////////////
-bool SoundStream::OnStart()
-{
- // Does nothing by default
-
- return true;
+ ALuint buffer;
+ for (ALint i = 0; i < nbQueued; ++i)
+ alCheck(alSourceUnqueueBuffers(m_source, 1, &buffer));
}
} // namespace sf
diff --git a/src/SFML/Audio/stb_vorbis/stb_vorbis.c b/src/SFML/Audio/stb_vorbis/stb_vorbis.c
deleted file mode 100755
index 902761a..0000000
--- a/src/SFML/Audio/stb_vorbis/stb_vorbis.c
+++ /dev/null
@@ -1,5039 +0,0 @@
-// Ogg Vorbis I audio decoder -- version 0.99994
-//
-// Written in April 2007 by Sean Barrett, sponsored by RAD Game Tools.
-//
-// Placed in the public domain April 2007 by the author: no copyright is
-// claimed, and you may use it for any purpose you like.
-//
-// No warranty for any purpose is expressed or implied by the author (nor
-// by RAD Game Tools). Report bugs and send enhancements to the author.
-//
-// Get the latest version and other information at:
-// http://nothings.org/stb_vorbis/
-
-
-// Todo:
-//
-// - seeking (note you can seek yourself using the pushdata API)
-//
-// Limitations:
-//
-// - floor 0 not supported (used in old ogg vorbis files)
-// - lossless sample-truncation at beginning ignored
-// - cannot concatenate multiple vorbis streams
-// - sample positions are 32-bit, limiting seekable 192Khz
-// files to around 6 hours (Ogg supports 64-bit)
-//
-// All of these limitations may be removed in future versions.
-
-#include "stb_vorbis.h"
-
-#ifndef STB_VORBIS_HEADER_ONLY
-
-// global configuration settings (e.g. set these in the project/makefile),
-// or just set them in this file at the top (although ideally the first few
-// should be visible when the header file is compiled too, although it's not
-// crucial)
-
-// STB_VORBIS_NO_PUSHDATA_API
-// does not compile the code for the various stb_vorbis_*_pushdata()
-// functions
-// #define STB_VORBIS_NO_PUSHDATA_API
-
-// STB_VORBIS_NO_PULLDATA_API
-// does not compile the code for the non-pushdata APIs
-// #define STB_VORBIS_NO_PULLDATA_API
-
-// STB_VORBIS_NO_STDIO
-// does not compile the code for the APIs that use FILE *s internally
-// or externally (implied by STB_VORBIS_NO_PULLDATA_API)
-// #define STB_VORBIS_NO_STDIO
-
-// STB_VORBIS_NO_INTEGER_CONVERSION
-// does not compile the code for converting audio sample data from
-// float to integer (implied by STB_VORBIS_NO_PULLDATA_API)
-// #define STB_VORBIS_NO_INTEGER_CONVERSION
-
-// STB_VORBIS_NO_FAST_SCALED_FLOAT
-// does not use a fast float-to-int trick to accelerate float-to-int on
-// most platforms which requires endianness be defined correctly.
-#define STB_VORBIS_NO_FAST_SCALED_FLOAT
-
-
-// STB_VORBIS_MAX_CHANNELS [number]
-// globally define this to the maximum number of channels you need.
-// The spec does not put a restriction on channels except that
-// the count is stored in a byte, so 255 is the hard limit.
-// Reducing this saves about 16 bytes per value, so using 16 saves
-// (255-16)*16 or around 4KB. Plus anything other memory usage
-// I forgot to account for. Can probably go as low as 8 (7.1 audio),
-// 6 (5.1 audio), or 2 (stereo only).
-#ifndef STB_VORBIS_MAX_CHANNELS
-#define STB_VORBIS_MAX_CHANNELS 16 // enough for anyone?
-#endif
-
-// STB_VORBIS_PUSHDATA_CRC_COUNT [number]
-// after a flush_pushdata(), stb_vorbis begins scanning for the
-// next valid page, without backtracking. when it finds something
-// that looks like a page, it streams through it and verifies its
-// CRC32. Should that validation fail, it keeps scanning. But it's
-// possible that _while_ streaming through to check the CRC32 of
-// one candidate page, it sees another candidate page. This #define
-// determines how many "overlapping" candidate pages it can search
-// at once. Note that "real" pages are typically ~4KB to ~8KB, whereas
-// garbage pages could be as big as 64KB, but probably average ~16KB.
-// So don't hose ourselves by scanning an apparent 64KB page and
-// missing a ton of real ones in the interim; so minimum of 2
-#ifndef STB_VORBIS_PUSHDATA_CRC_COUNT
-#define STB_VORBIS_PUSHDATA_CRC_COUNT 4
-#endif
-
-// STB_VORBIS_FAST_HUFFMAN_LENGTH [number]
-// sets the log size of the huffman-acceleration table. Maximum
-// supported value is 24. with larger numbers, more decodings are O(1),
-// but the table size is larger so worse cache missing, so you'll have
-// to probe (and try multiple ogg vorbis files) to find the sweet spot.
-#ifndef STB_VORBIS_FAST_HUFFMAN_LENGTH
-#define STB_VORBIS_FAST_HUFFMAN_LENGTH 10
-#endif
-
-// STB_VORBIS_FAST_BINARY_LENGTH [number]
-// sets the log size of the binary-search acceleration table. this
-// is used in similar fashion to the fast-huffman size to set initial
-// parameters for the binary search
-
-// STB_VORBIS_FAST_HUFFMAN_INT
-// The fast huffman tables are much more efficient if they can be
-// stored as 16-bit results instead of 32-bit results. This restricts
-// the codebooks to having only 65535 possible outcomes, though.
-// (At least, accelerated by the huffman table.)
-#ifndef STB_VORBIS_FAST_HUFFMAN_INT
-#define STB_VORBIS_FAST_HUFFMAN_SHORT
-#endif
-
-// STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
-// If the 'fast huffman' search doesn't succeed, then stb_vorbis falls
-// back on binary searching for the correct one. This requires storing
-// extra tables with the huffman codes in sorted order. Defining this
-// symbol trades off space for speed by forcing a linear search in the
-// non-fast case, except for "sparse" codebooks.
-// #define STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
-
-// STB_VORBIS_DIVIDES_IN_RESIDUE
-// stb_vorbis precomputes the result of the scalar residue decoding
-// that would otherwise require a divide per chunk. you can trade off
-// space for time by defining this symbol.
-// #define STB_VORBIS_DIVIDES_IN_RESIDUE
-
-// STB_VORBIS_DIVIDES_IN_CODEBOOK
-// vorbis VQ codebooks can be encoded two ways: with every case explicitly
-// stored, or with all elements being chosen from a small range of values,
-// and all values possible in all elements. By default, stb_vorbis expands
-// this latter kind out to look like the former kind for ease of decoding,
-// because otherwise an integer divide-per-vector-element is required to
-// unpack the index. If you define STB_VORBIS_DIVIDES_IN_CODEBOOK, you can
-// trade off storage for speed.
-//#define STB_VORBIS_DIVIDES_IN_CODEBOOK
-
-// STB_VORBIS_CODEBOOK_SHORTS
-// The vorbis file format encodes VQ codebook floats as ax+b where a and
-// b are floating point per-codebook constants, and x is a 16-bit int.
-// Normally, stb_vorbis decodes them to floats rather than leaving them
-// as 16-bit ints and computing ax+b while decoding. This is a speed/space
-// tradeoff; you can save space by defining this flag.
-#ifndef STB_VORBIS_CODEBOOK_SHORTS
-#define STB_VORBIS_CODEBOOK_FLOATS
-#endif
-
-// STB_VORBIS_DIVIDE_TABLE
-// this replaces small integer divides in the floor decode loop with
-// table lookups. made less than 1% difference, so disabled by default.
-
-// STB_VORBIS_NO_INLINE_DECODE
-// disables the inlining of the scalar codebook fast-huffman decode.
-// might save a little codespace; useful for debugging
-// #define STB_VORBIS_NO_INLINE_DECODE
-
-// STB_VORBIS_NO_DEFER_FLOOR
-// Normally we only decode the floor without synthesizing the actual
-// full curve. We can instead synthesize the curve immediately. This
-// requires more memory and is very likely slower, so I don't think
-// you'd ever want to do it except for debugging.
-// #define STB_VORBIS_NO_DEFER_FLOOR
-
-
-
-
-//////////////////////////////////////////////////////////////////////////////
-
-#ifdef STB_VORBIS_NO_PULLDATA_API
- #define STB_VORBIS_NO_INTEGER_CONVERSION
- #define STB_VORBIS_NO_STDIO
-#endif
-
-#if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO)
- #define STB_VORBIS_NO_STDIO 1
-#endif
-
-#ifndef STB_VORBIS_NO_INTEGER_CONVERSION
-#ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT
-
- // only need endianness for fast-float-to-int, which we don't
- // use for pushdata
-
- #ifndef STB_VORBIS_BIG_ENDIAN
- #define STB_VORBIS_ENDIAN 0
- #else
- #define STB_VORBIS_ENDIAN 1
- #endif
-
-#endif
-#endif
-
-
-#ifndef STB_VORBIS_NO_STDIO
-#include <stdio.h>
-#endif
-
-#ifndef STB_VORBIS_NO_CRT
-#include <stdlib.h>
-#include <string.h>
-#include <assert.h>
-#include <math.h>
-
-#if !defined(__APPLE__) && !defined(MACOSX) && !defined(macintosh) && !defined(Macintosh) &&!defined(__FreeBSD__)
-#include <malloc.h>
-#endif
-
-#else
-#define NULL 0
-#endif
-
-#ifndef _MSC_VER
- #if __GNUC__
- #define __forceinline inline
- #else
- #define __forceinline
- #endif
-#endif
-
-#if STB_VORBIS_MAX_CHANNELS > 256
-#error "Value of STB_VORBIS_MAX_CHANNELS outside of allowed range"
-#endif
-
-#if STB_VORBIS_FAST_HUFFMAN_LENGTH > 24
-#error "Value of STB_VORBIS_FAST_HUFFMAN_LENGTH outside of allowed range"
-#endif
-
-
-#define MAX_BLOCKSIZE_LOG 13 // from specification
-#define MAX_BLOCKSIZE (1 << MAX_BLOCKSIZE_LOG)
-
-
-typedef unsigned char uint8;
-typedef signed char int8;
-typedef unsigned short uint16;
-typedef signed short int16;
-typedef unsigned int uint32;
-typedef signed int int32;
-
-#ifndef TRUE
-#define TRUE 1
-#define FALSE 0
-#endif
-
-#ifdef STB_VORBIS_CODEBOOK_FLOATS
-typedef float codetype;
-#else
-typedef uint16 codetype;
-#endif
-
-// @NOTE
-//
-// Some arrays below are tagged "//varies", which means it's actually
-// a variable-sized piece of data, but rather than malloc I assume it's
-// small enough it's better to just allocate it all together with the
-// main thing
-//
-// Most of the variables are specified with the smallest size I could pack
-// them into. It might give better performance to make them all full-sized
-// integers. It should be safe to freely rearrange the structures or change
-// the sizes larger--nothing relies on silently truncating etc., nor the
-// order of variables.
-
-#define FAST_HUFFMAN_TABLE_SIZE (1 << STB_VORBIS_FAST_HUFFMAN_LENGTH)
-#define FAST_HUFFMAN_TABLE_MASK (FAST_HUFFMAN_TABLE_SIZE - 1)
-
-typedef struct
-{
- int dimensions, entries;
- uint8 *codeword_lengths;
- float minimum_value;
- float delta_value;
- uint8 value_bits;
- uint8 lookup_type;
- uint8 sequence_p;
- uint8 sparse;
- uint32 lookup_values;
- codetype *multiplicands;
- uint32 *codewords;
- #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT
- int16 fast_huffman[FAST_HUFFMAN_TABLE_SIZE];
- #else
- int32 fast_huffman[FAST_HUFFMAN_TABLE_SIZE];
- #endif
- uint32 *sorted_codewords;
- int *sorted_values;
- int sorted_entries;
-} Codebook;
-
-typedef struct
-{
- uint8 order;
- uint16 rate;
- uint16 bark_map_size;
- uint8 amplitude_bits;
- uint8 amplitude_offset;
- uint8 number_of_books;
- uint8 book_list[16]; // varies
-} Floor0;
-
-typedef struct
-{
- uint8 partitions;
- uint8 partition_class_list[32]; // varies
- uint8 class_dimensions[16]; // varies
- uint8 class_subclasses[16]; // varies
- uint8 class_masterbooks[16]; // varies
- int16 subclass_books[16][8]; // varies
- uint16 Xlist[31*8+2]; // varies
- uint8 sorted_order[31*8+2];
- uint8 neighbors[31*8+2][2];
- uint8 floor1_multiplier;
- uint8 rangebits;
- int values;
-} Floor1;
-
-typedef union
-{
- Floor0 floor0;
- Floor1 floor1;
-} Floor;
-
-typedef struct
-{
- uint32 begin, end;
- uint32 part_size;
- uint8 classifications;
- uint8 classbook;
- uint8 **classdata;
- int16 (*residue_books)[8];
-} Residue;
-
-typedef struct
-{
- uint8 magnitude;
- uint8 angle;
- uint8 mux;
-} MappingChannel;
-
-typedef struct
-{
- uint16 coupling_steps;
- MappingChannel *chan;
- uint8 submaps;
- uint8 submap_floor[15]; // varies
- uint8 submap_residue[15]; // varies
-} Mapping;
-
-typedef struct
-{
- uint8 blockflag;
- uint8 mapping;
- uint16 windowtype;
- uint16 transformtype;
-} Mode;
-
-typedef struct
-{
- uint32 goal_crc; // expected crc if match
- int bytes_left; // bytes left in packet
- uint32 crc_so_far; // running crc
- int bytes_done; // bytes processed in _current_ chunk
- uint32 sample_loc; // granule pos encoded in page
-} CRCscan;
-
-typedef struct
-{
- uint32 page_start, page_end;
- uint32 after_previous_page_start;
- uint32 first_decoded_sample;
- uint32 last_decoded_sample;
-} ProbedPage;
-
-struct stb_vorbis
-{
- // user-accessible info
- unsigned int sample_rate;
- int channels;
-
- unsigned int setup_memory_required;
- unsigned int temp_memory_required;
- unsigned int setup_temp_memory_required;
-
- // input config
-#ifndef STB_VORBIS_NO_STDIO
- FILE *f;
- uint32 f_start;
- int close_on_free;
-#endif
-
- uint8 *stream;
- uint8 *stream_start;
- uint8 *stream_end;
-
- uint32 stream_len;
-
- uint8 push_mode;
-
- uint32 first_audio_page_offset;
-
- ProbedPage p_first, p_last;
-
- // memory management
- stb_vorbis_alloc alloc;
- int setup_offset;
- int temp_offset;
-
- // run-time results
- int eof;
- enum STBVorbisError error;
-
- // user-useful data
-
- // header info
- int blocksize[2];
- int blocksize_0, blocksize_1;
- int codebook_count;
- Codebook *codebooks;
- int floor_count;
- uint16 floor_types[64]; // varies
- Floor *floor_config;
- int residue_count;
- uint16 residue_types[64]; // varies
- Residue *residue_config;
- int mapping_count;
- Mapping *mapping;
- int mode_count;
- Mode mode_config[64]; // varies
-
- uint32 total_samples;
-
- // decode buffer
- float *channel_buffers[STB_VORBIS_MAX_CHANNELS];
- float *outputs [STB_VORBIS_MAX_CHANNELS];
-
- float *previous_window[STB_VORBIS_MAX_CHANNELS];
- int previous_length;
-
- #ifndef STB_VORBIS_NO_DEFER_FLOOR
- int16 *finalY[STB_VORBIS_MAX_CHANNELS];
- #else
- float *floor_buffers[STB_VORBIS_MAX_CHANNELS];
- #endif
-
- uint32 current_loc; // sample location of next frame to decode
- int current_loc_valid;
-
- // per-blocksize precomputed data
-
- // twiddle factors
- float *A[2],*B[2],*C[2];
- float *window[2];
- uint16 *bit_reverse[2];
-
- // current page/packet/segment streaming info
- uint32 serial; // stream serial number for verification
- int last_page;
- int segment_count;
- uint8 segments[255];
- uint8 page_flag;
- uint8 bytes_in_seg;
- uint8 first_decode;
- int next_seg;
- int last_seg; // flag that we're on the last segment
- int last_seg_which; // what was the segment number of the last seg?
- uint32 acc;
- int valid_bits;
- int packet_bytes;
- int end_seg_with_known_loc;
- uint32 known_loc_for_packet;
- int discard_samples_deferred;
- uint32 samples_output;
-
- // push mode scanning
- int page_crc_tests; // only in push_mode: number of tests active; -1 if not searching
-#ifndef STB_VORBIS_NO_PUSHDATA_API
- CRCscan scan[STB_VORBIS_PUSHDATA_CRC_COUNT];
-#endif
-
- // sample-access
- int channel_buffer_start;
- int channel_buffer_end;
-};
-
-extern int my_prof(int slot);
-//#define stb_prof my_prof
-
-#ifndef stb_prof
-#define stb_prof(x) 0
-#endif
-
-#if defined(STB_VORBIS_NO_PUSHDATA_API)
- #define IS_PUSH_MODE(f) FALSE
-#elif defined(STB_VORBIS_NO_PULLDATA_API)
- #define IS_PUSH_MODE(f) TRUE
-#else
- #define IS_PUSH_MODE(f) ((f)->push_mode)
-#endif
-
-typedef struct stb_vorbis vorb;
-
-static int error(vorb *f, enum STBVorbisError e)
-{
- f->error = e;
- if (!f->eof && e != VORBIS_need_more_data) {
- f->error=e; // breakpoint for debugging
- }
- return 0;
-}
-
-
-// these functions are used for allocating temporary memory
-// while decoding. if you can afford the stack space, use
-// alloca(); otherwise, provide a temp buffer and it will
-// allocate out of those.
-
-#define array_size_required(count,size) (count*(sizeof(void *)+(size)))
-
-#define temp_alloc(f,size) (f->alloc.alloc_buffer ? setup_temp_malloc(f,size) : alloca(size))
-#ifdef dealloca
-#define temp_free(f,p) (f->alloc.alloc_buffer ? 0 : dealloca(size))
-#else
-#define temp_free(f,p) 0
-#endif
-#define temp_alloc_save(f) ((f)->temp_offset)
-#define temp_alloc_restore(f,p) ((f)->temp_offset = (p))
-
-#define temp_block_array(f,count,size) make_block_array(temp_alloc(f,array_size_required(count,size)), count, size)
-
-// given a sufficiently large block of memory, make an array of pointers to subblocks of it
-static void *make_block_array(void *mem, int count, int size)
-{
- int i;
- void ** p = (void **) mem;
- char *q = (char *) (p + count);
- for (i=0; i < count; ++i) {
- p[i] = q;
- q += size;
- }
- return p;
-}
-
-static void *setup_malloc(vorb *f, int sz)
-{
- sz = (sz+3) & ~3;
- f->setup_memory_required += sz;
- if (f->alloc.alloc_buffer) {
- void *p = (char *) f->alloc.alloc_buffer + f->setup_offset;
- if (f->setup_offset + sz > f->temp_offset) return NULL;
- f->setup_offset += sz;
- return p;
- }
- return sz ? malloc(sz) : NULL;
-}
-
-static void setup_free(vorb *f, void *p)
-{
- if (f->alloc.alloc_buffer) return; // do nothing; setup mem is not a stack
- free(p);
-}
-
-static void *setup_temp_malloc(vorb *f, int sz)
-{
- sz = (sz+3) & ~3;
- if (f->alloc.alloc_buffer) {
- if (f->temp_offset - sz < f->setup_offset) return NULL;
- f->temp_offset -= sz;
- return (char *) f->alloc.alloc_buffer + f->temp_offset;
- }
- return malloc(sz);
-}
-
-static void setup_temp_free(vorb *f, void *p, size_t sz)
-{
- if (f->alloc.alloc_buffer) {
- f->temp_offset += (sz+3)&~3;
- return;
- }
- free(p);
-}
-
-#define CRC32_POLY 0x04c11db7 // from spec
-
-static uint32 crc_table[256];
-static void crc32_init(void)
-{
- int i,j;
- uint32 s;
- for(i=0; i < 256; i++) {
- for (s=i<<24, j=0; j < 8; ++j)
- s = (s << 1) ^ (s >= (1<<31) ? CRC32_POLY : 0);
- crc_table[i] = s;
- }
-}
-
-static __forceinline uint32 crc32_update(uint32 crc, uint8 byte)
-{
- return (crc << 8) ^ crc_table[byte ^ (crc >> 24)];
-}
-
-
-// used in setup, and for huffman that doesn't go fast path
-static unsigned int bit_reverse(unsigned int n)
-{
- n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1);
- n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2);
- n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4);
- n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8);
- return (n >> 16) | (n << 16);
-}
-
-static float square(float x)
-{
- return x*x;
-}
-
-// this is a weird definition of log2() for which log2(1) = 1, log2(2) = 2, log2(4) = 3
-// as required by the specification. fast(?) implementation from stb.h
-// @OPTIMIZE: called multiple times per-packet with "constants"; move to setup
-static int ilog(int32 n)
-{
- static signed char log2_4[16] = { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 };
-
- // 2 compares if n < 16, 3 compares otherwise (4 if signed or n > 1<<29)
- if (n < (1U << 14))
- if (n < (1U << 4)) return 0 + log2_4[n ];
- else if (n < (1U << 9)) return 5 + log2_4[n >> 5];
- else return 10 + log2_4[n >> 10];
- else if (n < (1U << 24))
- if (n < (1U << 19)) return 15 + log2_4[n >> 15];
- else return 20 + log2_4[n >> 20];
- else if (n < (1U << 29)) return 25 + log2_4[n >> 25];
- else if (n < (1U << 31)) return 30 + log2_4[n >> 30];
- else return 0; // signed n returns 0
-}
-
-#ifndef M_PI
- #define M_PI 3.14159265358979323846264f // from CRC
-#endif
-
-// code length assigned to a value with no huffman encoding
-#define NO_CODE 255
-
-/////////////////////// LEAF SETUP FUNCTIONS //////////////////////////
-//
-// these functions are only called at setup, and only a few times
-// per file
-
-static float float32_unpack(uint32 x)
-{
- // from the specification
- uint32 mantissa = x & 0x1fffff;
- uint32 sign = x & 0x80000000;
- uint32 exp = (x & 0x7fe00000) >> 21;
- double res = sign ? -(double)mantissa : (double)mantissa;
- return (float) ldexp((float)res, exp-788);
-}
-
-
-// zlib & jpeg huffman tables assume that the output symbols
-// can either be arbitrarily arranged, or have monotonically
-// increasing frequencies--they rely on the lengths being sorted;
-// this makes for a very simple generation algorithm.
-// vorbis allows a huffman table with non-sorted lengths. This
-// requires a more sophisticated construction, since symbols in
-// order do not map to huffman codes "in order".
-static void add_entry(Codebook *c, uint32 huff_code, int symbol, int count, int len, uint32 *values)
-{
- if (!c->sparse) {
- c->codewords [symbol] = huff_code;
- } else {
- c->codewords [count] = huff_code;
- c->codeword_lengths[count] = len;
- values [count] = symbol;
- }
-}
-
-static int compute_codewords(Codebook *c, uint8 *len, int n, uint32 *values)
-{
- int i,k,m=0;
- uint32 available[32];
-
- memset(available, 0, sizeof(available));
- // find the first entry
- for (k=0; k < n; ++k) if (len[k] < NO_CODE) break;
- if (k == n) { assert(c->sorted_entries == 0); return TRUE; }
- // add to the list
- add_entry(c, 0, k, m++, len[k], values);
- // add all available leaves
- for (i=1; i <= len[k]; ++i)
- available[i] = 1 << (32-i);
- // note that the above code treats the first case specially,
- // but it's really the same as the following code, so they
- // could probably be combined (except the initial code is 0,
- // and I use 0 in available[] to mean 'empty')
- for (i=k+1; i < n; ++i) {
- uint32 res;
- int z = len[i], y;
- if (z == NO_CODE) continue;
- // find lowest available leaf (should always be earliest,
- // which is what the specification calls for)
- // note that this property, and the fact we can never have
- // more than one free leaf at a given level, isn't totally
- // trivial to prove, but it seems true and the assert never
- // fires, so!
- while (z > 0 && !available[z]) --z;
- if (z == 0) { assert(0); return FALSE; }
- res = available[z];
- available[z] = 0;
- add_entry(c, bit_reverse(res), i, m++, len[i], values);
- // propogate availability up the tree
- if (z != len[i]) {
- for (y=len[i]; y > z; --y) {
- assert(available[y] == 0);
- available[y] = res + (1 << (32-y));
- }
- }
- }
- return TRUE;
-}
-
-// accelerated huffman table allows fast O(1) match of all symbols
-// of length <= STB_VORBIS_FAST_HUFFMAN_LENGTH
-static void compute_accelerated_huffman(Codebook *c)
-{
- int i, len;
- for (i=0; i < FAST_HUFFMAN_TABLE_SIZE; ++i)
- c->fast_huffman[i] = -1;
-
- len = c->sparse ? c->sorted_entries : c->entries;
- #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT
- if (len > 32767) len = 32767; // largest possible value we can encode!
- #endif
- for (i=0; i < len; ++i) {
- if (c->codeword_lengths[i] <= STB_VORBIS_FAST_HUFFMAN_LENGTH) {
- uint32 z = c->sparse ? bit_reverse(c->sorted_codewords[i]) : c->codewords[i];
- // set table entries for all bit combinations in the higher bits
- while (z < FAST_HUFFMAN_TABLE_SIZE) {
- c->fast_huffman[z] = i;
- z += 1 << c->codeword_lengths[i];
- }
- }
- }
-}
-
-static int uint32_compare(const void *p, const void *q)
-{
- uint32 x = * (uint32 *) p;
- uint32 y = * (uint32 *) q;
- return x < y ? -1 : x > y;
-}
-
-static int include_in_sort(Codebook *c, uint8 len)
-{
- if (c->sparse) { assert(len != NO_CODE); return TRUE; }
- if (len == NO_CODE) return FALSE;
- if (len > STB_VORBIS_FAST_HUFFMAN_LENGTH) return TRUE;
- return FALSE;
-}
-
-// if the fast table above doesn't work, we want to binary
-// search them... need to reverse the bits
-static void compute_sorted_huffman(Codebook *c, uint8 *lengths, uint32 *values)
-{
- int i, len;
- // build a list of all the entries
- // OPTIMIZATION: don't include the short ones, since they'll be caught by FAST_HUFFMAN.
- // this is kind of a frivolous optimization--I don't see any performance improvement,
- // but it's like 4 extra lines of code, so.
- if (!c->sparse) {
- int k = 0;
- for (i=0; i < c->entries; ++i)
- if (include_in_sort(c, lengths[i]))
- c->sorted_codewords[k++] = bit_reverse(c->codewords[i]);
- assert(k == c->sorted_entries);
- } else {
- for (i=0; i < c->sorted_entries; ++i)
- c->sorted_codewords[i] = bit_reverse(c->codewords[i]);
- }
-
- qsort(c->sorted_codewords, c->sorted_entries, sizeof(c->sorted_codewords[0]), uint32_compare);
- c->sorted_codewords[c->sorted_entries] = 0xffffffff;
-
- len = c->sparse ? c->sorted_entries : c->entries;
- // now we need to indicate how they correspond; we could either
- // #1: sort a different data structure that says who they correspond to
- // #2: for each sorted entry, search the original list to find who corresponds
- // #3: for each original entry, find the sorted entry
- // #1 requires extra storage, #2 is slow, #3 can use binary search!
- for (i=0; i < len; ++i) {
- int huff_len = c->sparse ? lengths[values[i]] : lengths[i];
- if (include_in_sort(c,huff_len)) {
- uint32 code = bit_reverse(c->codewords[i]);
- int x=0, n=c->sorted_entries;
- while (n > 1) {
- // invariant: sc[x] <= code < sc[x+n]
- int m = x + (n >> 1);
- if (c->sorted_codewords[m] <= code) {
- x = m;
- n -= (n>>1);
- } else {
- n >>= 1;
- }
- }
- assert(c->sorted_codewords[x] == code);
- if (c->sparse) {
- c->sorted_values[x] = values[i];
- c->codeword_lengths[x] = huff_len;
- } else {
- c->sorted_values[x] = i;
- }
- }
- }
-}
-
-// only run while parsing the header (3 times)
-static int vorbis_validate(uint8 *data)
-{
- static uint8 vorbis[6] = { 'v', 'o', 'r', 'b', 'i', 's' };
- return memcmp(data, vorbis, 6) == 0;
-}
-
-// called from setup only, once per code book
-// (formula implied by specification)
-static int lookup1_values(int entries, int dim)
-{
- int r = (int) floor(exp((float) log((float) entries) / dim));
- if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning;
- ++r; // floor() to avoid _ftol() when non-CRT
- assert(pow((float) r+1, dim) > entries);
- assert((int) floor(pow((float) r, dim)) <= entries); // (int),floor() as above
- return r;
-}
-
-// called twice per file
-static void compute_twiddle_factors(int n, float *A, float *B, float *C)
-{
- int n4 = n >> 2, n8 = n >> 3;
- int k,k2;
-
- for (k=k2=0; k < n4; ++k,k2+=2) {
- A[k2 ] = (float) cos(4*k*M_PI/n);
- A[k2+1] = (float) -sin(4*k*M_PI/n);
- B[k2 ] = (float) cos((k2+1)*M_PI/n/2) * 0.5f;
- B[k2+1] = (float) sin((k2+1)*M_PI/n/2) * 0.5f;
- }
- for (k=k2=0; k < n8; ++k,k2+=2) {
- C[k2 ] = (float) cos(2*(k2+1)*M_PI/n);
- C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n);
- }
-}
-
-static void compute_window(int n, float *window)
-{
- int n2 = n >> 1, i;
- for (i=0; i < n2; ++i)
- window[i] = (float) sin(0.5 * M_PI * square((float) sin((i - 0 + 0.5) / n2 * 0.5 * M_PI)));
-}
-
-static void compute_bitreverse(int n, uint16 *rev)
-{
- int ld = ilog(n) - 1; // ilog is off-by-one from normal definitions
- int i, n8 = n >> 3;
- for (i=0; i < n8; ++i)
- rev[i] = (bit_reverse(i) >> (32-ld+3)) << 2;
-}
-
-static int init_blocksize(vorb *f, int b, int n)
-{
- int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3;
- f->A[b] = (float *) setup_malloc(f, sizeof(float) * n2);
- f->B[b] = (float *) setup_malloc(f, sizeof(float) * n2);
- f->C[b] = (float *) setup_malloc(f, sizeof(float) * n4);
- if (!f->A[b] || !f->B[b] || !f->C[b]) return error(f, VORBIS_outofmem);
- compute_twiddle_factors(n, f->A[b], f->B[b], f->C[b]);
- f->window[b] = (float *) setup_malloc(f, sizeof(float) * n2);
- if (!f->window[b]) return error(f, VORBIS_outofmem);
- compute_window(n, f->window[b]);
- f->bit_reverse[b] = (uint16 *) setup_malloc(f, sizeof(uint16) * n8);
- if (!f->bit_reverse[b]) return error(f, VORBIS_outofmem);
- compute_bitreverse(n, f->bit_reverse[b]);
- return TRUE;
-}
-
-static void neighbors(uint16 *x, int n, int *plow, int *phigh)
-{
- int low = -1;
- int high = 65536;
- int i;
- for (i=0; i < n; ++i) {
- if (x[i] > low && x[i] < x[n]) { *plow = i; low = x[i]; }
- if (x[i] < high && x[i] > x[n]) { *phigh = i; high = x[i]; }
- }
-}
-
-// this has been repurposed so y is now the original index instead of y
-typedef struct
-{
- uint16 x,y;
-} Point;
-
-int point_compare(const void *p, const void *q)
-{
- Point *a = (Point *) p;
- Point *b = (Point *) q;
- return a->x < b->x ? -1 : a->x > b->x;
-}
-
-//
-/////////////////////// END LEAF SETUP FUNCTIONS //////////////////////////
-
-
-#if defined(STB_VORBIS_NO_STDIO)
- #define USE_MEMORY(z) TRUE
-#else
- #define USE_MEMORY(z) ((z)->stream)
-#endif
-
-static uint8 get8(vorb *z)
-{
- if (USE_MEMORY(z)) {
- if (z->stream >= z->stream_end) { z->eof = TRUE; return 0; }
- return *z->stream++;
- }
-
- #ifndef STB_VORBIS_NO_STDIO
- {
- int c = fgetc(z->f);
- if (c == EOF) { z->eof = TRUE; return 0; }
- return c;
- }
- #endif
-}
-
-static uint32 get32(vorb *f)
-{
- uint32 x;
- x = get8(f);
- x += get8(f) << 8;
- x += get8(f) << 16;
- x += get8(f) << 24;
- return x;
-}
-
-static int getn(vorb *z, uint8 *data, int n)
-{
- if (USE_MEMORY(z)) {
- if (z->stream+n > z->stream_end) { z->eof = 1; return 0; }
- memcpy(data, z->stream, n);
- z->stream += n;
- return 1;
- }
-
- #ifndef STB_VORBIS_NO_STDIO
- if (fread(data, n, 1, z->f) == 1)
- return 1;
- else {
- z->eof = 1;
- return 0;
- }
- #endif
-}
-
-static void skip(vorb *z, int n)
-{
- if (USE_MEMORY(z)) {
- z->stream += n;
- if (z->stream >= z->stream_end) z->eof = 1;
- return;
- }
- #ifndef STB_VORBIS_NO_STDIO
- {
- long x = ftell(z->f);
- fseek(z->f, x+n, SEEK_SET);
- }
- #endif
-}
-
-static int set_file_offset(stb_vorbis *f, unsigned int loc)
-{
- #ifndef STB_VORBIS_NO_PUSHDATA_API
- if (f->push_mode) return 0;
- #endif
- f->eof = 0;
- if (USE_MEMORY(f)) {
- if (f->stream_start + loc >= f->stream_end || f->stream_start + loc < f->stream_start) {
- f->stream = f->stream_end;
- f->eof = 1;
- return 0;
- } else {
- f->stream = f->stream_start + loc;
- return 1;
- }
- }
- #ifndef STB_VORBIS_NO_STDIO
- if (loc + f->f_start < loc || loc >= 0x80000000) {
- loc = 0x7fffffff;
- f->eof = 1;
- } else {
- loc += f->f_start;
- }
- if (!fseek(f->f, loc, SEEK_SET))
- return 1;
- f->eof = 1;
- fseek(f->f, f->f_start, SEEK_END);
- return 0;
- #endif
-}
-
-
-static uint8 ogg_page_header[4] = { 0x4f, 0x67, 0x67, 0x53 };
-
-static int capture_pattern(vorb *f)
-{
- if (0x4f != get8(f)) return FALSE;
- if (0x67 != get8(f)) return FALSE;
- if (0x67 != get8(f)) return FALSE;
- if (0x53 != get8(f)) return FALSE;
- return TRUE;
-}
-
-#define PAGEFLAG_continued_packet 1
-#define PAGEFLAG_first_page 2
-#define PAGEFLAG_last_page 4
-
-static int start_page_no_capturepattern(vorb *f)
-{
- uint32 loc0,loc1,n,i;
- // stream structure version
- if (0 != get8(f)) return error(f, VORBIS_invalid_stream_structure_version);
- // header flag
- f->page_flag = get8(f);
- // absolute granule position
- loc0 = get32(f);
- loc1 = get32(f);
- // @TODO: validate loc0,loc1 as valid positions?
- // stream serial number -- vorbis doesn't interleave, so discard
- get32(f);
- //if (f->serial != get32(f)) return error(f, VORBIS_incorrect_stream_serial_number);
- // page sequence number
- n = get32(f);
- f->last_page = n;
- // CRC32
- get32(f);
- // page_segments
- f->segment_count = get8(f);
- if (!getn(f, f->segments, f->segment_count))
- return error(f, VORBIS_unexpected_eof);
- // assume we _don't_ know any the sample position of any segments
- f->end_seg_with_known_loc = -2;
- if (loc0 != ~0 || loc1 != ~0) {
- // determine which packet is the last one that will complete
- for (i=f->segment_count-1; i >= 0; --i)
- if (f->segments[i] < 255)
- break;
- // 'i' is now the index of the _last_ segment of a packet that ends
- if (i >= 0) {
- f->end_seg_with_known_loc = i;
- f->known_loc_for_packet = loc0;
- }
- }
- if (f->first_decode) {
- int i,len;
- ProbedPage p;
- len = 0;
- for (i=0; i < f->segment_count; ++i)
- len += f->segments[i];
- len += 27 + f->segment_count;
- p.page_start = f->first_audio_page_offset;
- p.page_end = p.page_start + len;
- p.after_previous_page_start = p.page_start;
- p.first_decoded_sample = 0;
- p.last_decoded_sample = loc0;
- f->p_first = p;
- }
- f->next_seg = 0;
- return TRUE;
-}
-
-static int start_page(vorb *f)
-{
- if (!capture_pattern(f)) return error(f, VORBIS_missing_capture_pattern);
- return start_page_no_capturepattern(f);
-}
-
-static int start_packet(vorb *f)
-{
- while (f->next_seg == -1) {
- if (!start_page(f)) return FALSE;
- if (f->page_flag & PAGEFLAG_continued_packet)
- return error(f, VORBIS_continued_packet_flag_invalid);
- }
- f->last_seg = FALSE;
- f->valid_bits = 0;
- f->packet_bytes = 0;
- f->bytes_in_seg = 0;
- // f->next_seg is now valid
- return TRUE;
-}
-
-static int maybe_start_packet(vorb *f)
-{
- if (f->next_seg == -1) {
- int x = get8(f);
- if (f->eof) return FALSE; // EOF at page boundary is not an error!
- if (0x4f != x ) return error(f, VORBIS_missing_capture_pattern);
- if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern);
- if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern);
- if (0x53 != get8(f)) return error(f, VORBIS_missing_capture_pattern);
- if (!start_page_no_capturepattern(f)) return FALSE;
- if (f->page_flag & PAGEFLAG_continued_packet) {
- // set up enough state that we can read this packet if we want,
- // e.g. during recovery
- f->last_seg = FALSE;
- f->bytes_in_seg = 0;
- return error(f, VORBIS_continued_packet_flag_invalid);
- }
- }
- return start_packet(f);
-}
-
-static int next_segment(vorb *f)
-{
- int len;
- if (f->last_seg) return 0;
- if (f->next_seg == -1) {
- f->last_seg_which = f->segment_count-1; // in case start_page fails
- if (!start_page(f)) { f->last_seg = 1; return 0; }
- if (!(f->page_flag & PAGEFLAG_continued_packet)) return error(f, VORBIS_continued_packet_flag_invalid);
- }
- len = f->segments[f->next_seg++];
- if (len < 255) {
- f->last_seg = TRUE;
- f->last_seg_which = f->next_seg-1;
- }
- if (f->next_seg >= f->segment_count)
- f->next_seg = -1;
- assert(f->bytes_in_seg == 0);
- f->bytes_in_seg = len;
- return len;
-}
-
-#define EOP (-1)
-#define INVALID_BITS (-1)
-
-static int get8_packet_raw(vorb *f)
-{
- if (!f->bytes_in_seg)
- if (f->last_seg) return EOP;
- else if (!next_segment(f)) return EOP;
- assert(f->bytes_in_seg > 0);
- --f->bytes_in_seg;
- ++f->packet_bytes;
- return get8(f);
-}
-
-static int get8_packet(vorb *f)
-{
- int x = get8_packet_raw(f);
- f->valid_bits = 0;
- return x;
-}
-
-static void flush_packet(vorb *f)
-{
- while (get8_packet_raw(f) != EOP);
-}
-
-// @OPTIMIZE: this is the secondary bit decoder, so it's probably not as important
-// as the huffman decoder?
-static uint32 get_bits(vorb *f, int n)
-{
- uint32 z;
-
- if (f->valid_bits < 0) return 0;
- if (f->valid_bits < n) {
- if (n > 24) {
- // the accumulator technique below would not work correctly in this case
- z = get_bits(f, 24);
- z += get_bits(f, n-24) << 24;
- return z;
- }
- if (f->valid_bits == 0) f->acc = 0;
- while (f->valid_bits < n) {
- int z = get8_packet_raw(f);
- if (z == EOP) {
- f->valid_bits = INVALID_BITS;
- return 0;
- }
- f->acc += z << f->valid_bits;
- f->valid_bits += 8;
- }
- }
- if (f->valid_bits < 0) return 0;
- z = f->acc & ((1 << n)-1);
- f->acc >>= n;
- f->valid_bits -= n;
- return z;
-}
-
-static int32 get_bits_signed(vorb *f, int n)
-{
- uint32 z = get_bits(f, n);
- if (z & (1 << (n-1)))
- z += ~((1 << n) - 1);
- return (int32) z;
-}
-
-// @OPTIMIZE: primary accumulator for huffman
-// expand the buffer to as many bits as possible without reading off end of packet
-// it might be nice to allow f->valid_bits and f->acc to be stored in registers,
-// e.g. cache them locally and decode locally
-static __forceinline void prep_huffman(vorb *f)
-{
- if (f->valid_bits <= 24) {
- if (f->valid_bits == 0) f->acc = 0;
- do {
- int z;
- if (f->last_seg && !f->bytes_in_seg) return;
- z = get8_packet_raw(f);
- if (z == EOP) return;
- f->acc += z << f->valid_bits;
- f->valid_bits += 8;
- } while (f->valid_bits <= 24);
- }
-}
-
-enum
-{
- VORBIS_packet_id = 1,
- VORBIS_packet_comment = 3,
- VORBIS_packet_setup = 5,
-};
-
-static int codebook_decode_scalar_raw(vorb *f, Codebook *c)
-{
- int i;
- prep_huffman(f);
-
- assert(c->sorted_codewords || c->codewords);
- // cases to use binary search: sorted_codewords && !c->codewords
- // sorted_codewords && c->entries > 8
- if (c->entries > 8 ? c->sorted_codewords!=NULL : !c->codewords) {
- // binary search
- uint32 code = bit_reverse(f->acc);
- int x=0, n=c->sorted_entries, len;
-
- while (n > 1) {
- // invariant: sc[x] <= code < sc[x+n]
- int m = x + (n >> 1);
- if (c->sorted_codewords[m] <= code) {
- x = m;
- n -= (n>>1);
- } else {
- n >>= 1;
- }
- }
- // x is now the sorted index
- if (!c->sparse) x = c->sorted_values[x];
- // x is now sorted index if sparse, or symbol otherwise
- len = c->codeword_lengths[x];
- if (f->valid_bits >= len) {
- f->acc >>= len;
- f->valid_bits -= len;
- return x;
- }
-
- f->valid_bits = 0;
- return -1;
- }
-
- // if small, linear search
- assert(!c->sparse);
- for (i=0; i < c->entries; ++i) {
- if (c->codeword_lengths[i] == NO_CODE) continue;
- if (c->codewords[i] == (f->acc & ((1 << c->codeword_lengths[i])-1))) {
- if (f->valid_bits >= c->codeword_lengths[i]) {
- f->acc >>= c->codeword_lengths[i];
- f->valid_bits -= c->codeword_lengths[i];
- return i;
- }
- f->valid_bits = 0;
- return -1;
- }
- }
-
- error(f, VORBIS_invalid_stream);
- f->valid_bits = 0;
- return -1;
-}
-
-static int codebook_decode_scalar(vorb *f, Codebook *c)
-{
- int i;
- if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH)
- prep_huffman(f);
- // fast huffman table lookup
- i = f->acc & FAST_HUFFMAN_TABLE_MASK;
- i = c->fast_huffman[i];
- if (i >= 0) {
- f->acc >>= c->codeword_lengths[i];
- f->valid_bits -= c->codeword_lengths[i];
- if (f->valid_bits < 0) { f->valid_bits = 0; return -1; }
- return i;
- }
- return codebook_decode_scalar_raw(f,c);
-}
-
-#ifndef STB_VORBIS_NO_INLINE_DECODE
-
-#define DECODE_RAW(var, f,c) \
- if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) \
- prep_huffman(f); \
- var = f->acc & FAST_HUFFMAN_TABLE_MASK; \
- var = c->fast_huffman[var]; \
- if (var >= 0) { \
- int n = c->codeword_lengths[var]; \
- f->acc >>= n; \
- f->valid_bits -= n; \
- if (f->valid_bits < 0) { f->valid_bits = 0; var = -1; } \
- } else { \
- var = codebook_decode_scalar_raw(f,c); \
- }
-
-#else
-
-#define DECODE_RAW(var,f,c) var = codebook_decode_scalar(f,c);
-
-#endif
-
-#define DECODE(var,f,c) \
- DECODE_RAW(var,f,c) \
- if (c->sparse) var = c->sorted_values[var];
-
-#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
- #define DECODE_VQ(var,f,c) DECODE_RAW(var,f,c)
-#else
- #define DECODE_VQ(var,f,c) DECODE(var,f,c)
-#endif
-
-
-
-
-
-
-// CODEBOOK_ELEMENT_FAST is an optimization for the CODEBOOK_FLOATS case
-// where we avoid one addition
-#ifndef STB_VORBIS_CODEBOOK_FLOATS
- #define CODEBOOK_ELEMENT(c,off) (c->multiplicands[off] * c->delta_value + c->minimum_value)
- #define CODEBOOK_ELEMENT_FAST(c,off) (c->multiplicands[off] * c->delta_value)
- #define CODEBOOK_ELEMENT_BASE(c) (c->minimum_value)
-#else
- #define CODEBOOK_ELEMENT(c,off) (c->multiplicands[off])
- #define CODEBOOK_ELEMENT_FAST(c,off) (c->multiplicands[off])
- #define CODEBOOK_ELEMENT_BASE(c) (0)
-#endif
-
-static int codebook_decode_start(vorb *f, Codebook *c, int len)
-{
- int z = -1;
-
- // type 0 is only legal in a scalar context
- if (c->lookup_type == 0)
- error(f, VORBIS_invalid_stream);
- else {
- DECODE_VQ(z,f,c);
- if (c->sparse) assert(z < c->sorted_entries);
- if (z < 0) { // check for EOP
- if (!f->bytes_in_seg)
- if (f->last_seg)
- return z;
- error(f, VORBIS_invalid_stream);
- }
- }
- return z;
-}
-
-static int codebook_decode(vorb *f, Codebook *c, float *output, int len)
-{
- int i,z = codebook_decode_start(f,c,len);
- if (z < 0) return FALSE;
- if (len > c->dimensions) len = c->dimensions;
-
-#ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
- if (c->lookup_type == 1) {
- float last = CODEBOOK_ELEMENT_BASE(c);
- int div = 1;
- for (i=0; i < len; ++i) {
- int off = (z / div) % c->lookup_values;
- float val = CODEBOOK_ELEMENT_FAST(c,off) + last;
- output[i] += val;
- if (c->sequence_p) last = val + c->minimum_value;
- div *= c->lookup_values;
- }
- return TRUE;
- }
-#endif
-
- z *= c->dimensions;
- if (c->sequence_p) {
- float last = CODEBOOK_ELEMENT_BASE(c);
- for (i=0; i < len; ++i) {
- float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
- output[i] += val;
- last = val + c->minimum_value;
- }
- } else {
- float last = CODEBOOK_ELEMENT_BASE(c);
- for (i=0; i < len; ++i) {
- output[i] += CODEBOOK_ELEMENT_FAST(c,z+i) + last;
- }
- }
-
- return TRUE;
-}
-
-static int codebook_decode_step(vorb *f, Codebook *c, float *output, int len, int step)
-{
- int i,z = codebook_decode_start(f,c,len);
- float last = CODEBOOK_ELEMENT_BASE(c);
- if (z < 0) return FALSE;
- if (len > c->dimensions) len = c->dimensions;
-
-#ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
- if (c->lookup_type == 1) {
- int div = 1;
- for (i=0; i < len; ++i) {
- int off = (z / div) % c->lookup_values;
- float val = CODEBOOK_ELEMENT_FAST(c,off) + last;
- output[i*step] += val;
- if (c->sequence_p) last = val;
- div *= c->lookup_values;
- }
- return TRUE;
- }
-#endif
-
- z *= c->dimensions;
- for (i=0; i < len; ++i) {
- float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
- output[i*step] += val;
- if (c->sequence_p) last = val;
- }
-
- return TRUE;
-}
-
-static int codebook_decode_deinterleave_repeat(vorb *f, Codebook *c, float **outputs, int ch, int *c_inter_p, int *p_inter_p, int len, int total_decode)
-{
- int c_inter = *c_inter_p;
- int p_inter = *p_inter_p;
- int i,z, effective = c->dimensions;
-
- // type 0 is only legal in a scalar context
- if (c->lookup_type == 0) return error(f, VORBIS_invalid_stream);
-
- while (total_decode > 0) {
- float last = CODEBOOK_ELEMENT_BASE(c);
- DECODE_VQ(z,f,c);
- #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
- assert(!c->sparse || z < c->sorted_entries);
- #endif
- if (z < 0) {
- if (!f->bytes_in_seg)
- if (f->last_seg) return FALSE;
- return error(f, VORBIS_invalid_stream);
- }
-
- // if this will take us off the end of the buffers, stop short!
- // we check by computing the length of the virtual interleaved
- // buffer (len*ch), our current offset within it (p_inter*ch)+(c_inter),
- // and the length we'll be using (effective)
- if (c_inter + p_inter*ch + effective > len * ch) {
- effective = len*ch - (p_inter*ch - c_inter);
- }
-
- #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
- if (c->lookup_type == 1) {
- int div = 1;
- for (i=0; i < effective; ++i) {
- int off = (z / div) % c->lookup_values;
- float val = CODEBOOK_ELEMENT_FAST(c,off) + last;
- outputs[c_inter][p_inter] += val;
- if (++c_inter == ch) { c_inter = 0; ++p_inter; }
- if (c->sequence_p) last = val;
- div *= c->lookup_values;
- }
- } else
- #endif
- {
- z *= c->dimensions;
- if (c->sequence_p) {
- for (i=0; i < effective; ++i) {
- float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
- outputs[c_inter][p_inter] += val;
- if (++c_inter == ch) { c_inter = 0; ++p_inter; }
- last = val;
- }
- } else {
- for (i=0; i < effective; ++i) {
- float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
- outputs[c_inter][p_inter] += val;
- if (++c_inter == ch) { c_inter = 0; ++p_inter; }
- }
- }
- }
-
- total_decode -= effective;
- }
- *c_inter_p = c_inter;
- *p_inter_p = p_inter;
- return TRUE;
-}
-
-#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
-static int codebook_decode_deinterleave_repeat_2(vorb *f, Codebook *c, float **outputs, int *c_inter_p, int *p_inter_p, int len, int total_decode)
-{
- int c_inter = *c_inter_p;
- int p_inter = *p_inter_p;
- int i,z, effective = c->dimensions;
-
- // type 0 is only legal in a scalar context
- if (c->lookup_type == 0) return error(f, VORBIS_invalid_stream);
-
- while (total_decode > 0) {
- float last = CODEBOOK_ELEMENT_BASE(c);
- DECODE_VQ(z,f,c);
-
- if (z < 0) {
- if (!f->bytes_in_seg)
- if (f->last_seg) return FALSE;
- return error(f, VORBIS_invalid_stream);
- }
-
- // if this will take us off the end of the buffers, stop short!
- // we check by computing the length of the virtual interleaved
- // buffer (len*ch), our current offset within it (p_inter*ch)+(c_inter),
- // and the length we'll be using (effective)
- if (c_inter + p_inter*2 + effective > len * 2) {
- effective = len*2 - (p_inter*2 - c_inter);
- }
-
- {
- z *= c->dimensions;
- stb_prof(11);
- if (c->sequence_p) {
- // haven't optimized this case because I don't have any examples
- for (i=0; i < effective; ++i) {
- float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
- outputs[c_inter][p_inter] += val;
- if (++c_inter == 2) { c_inter = 0; ++p_inter; }
- last = val;
- }
- } else {
- i=0;
- if (c_inter == 1) {
- float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
- outputs[c_inter][p_inter] += val;
- c_inter = 0; ++p_inter;
- ++i;
- }
- {
- float *z0 = outputs[0];
- float *z1 = outputs[1];
- for (; i+1 < effective;) {
- z0[p_inter] += CODEBOOK_ELEMENT_FAST(c,z+i) + last;
- z1[p_inter] += CODEBOOK_ELEMENT_FAST(c,z+i+1) + last;
- ++p_inter;
- i += 2;
- }
- }
- if (i < effective) {
- float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
- outputs[c_inter][p_inter] += val;
- if (++c_inter == 2) { c_inter = 0; ++p_inter; }
- }
- }
- }
-
- total_decode -= effective;
- }
- *c_inter_p = c_inter;
- *p_inter_p = p_inter;
- return TRUE;
-}
-#endif
-
-static int predict_point(int x, int x0, int x1, int y0, int y1)
-{
- int dy = y1 - y0;
- int adx = x1 - x0;
- // @OPTIMIZE: force int division to round in the right direction... is this necessary on x86?
- int err = abs(dy) * (x - x0);
- int off = err / adx;
- return dy < 0 ? y0 - off : y0 + off;
-}
-
-// the following table is block-copied from the specification
-static float inverse_db_table[256] =
-{
- 1.0649863e-07f, 1.1341951e-07f, 1.2079015e-07f, 1.2863978e-07f,
- 1.3699951e-07f, 1.4590251e-07f, 1.5538408e-07f, 1.6548181e-07f,
- 1.7623575e-07f, 1.8768855e-07f, 1.9988561e-07f, 2.1287530e-07f,
- 2.2670913e-07f, 2.4144197e-07f, 2.5713223e-07f, 2.7384213e-07f,
- 2.9163793e-07f, 3.1059021e-07f, 3.3077411e-07f, 3.5226968e-07f,
- 3.7516214e-07f, 3.9954229e-07f, 4.2550680e-07f, 4.5315863e-07f,
- 4.8260743e-07f, 5.1396998e-07f, 5.4737065e-07f, 5.8294187e-07f,
- 6.2082472e-07f, 6.6116941e-07f, 7.0413592e-07f, 7.4989464e-07f,
- 7.9862701e-07f, 8.5052630e-07f, 9.0579828e-07f, 9.6466216e-07f,
- 1.0273513e-06f, 1.0941144e-06f, 1.1652161e-06f, 1.2409384e-06f,
- 1.3215816e-06f, 1.4074654e-06f, 1.4989305e-06f, 1.5963394e-06f,
- 1.7000785e-06f, 1.8105592e-06f, 1.9282195e-06f, 2.0535261e-06f,
- 2.1869758e-06f, 2.3290978e-06f, 2.4804557e-06f, 2.6416497e-06f,
- 2.8133190e-06f, 2.9961443e-06f, 3.1908506e-06f, 3.3982101e-06f,
- 3.6190449e-06f, 3.8542308e-06f, 4.1047004e-06f, 4.3714470e-06f,
- 4.6555282e-06f, 4.9580707e-06f, 5.2802740e-06f, 5.6234160e-06f,
- 5.9888572e-06f, 6.3780469e-06f, 6.7925283e-06f, 7.2339451e-06f,
- 7.7040476e-06f, 8.2047000e-06f, 8.7378876e-06f, 9.3057248e-06f,
- 9.9104632e-06f, 1.0554501e-05f, 1.1240392e-05f, 1.1970856e-05f,
- 1.2748789e-05f, 1.3577278e-05f, 1.4459606e-05f, 1.5399272e-05f,
- 1.6400004e-05f, 1.7465768e-05f, 1.8600792e-05f, 1.9809576e-05f,
- 2.1096914e-05f, 2.2467911e-05f, 2.3928002e-05f, 2.5482978e-05f,
- 2.7139006e-05f, 2.8902651e-05f, 3.0780908e-05f, 3.2781225e-05f,
- 3.4911534e-05f, 3.7180282e-05f, 3.9596466e-05f, 4.2169667e-05f,
- 4.4910090e-05f, 4.7828601e-05f, 5.0936773e-05f, 5.4246931e-05f,
- 5.7772202e-05f, 6.1526565e-05f, 6.5524908e-05f, 6.9783085e-05f,
- 7.4317983e-05f, 7.9147585e-05f, 8.4291040e-05f, 8.9768747e-05f,
- 9.5602426e-05f, 0.00010181521f, 0.00010843174f, 0.00011547824f,
- 0.00012298267f, 0.00013097477f, 0.00013948625f, 0.00014855085f,
- 0.00015820453f, 0.00016848555f, 0.00017943469f, 0.00019109536f,
- 0.00020351382f, 0.00021673929f, 0.00023082423f, 0.00024582449f,
- 0.00026179955f, 0.00027881276f, 0.00029693158f, 0.00031622787f,
- 0.00033677814f, 0.00035866388f, 0.00038197188f, 0.00040679456f,
- 0.00043323036f, 0.00046138411f, 0.00049136745f, 0.00052329927f,
- 0.00055730621f, 0.00059352311f, 0.00063209358f, 0.00067317058f,
- 0.00071691700f, 0.00076350630f, 0.00081312324f, 0.00086596457f,
- 0.00092223983f, 0.00098217216f, 0.0010459992f, 0.0011139742f,
- 0.0011863665f, 0.0012634633f, 0.0013455702f, 0.0014330129f,
- 0.0015261382f, 0.0016253153f, 0.0017309374f, 0.0018434235f,
- 0.0019632195f, 0.0020908006f, 0.0022266726f, 0.0023713743f,
- 0.0025254795f, 0.0026895994f, 0.0028643847f, 0.0030505286f,
- 0.0032487691f, 0.0034598925f, 0.0036847358f, 0.0039241906f,
- 0.0041792066f, 0.0044507950f, 0.0047400328f, 0.0050480668f,
- 0.0053761186f, 0.0057254891f, 0.0060975636f, 0.0064938176f,
- 0.0069158225f, 0.0073652516f, 0.0078438871f, 0.0083536271f,
- 0.0088964928f, 0.009474637f, 0.010090352f, 0.010746080f,
- 0.011444421f, 0.012188144f, 0.012980198f, 0.013823725f,
- 0.014722068f, 0.015678791f, 0.016697687f, 0.017782797f,
- 0.018938423f, 0.020169149f, 0.021479854f, 0.022875735f,
- 0.024362330f, 0.025945531f, 0.027631618f, 0.029427276f,
- 0.031339626f, 0.033376252f, 0.035545228f, 0.037855157f,
- 0.040315199f, 0.042935108f, 0.045725273f, 0.048696758f,
- 0.051861348f, 0.055231591f, 0.058820850f, 0.062643361f,
- 0.066714279f, 0.071049749f, 0.075666962f, 0.080584227f,
- 0.085821044f, 0.091398179f, 0.097337747f, 0.10366330f,
- 0.11039993f, 0.11757434f, 0.12521498f, 0.13335215f,
- 0.14201813f, 0.15124727f, 0.16107617f, 0.17154380f,
- 0.18269168f, 0.19456402f, 0.20720788f, 0.22067342f,
- 0.23501402f, 0.25028656f, 0.26655159f, 0.28387361f,
- 0.30232132f, 0.32196786f, 0.34289114f, 0.36517414f,
- 0.38890521f, 0.41417847f, 0.44109412f, 0.46975890f,
- 0.50028648f, 0.53279791f, 0.56742212f, 0.60429640f,
- 0.64356699f, 0.68538959f, 0.72993007f, 0.77736504f,
- 0.82788260f, 0.88168307f, 0.9389798f, 1.0f
-};
-
-
-// @OPTIMIZE: if you want to replace this bresenham line-drawing routine,
-// note that you must produce bit-identical output to decode correctly;
-// this specific sequence of operations is specified in the spec (it's
-// drawing integer-quantized frequency-space lines that the encoder
-// expects to be exactly the same)
-// ... also, isn't the whole point of Bresenham's algorithm to NOT
-// have to divide in the setup? sigh.
-#ifndef STB_VORBIS_NO_DEFER_FLOOR
-#define LINE_OP(a,b) a *= b
-#else
-#define LINE_OP(a,b) a = b
-#endif
-
-#ifdef STB_VORBIS_DIVIDE_TABLE
-#define DIVTAB_NUMER 32
-#define DIVTAB_DENOM 64
-int8 integer_divide_table[DIVTAB_NUMER][DIVTAB_DENOM]; // 2KB
-#endif
-
-static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n)
-{
- int dy = y1 - y0;
- int adx = x1 - x0;
- int ady = abs(dy);
- int base;
- int x=x0,y=y0;
- int err = 0;
- int sy;
-
-#ifdef STB_VORBIS_DIVIDE_TABLE
- if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) {
- if (dy < 0) {
- base = -integer_divide_table[ady][adx];
- sy = base-1;
- } else {
- base = integer_divide_table[ady][adx];
- sy = base+1;
- }
- } else {
- base = dy / adx;
- if (dy < 0)
- sy = base - 1;
- else
- sy = base+1;
- }
-#else
- base = dy / adx;
- if (dy < 0)
- sy = base - 1;
- else
- sy = base+1;
-#endif
- ady -= abs(base) * adx;
- if (x1 > n) x1 = n;
- LINE_OP(output[x], inverse_db_table[y]);
- for (++x; x < x1; ++x) {
- err += ady;
- if (err >= adx) {
- err -= adx;
- y += sy;
- } else
- y += base;
- LINE_OP(output[x], inverse_db_table[y]);
- }
-}
-
-static int residue_decode(vorb *f, Codebook *book, float *target, int offset, int n, int rtype)
-{
- int k;
- if (rtype == 0) {
- int step = n / book->dimensions;
- for (k=0; k < step; ++k)
- if (!codebook_decode_step(f, book, target+offset+k, n-offset-k, step))
- return FALSE;
- } else {
- for (k=0; k < n; ) {
- if (!codebook_decode(f, book, target+offset, n-k))
- return FALSE;
- k += book->dimensions;
- offset += book->dimensions;
- }
- }
- return TRUE;
-}
-
-static void decode_residue(vorb *f, float *residue_buffers[], int ch, int n, int rn, uint8 *do_not_decode)
-{
- int i,j,pass;
- Residue *r = f->residue_config + rn;
- int rtype = f->residue_types[rn];
- int c = r->classbook;
- int classwords = f->codebooks[c].dimensions;
- int n_read = r->end - r->begin;
- int part_read = n_read / r->part_size;
- int temp_alloc_point = temp_alloc_save(f);
- #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
- uint8 ***part_classdata = (uint8 ***) temp_block_array(f,f->channels, part_read * sizeof(**part_classdata));
- #else
- int **classifications = (int **) temp_block_array(f,f->channels, part_read * sizeof(**classifications));
- #endif
-
- stb_prof(2);
- for (i=0; i < ch; ++i)
- if (!do_not_decode[i])
- memset(residue_buffers[i], 0, sizeof(float) * n);
-
- if (rtype == 2 && ch != 1) {
- int len = ch * n;
- for (j=0; j < ch; ++j)
- if (!do_not_decode[j])
- break;
- if (j == ch)
- goto done;
-
- stb_prof(3);
- for (pass=0; pass < 8; ++pass) {
- int pcount = 0, class_set = 0;
- if (ch == 2) {
- stb_prof(13);
- while (pcount < part_read) {
- int z = r->begin + pcount*r->part_size;
- int c_inter = (z & 1), p_inter = z>>1;
- if (pass == 0) {
- Codebook *c = f->codebooks+r->classbook;
- int q;
- DECODE(q,f,c);
- if (q == EOP) goto done;
- #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
- part_classdata[0][class_set] = r->classdata[q];
- #else
- for (i=classwords-1; i >= 0; --i) {
- classifications[0][i+pcount] = q % r->classifications;
- q /= r->classifications;
- }
- #endif
- }
- stb_prof(5);
- for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
- int z = r->begin + pcount*r->part_size;
- #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
- int c = part_classdata[0][class_set][i];
- #else
- int c = classifications[0][pcount];
- #endif
- int b = r->residue_books[c][pass];
- if (b >= 0) {
- Codebook *book = f->codebooks + b;
- stb_prof(20); // accounts for X time
- #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
- if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
- goto done;
- #else
- // saves 1%
- if (!codebook_decode_deinterleave_repeat_2(f, book, residue_buffers, &c_inter, &p_inter, n, r->part_size))
- goto done;
- #endif
- stb_prof(7);
- } else {
- z += r->part_size;
- c_inter = z & 1;
- p_inter = z >> 1;
- }
- }
- stb_prof(8);
- #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
- ++class_set;
- #endif
- }
- } else if (ch == 1) {
- while (pcount < part_read) {
- int z = r->begin + pcount*r->part_size;
- int c_inter = 0, p_inter = z;
- if (pass == 0) {
- Codebook *c = f->codebooks+r->classbook;
- int q;
- DECODE(q,f,c);
- if (q == EOP) goto done;
- #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
- part_classdata[0][class_set] = r->classdata[q];
- #else
- for (i=classwords-1; i >= 0; --i) {
- classifications[0][i+pcount] = q % r->classifications;
- q /= r->classifications;
- }
- #endif
- }
- for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
- int z = r->begin + pcount*r->part_size;
- #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
- int c = part_classdata[0][class_set][i];
- #else
- int c = classifications[0][pcount];
- #endif
- int b = r->residue_books[c][pass];
- if (b >= 0) {
- Codebook *book = f->codebooks + b;
- stb_prof(22);
- if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
- goto done;
- stb_prof(3);
- } else {
- z += r->part_size;
- c_inter = 0;
- p_inter = z;
- }
- }
- #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
- ++class_set;
- #endif
- }
- } else {
- while (pcount < part_read) {
- int z = r->begin + pcount*r->part_size;
- int c_inter = z % ch, p_inter = z/ch;
- if (pass == 0) {
- Codebook *c = f->codebooks+r->classbook;
- int q;
- DECODE(q,f,c);
- if (q == EOP) goto done;
- #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
- part_classdata[0][class_set] = r->classdata[q];
- #else
- for (i=classwords-1; i >= 0; --i) {
- classifications[0][i+pcount] = q % r->classifications;
- q /= r->classifications;
- }
- #endif
- }
- for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
- int z = r->begin + pcount*r->part_size;
- #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
- int c = part_classdata[0][class_set][i];
- #else
- int c = classifications[0][pcount];
- #endif
- int b = r->residue_books[c][pass];
- if (b >= 0) {
- Codebook *book = f->codebooks + b;
- stb_prof(22);
- if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
- goto done;
- stb_prof(3);
- } else {
- z += r->part_size;
- c_inter = z % ch;
- p_inter = z / ch;
- }
- }
- #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
- ++class_set;
- #endif
- }
- }
- }
- goto done;
- }
- stb_prof(9);
-
- for (pass=0; pass < 8; ++pass) {
- int pcount = 0, class_set=0;
- while (pcount < part_read) {
- if (pass == 0) {
- for (j=0; j < ch; ++j) {
- if (!do_not_decode[j]) {
- Codebook *c = f->codebooks+r->classbook;
- int temp;
- DECODE(temp,f,c);
- if (temp == EOP) goto done;
- #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
- part_classdata[j][class_set] = r->classdata[temp];
- #else
- for (i=classwords-1; i >= 0; --i) {
- classifications[j][i+pcount] = temp % r->classifications;
- temp /= r->classifications;
- }
- #endif
- }
- }
- }
- for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
- for (j=0; j < ch; ++j) {
- if (!do_not_decode[j]) {
- #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
- int c = part_classdata[j][class_set][i];
- #else
- int c = classifications[j][pcount];
- #endif
- int b = r->residue_books[c][pass];
- if (b >= 0) {
- float *target = residue_buffers[j];
- int offset = r->begin + pcount * r->part_size;
- int n = r->part_size;
- Codebook *book = f->codebooks + b;
- if (!residue_decode(f, book, target, offset, n, rtype))
- goto done;
- }
- }
- }
- }
- #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
- ++class_set;
- #endif
- }
- }
- done:
- stb_prof(0);
- temp_alloc_restore(f,temp_alloc_point);
-}
-
-
-#if 0
-// slow way for debugging
-void inverse_mdct_slow(float *buffer, int n)
-{
- int i,j;
- int n2 = n >> 1;
- float *x = (float *) malloc(sizeof(*x) * n2);
- memcpy(x, buffer, sizeof(*x) * n2);
- for (i=0; i < n; ++i) {
- float acc = 0;
- for (j=0; j < n2; ++j)
- // formula from paper:
- //acc += n/4.0f * x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1));
- // formula from wikipedia
- //acc += 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5));
- // these are equivalent, except the formula from the paper inverts the multiplier!
- // however, what actually works is NO MULTIPLIER!?!
- //acc += 64 * 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5));
- acc += x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1));
- buffer[i] = acc;
- }
- free(x);
-}
-#elif 0
-// same as above, but just barely able to run in real time on modern machines
-void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype)
-{
- float mcos[16384];
- int i,j;
- int n2 = n >> 1, nmask = (n << 2) -1;
- float *x = (float *) malloc(sizeof(*x) * n2);
- memcpy(x, buffer, sizeof(*x) * n2);
- for (i=0; i < 4*n; ++i)
- mcos[i] = (float) cos(M_PI / 2 * i / n);
-
- for (i=0; i < n; ++i) {
- float acc = 0;
- for (j=0; j < n2; ++j)
- acc += x[j] * mcos[(2 * i + 1 + n2)*(2*j+1) & nmask];
- buffer[i] = acc;
- }
- free(x);
-}
-#else
-// transform to use a slow dct-iv; this is STILL basically trivial,
-// but only requires half as many ops
-void dct_iv_slow(float *buffer, int n)
-{
- float mcos[16384];
- float x[2048];
- int i,j;
- int n2 = n >> 1, nmask = (n << 3) - 1;
- memcpy(x, buffer, sizeof(*x) * n);
- for (i=0; i < 8*n; ++i)
- mcos[i] = (float) cos(M_PI / 4 * i / n);
- for (i=0; i < n; ++i) {
- float acc = 0;
- for (j=0; j < n; ++j)
- acc += x[j] * mcos[((2 * i + 1)*(2*j+1)) & nmask];
- //acc += x[j] * cos(M_PI / n * (i + 0.5) * (j + 0.5));
- buffer[i] = acc;
- }
-}
-
-void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype)
-{
- int i, n4 = n >> 2, n2 = n >> 1, n3_4 = n - n4;
- float temp[4096];
-
- memcpy(temp, buffer, n2 * sizeof(float));
- dct_iv_slow(temp, n2); // returns -c'-d, a-b'
-
- for (i=0; i < n4 ; ++i) buffer[i] = temp[i+n4]; // a-b'
- for ( ; i < n3_4; ++i) buffer[i] = -temp[n3_4 - i - 1]; // b-a', c+d'
- for ( ; i < n ; ++i) buffer[i] = -temp[i - n3_4]; // c'+d
-}
-#endif
-
-#ifndef LIBVORBIS_MDCT
-#define LIBVORBIS_MDCT 0
-#endif
-
-#if LIBVORBIS_MDCT
-// directly call the vorbis MDCT using an interface documented
-// by Jeff Roberts... useful for performance comparison
-typedef struct
-{
- int n;
- int log2n;
-
- float *trig;
- int *bitrev;
-
- float scale;
-} mdct_lookup;
-
-extern void mdct_init(mdct_lookup *lookup, int n);
-extern void mdct_clear(mdct_lookup *l);
-extern void mdct_backward(mdct_lookup *init, float *in, float *out);
-
-mdct_lookup M1,M2;
-
-void inverse_mdct(float *buffer, int n, vorb *f, int blocktype)
-{
- mdct_lookup *M;
- if (M1.n == n) M = &M1;
- else if (M2.n == n) M = &M2;
- else if (M1.n == 0) { mdct_init(&M1, n); M = &M1; }
- else {
- if (M2.n) __asm int 3;
- mdct_init(&M2, n);
- M = &M2;
- }
-
- mdct_backward(M, buffer, buffer);
-}
-#endif
-
-
-// the following were split out into separate functions while optimizing;
-// they could be pushed back up but eh. __forceinline showed no change;
-// they're probably already being inlined.
-static void imdct_step3_iter0_loop(int n, float *e, int i_off, int k_off, float *A)
-{
- float *ee0 = e + i_off;
- float *ee2 = ee0 + k_off;
- int i;
-
- assert((n & 3) == 0);
- for (i=(n>>2); i > 0; --i) {
- float k00_20, k01_21;
- k00_20 = ee0[ 0] - ee2[ 0];
- k01_21 = ee0[-1] - ee2[-1];
- ee0[ 0] += ee2[ 0];//ee0[ 0] = ee0[ 0] + ee2[ 0];
- ee0[-1] += ee2[-1];//ee0[-1] = ee0[-1] + ee2[-1];
- ee2[ 0] = k00_20 * A[0] - k01_21 * A[1];
- ee2[-1] = k01_21 * A[0] + k00_20 * A[1];
- A += 8;
-
- k00_20 = ee0[-2] - ee2[-2];
- k01_21 = ee0[-3] - ee2[-3];
- ee0[-2] += ee2[-2];//ee0[-2] = ee0[-2] + ee2[-2];
- ee0[-3] += ee2[-3];//ee0[-3] = ee0[-3] + ee2[-3];
- ee2[-2] = k00_20 * A[0] - k01_21 * A[1];
- ee2[-3] = k01_21 * A[0] + k00_20 * A[1];
- A += 8;
-
- k00_20 = ee0[-4] - ee2[-4];
- k01_21 = ee0[-5] - ee2[-5];
- ee0[-4] += ee2[-4];//ee0[-4] = ee0[-4] + ee2[-4];
- ee0[-5] += ee2[-5];//ee0[-5] = ee0[-5] + ee2[-5];
- ee2[-4] = k00_20 * A[0] - k01_21 * A[1];
- ee2[-5] = k01_21 * A[0] + k00_20 * A[1];
- A += 8;
-
- k00_20 = ee0[-6] - ee2[-6];
- k01_21 = ee0[-7] - ee2[-7];
- ee0[-6] += ee2[-6];//ee0[-6] = ee0[-6] + ee2[-6];
- ee0[-7] += ee2[-7];//ee0[-7] = ee0[-7] + ee2[-7];
- ee2[-6] = k00_20 * A[0] - k01_21 * A[1];
- ee2[-7] = k01_21 * A[0] + k00_20 * A[1];
- A += 8;
- ee0 -= 8;
- ee2 -= 8;
- }
-}
-
-static void imdct_step3_inner_r_loop(int lim, float *e, int d0, int k_off, float *A, int k1)
-{
- int i;
- float k00_20, k01_21;
-
- float *e0 = e + d0;
- float *e2 = e0 + k_off;
-
- for (i=lim >> 2; i > 0; --i) {
- k00_20 = e0[-0] - e2[-0];
- k01_21 = e0[-1] - e2[-1];
- e0[-0] += e2[-0];//e0[-0] = e0[-0] + e2[-0];
- e0[-1] += e2[-1];//e0[-1] = e0[-1] + e2[-1];
- e2[-0] = (k00_20)*A[0] - (k01_21) * A[1];
- e2[-1] = (k01_21)*A[0] + (k00_20) * A[1];
-
- A += k1;
-
- k00_20 = e0[-2] - e2[-2];
- k01_21 = e0[-3] - e2[-3];
- e0[-2] += e2[-2];//e0[-2] = e0[-2] + e2[-2];
- e0[-3] += e2[-3];//e0[-3] = e0[-3] + e2[-3];
- e2[-2] = (k00_20)*A[0] - (k01_21) * A[1];
- e2[-3] = (k01_21)*A[0] + (k00_20) * A[1];
-
- A += k1;
-
- k00_20 = e0[-4] - e2[-4];
- k01_21 = e0[-5] - e2[-5];
- e0[-4] += e2[-4];//e0[-4] = e0[-4] + e2[-4];
- e0[-5] += e2[-5];//e0[-5] = e0[-5] + e2[-5];
- e2[-4] = (k00_20)*A[0] - (k01_21) * A[1];
- e2[-5] = (k01_21)*A[0] + (k00_20) * A[1];
-
- A += k1;
-
- k00_20 = e0[-6] - e2[-6];
- k01_21 = e0[-7] - e2[-7];
- e0[-6] += e2[-6];//e0[-6] = e0[-6] + e2[-6];
- e0[-7] += e2[-7];//e0[-7] = e0[-7] + e2[-7];
- e2[-6] = (k00_20)*A[0] - (k01_21) * A[1];
- e2[-7] = (k01_21)*A[0] + (k00_20) * A[1];
-
- e0 -= 8;
- e2 -= 8;
-
- A += k1;
- }
-}
-
-static void imdct_step3_inner_s_loop(int n, float *e, int i_off, int k_off, float *A, int a_off, int k0)
-{
- int i;
- float A0 = A[0];
- float A1 = A[0+1];
- float A2 = A[0+a_off];
- float A3 = A[0+a_off+1];
- float A4 = A[0+a_off*2+0];
- float A5 = A[0+a_off*2+1];
- float A6 = A[0+a_off*3+0];
- float A7 = A[0+a_off*3+1];
-
- float k00,k11;
-
- float *ee0 = e +i_off;
- float *ee2 = ee0+k_off;
-
- for (i=n; i > 0; --i) {
- k00 = ee0[ 0] - ee2[ 0];
- k11 = ee0[-1] - ee2[-1];
- ee0[ 0] = ee0[ 0] + ee2[ 0];
- ee0[-1] = ee0[-1] + ee2[-1];
- ee2[ 0] = (k00) * A0 - (k11) * A1;
- ee2[-1] = (k11) * A0 + (k00) * A1;
-
- k00 = ee0[-2] - ee2[-2];
- k11 = ee0[-3] - ee2[-3];
- ee0[-2] = ee0[-2] + ee2[-2];
- ee0[-3] = ee0[-3] + ee2[-3];
- ee2[-2] = (k00) * A2 - (k11) * A3;
- ee2[-3] = (k11) * A2 + (k00) * A3;
-
- k00 = ee0[-4] - ee2[-4];
- k11 = ee0[-5] - ee2[-5];
- ee0[-4] = ee0[-4] + ee2[-4];
- ee0[-5] = ee0[-5] + ee2[-5];
- ee2[-4] = (k00) * A4 - (k11) * A5;
- ee2[-5] = (k11) * A4 + (k00) * A5;
-
- k00 = ee0[-6] - ee2[-6];
- k11 = ee0[-7] - ee2[-7];
- ee0[-6] = ee0[-6] + ee2[-6];
- ee0[-7] = ee0[-7] + ee2[-7];
- ee2[-6] = (k00) * A6 - (k11) * A7;
- ee2[-7] = (k11) * A6 + (k00) * A7;
-
- ee0 -= k0;
- ee2 -= k0;
- }
-}
-
-static __forceinline void iter_54(float *z)
-{
- float k00,k11,k22,k33;
- float y0,y1,y2,y3;
-
- k00 = z[ 0] - z[-4];
- y0 = z[ 0] + z[-4];
- y2 = z[-2] + z[-6];
- k22 = z[-2] - z[-6];
-
- z[-0] = y0 + y2; // z0 + z4 + z2 + z6
- z[-2] = y0 - y2; // z0 + z4 - z2 - z6
-
- // done with y0,y2
-
- k33 = z[-3] - z[-7];
-
- z[-4] = k00 + k33; // z0 - z4 + z3 - z7
- z[-6] = k00 - k33; // z0 - z4 - z3 + z7
-
- // done with k33
-
- k11 = z[-1] - z[-5];
- y1 = z[-1] + z[-5];
- y3 = z[-3] + z[-7];
-
- z[-1] = y1 + y3; // z1 + z5 + z3 + z7
- z[-3] = y1 - y3; // z1 + z5 - z3 - z7
- z[-5] = k11 - k22; // z1 - z5 + z2 - z6
- z[-7] = k11 + k22; // z1 - z5 - z2 + z6
-}
-
-static void imdct_step3_inner_s_loop_ld654(int n, float *e, int i_off, float *A, int base_n)
-{
- int k_off = -8;
- int a_off = base_n >> 3;
- float A2 = A[0+a_off];
- float *z = e + i_off;
- float *base = z - 16 * n;
-
- while (z > base) {
- float k00,k11;
-
- k00 = z[-0] - z[-8];
- k11 = z[-1] - z[-9];
- z[-0] = z[-0] + z[-8];
- z[-1] = z[-1] + z[-9];
- z[-8] = k00;
- z[-9] = k11 ;
-
- k00 = z[ -2] - z[-10];
- k11 = z[ -3] - z[-11];
- z[ -2] = z[ -2] + z[-10];
- z[ -3] = z[ -3] + z[-11];
- z[-10] = (k00+k11) * A2;
- z[-11] = (k11-k00) * A2;
-
- k00 = z[-12] - z[ -4]; // reverse to avoid a unary negation
- k11 = z[ -5] - z[-13];
- z[ -4] = z[ -4] + z[-12];
- z[ -5] = z[ -5] + z[-13];
- z[-12] = k11;
- z[-13] = k00;
-
- k00 = z[-14] - z[ -6]; // reverse to avoid a unary negation
- k11 = z[ -7] - z[-15];
- z[ -6] = z[ -6] + z[-14];
- z[ -7] = z[ -7] + z[-15];
- z[-14] = (k00+k11) * A2;
- z[-15] = (k00-k11) * A2;
-
- iter_54(z);
- iter_54(z-8);
- z -= 16;
- }
-}
-
-static void inverse_mdct(float *buffer, int n, vorb *f, int blocktype)
-{
- int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l;
- int n3_4 = n - n4, ld;
- // @OPTIMIZE: reduce register pressure by using fewer variables?
- int save_point = temp_alloc_save(f);
- float *buf2 = (float *) temp_alloc(f, n2 * sizeof(*buf2));
- float *u=NULL,*v=NULL;
- // twiddle factors
- float *A = f->A[blocktype];
-
- // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio"
- // See notes about bugs in that paper in less-optimal implementation 'inverse_mdct_old' after this function.
-
- // kernel from paper
-
-
- // merged:
- // copy and reflect spectral data
- // step 0
-
- // note that it turns out that the items added together during
- // this step are, in fact, being added to themselves (as reflected
- // by step 0). inexplicable inefficiency! this became obvious
- // once I combined the passes.
-
- // so there's a missing 'times 2' here (for adding X to itself).
- // this propogates through linearly to the end, where the numbers
- // are 1/2 too small, and need to be compensated for.
-
- {
- float *d,*e, *AA, *e_stop;
- d = &buf2[n2-2];
- AA = A;
- e = &buffer[0];
- e_stop = &buffer[n2];
- while (e != e_stop) {
- d[1] = (e[0] * AA[0] - e[2]*AA[1]);
- d[0] = (e[0] * AA[1] + e[2]*AA[0]);
- d -= 2;
- AA += 2;
- e += 4;
- }
-
- e = &buffer[n2-3];
- while (d >= buf2) {
- d[1] = (-e[2] * AA[0] - -e[0]*AA[1]);
- d[0] = (-e[2] * AA[1] + -e[0]*AA[0]);
- d -= 2;
- AA += 2;
- e -= 4;
- }
- }
-
- // now we use symbolic names for these, so that we can
- // possibly swap their meaning as we change which operations
- // are in place
-
- u = buffer;
- v = buf2;
-
- // step 2 (paper output is w, now u)
- // this could be in place, but the data ends up in the wrong
- // place... _somebody_'s got to swap it, so this is nominated
- {
- float *AA = &A[n2-8];
- float *d0,*d1, *e0, *e1;
-
- e0 = &v[n4];
- e1 = &v[0];
-
- d0 = &u[n4];
- d1 = &u[0];
-
- while (AA >= A) {
- float v40_20, v41_21;
-
- v41_21 = e0[1] - e1[1];
- v40_20 = e0[0] - e1[0];
- d0[1] = e0[1] + e1[1];
- d0[0] = e0[0] + e1[0];
- d1[1] = v41_21*AA[4] - v40_20*AA[5];
- d1[0] = v40_20*AA[4] + v41_21*AA[5];
-
- v41_21 = e0[3] - e1[3];
- v40_20 = e0[2] - e1[2];
- d0[3] = e0[3] + e1[3];
- d0[2] = e0[2] + e1[2];
- d1[3] = v41_21*AA[0] - v40_20*AA[1];
- d1[2] = v40_20*AA[0] + v41_21*AA[1];
-
- AA -= 8;
-
- d0 += 4;
- d1 += 4;
- e0 += 4;
- e1 += 4;
- }
- }
-
- // step 3
- ld = ilog(n) - 1; // ilog is off-by-one from normal definitions
-
- // optimized step 3:
-
- // the original step3 loop can be nested r inside s or s inside r;
- // it's written originally as s inside r, but this is dumb when r
- // iterates many times, and s few. So I have two copies of it and
- // switch between them halfway.
-
- // this is iteration 0 of step 3
- imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*0, -(n >> 3), A);
- imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*1, -(n >> 3), A);
-
- // this is iteration 1 of step 3
- imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*0, -(n >> 4), A, 16);
- imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*1, -(n >> 4), A, 16);
- imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*2, -(n >> 4), A, 16);
- imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*3, -(n >> 4), A, 16);
-
- l=2;
- for (; l < (ld-3)>>1; ++l) {
- int k0 = n >> (l+2), k0_2 = k0>>1;
- int lim = 1 << (l+1);
- int i;
- for (i=0; i < lim; ++i)
- imdct_step3_inner_r_loop(n >> (l+4), u, n2-1 - k0*i, -k0_2, A, 1 << (l+3));
- }
-
- for (; l < ld-6; ++l) {
- int k0 = n >> (l+2), k1 = 1 << (l+3), k0_2 = k0>>1;
- int rlim = n >> (l+6), r;
- int lim = 1 << (l+1);
- int i_off;
- float *A0 = A;
- i_off = n2-1;
- for (r=rlim; r > 0; --r) {
- imdct_step3_inner_s_loop(lim, u, i_off, -k0_2, A0, k1, k0);
- A0 += k1*4;
- i_off -= 8;
- }
- }
-
- // iterations with count:
- // ld-6,-5,-4 all interleaved together
- // the big win comes from getting rid of needless flops
- // due to the constants on pass 5 & 4 being all 1 and 0;
- // combining them to be simultaneous to improve cache made little difference
- imdct_step3_inner_s_loop_ld654(n >> 5, u, n2-1, A, n);
-
- // output is u
-
- // step 4, 5, and 6
- // cannot be in-place because of step 5
- {
- uint16 *bitrev = f->bit_reverse[blocktype];
- // weirdly, I'd have thought reading sequentially and writing
- // erratically would have been better than vice-versa, but in
- // fact that's not what my testing showed. (That is, with
- // j = bitreverse(i), do you read i and write j, or read j and write i.)
-
- float *d0 = &v[n4-4];
- float *d1 = &v[n2-4];
- while (d0 >= v) {
- int k4;
-
- k4 = bitrev[0];
- d1[3] = u[k4+0];
- d1[2] = u[k4+1];
- d0[3] = u[k4+2];
- d0[2] = u[k4+3];
-
- k4 = bitrev[1];
- d1[1] = u[k4+0];
- d1[0] = u[k4+1];
- d0[1] = u[k4+2];
- d0[0] = u[k4+3];
-
- d0 -= 4;
- d1 -= 4;
- bitrev += 2;
- }
- }
- // (paper output is u, now v)
-
-
- // data must be in buf2
- assert(v == buf2);
-
- // step 7 (paper output is v, now v)
- // this is now in place
- {
- float *C = f->C[blocktype];
- float *d, *e;
-
- d = v;
- e = v + n2 - 4;
-
- while (d < e) {
- float a02,a11,b0,b1,b2,b3;
-
- a02 = d[0] - e[2];
- a11 = d[1] + e[3];
-
- b0 = C[1]*a02 + C[0]*a11;
- b1 = C[1]*a11 - C[0]*a02;
-
- b2 = d[0] + e[ 2];
- b3 = d[1] - e[ 3];
-
- d[0] = b2 + b0;
- d[1] = b3 + b1;
- e[2] = b2 - b0;
- e[3] = b1 - b3;
-
- a02 = d[2] - e[0];
- a11 = d[3] + e[1];
-
- b0 = C[3]*a02 + C[2]*a11;
- b1 = C[3]*a11 - C[2]*a02;
-
- b2 = d[2] + e[ 0];
- b3 = d[3] - e[ 1];
-
- d[2] = b2 + b0;
- d[3] = b3 + b1;
- e[0] = b2 - b0;
- e[1] = b1 - b3;
-
- C += 4;
- d += 4;
- e -= 4;
- }
- }
-
- // data must be in buf2
-
-
- // step 8+decode (paper output is X, now buffer)
- // this generates pairs of data a la 8 and pushes them directly through
- // the decode kernel (pushing rather than pulling) to avoid having
- // to make another pass later
-
- // this cannot POSSIBLY be in place, so we refer to the buffers directly
-
- {
- float *d0,*d1,*d2,*d3;
-
- float *B = f->B[blocktype] + n2 - 8;
- float *e = buf2 + n2 - 8;
- d0 = &buffer[0];
- d1 = &buffer[n2-4];
- d2 = &buffer[n2];
- d3 = &buffer[n-4];
- while (e >= v) {
- float p0,p1,p2,p3;
-
- p3 = e[6]*B[7] - e[7]*B[6];
- p2 = -e[6]*B[6] - e[7]*B[7];
-
- d0[0] = p3;
- d1[3] = - p3;
- d2[0] = p2;
- d3[3] = p2;
-
- p1 = e[4]*B[5] - e[5]*B[4];
- p0 = -e[4]*B[4] - e[5]*B[5];
-
- d0[1] = p1;
- d1[2] = - p1;
- d2[1] = p0;
- d3[2] = p0;
-
- p3 = e[2]*B[3] - e[3]*B[2];
- p2 = -e[2]*B[2] - e[3]*B[3];
-
- d0[2] = p3;
- d1[1] = - p3;
- d2[2] = p2;
- d3[1] = p2;
-
- p1 = e[0]*B[1] - e[1]*B[0];
- p0 = -e[0]*B[0] - e[1]*B[1];
-
- d0[3] = p1;
- d1[0] = - p1;
- d2[3] = p0;
- d3[0] = p0;
-
- B -= 8;
- e -= 8;
- d0 += 4;
- d2 += 4;
- d1 -= 4;
- d3 -= 4;
- }
- }
-
- temp_alloc_restore(f,save_point);
-}
-
-#if 0
-// this is the original version of the above code, if you want to optimize it from scratch
-void inverse_mdct_naive(float *buffer, int n)
-{
- float s;
- float A[1 << 12], B[1 << 12], C[1 << 11];
- int i,k,k2,k4, n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l;
- int n3_4 = n - n4, ld;
- // how can they claim this only uses N words?!
- // oh, because they're only used sparsely, whoops
- float u[1 << 13], X[1 << 13], v[1 << 13], w[1 << 13];
- // set up twiddle factors
-
- for (k=k2=0; k < n4; ++k,k2+=2) {
- A[k2 ] = (float) cos(4*k*M_PI/n);
- A[k2+1] = (float) -sin(4*k*M_PI/n);
- B[k2 ] = (float) cos((k2+1)*M_PI/n/2);
- B[k2+1] = (float) sin((k2+1)*M_PI/n/2);
- }
- for (k=k2=0; k < n8; ++k,k2+=2) {
- C[k2 ] = (float) cos(2*(k2+1)*M_PI/n);
- C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n);
- }
-
- // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio"
- // Note there are bugs in that pseudocode, presumably due to them attempting
- // to rename the arrays nicely rather than representing the way their actual
- // implementation bounces buffers back and forth. As a result, even in the
- // "some formulars corrected" version, a direct implementation fails. These
- // are noted below as "paper bug".
-
- // copy and reflect spectral data
- for (k=0; k < n2; ++k) u[k] = buffer[k];
- for ( ; k < n ; ++k) u[k] = -buffer[n - k - 1];
- // kernel from paper
- // step 1
- for (k=k2=k4=0; k < n4; k+=1, k2+=2, k4+=4) {
- v[n-k4-1] = (u[k4] - u[n-k4-1]) * A[k2] - (u[k4+2] - u[n-k4-3])*A[k2+1];
- v[n-k4-3] = (u[k4] - u[n-k4-1]) * A[k2+1] + (u[k4+2] - u[n-k4-3])*A[k2];
- }
- // step 2
- for (k=k4=0; k < n8; k+=1, k4+=4) {
- w[n2+3+k4] = v[n2+3+k4] + v[k4+3];
- w[n2+1+k4] = v[n2+1+k4] + v[k4+1];
- w[k4+3] = (v[n2+3+k4] - v[k4+3])*A[n2-4-k4] - (v[n2+1+k4]-v[k4+1])*A[n2-3-k4];
- w[k4+1] = (v[n2+1+k4] - v[k4+1])*A[n2-4-k4] + (v[n2+3+k4]-v[k4+3])*A[n2-3-k4];
- }
- // step 3
- ld = ilog(n) - 1; // ilog is off-by-one from normal definitions
- for (l=0; l < ld-3; ++l) {
- int k0 = n >> (l+2), k1 = 1 << (l+3);
- int rlim = n >> (l+4), r4, r;
- int s2lim = 1 << (l+2), s2;
- for (r=r4=0; r < rlim; r4+=4,++r) {
- for (s2=0; s2 < s2lim; s2+=2) {
- u[n-1-k0*s2-r4] = w[n-1-k0*s2-r4] + w[n-1-k0*(s2+1)-r4];
- u[n-3-k0*s2-r4] = w[n-3-k0*s2-r4] + w[n-3-k0*(s2+1)-r4];
- u[n-1-k0*(s2+1)-r4] = (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1]
- - (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1+1];
- u[n-3-k0*(s2+1)-r4] = (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1]
- + (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1+1];
- }
- }
- if (l+1 < ld-3) {
- // paper bug: ping-ponging of u&w here is omitted
- memcpy(w, u, sizeof(u));
- }
- }
-
- // step 4
- for (i=0; i < n8; ++i) {
- int j = bit_reverse(i) >> (32-ld+3);
- assert(j < n8);
- if (i == j) {
- // paper bug: original code probably swapped in place; if copying,
- // need to directly copy in this case
- int i8 = i << 3;
- v[i8+1] = u[i8+1];
- v[i8+3] = u[i8+3];
- v[i8+5] = u[i8+5];
- v[i8+7] = u[i8+7];
- } else if (i < j) {
- int i8 = i << 3, j8 = j << 3;
- v[j8+1] = u[i8+1], v[i8+1] = u[j8 + 1];
- v[j8+3] = u[i8+3], v[i8+3] = u[j8 + 3];
- v[j8+5] = u[i8+5], v[i8+5] = u[j8 + 5];
- v[j8+7] = u[i8+7], v[i8+7] = u[j8 + 7];
- }
- }
- // step 5
- for (k=0; k < n2; ++k) {
- w[k] = v[k*2+1];
- }
- // step 6
- for (k=k2=k4=0; k < n8; ++k, k2 += 2, k4 += 4) {
- u[n-1-k2] = w[k4];
- u[n-2-k2] = w[k4+1];
- u[n3_4 - 1 - k2] = w[k4+2];
- u[n3_4 - 2 - k2] = w[k4+3];
- }
- // step 7
- for (k=k2=0; k < n8; ++k, k2 += 2) {
- v[n2 + k2 ] = ( u[n2 + k2] + u[n-2-k2] + C[k2+1]*(u[n2+k2]-u[n-2-k2]) + C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2;
- v[n-2 - k2] = ( u[n2 + k2] + u[n-2-k2] - C[k2+1]*(u[n2+k2]-u[n-2-k2]) - C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2;
- v[n2+1+ k2] = ( u[n2+1+k2] - u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2;
- v[n-1 - k2] = (-u[n2+1+k2] + u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2;
- }
- // step 8
- for (k=k2=0; k < n4; ++k,k2 += 2) {
- X[k] = v[k2+n2]*B[k2 ] + v[k2+1+n2]*B[k2+1];
- X[n2-1-k] = v[k2+n2]*B[k2+1] - v[k2+1+n2]*B[k2 ];
- }
-
- // decode kernel to output
- // determined the following value experimentally
- // (by first figuring out what made inverse_mdct_slow work); then matching that here
- // (probably vorbis encoder premultiplies by n or n/2, to save it on the decoder?)
- s = 0.5; // theoretically would be n4
-
- // [[[ note! the s value of 0.5 is compensated for by the B[] in the current code,
- // so it needs to use the "old" B values to behave correctly, or else
- // set s to 1.0 ]]]
- for (i=0; i < n4 ; ++i) buffer[i] = s * X[i+n4];
- for ( ; i < n3_4; ++i) buffer[i] = -s * X[n3_4 - i - 1];
- for ( ; i < n ; ++i) buffer[i] = -s * X[i - n3_4];
-}
-#endif
-
-static float *get_window(vorb *f, int len)
-{
- len <<= 1;
- if (len == f->blocksize_0) return f->window[0];
- if (len == f->blocksize_1) return f->window[1];
- assert(0);
- return NULL;
-}
-
-#ifndef STB_VORBIS_NO_DEFER_FLOOR
-typedef int16 YTYPE;
-#else
-typedef int YTYPE;
-#endif
-static int do_floor(vorb *f, Mapping *map, int i, int n, float *target, YTYPE *finalY, uint8 *step2_flag)
-{
- int n2 = n >> 1;
- int s = map->chan[i].mux, floor;
- floor = map->submap_floor[s];
- if (f->floor_types[floor] == 0) {
- return error(f, VORBIS_invalid_stream);
- } else {
- Floor1 *g = &f->floor_config[floor].floor1;
- int j,q;
- int lx = 0, ly = finalY[0] * g->floor1_multiplier;
- for (q=1; q < g->values; ++q) {
- j = g->sorted_order[q];
- #ifndef STB_VORBIS_NO_DEFER_FLOOR
- if (finalY[j] >= 0)
- #else
- if (step2_flag[j])
- #endif
- {
- int hy = finalY[j] * g->floor1_multiplier;
- int hx = g->Xlist[j];
- draw_line(target, lx,ly, hx,hy, n2);
- lx = hx, ly = hy;
- }
- }
- if (lx < n2)
- // optimization of: draw_line(target, lx,ly, n,ly, n2);
- for (j=lx; j < n2; ++j)
- LINE_OP(target[j], inverse_db_table[ly]);
- }
- return TRUE;
-}
-
-static int vorbis_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode)
-{
- Mode *m;
- int i, n, prev, next, window_center;
- f->channel_buffer_start = f->channel_buffer_end = 0;
-
- retry:
- if (f->eof) return FALSE;
- if (!maybe_start_packet(f))
- return FALSE;
- // check packet type
- if (get_bits(f,1) != 0) {
- if (IS_PUSH_MODE(f))
- return error(f,VORBIS_bad_packet_type);
- while (EOP != get8_packet(f));
- goto retry;
- }
-
- if (f->alloc.alloc_buffer)
- assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
-
- i = get_bits(f, ilog(f->mode_count-1));
- if (i == EOP) return FALSE;
- if (i >= f->mode_count) return FALSE;
- *mode = i;
- m = f->mode_config + i;
- if (m->blockflag) {
- n = f->blocksize_1;
- prev = get_bits(f,1);
- next = get_bits(f,1);
- } else {
- prev = next = 0;
- n = f->blocksize_0;
- }
-
-// WINDOWING
-
- window_center = n >> 1;
- if (m->blockflag && !prev) {
- *p_left_start = (n - f->blocksize_0) >> 2;
- *p_left_end = (n + f->blocksize_0) >> 2;
- } else {
- *p_left_start = 0;
- *p_left_end = window_center;
- }
- if (m->blockflag && !next) {
- *p_right_start = (n*3 - f->blocksize_0) >> 2;
- *p_right_end = (n*3 + f->blocksize_0) >> 2;
- } else {
- *p_right_start = window_center;
- *p_right_end = n;
- }
- return TRUE;
-}
-
-static int vorbis_decode_packet_rest(vorb *f, int *len, Mode *m, int left_start, int left_end, int right_start, int right_end, int *p_left)
-{
- Mapping *map;
- int i,j,k,n,n2;
- int zero_channel[256];
- int really_zero_channel[256];
- int window_center;
-
-// WINDOWING
-
- n = f->blocksize[m->blockflag];
- window_center = n >> 1;
-
- map = &f->mapping[m->mapping];
-
-// FLOORS
- n2 = n >> 1;
-
- stb_prof(1);
- for (i=0; i < f->channels; ++i) {
- int s = map->chan[i].mux, floor;
- zero_channel[i] = FALSE;
- floor = map->submap_floor[s];
- if (f->floor_types[floor] == 0) {
- return error(f, VORBIS_invalid_stream);
- } else {
- Floor1 *g = &f->floor_config[floor].floor1;
- if (get_bits(f, 1)) {
- short *finalY;
- uint8 step2_flag[256];
- static int range_list[4] = { 256, 128, 86, 64 };
- int range = range_list[g->floor1_multiplier-1];
- int offset = 2;
- finalY = f->finalY[i];
- finalY[0] = get_bits(f, ilog(range)-1);
- finalY[1] = get_bits(f, ilog(range)-1);
- for (j=0; j < g->partitions; ++j) {
- int pclass = g->partition_class_list[j];
- int cdim = g->class_dimensions[pclass];
- int cbits = g->class_subclasses[pclass];
- int csub = (1 << cbits)-1;
- int cval = 0;
- if (cbits) {
- Codebook *c = f->codebooks + g->class_masterbooks[pclass];
- DECODE(cval,f,c);
- }
- for (k=0; k < cdim; ++k) {
- int book = g->subclass_books[pclass][cval & csub];
- cval = cval >> cbits;
- if (book >= 0) {
- int temp;
- Codebook *c = f->codebooks + book;
- DECODE(temp,f,c);
- finalY[offset++] = temp;
- } else
- finalY[offset++] = 0;
- }
- }
- if (f->valid_bits == INVALID_BITS) goto error; // behavior according to spec
- step2_flag[0] = step2_flag[1] = 1;
- for (j=2; j < g->values; ++j) {
- int low, high, pred, highroom, lowroom, room, val;
- low = g->neighbors[j][0];
- high = g->neighbors[j][1];
- //neighbors(g->Xlist, j, &low, &high);
- pred = predict_point(g->Xlist[j], g->Xlist[low], g->Xlist[high], finalY[low], finalY[high]);
- val = finalY[j];
- highroom = range - pred;
- lowroom = pred;
- if (highroom < lowroom)
- room = highroom * 2;
- else
- room = lowroom * 2;
- if (val) {
- step2_flag[low] = step2_flag[high] = 1;
- step2_flag[j] = 1;
- if (val >= room)
- if (highroom > lowroom)
- finalY[j] = val - lowroom + pred;
- else
- finalY[j] = pred - val + highroom - 1;
- else
- if (val & 1)
- finalY[j] = pred - ((val+1)>>1);
- else
- finalY[j] = pred + (val>>1);
- } else {
- step2_flag[j] = 0;
- finalY[j] = pred;
- }
- }
-
-#ifdef STB_VORBIS_NO_DEFER_FLOOR
- do_floor(f, map, i, n, f->floor_buffers[i], finalY, step2_flag);
-#else
- // defer final floor computation until _after_ residue
- for (j=0; j < g->values; ++j) {
- if (!step2_flag[j])
- finalY[j] = -1;
- }
-#endif
- } else {
- error:
- zero_channel[i] = TRUE;
- }
- // So we just defer everything else to later
-
- // at this point we've decoded the floor into buffer
- }
- }
- stb_prof(0);
- // at this point we've decoded all floors
-
- if (f->alloc.alloc_buffer)
- assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
-
- // re-enable coupled channels if necessary
- memcpy(really_zero_channel, zero_channel, sizeof(really_zero_channel[0]) * f->channels);
- for (i=0; i < map->coupling_steps; ++i)
- if (!zero_channel[map->chan[i].magnitude] || !zero_channel[map->chan[i].angle]) {
- zero_channel[map->chan[i].magnitude] = zero_channel[map->chan[i].angle] = FALSE;
- }
-
-// RESIDUE DECODE
- for (i=0; i < map->submaps; ++i) {
- float *residue_buffers[STB_VORBIS_MAX_CHANNELS];
- int r,t;
- uint8 do_not_decode[256];
- int ch = 0;
- for (j=0; j < f->channels; ++j) {
- if (map->chan[j].mux == i) {
- if (zero_channel[j]) {
- do_not_decode[ch] = TRUE;
- residue_buffers[ch] = NULL;
- } else {
- do_not_decode[ch] = FALSE;
- residue_buffers[ch] = f->channel_buffers[j];
- }
- ++ch;
- }
- }
- r = map->submap_residue[i];
- t = f->residue_types[r];
- decode_residue(f, residue_buffers, ch, n2, r, do_not_decode);
- }
-
- if (f->alloc.alloc_buffer)
- assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
-
-// INVERSE COUPLING
- stb_prof(14);
- for (i = map->coupling_steps-1; i >= 0; --i) {
- int n2 = n >> 1;
- float *m = f->channel_buffers[map->chan[i].magnitude];
- float *a = f->channel_buffers[map->chan[i].angle ];
- for (j=0; j < n2; ++j) {
- float a2,m2;
- if (m[j] > 0)
- if (a[j] > 0)
- m2 = m[j], a2 = m[j] - a[j];
- else
- a2 = m[j], m2 = m[j] + a[j];
- else
- if (a[j] > 0)
- m2 = m[j], a2 = m[j] + a[j];
- else
- a2 = m[j], m2 = m[j] - a[j];
- m[j] = m2;
- a[j] = a2;
- }
- }
-
- // finish decoding the floors
-#ifndef STB_VORBIS_NO_DEFER_FLOOR
- stb_prof(15);
- for (i=0; i < f->channels; ++i) {
- if (really_zero_channel[i]) {
- memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2);
- } else {
- do_floor(f, map, i, n, f->channel_buffers[i], f->finalY[i], NULL);
- }
- }
-#else
- for (i=0; i < f->channels; ++i) {
- if (really_zero_channel[i]) {
- memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2);
- } else {
- for (j=0; j < n2; ++j)
- f->channel_buffers[i][j] *= f->floor_buffers[i][j];
- }
- }
-#endif
-
-// INVERSE MDCT
- stb_prof(16);
- for (i=0; i < f->channels; ++i)
- inverse_mdct(f->channel_buffers[i], n, f, m->blockflag);
- stb_prof(0);
-
- // this shouldn't be necessary, unless we exited on an error
- // and want to flush to get to the next packet
- flush_packet(f);
-
- if (f->first_decode) {
- // assume we start so first non-discarded sample is sample 0
- // this isn't to spec, but spec would require us to read ahead
- // and decode the size of all current frames--could be done,
- // but presumably it's not a commonly used feature
- f->current_loc = -n2; // start of first frame is positioned for discard
- // we might have to discard samples "from" the next frame too,
- // if we're lapping a large block then a small at the start?
- f->discard_samples_deferred = n - right_end;
- f->current_loc_valid = TRUE;
- f->first_decode = FALSE;
- } else if (f->discard_samples_deferred) {
- left_start += f->discard_samples_deferred;
- *p_left = left_start;
- f->discard_samples_deferred = 0;
- } else if (f->previous_length == 0 && f->current_loc_valid) {
- // we're recovering from a seek... that means we're going to discard
- // the samples from this packet even though we know our position from
- // the last page header, so we need to update the position based on
- // the discarded samples here
- // but wait, the code below is going to add this in itself even
- // on a discard, so we don't need to do it here...
- }
-
- // check if we have ogg information about the sample # for this packet
- if (f->last_seg_which == f->end_seg_with_known_loc) {
- // if we have a valid current loc, and this is final:
- if (f->current_loc_valid && (f->page_flag & PAGEFLAG_last_page)) {
- uint32 current_end = f->known_loc_for_packet - (n-right_end);
- // then let's infer the size of the (probably) short final frame
- if (current_end < f->current_loc + right_end) {
- if (current_end < f->current_loc) {
- // negative truncation, that's impossible!
- *len = 0;
- } else {
- *len = current_end - f->current_loc;
- }
- *len += left_start;
- f->current_loc += *len;
- return TRUE;
- }
- }
- // otherwise, just set our sample loc
- // guess that the ogg granule pos refers to the _middle_ of the
- // last frame?
- // set f->current_loc to the position of left_start
- f->current_loc = f->known_loc_for_packet - (n2-left_start);
- f->current_loc_valid = TRUE;
- }
- if (f->current_loc_valid)
- f->current_loc += (right_start - left_start);
-
- if (f->alloc.alloc_buffer)
- assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
- *len = right_end; // ignore samples after the window goes to 0
- return TRUE;
-}
-
-static int vorbis_decode_packet(vorb *f, int *len, int *p_left, int *p_right)
-{
- int mode, left_end, right_end;
- if (!vorbis_decode_initial(f, p_left, &left_end, p_right, &right_end, &mode)) return 0;
- return vorbis_decode_packet_rest(f, len, f->mode_config + mode, *p_left, left_end, *p_right, right_end, p_left);
-}
-
-static int vorbis_finish_frame(stb_vorbis *f, int len, int left, int right)
-{
- int prev,i,j;
- // we use right&left (the start of the right- and left-window sin()-regions)
- // to determine how much to return, rather than inferring from the rules
- // (same result, clearer code); 'left' indicates where our sin() window
- // starts, therefore where the previous window's right edge starts, and
- // therefore where to start mixing from the previous buffer. 'right'
- // indicates where our sin() ending-window starts, therefore that's where
- // we start saving, and where our returned-data ends.
-
- // mixin from previous window
- if (f->previous_length) {
- int i,j, n = f->previous_length;
- float *w = get_window(f, n);
- for (i=0; i < f->channels; ++i) {
- for (j=0; j < n; ++j)
- f->channel_buffers[i][left+j] =
- f->channel_buffers[i][left+j]*w[ j] +
- f->previous_window[i][ j]*w[n-1-j];
- }
- }
-
- prev = f->previous_length;
-
- // last half of this data becomes previous window
- f->previous_length = len - right;
-
- // @OPTIMIZE: could avoid this copy by double-buffering the
- // output (flipping previous_window with channel_buffers), but
- // then previous_window would have to be 2x as large, and
- // channel_buffers couldn't be temp mem (although they're NOT
- // currently temp mem, they could be (unless we want to level
- // performance by spreading out the computation))
- for (i=0; i < f->channels; ++i)
- for (j=0; right+j < len; ++j)
- f->previous_window[i][j] = f->channel_buffers[i][right+j];
-
- if (!prev)
- // there was no previous packet, so this data isn't valid...
- // this isn't entirely true, only the would-have-overlapped data
- // isn't valid, but this seems to be what the spec requires
- return 0;
-
- // truncate a short frame
- if (len < right) right = len;
-
- f->samples_output += right-left;
-
- return right - left;
-}
-
-static void vorbis_pump_first_frame(stb_vorbis *f)
-{
- int len, right, left;
- if (vorbis_decode_packet(f, &len, &left, &right))
- vorbis_finish_frame(f, len, left, right);
-}
-
-#ifndef STB_VORBIS_NO_PUSHDATA_API
-static int is_whole_packet_present(stb_vorbis *f, int end_page)
-{
- // make sure that we have the packet available before continuing...
- // this requires a full ogg parse, but we know we can fetch from f->stream
-
- // instead of coding this out explicitly, we could save the current read state,
- // read the next packet with get8() until end-of-packet, check f->eof, then
- // reset the state? but that would be slower, esp. since we'd have over 256 bytes
- // of state to restore (primarily the page segment table)
-
- int s = f->next_seg, first = TRUE;
- uint8 *p = f->stream;
-
- if (s != -1) { // if we're not starting the packet with a 'continue on next page' flag
- for (; s < f->segment_count; ++s) {
- p += f->segments[s];
- if (f->segments[s] < 255) // stop at first short segment
- break;
- }
- // either this continues, or it ends it...
- if (end_page)
- if (s < f->segment_count-1) return error(f, VORBIS_invalid_stream);
- if (s == f->segment_count)
- s = -1; // set 'crosses page' flag
- if (p > f->stream_end) return error(f, VORBIS_need_more_data);
- first = FALSE;
- }
- for (; s == -1;) {
- uint8 *q;
- int n;
-
- // check that we have the page header ready
- if (p + 26 >= f->stream_end) return error(f, VORBIS_need_more_data);
- // validate the page
- if (memcmp(p, ogg_page_header, 4)) return error(f, VORBIS_invalid_stream);
- if (p[4] != 0) return error(f, VORBIS_invalid_stream);
- if (first) { // the first segment must NOT have 'continued_packet', later ones MUST
- if (f->previous_length)
- if ((p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream);
- // if no previous length, we're resynching, so we can come in on a continued-packet,
- // which we'll just drop
- } else {
- if (!(p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream);
- }
- n = p[26]; // segment counts
- q = p+27; // q points to segment table
- p = q + n; // advance past header
- // make sure we've read the segment table
- if (p > f->stream_end) return error(f, VORBIS_need_more_data);
- for (s=0; s < n; ++s) {
- p += q[s];
- if (q[s] < 255)
- break;
- }
- if (end_page)
- if (s < n-1) return error(f, VORBIS_invalid_stream);
- if (s == f->segment_count)
- s = -1; // set 'crosses page' flag
- if (p > f->stream_end) return error(f, VORBIS_need_more_data);
- first = FALSE;
- }
- return TRUE;
-}
-#endif // !STB_VORBIS_NO_PUSHDATA_API
-
-static int start_decoder(vorb *f)
-{
- uint8 header[6], x,y;
- int len,i,j,k, max_submaps = 0;
- int longest_floorlist=0;
-
- // first page, first packet
-
- if (!start_page(f)) return FALSE;
- // validate page flag
- if (!(f->page_flag & PAGEFLAG_first_page)) return error(f, VORBIS_invalid_first_page);
- if (f->page_flag & PAGEFLAG_last_page) return error(f, VORBIS_invalid_first_page);
- if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_invalid_first_page);
- // check for expected packet length
- if (f->segment_count != 1) return error(f, VORBIS_invalid_first_page);
- if (f->segments[0] != 30) return error(f, VORBIS_invalid_first_page);
- // read packet
- // check packet header
- if (get8(f) != VORBIS_packet_id) return error(f, VORBIS_invalid_first_page);
- if (!getn(f, header, 6)) return error(f, VORBIS_unexpected_eof);
- if (!vorbis_validate(header)) return error(f, VORBIS_invalid_first_page);
- // vorbis_version
- if (get32(f) != 0) return error(f, VORBIS_invalid_first_page);
- f->channels = get8(f); if (!f->channels) return error(f, VORBIS_invalid_first_page);
- if (f->channels > STB_VORBIS_MAX_CHANNELS) return error(f, VORBIS_too_many_channels);
- f->sample_rate = get32(f); if (!f->sample_rate) return error(f, VORBIS_invalid_first_page);
- get32(f); // bitrate_maximum
- get32(f); // bitrate_nominal
- get32(f); // bitrate_minimum
- x = get8(f);
- { int log0,log1;
- log0 = x & 15;
- log1 = x >> 4;
- f->blocksize_0 = 1 << log0;
- f->blocksize_1 = 1 << log1;
- if (log0 < 6 || log0 > 13) return error(f, VORBIS_invalid_setup);
- if (log1 < 6 || log1 > 13) return error(f, VORBIS_invalid_setup);
- if (log0 > log1) return error(f, VORBIS_invalid_setup);
- }
-
- // framing_flag
- x = get8(f);
- if (!(x & 1)) return error(f, VORBIS_invalid_first_page);
-
- // second packet!
- if (!start_page(f)) return FALSE;
-
- if (!start_packet(f)) return FALSE;
- do {
- len = next_segment(f);
- skip(f, len);
- f->bytes_in_seg = 0;
- } while (len);
-
- // third packet!
- if (!start_packet(f)) return FALSE;
-
- #ifndef STB_VORBIS_NO_PUSHDATA_API
- if (IS_PUSH_MODE(f)) {
- if (!is_whole_packet_present(f, TRUE)) {
- // convert error in ogg header to write type
- if (f->error == VORBIS_invalid_stream)
- f->error = VORBIS_invalid_setup;
- return FALSE;
- }
- }
- #endif
-
- crc32_init(); // always init it, to avoid multithread race conditions
-
- if (get8_packet(f) != VORBIS_packet_setup) return error(f, VORBIS_invalid_setup);
- for (i=0; i < 6; ++i) header[i] = get8_packet(f);
- if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup);
-
- // codebooks
-
- f->codebook_count = get_bits(f,8) + 1;
- f->codebooks = (Codebook *) setup_malloc(f, sizeof(*f->codebooks) * f->codebook_count);
- if (f->codebooks == NULL) return error(f, VORBIS_outofmem);
- memset(f->codebooks, 0, sizeof(*f->codebooks) * f->codebook_count);
- for (i=0; i < f->codebook_count; ++i) {
- uint32 *values;
- int ordered, sorted_count;
- int total=0;
- uint8 *lengths;
- Codebook *c = f->codebooks+i;
- x = get_bits(f, 8); if (x != 0x42) return error(f, VORBIS_invalid_setup);
- x = get_bits(f, 8); if (x != 0x43) return error(f, VORBIS_invalid_setup);
- x = get_bits(f, 8); if (x != 0x56) return error(f, VORBIS_invalid_setup);
- x = get_bits(f, 8);
- c->dimensions = (get_bits(f, 8)<<8) + x;
- x = get_bits(f, 8);
- y = get_bits(f, 8);
- c->entries = (get_bits(f, 8)<<16) + (y<<8) + x;
- ordered = get_bits(f,1);
- c->sparse = ordered ? 0 : get_bits(f,1);
-
- if (c->sparse)
- lengths = (uint8 *) setup_temp_malloc(f, c->entries);
- else
- lengths = c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);
-
- if (!lengths) return error(f, VORBIS_outofmem);
-
- if (ordered) {
- int current_entry = 0;
- int current_length = get_bits(f,5) + 1;
- while (current_entry < c->entries) {
- int limit = c->entries - current_entry;
- int n = get_bits(f, ilog(limit));
- if (current_entry + n > (int) c->entries) { return error(f, VORBIS_invalid_setup); }
- memset(lengths + current_entry, current_length, n);
- current_entry += n;
- ++current_length;
- }
- } else {
- for (j=0; j < c->entries; ++j) {
- int present = c->sparse ? get_bits(f,1) : 1;
- if (present) {
- lengths[j] = get_bits(f, 5) + 1;
- ++total;
- } else {
- lengths[j] = NO_CODE;
- }
- }
- }
-
- if (c->sparse && total >= c->entries >> 2) {
- // convert sparse items to non-sparse!
- if (c->entries > (int) f->setup_temp_memory_required)
- f->setup_temp_memory_required = c->entries;
-
- c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);
- memcpy(c->codeword_lengths, lengths, c->entries);
- setup_temp_free(f, lengths, c->entries); // note this is only safe if there have been no intervening temp mallocs!
- lengths = c->codeword_lengths;
- c->sparse = 0;
- }
-
- // compute the size of the sorted tables
- if (c->sparse) {
- sorted_count = total;
- //assert(total != 0);
- } else {
- sorted_count = 0;
- #ifndef STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
- for (j=0; j < c->entries; ++j)
- if (lengths[j] > STB_VORBIS_FAST_HUFFMAN_LENGTH && lengths[j] != NO_CODE)
- ++sorted_count;
- #endif
- }
-
- c->sorted_entries = sorted_count;
- values = NULL;
-
- if (!c->sparse) {
- c->codewords = (uint32 *) setup_malloc(f, sizeof(c->codewords[0]) * c->entries);
- if (!c->codewords) return error(f, VORBIS_outofmem);
- } else {
- unsigned int size;
- if (c->sorted_entries) {
- c->codeword_lengths = (uint8 *) setup_malloc(f, c->sorted_entries);
- if (!c->codeword_lengths) return error(f, VORBIS_outofmem);
- c->codewords = (uint32 *) setup_temp_malloc(f, sizeof(*c->codewords) * c->sorted_entries);
- if (!c->codewords) return error(f, VORBIS_outofmem);
- values = (uint32 *) setup_temp_malloc(f, sizeof(*values) * c->sorted_entries);
- if (!values) return error(f, VORBIS_outofmem);
- }
- size = c->entries + (sizeof(*c->codewords) + sizeof(*values)) * c->sorted_entries;
- if (size > f->setup_temp_memory_required)
- f->setup_temp_memory_required = size;
- }
-
- if (!compute_codewords(c, lengths, c->entries, values)) {
- if (c->sparse) setup_temp_free(f, values, 0);
- return error(f, VORBIS_invalid_setup);
- }
-
- if (c->sorted_entries) {
- // allocate an extra slot for sentinels
- c->sorted_codewords = (uint32 *) setup_malloc(f, sizeof(*c->sorted_codewords) * (c->sorted_entries+1));
- // allocate an extra slot at the front so that c->sorted_values[-1] is defined
- // so that we can catch that case without an extra if
- c->sorted_values = ( int *) setup_malloc(f, sizeof(*c->sorted_values ) * (c->sorted_entries+1));
- if (c->sorted_values) { ++c->sorted_values; c->sorted_values[-1] = -1; }
- compute_sorted_huffman(c, lengths, values);
- }
-
- if (c->sparse) {
- setup_temp_free(f, values, sizeof(*values)*c->sorted_entries);
- setup_temp_free(f, c->codewords, sizeof(*c->codewords)*c->sorted_entries);
- setup_temp_free(f, lengths, c->entries);
- c->codewords = NULL;
- }
-
- compute_accelerated_huffman(c);
-
- c->lookup_type = get_bits(f, 4);
- if (c->lookup_type > 2) return error(f, VORBIS_invalid_setup);
- if (c->lookup_type > 0) {
- uint16 *mults;
- c->minimum_value = float32_unpack(get_bits(f, 32));
- c->delta_value = float32_unpack(get_bits(f, 32));
- c->value_bits = get_bits(f, 4)+1;
- c->sequence_p = get_bits(f,1);
- if (c->lookup_type == 1) {
- c->lookup_values = lookup1_values(c->entries, c->dimensions);
- } else {
- c->lookup_values = c->entries * c->dimensions;
- }
- mults = (uint16 *) setup_temp_malloc(f, sizeof(mults[0]) * c->lookup_values);
- if (mults == NULL) return error(f, VORBIS_outofmem);
- for (j=0; j < (int) c->lookup_values; ++j) {
- int q = get_bits(f, c->value_bits);
- if (q == EOP) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); }
- mults[j] = q;
- }
-
-#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
- if (c->lookup_type == 1) {
- int len, sparse = c->sparse;
- // pre-expand the lookup1-style multiplicands, to avoid a divide in the inner loop
- if (sparse) {
- if (c->sorted_entries == 0) goto skip;
- c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->sorted_entries * c->dimensions);
- } else
- c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->entries * c->dimensions);
- if (c->multiplicands == NULL) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); }
- len = sparse ? c->sorted_entries : c->entries;
- for (j=0; j < len; ++j) {
- int z = sparse ? c->sorted_values[j] : j, div=1;
- for (k=0; k < c->dimensions; ++k) {
- int off = (z / div) % c->lookup_values;
- c->multiplicands[j*c->dimensions + k] =
- #ifndef STB_VORBIS_CODEBOOK_FLOATS
- mults[off];
- #else
- mults[off]*c->delta_value + c->minimum_value;
- // in this case (and this case only) we could pre-expand c->sequence_p,
- // and throw away the decode logic for it; have to ALSO do
- // it in the case below, but it can only be done if
- // STB_VORBIS_CODEBOOK_FLOATS
- // !STB_VORBIS_DIVIDES_IN_CODEBOOK
- #endif
- div *= c->lookup_values;
- }
- }
- setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values);
- c->lookup_type = 2;
- }
- else
-#endif
- {
- c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->lookup_values);
- #ifndef STB_VORBIS_CODEBOOK_FLOATS
- memcpy(c->multiplicands, mults, sizeof(c->multiplicands[0]) * c->lookup_values);
- #else
- for (j=0; j < (int) c->lookup_values; ++j)
- c->multiplicands[j] = mults[j] * c->delta_value + c->minimum_value;
- #endif
- setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values);
- }
- skip:;
-
- #ifdef STB_VORBIS_CODEBOOK_FLOATS
- if (c->lookup_type == 2 && c->sequence_p) {
- for (j=1; j < (int) c->lookup_values; ++j)
- c->multiplicands[j] = c->multiplicands[j-1];
- c->sequence_p = 0;
- }
- #endif
- }
- }
-
- // time domain transfers (notused)
-
- x = get_bits(f, 6) + 1;
- for (i=0; i < x; ++i) {
- uint32 z = get_bits(f, 16);
- if (z != 0) return error(f, VORBIS_invalid_setup);
- }
-
- // Floors
- f->floor_count = get_bits(f, 6)+1;
- f->floor_config = (Floor *) setup_malloc(f, f->floor_count * sizeof(*f->floor_config));
- for (i=0; i < f->floor_count; ++i) {
- f->floor_types[i] = get_bits(f, 16);
- if (f->floor_types[i] > 1) return error(f, VORBIS_invalid_setup);
- if (f->floor_types[i] == 0) {
- Floor0 *g = &f->floor_config[i].floor0;
- g->order = get_bits(f,8);
- g->rate = get_bits(f,16);
- g->bark_map_size = get_bits(f,16);
- g->amplitude_bits = get_bits(f,6);
- g->amplitude_offset = get_bits(f,8);
- g->number_of_books = get_bits(f,4) + 1;
- for (j=0; j < g->number_of_books; ++j)
- g->book_list[j] = get_bits(f,8);
- return error(f, VORBIS_feature_not_supported);
- } else {
- Point p[31*8+2];
- Floor1 *g = &f->floor_config[i].floor1;
- int max_class = -1;
- g->partitions = get_bits(f, 5);
- for (j=0; j < g->partitions; ++j) {
- g->partition_class_list[j] = get_bits(f, 4);
- if (g->partition_class_list[j] > max_class)
- max_class = g->partition_class_list[j];
- }
- for (j=0; j <= max_class; ++j) {
- g->class_dimensions[j] = get_bits(f, 3)+1;
- g->class_subclasses[j] = get_bits(f, 2);
- if (g->class_subclasses[j]) {
- g->class_masterbooks[j] = get_bits(f, 8);
- if (g->class_masterbooks[j] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
- }
- for (k=0; k < 1 << g->class_subclasses[j]; ++k) {
- g->subclass_books[j][k] = get_bits(f,8)-1;
- if (g->subclass_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
- }
- }
- g->floor1_multiplier = get_bits(f,2)+1;
- g->rangebits = get_bits(f,4);
- g->Xlist[0] = 0;
- g->Xlist[1] = 1 << g->rangebits;
- g->values = 2;
- for (j=0; j < g->partitions; ++j) {
- int c = g->partition_class_list[j];
- for (k=0; k < g->class_dimensions[c]; ++k) {
- g->Xlist[g->values] = get_bits(f, g->rangebits);
- ++g->values;
- }
- }
- // precompute the sorting
- for (j=0; j < g->values; ++j) {
- p[j].x = g->Xlist[j];
- p[j].y = j;
- }
- qsort(p, g->values, sizeof(p[0]), point_compare);
- for (j=0; j < g->values; ++j)
- g->sorted_order[j] = (uint8) p[j].y;
- // precompute the neighbors
- for (j=2; j < g->values; ++j) {
- int low,hi;
- neighbors(g->Xlist, j, &low,&hi);
- g->neighbors[j][0] = low;
- g->neighbors[j][1] = hi;
- }
-
- if (g->values > longest_floorlist)
- longest_floorlist = g->values;
- }
- }
-
- // Residue
- f->residue_count = get_bits(f, 6)+1;
- f->residue_config = (Residue *) setup_malloc(f, f->residue_count * sizeof(*f->residue_config));
- for (i=0; i < f->residue_count; ++i) {
- uint8 residue_cascade[64];
- Residue *r = f->residue_config+i;
- f->residue_types[i] = get_bits(f, 16);
- if (f->residue_types[i] > 2) return error(f, VORBIS_invalid_setup);
- r->begin = get_bits(f, 24);
- r->end = get_bits(f, 24);
- r->part_size = get_bits(f,24)+1;
- r->classifications = get_bits(f,6)+1;
- r->classbook = get_bits(f,8);
- for (j=0; j < r->classifications; ++j) {
- uint8 high_bits=0;
- uint8 low_bits=get_bits(f,3);
- if (get_bits(f,1))
- high_bits = get_bits(f,5);
- residue_cascade[j] = high_bits*8 + low_bits;
- }
- r->residue_books = (short (*)[8]) setup_malloc(f, sizeof(r->residue_books[0]) * r->classifications);
- for (j=0; j < r->classifications; ++j) {
- for (k=0; k < 8; ++k) {
- if (residue_cascade[j] & (1 << k)) {
- r->residue_books[j][k] = get_bits(f, 8);
- if (r->residue_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
- } else {
- r->residue_books[j][k] = -1;
- }
- }
- }
- // precompute the classifications[] array to avoid inner-loop mod/divide
- // call it 'classdata' since we already have r->classifications
- r->classdata = (uint8 **) setup_malloc(f, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
- if (!r->classdata) return error(f, VORBIS_outofmem);
- memset(r->classdata, 0, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
- for (j=0; j < f->codebooks[r->classbook].entries; ++j) {
- int classwords = f->codebooks[r->classbook].dimensions;
- int temp = j;
- r->classdata[j] = (uint8 *) setup_malloc(f, sizeof(r->classdata[j][0]) * classwords);
- for (k=classwords-1; k >= 0; --k) {
- r->classdata[j][k] = temp % r->classifications;
- temp /= r->classifications;
- }
- }
- }
-
- f->mapping_count = get_bits(f,6)+1;
- f->mapping = (Mapping *) setup_malloc(f, f->mapping_count * sizeof(*f->mapping));
- for (i=0; i < f->mapping_count; ++i) {
- Mapping *m = f->mapping + i;
- int mapping_type = get_bits(f,16);
- if (mapping_type != 0) return error(f, VORBIS_invalid_setup);
- m->chan = (MappingChannel *) setup_malloc(f, f->channels * sizeof(*m->chan));
- if (get_bits(f,1))
- m->submaps = get_bits(f,4);
- else
- m->submaps = 1;
- if (m->submaps > max_submaps)
- max_submaps = m->submaps;
- if (get_bits(f,1)) {
- m->coupling_steps = get_bits(f,8)+1;
- for (k=0; k < m->coupling_steps; ++k) {
- m->chan[k].magnitude = get_bits(f, ilog(f->channels)-1);
- m->chan[k].angle = get_bits(f, ilog(f->channels)-1);
- if (m->chan[k].magnitude >= f->channels) return error(f, VORBIS_invalid_setup);
- if (m->chan[k].angle >= f->channels) return error(f, VORBIS_invalid_setup);
- if (m->chan[k].magnitude == m->chan[k].angle) return error(f, VORBIS_invalid_setup);
- }
- } else
- m->coupling_steps = 0;
-
- // reserved field
- if (get_bits(f,2)) return error(f, VORBIS_invalid_setup);
- if (m->submaps > 1) {
- for (j=0; j < f->channels; ++j) {
- m->chan[j].mux = get_bits(f, 4);
- if (m->chan[j].mux >= m->submaps) return error(f, VORBIS_invalid_setup);
- }
- } else
- // @SPECIFICATION: this case is missing from the spec
- for (j=0; j < f->channels; ++j)
- m->chan[j].mux = 0;
-
- for (j=0; j < m->submaps; ++j) {
- get_bits(f,8); // discard
- m->submap_floor[j] = get_bits(f,8);
- m->submap_residue[j] = get_bits(f,8);
- if (m->submap_floor[j] >= f->floor_count) return error(f, VORBIS_invalid_setup);
- if (m->submap_residue[j] >= f->residue_count) return error(f, VORBIS_invalid_setup);
- }
- }
-
- // Modes
- f->mode_count = get_bits(f, 6)+1;
- for (i=0; i < f->mode_count; ++i) {
- Mode *m = f->mode_config+i;
- m->blockflag = get_bits(f,1);
- m->windowtype = get_bits(f,16);
- m->transformtype = get_bits(f,16);
- m->mapping = get_bits(f,8);
- if (m->windowtype != 0) return error(f, VORBIS_invalid_setup);
- if (m->transformtype != 0) return error(f, VORBIS_invalid_setup);
- if (m->mapping >= f->mapping_count) return error(f, VORBIS_invalid_setup);
- }
-
- flush_packet(f);
-
- f->previous_length = 0;
-
- for (i=0; i < f->channels; ++i) {
- f->channel_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1);
- f->previous_window[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);
- f->finalY[i] = (int16 *) setup_malloc(f, sizeof(int16) * longest_floorlist);
- #ifdef STB_VORBIS_NO_DEFER_FLOOR
- f->floor_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);
- #endif
- }
-
- if (!init_blocksize(f, 0, f->blocksize_0)) return FALSE;
- if (!init_blocksize(f, 1, f->blocksize_1)) return FALSE;
- f->blocksize[0] = f->blocksize_0;
- f->blocksize[1] = f->blocksize_1;
-
-#ifdef STB_VORBIS_DIVIDE_TABLE
- if (integer_divide_table[1][1]==0)
- for (i=0; i < DIVTAB_NUMER; ++i)
- for (j=1; j < DIVTAB_DENOM; ++j)
- integer_divide_table[i][j] = i / j;
-#endif
-
- // compute how much temporary memory is needed
-
- // 1.
- {
- uint32 imdct_mem = (f->blocksize_1 * sizeof(float) >> 1);
- uint32 classify_mem;
- int i,max_part_read=0;
- for (i=0; i < f->residue_count; ++i) {
- Residue *r = f->residue_config + i;
- int n_read = r->end - r->begin;
- int part_read = n_read / r->part_size;
- if (part_read > max_part_read)
- max_part_read = part_read;
- }
- #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
- classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(uint8 *));
- #else
- classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(int *));
- #endif
-
- f->temp_memory_required = classify_mem;
- if (imdct_mem > f->temp_memory_required)
- f->temp_memory_required = imdct_mem;
- }
-
- f->first_decode = TRUE;
-
- if (f->alloc.alloc_buffer) {
- assert(f->temp_offset == f->alloc.alloc_buffer_length_in_bytes);
- // check if there's enough temp memory so we don't error later
- if (f->setup_offset + sizeof(*f) + f->temp_memory_required > (unsigned) f->temp_offset)
- return error(f, VORBIS_outofmem);
- }
-
- f->first_audio_page_offset = stb_vorbis_get_file_offset(f);
-
- return TRUE;
-}
-
-static void vorbis_deinit(stb_vorbis *p)
-{
- int i,j;
- for (i=0; i < p->residue_count; ++i) {
- Residue *r = p->residue_config+i;
- if (r->classdata) {
- for (j=0; j < p->codebooks[r->classbook].entries; ++j)
- setup_free(p, r->classdata[j]);
- setup_free(p, r->classdata);
- }
- setup_free(p, r->residue_books);
- }
-
- if (p->codebooks) {
- for (i=0; i < p->codebook_count; ++i) {
- Codebook *c = p->codebooks + i;
- setup_free(p, c->codeword_lengths);
- setup_free(p, c->multiplicands);
- setup_free(p, c->codewords);
- setup_free(p, c->sorted_codewords);
- // c->sorted_values[-1] is the first entry in the array
- setup_free(p, c->sorted_values ? c->sorted_values-1 : NULL);
- }
- setup_free(p, p->codebooks);
- }
- setup_free(p, p->floor_config);
- setup_free(p, p->residue_config);
- for (i=0; i < p->mapping_count; ++i)
- setup_free(p, p->mapping[i].chan);
- setup_free(p, p->mapping);
- for (i=0; i < p->channels; ++i) {
- setup_free(p, p->channel_buffers[i]);
- setup_free(p, p->previous_window[i]);
- #ifdef STB_VORBIS_NO_DEFER_FLOOR
- setup_free(p, p->floor_buffers[i]);
- #endif
- setup_free(p, p->finalY[i]);
- }
- for (i=0; i < 2; ++i) {
- setup_free(p, p->A[i]);
- setup_free(p, p->B[i]);
- setup_free(p, p->C[i]);
- setup_free(p, p->window[i]);
- setup_free(p, p->bit_reverse[i]);
- }
- #ifndef STB_VORBIS_NO_STDIO
- if (p->close_on_free) fclose(p->f);
- #endif
-}
-
-void stb_vorbis_close(stb_vorbis *p)
-{
- if (p == NULL) return;
- vorbis_deinit(p);
- setup_free(p,p);
-}
-
-static void vorbis_init(stb_vorbis *p, stb_vorbis_alloc *z)
-{
- memset(p, 0, sizeof(*p)); // NULL out all malloc'd pointers to start
- if (z) {
- p->alloc = *z;
- p->alloc.alloc_buffer_length_in_bytes = (p->alloc.alloc_buffer_length_in_bytes+3) & ~3;
- p->temp_offset = p->alloc.alloc_buffer_length_in_bytes;
- }
- p->eof = 0;
- p->error = VORBIS__no_error;
- p->stream = NULL;
- p->codebooks = NULL;
- p->page_crc_tests = -1;
- #ifndef STB_VORBIS_NO_STDIO
- p->close_on_free = FALSE;
- p->f = NULL;
- #endif
-}
-
-int stb_vorbis_get_sample_offset(stb_vorbis *f)
-{
- if (f->current_loc_valid)
- return f->current_loc;
- else
- return -1;
-}
-
-stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f)
-{
- stb_vorbis_info d;
- d.channels = f->channels;
- d.sample_rate = f->sample_rate;
- d.setup_memory_required = f->setup_memory_required;
- d.setup_temp_memory_required = f->setup_temp_memory_required;
- d.temp_memory_required = f->temp_memory_required;
- d.max_frame_size = f->blocksize_1 >> 1;
- return d;
-}
-
-int stb_vorbis_get_error(stb_vorbis *f)
-{
- int e = f->error;
- f->error = VORBIS__no_error;
- return e;
-}
-
-static stb_vorbis * vorbis_alloc(stb_vorbis *f)
-{
- stb_vorbis *p = (stb_vorbis *) setup_malloc(f, sizeof(*p));
- return p;
-}
-
-#ifndef STB_VORBIS_NO_PUSHDATA_API
-
-void stb_vorbis_flush_pushdata(stb_vorbis *f)
-{
- f->previous_length = 0;
- f->page_crc_tests = 0;
- f->discard_samples_deferred = 0;
- f->current_loc_valid = FALSE;
- f->first_decode = FALSE;
- f->samples_output = 0;
- f->channel_buffer_start = 0;
- f->channel_buffer_end = 0;
-}
-
-static int vorbis_search_for_page_pushdata(vorb *f, uint8 *data, int data_len)
-{
- int i,n;
- for (i=0; i < f->page_crc_tests; ++i)
- f->scan[i].bytes_done = 0;
-
- // if we have room for more scans, search for them first, because
- // they may cause us to stop early if their header is incomplete
- if (f->page_crc_tests < STB_VORBIS_PUSHDATA_CRC_COUNT) {
- if (data_len < 4) return 0;
- data_len -= 3; // need to look for 4-byte sequence, so don't miss
- // one that straddles a boundary
- for (i=0; i < data_len; ++i) {
- if (data[i] == 0x4f) {
- if (0==memcmp(data+i, ogg_page_header, 4)) {
- int j,len;
- uint32 crc;
- // make sure we have the whole page header
- if (i+26 >= data_len || i+27+data[i+26] >= data_len) {
- // only read up to this page start, so hopefully we'll
- // have the whole page header start next time
- data_len = i;
- break;
- }
- // ok, we have it all; compute the length of the page
- len = 27 + data[i+26];
- for (j=0; j < data[i+26]; ++j)
- len += data[i+27+j];
- // scan everything up to the embedded crc (which we must 0)
- crc = 0;
- for (j=0; j < 22; ++j)
- crc = crc32_update(crc, data[i+j]);
- // now process 4 0-bytes
- for ( ; j < 26; ++j)
- crc = crc32_update(crc, 0);
- // len is the total number of bytes we need to scan
- n = f->page_crc_tests++;
- f->scan[n].bytes_left = len-j;
- f->scan[n].crc_so_far = crc;
- f->scan[n].goal_crc = data[i+22] + (data[i+23] << 8) + (data[i+24]<<16) + (data[i+25]<<24);
- // if the last frame on a page is continued to the next, then
- // we can't recover the sample_loc immediately
- if (data[i+27+data[i+26]-1] == 255)
- f->scan[n].sample_loc = ~0;
- else
- f->scan[n].sample_loc = data[i+6] + (data[i+7] << 8) + (data[i+ 8]<<16) + (data[i+ 9]<<24);
- f->scan[n].bytes_done = i+j;
- if (f->page_crc_tests == STB_VORBIS_PUSHDATA_CRC_COUNT)
- break;
- // keep going if we still have room for more
- }
- }
- }
- }
-
- for (i=0; i < f->page_crc_tests;) {
- uint32 crc;
- int j;
- int n = f->scan[i].bytes_done;
- int m = f->scan[i].bytes_left;
- if (m > data_len - n) m = data_len - n;
- // m is the bytes to scan in the current chunk
- crc = f->scan[i].crc_so_far;
- for (j=0; j < m; ++j)
- crc = crc32_update(crc, data[n+j]);
- f->scan[i].bytes_left -= m;
- f->scan[i].crc_so_far = crc;
- if (f->scan[i].bytes_left == 0) {
- // does it match?
- if (f->scan[i].crc_so_far == f->scan[i].goal_crc) {
- // Houston, we have page
- data_len = n+m; // consumption amount is wherever that scan ended
- f->page_crc_tests = -1; // drop out of page scan mode
- f->previous_length = 0; // decode-but-don't-output one frame
- f->next_seg = -1; // start a new page
- f->current_loc = f->scan[i].sample_loc; // set the current sample location
- // to the amount we'd have decoded had we decoded this page
- f->current_loc_valid = f->current_loc != ~0;
- return data_len;
- }
- // delete entry
- f->scan[i] = f->scan[--f->page_crc_tests];
- } else {
- ++i;
- }
- }
-
- return data_len;
-}
-
-// return value: number of bytes we used
-int stb_vorbis_decode_frame_pushdata(
- stb_vorbis *f, // the file we're decoding
- uint8 *data, int data_len, // the memory available for decoding
- int *channels, // place to write number of float * buffers
- float ***output, // place to write float ** array of float * buffers
- int *samples // place to write number of output samples
- )
-{
- int i;
- int len,right,left;
-
- if (!IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
-
- if (f->page_crc_tests >= 0) {
- *samples = 0;
- return vorbis_search_for_page_pushdata(f, data, data_len);
- }
-
- f->stream = data;
- f->stream_end = data + data_len;
- f->error = VORBIS__no_error;
-
- // check that we have the entire packet in memory
- if (!is_whole_packet_present(f, FALSE)) {
- *samples = 0;
- return 0;
- }
-
- if (!vorbis_decode_packet(f, &len, &left, &right)) {
- // save the actual error we encountered
- enum STBVorbisError error = f->error;
- if (error == VORBIS_bad_packet_type) {
- // flush and resynch
- f->error = VORBIS__no_error;
- while (get8_packet(f) != EOP)
- if (f->eof) break;
- *samples = 0;
- return f->stream - data;
- }
- if (error == VORBIS_continued_packet_flag_invalid) {
- if (f->previous_length == 0) {
- // we may be resynching, in which case it's ok to hit one
- // of these; just discard the packet
- f->error = VORBIS__no_error;
- while (get8_packet(f) != EOP)
- if (f->eof) break;
- *samples = 0;
- return f->stream - data;
- }
- }
- // if we get an error while parsing, what to do?
- // well, it DEFINITELY won't work to continue from where we are!
- stb_vorbis_flush_pushdata(f);
- // restore the error that actually made us bail
- f->error = error;
- *samples = 0;
- return 1;
- }
-
- // success!
- len = vorbis_finish_frame(f, len, left, right);
- for (i=0; i < f->channels; ++i)
- f->outputs[i] = f->channel_buffers[i] + left;
-
- if (channels) *channels = f->channels;
- *samples = len;
- *output = f->outputs;
- return f->stream - data;
-}
-
-stb_vorbis *stb_vorbis_open_pushdata(
- unsigned char *data, int data_len, // the memory available for decoding
- int *data_used, // only defined if result is not NULL
- int *error, stb_vorbis_alloc *alloc)
-{
- stb_vorbis *f, p;
- vorbis_init(&p, alloc);
- p.stream = data;
- p.stream_end = data + data_len;
- p.push_mode = TRUE;
- if (!start_decoder(&p)) {
- if (p.eof)
- *error = VORBIS_need_more_data;
- else
- *error = p.error;
- return NULL;
- }
- f = vorbis_alloc(&p);
- if (f) {
- *f = p;
- *data_used = f->stream - data;
- *error = 0;
- return f;
- } else {
- vorbis_deinit(&p);
- return NULL;
- }
-}
-#endif // STB_VORBIS_NO_PUSHDATA_API
-
-unsigned int stb_vorbis_get_file_offset(stb_vorbis *f)
-{
- #ifndef STB_VORBIS_NO_PUSHDATA_API
- if (f->push_mode) return 0;
- #endif
- if (USE_MEMORY(f)) return f->stream - f->stream_start;
- #ifndef STB_VORBIS_NO_STDIO
- return ftell(f->f) - f->f_start;
- #endif
-}
-
-#ifndef STB_VORBIS_NO_PULLDATA_API
-//
-// DATA-PULLING API
-//
-
-static uint32 vorbis_find_page(stb_vorbis *f, uint32 *end, uint32 *last)
-{
- for(;;) {
- int n;
- if (f->eof) return 0;
- n = get8(f);
- if (n == 0x4f) { // page header
- unsigned int retry_loc = stb_vorbis_get_file_offset(f);
- int i;
- // check if we're off the end of a file_section stream
- if (retry_loc - 25 > f->stream_len)
- return 0;
- // check the rest of the header
- for (i=1; i < 4; ++i)
- if (get8(f) != ogg_page_header[i])
- break;
- if (f->eof) return 0;
- if (i == 4) {
- uint8 header[27];
- uint32 i, crc, goal, len;
- for (i=0; i < 4; ++i)
- header[i] = ogg_page_header[i];
- for (; i < 27; ++i)
- header[i] = get8(f);
- if (f->eof) return 0;
- if (header[4] != 0) goto invalid;
- goal = header[22] + (header[23] << 8) + (header[24]<<16) + (header[25]<<24);
- for (i=22; i < 26; ++i)
- header[i] = 0;
- crc = 0;
- for (i=0; i < 27; ++i)
- crc = crc32_update(crc, header[i]);
- len = 0;
- for (i=0; i < header[26]; ++i) {
- int s = get8(f);
- crc = crc32_update(crc, s);
- len += s;
- }
- if (len && f->eof) return 0;
- for (i=0; i < len; ++i)
- crc = crc32_update(crc, get8(f));
- // finished parsing probable page
- if (crc == goal) {
- // we could now check that it's either got the last
- // page flag set, OR it's followed by the capture
- // pattern, but I guess TECHNICALLY you could have
- // a file with garbage between each ogg page and recover
- // from it automatically? So even though that paranoia
- // might decrease the chance of an invalid decode by
- // another 2^32, not worth it since it would hose those
- // invalid-but-useful files?
- if (end)
- *end = stb_vorbis_get_file_offset(f);
- if (last)
- if (header[5] & 0x04)
- *last = 1;
- else
- *last = 0;
- set_file_offset(f, retry_loc-1);
- return 1;
- }
- }
- invalid:
- // not a valid page, so rewind and look for next one
- set_file_offset(f, retry_loc);
- }
- }
-}
-
-// seek is implemented with 'interpolation search'--this is like
-// binary search, but we use the data values to estimate the likely
-// location of the data item (plus a bit of a bias so when the
-// estimation is wrong we don't waste overly much time)
-
-#define SAMPLE_unknown 0xffffffff
-
-
-// ogg vorbis, in its insane infinite wisdom, only provides
-// information about the sample at the END of the page.
-// therefore we COULD have the data we need in the current
-// page, and not know it. we could just use the end location
-// as our only knowledge for bounds, seek back, and eventually
-// the binary search finds it. or we can try to be smart and
-// not waste time trying to locate more pages. we try to be
-// smart, since this data is already in memory anyway, so
-// doing needless I/O would be crazy!
-static int vorbis_analyze_page(stb_vorbis *f, ProbedPage *z)
-{
- uint8 header[27], lacing[255];
- uint8 packet_type[255];
- int num_packet, packet_start, previous =0;
- int i,len;
- uint32 samples;
-
- // record where the page starts
- z->page_start = stb_vorbis_get_file_offset(f);
-
- // parse the header
- getn(f, header, 27);
- assert(header[0] == 'O' && header[1] == 'g' && header[2] == 'g' && header[3] == 'S');
- getn(f, lacing, header[26]);
-
- // determine the length of the payload
- len = 0;
- for (i=0; i < header[26]; ++i)
- len += lacing[i];
-
- // this implies where the page ends
- z->page_end = z->page_start + 27 + header[26] + len;
-
- // read the last-decoded sample out of the data
- z->last_decoded_sample = header[6] + (header[7] << 8) + (header[8] << 16) + (header[9] << 16);
-
- if (header[5] & 4) {
- // if this is the last page, it's not possible to work
- // backwards to figure out the first sample! whoops! fuck.
- z->first_decoded_sample = SAMPLE_unknown;
- set_file_offset(f, z->page_start);
- return 1;
- }
-
- // scan through the frames to determine the sample-count of each one...
- // our goal is the sample # of the first fully-decoded sample on the
- // page, which is the first decoded sample of the 2nd page
-
- num_packet=0;
-
- packet_start = ((header[5] & 1) == 0);
-
- for (i=0; i < header[26]; ++i) {
- if (packet_start) {
- uint8 n,b,m;
- if (lacing[i] == 0) goto bail; // trying to read from zero-length packet
- n = get8(f);
- // if bottom bit is non-zero, we've got corruption
- if (n & 1) goto bail;
- n >>= 1;
- b = ilog(f->mode_count-1);
- m = n >> b;
- n &= (1 << b)-1;
- if (n >= f->mode_count) goto bail;
- if (num_packet == 0 && f->mode_config[n].blockflag)
- previous = (m & 1);
- packet_type[num_packet++] = f->mode_config[n].blockflag;
- skip(f, lacing[i]-1);
- } else
- skip(f, lacing[i]);
- packet_start = (lacing[i] < 255);
- }
-
- // now that we know the sizes of all the pages, we can start determining
- // how much sample data there is.
-
- samples = 0;
-
- // for the last packet, we step by its whole length, because the definition
- // is that we encoded the end sample loc of the 'last packet completed',
- // where 'completed' refers to packets being split, and we are left to guess
- // what 'end sample loc' means. we assume it means ignoring the fact that
- // the last half of the data is useless without windowing against the next
- // packet... (so it's not REALLY complete in that sense)
- if (num_packet > 1)
- samples += f->blocksize[packet_type[num_packet-1]];
-
- for (i=num_packet-2; i >= 1; --i) {
- // now, for this packet, how many samples do we have that
- // do not overlap the following packet?
- if (packet_type[i] == 1)
- if (packet_type[i+1] == 1)
- samples += f->blocksize_1 >> 1;
- else
- samples += ((f->blocksize_1 - f->blocksize_0) >> 2) + (f->blocksize_0 >> 1);
- else
- samples += f->blocksize_0 >> 1;
- }
- // now, at this point, we've rewound to the very beginning of the
- // _second_ packet. if we entirely discard the first packet after
- // a seek, this will be exactly the right sample number. HOWEVER!
- // we can't as easily compute this number for the LAST page. The
- // only way to get the sample offset of the LAST page is to use
- // the end loc from the previous page. But what that returns us
- // is _exactly_ the place where we get our first non-overlapped
- // sample. (I think. Stupid spec for being ambiguous.) So for
- // consistency it's better to do that here, too. However, that
- // will then require us to NOT discard all of the first frame we
- // decode, in some cases, which means an even weirder frame size
- // and extra code. what a fucking pain.
-
- // we're going to discard the first packet if we
- // start the seek here, so we don't care about it. (we could actually
- // do better; if the first packet is long, and the previous packet
- // is short, there's actually data in the first half of the first
- // packet that doesn't need discarding... but not worth paying the
- // effort of tracking that of that here and in the seeking logic)
- // except crap, if we infer it from the _previous_ packet's end
- // location, we DO need to use that definition... and we HAVE to
- // infer the start loc of the LAST packet from the previous packet's
- // end location. fuck you, ogg vorbis.
-
- z->first_decoded_sample = z->last_decoded_sample - samples;
-
- // restore file state to where we were
- set_file_offset(f, z->page_start);
- return 1;
-
- // restore file state to where we were
- bail:
- set_file_offset(f, z->page_start);
- return 0;
-}
-
-static int vorbis_seek_frame_from_page(stb_vorbis *f, uint32 page_start, uint32 first_sample, uint32 target_sample, int fine)
-{
- int left_start, left_end, right_start, right_end, mode,i;
- int frame=0;
- uint32 frame_start;
- int frames_to_skip, data_to_skip;
-
- // first_sample is the sample # of the first sample that doesn't
- // overlap the previous page... note that this requires us to
- // _partially_ discard the first packet! bleh.
- set_file_offset(f, page_start);
-
- f->next_seg = -1; // force page resync
-
- frame_start = first_sample;
- // frame start is where the previous packet's last decoded sample
- // was, which corresponds to left_end... EXCEPT if the previous
- // packet was long and this packet is short? Probably a bug here.
-
-
- // now, we can start decoding frames... we'll only FAKE decode them,
- // until we find the frame that contains our sample; then we'll rewind,
- // and try again
- for (;;) {
- int start;
-
- if (!vorbis_decode_initial(f, &left_start, &left_end, &right_start, &right_end, &mode))
- return error(f, VORBIS_seek_failed);
-
- if (frame == 0)
- start = left_end;
- else
- start = left_start;
-
- // the window starts at left_start; the last valid sample we generate
- // before the next frame's window start is right_start-1
- if (target_sample < frame_start + right_start-start)
- break;
-
- flush_packet(f);
- if (f->eof)
- return error(f, VORBIS_seek_failed);
-
- frame_start += right_start - start;
-
- ++frame;
- }
-
- // ok, at this point, the sample we want is contained in frame #'frame'
-
- // to decode frame #'frame' normally, we have to decode the
- // previous frame first... but if it's the FIRST frame of the page
- // we can't. if it's the first frame, it means it falls in the part
- // of the first frame that doesn't overlap either of the other frames.
- // so, if we have to handle that case for the first frame, we might
- // as well handle it for all of them, so:
- if (target_sample > frame_start + (left_end - left_start)) {
- // so what we want to do is go ahead and just immediately decode
- // this frame, but then make it so the next get_frame_float() uses
- // this already-decoded data? or do we want to go ahead and rewind,
- // and leave a flag saying to skip the first N data? let's do that
- frames_to_skip = frame; // if this is frame #1, skip 1 frame (#0)
- data_to_skip = left_end - left_start;
- } else {
- // otherwise, we want to skip frames 0, 1, 2, ... frame-2
- // (which means frame-2+1 total frames) then decode frame-1,
- // then leave frame pending
- frames_to_skip = frame - 1;
- assert(frames_to_skip >= 0);
- data_to_skip = -1;
- }
-
- set_file_offset(f, page_start);
- f->next_seg = - 1; // force page resync
-
- for (i=0; i < frames_to_skip; ++i) {
- maybe_start_packet(f);
- flush_packet(f);
- }
-
- if (data_to_skip >= 0) {
- int i,j,n = f->blocksize_0 >> 1;
- f->discard_samples_deferred = data_to_skip;
- for (i=0; i < f->channels; ++i)
- for (j=0; j < n; ++j)
- f->previous_window[i][j] = 0;
- f->previous_length = n;
- frame_start += data_to_skip;
- } else {
- f->previous_length = 0;
- vorbis_pump_first_frame(f);
- }
-
- // at this point, the NEXT decoded frame will generate the desired sample
- if (fine) {
- // so if we're doing sample accurate streaming, we want to go ahead and decode it!
- if (target_sample != frame_start) {
- int n;
- stb_vorbis_get_frame_float(f, &n, NULL);
- assert(target_sample > frame_start);
- assert(f->channel_buffer_start + (int) (target_sample-frame_start) < f->channel_buffer_end);
- f->channel_buffer_start += (target_sample - frame_start);
- }
- }
-
- return 0;
-}
-
-static int vorbis_seek_base(stb_vorbis *f, unsigned int sample_number, int fine)
-{
- ProbedPage p[2],q;
- if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
-
- // do we know the location of the last page?
- if (f->p_last.page_start == 0) {
- uint32 z = stb_vorbis_stream_length_in_samples(f);
- if (z == 0) return error(f, VORBIS_cant_find_last_page);
- }
-
- p[0] = f->p_first;
- p[1] = f->p_last;
-
- if (sample_number >= f->p_last.last_decoded_sample)
- sample_number = f->p_last.last_decoded_sample-1;
-
- if (sample_number < f->p_first.last_decoded_sample) {
- vorbis_seek_frame_from_page(f, p[0].page_start, 0, sample_number, fine);
- return 0;
- } else {
- int attempts=0;
- while (p[0].page_end < p[1].page_start) {
- uint32 probe;
- uint32 start_offset, end_offset;
- uint32 start_sample, end_sample;
-
- // copy these into local variables so we can tweak them
- // if any are unknown
- start_offset = p[0].page_end;
- end_offset = p[1].after_previous_page_start; // an address known to seek to page p[1]
- start_sample = p[0].last_decoded_sample;
- end_sample = p[1].last_decoded_sample;
-
- // currently there is no such tweaking logic needed/possible?
- if (start_sample == SAMPLE_unknown || end_sample == SAMPLE_unknown)
- return error(f, VORBIS_seek_failed);
-
- // now we want to lerp between these for the target samples...
-
- // step 1: we need to bias towards the page start...
- if (start_offset + 4000 < end_offset)
- end_offset -= 4000;
-
- // now compute an interpolated search loc
- probe = start_offset + (int) floor((float) (end_offset - start_offset) / (end_sample - start_sample) * (sample_number - start_sample));
-
- // next we need to bias towards binary search...
- // code is a little wonky to allow for full 32-bit unsigned values
- if (attempts >= 4) {
- uint32 probe2 = start_offset + ((end_offset - start_offset) >> 1);
- if (attempts >= 8)
- probe = probe2;
- else if (probe < probe2)
- probe = probe + ((probe2 - probe) >> 1);
- else
- probe = probe2 + ((probe - probe2) >> 1);
- }
- ++attempts;
-
- set_file_offset(f, probe);
- if (!vorbis_find_page(f, NULL, NULL)) return error(f, VORBIS_seek_failed);
- if (!vorbis_analyze_page(f, &q)) return error(f, VORBIS_seek_failed);
- q.after_previous_page_start = probe;
-
- // it's possible we've just found the last page again
- if (q.page_start == p[1].page_start) {
- p[1] = q;
- continue;
- }
-
- if (sample_number < q.last_decoded_sample)
- p[1] = q;
- else
- p[0] = q;
- }
-
- if (p[0].last_decoded_sample <= sample_number && sample_number < p[1].last_decoded_sample) {
- vorbis_seek_frame_from_page(f, p[1].page_start, p[0].last_decoded_sample, sample_number, fine);
- return 0;
- }
- return error(f, VORBIS_seek_failed);
- }
-}
-
-int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number)
-{
- return vorbis_seek_base(f, sample_number, FALSE);
-}
-
-int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number)
-{
- return vorbis_seek_base(f, sample_number, TRUE);
-}
-
-void stb_vorbis_seek_start(stb_vorbis *f)
-{
- if (IS_PUSH_MODE(f)) { error(f, VORBIS_invalid_api_mixing); return; }
- set_file_offset(f, f->first_audio_page_offset);
- f->previous_length = 0;
- f->first_decode = TRUE;
- f->next_seg = -1;
- vorbis_pump_first_frame(f);
-}
-
-unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f)
-{
- unsigned int restore_offset, previous_safe;
- unsigned int end, last_page_loc;
-
- if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
- if (!f->total_samples) {
- int last;
- uint32 lo,hi;
- char header[6];
-
- // first, store the current decode position so we can restore it
- restore_offset = stb_vorbis_get_file_offset(f);
-
- // now we want to seek back 64K from the end (the last page must
- // be at most a little less than 64K, but let's allow a little slop)
- if (f->stream_len >= 65536 && f->stream_len-65536 >= f->first_audio_page_offset)
- previous_safe = f->stream_len - 65536;
- else
- previous_safe = f->first_audio_page_offset;
-
- set_file_offset(f, previous_safe);
- // previous_safe is now our candidate 'earliest known place that seeking
- // to will lead to the final page'
-
- if (!vorbis_find_page(f, &end, (int unsigned *)&last)) {
- // if we can't find a page, we're hosed!
- f->error = VORBIS_cant_find_last_page;
- f->total_samples = 0xffffffff;
- goto done;
- }
-
- // check if there are more pages
- last_page_loc = stb_vorbis_get_file_offset(f);
-
- // stop when the last_page flag is set, not when we reach eof;
- // this allows us to stop short of a 'file_section' end without
- // explicitly checking the length of the section
- while (!last) {
- set_file_offset(f, end);
- if (!vorbis_find_page(f, &end, (int unsigned *)&last)) {
- // the last page we found didn't have the 'last page' flag
- // set. whoops!
- break;
- }
- previous_safe = last_page_loc+1;
- last_page_loc = stb_vorbis_get_file_offset(f);
- }
-
- set_file_offset(f, last_page_loc);
-
- // parse the header
- getn(f, (unsigned char *)header, 6);
- // extract the absolute granule position
- lo = get32(f);
- hi = get32(f);
- if (lo == 0xffffffff && hi == 0xffffffff) {
- f->error = VORBIS_cant_find_last_page;
- f->total_samples = SAMPLE_unknown;
- goto done;
- }
- if (hi)
- lo = 0xfffffffe; // saturate
- f->total_samples = lo;
-
- f->p_last.page_start = last_page_loc;
- f->p_last.page_end = end;
- f->p_last.last_decoded_sample = lo;
- f->p_last.first_decoded_sample = SAMPLE_unknown;
- f->p_last.after_previous_page_start = previous_safe;
-
- done:
- set_file_offset(f, restore_offset);
- }
- return f->total_samples == SAMPLE_unknown ? 0 : f->total_samples;
-}
-
-float stb_vorbis_stream_length_in_seconds(stb_vorbis *f)
-{
- return stb_vorbis_stream_length_in_samples(f) / (float) f->sample_rate;
-}
-
-
-
-int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output)
-{
- int len, right,left,i;
- if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
-
- if (!vorbis_decode_packet(f, &len, &left, &right)) {
- f->channel_buffer_start = f->channel_buffer_end = 0;
- return 0;
- }
-
- len = vorbis_finish_frame(f, len, left, right);
- for (i=0; i < f->channels; ++i)
- f->outputs[i] = f->channel_buffers[i] + left;
-
- f->channel_buffer_start = left;
- f->channel_buffer_end = left+len;
-
- if (channels) *channels = f->channels;
- if (output) *output = f->outputs;
- return len;
-}
-
-#ifndef STB_VORBIS_NO_STDIO
-
-stb_vorbis * stb_vorbis_open_file_section(FILE *file, int close_on_free, int *error, stb_vorbis_alloc *alloc, unsigned int length)
-{
- stb_vorbis *f, p;
- vorbis_init(&p, alloc);
- p.f = file;
- p.f_start = ftell(file);
- p.stream_len = length;
- p.close_on_free = close_on_free;
- if (start_decoder(&p)) {
- f = vorbis_alloc(&p);
- if (f) {
- *f = p;
- vorbis_pump_first_frame(f);
- return f;
- }
- }
- if (error) *error = p.error;
- vorbis_deinit(&p);
- return NULL;
-}
-
-stb_vorbis * stb_vorbis_open_file(FILE *file, int close_on_free, int *error, stb_vorbis_alloc *alloc)
-{
- unsigned int len, start;
- start = ftell(file);
- fseek(file, 0, SEEK_END);
- len = ftell(file) - start;
- fseek(file, start, SEEK_SET);
- return stb_vorbis_open_file_section(file, close_on_free, error, alloc, len);
-}
-
-stb_vorbis * stb_vorbis_open_filename(char *filename, int *error, stb_vorbis_alloc *alloc)
-{
- FILE *f = fopen(filename, "rb");
- if (f)
- return stb_vorbis_open_file(f, TRUE, error, alloc);
- if (error) *error = VORBIS_file_open_failure;
- return NULL;
-}
-#endif // STB_VORBIS_NO_STDIO
-
-stb_vorbis * stb_vorbis_open_memory(unsigned char *data, int len, int *error, stb_vorbis_alloc *alloc)
-{
- stb_vorbis *f, p;
- if (data == NULL) return NULL;
- vorbis_init(&p, alloc);
- p.stream = data;
- p.stream_end = data + len;
- p.stream_start = p.stream;
- p.stream_len = len;
- p.push_mode = FALSE;
- if (start_decoder(&p)) {
- f = vorbis_alloc(&p);
- if (f) {
- *f = p;
- vorbis_pump_first_frame(f);
- return f;
- }
- }
- if (error) *error = p.error;
- vorbis_deinit(&p);
- return NULL;
-}
-
-#ifndef STB_VORBIS_NO_INTEGER_CONVERSION
-#define PLAYBACK_MONO 1
-#define PLAYBACK_LEFT 2
-#define PLAYBACK_RIGHT 4
-
-#define L (PLAYBACK_LEFT | PLAYBACK_MONO)
-#define C (PLAYBACK_LEFT | PLAYBACK_RIGHT | PLAYBACK_MONO)
-#define R (PLAYBACK_RIGHT | PLAYBACK_MONO)
-
-static int8 channel_position[7][6] =
-{
- { 0 },
- { C },
- { L, R },
- { L, C, R },
- { L, R, L, R },
- { L, C, R, L, R },
- { L, C, R, L, R, C },
-};
-
-
-#ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT
- // add (1<<23) to convert to int, then divide by 2^SHIFT, then add 0.5/2^SHIFT to round
- #define MAGIC(SHIFT) (1.5f * (1 << (23-SHIFT)) + 0.5f/(1 << SHIFT))
- #define ADDEND(SHIFT) (((150-SHIFT) << 23) + (1 << 22))
- #define FAST_SCALED_FLOAT_TO_INT(x,s) ((temp = (x) + MAGIC(s)), (*(int *)&temp) - ADDEND(s))
- #define check_endianness()
- typedef char stb_vorbis_float_size_test[sizeof(float)==4 && sizeof(int) == 4];
- #define FASTDEF(x) x
-#else
- #define FAST_SCALED_FLOAT_TO_INT(x,s) ((int) ((x) * (1 << (s))))
- #define check_endianness()
- #define FASTDEF(x)
-#endif
-
-static void copy_samples(short *dest, float *src, int len)
-{
- int i;
- FASTDEF(float temp);
- check_endianness();
- for (i=0; i < len; ++i) {
- int v = FAST_SCALED_FLOAT_TO_INT(src[i],15);
- if ((unsigned int) (v + 32768) > 65535)
- v = v < 0 ? -32768 : 32767;
- dest[i] = v;
- }
-}
-
-static void compute_samples(int mask, short *output, int num_c, float **data, int d_offset, int len)
-{
- #define BUFFER_SIZE 32
- float buffer[BUFFER_SIZE];
- int i,j,o,n = BUFFER_SIZE;
- FASTDEF(float temp);
- check_endianness();
- for (o = 0; o < len; o += BUFFER_SIZE) {
- memset(buffer, 0, sizeof(buffer));
- if (o + n > len) n = len - o;
- for (j=0; j < num_c; ++j) {
- if (channel_position[num_c][j] & mask) {
- for (i=0; i < n; ++i)
- buffer[i] += data[j][d_offset+o+i];
- }
- }
- for (i=0; i < n; ++i) {
- int v = FAST_SCALED_FLOAT_TO_INT(buffer[i],15);
- if ((unsigned int) (v + 32768) > 65535)
- v = v < 0 ? -32768 : 32767;
- output[o+i] = v;
- }
- }
-}
-
-static int channel_selector[3][2] = { {0}, {PLAYBACK_MONO}, {PLAYBACK_LEFT, PLAYBACK_RIGHT} };
-static void compute_stereo_samples(short *output, int num_c, float **data, int d_offset, int len)
-{
- #define BUFFER_SIZE 32
- float buffer[BUFFER_SIZE];
- int i,j,o,n = BUFFER_SIZE >> 1;
- FASTDEF(float temp);
- // o is the offset in the source data
- check_endianness();
- for (o = 0; o < len; o += BUFFER_SIZE >> 1) {
- // o2 is the offset in the output data
- int o2 = o << 1;
- memset(buffer, 0, sizeof(buffer));
- if (o + n > len) n = len - o;
- for (j=0; j < num_c; ++j) {
- int m = channel_position[num_c][j] & (PLAYBACK_LEFT | PLAYBACK_RIGHT);
- if (m == (PLAYBACK_LEFT | PLAYBACK_RIGHT)) {
- for (i=0; i < n; ++i) {
- buffer[i*2+0] += data[j][d_offset+o+i];
- buffer[i*2+1] += data[j][d_offset+o+i];
- }
- } else if (m == PLAYBACK_LEFT) {
- for (i=0; i < n; ++i) {
- buffer[i*2+0] += data[j][d_offset+o+i];
- }
- } else if (m == PLAYBACK_RIGHT) {
- for (i=0; i < n; ++i) {
- buffer[i*2+1] += data[j][d_offset+o+i];
- }
- }
- }
- for (i=0; i < (n<<1); ++i) {
- int v = FAST_SCALED_FLOAT_TO_INT(buffer[i],15);
- if ((unsigned int) (v + 32768) > 65535)
- v = v < 0 ? -32768 : 32767;
- output[o2+i] = v;
- }
- }
-}
-
-static void convert_samples_short(int buf_c, short **buffer, int b_offset, int data_c, float **data, int d_offset, int samples)
-{
- int i;
- if (buf_c != data_c && buf_c <= 2 && data_c <= 6) {
- static int channel_selector[3][2] = { {0}, {PLAYBACK_MONO}, {PLAYBACK_LEFT, PLAYBACK_RIGHT} };
- for (i=0; i < buf_c; ++i)
- compute_samples(channel_selector[buf_c][i], buffer[i]+b_offset, data_c, data, d_offset, samples);
- } else {
- int limit = buf_c < data_c ? buf_c : data_c;
- for (i=0; i < limit; ++i)
- copy_samples(buffer[i]+b_offset, data[i], samples);
- for ( ; i < buf_c; ++i)
- memset(buffer[i]+b_offset, 0, sizeof(short) * samples);
- }
-}
-
-int stb_vorbis_get_frame_short(stb_vorbis *f, int num_c, short **buffer, int num_samples)
-{
- float **output;
- int len = stb_vorbis_get_frame_float(f, NULL, &output);
- if (len > num_samples) len = num_samples;
- if (len)
- convert_samples_short(num_c, buffer, 0, f->channels, output, 0, len);
- return len;
-}
-
-static void convert_channels_short_interleaved(int buf_c, short *buffer, int data_c, float **data, int d_offset, int len)
-{
- int i;
- check_endianness();
- if (buf_c != data_c && buf_c <= 2 && data_c <= 6) {
- assert(buf_c == 2);
- for (i=0; i < buf_c; ++i)
- compute_stereo_samples(buffer, data_c, data, d_offset, len);
- } else {
- int limit = buf_c < data_c ? buf_c : data_c;
- int j;
- FASTDEF(float temp);
- for (j=0; j < len; ++j) {
- for (i=0; i < limit; ++i) {
- int v = FAST_SCALED_FLOAT_TO_INT(data[i][d_offset+j],15);
- if ((unsigned int) (v + 32768) > 65535)
- v = v < 0 ? -32768 : 32767;
- *buffer++ = v;
- }
- for ( ; i < buf_c; ++i)
- *buffer++ = 0;
- }
- }
-}
-
-int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts)
-{
- float **output;
- int len;
- if (num_c == 1) return stb_vorbis_get_frame_short(f,num_c,&buffer, num_shorts);
- len = stb_vorbis_get_frame_float(f, NULL, &output);
- if (len) {
- if (len*num_c > num_shorts) len = num_shorts / num_c;
- convert_channels_short_interleaved(num_c, buffer, f->channels, output, 0, len);
- }
- return len;
-}
-
-int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts)
-{
- float **outputs;
- int len = num_shorts / channels;
- int n=0;
- int z = f->channels;
- if (z > channels) z = channels;
- while (n < len) {
- int k = f->channel_buffer_end - f->channel_buffer_start;
- if (n+k >= len) k = len - n;
- if (k)
- convert_channels_short_interleaved(channels, buffer, f->channels, f->channel_buffers, f->channel_buffer_start, k);
- buffer += k*channels;
- n += k;
- f->channel_buffer_start += k;
- if (n == len) break;
- if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;
- }
- return n;
-}
-
-int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int len)
-{
- float **outputs;
- int n=0;
- int z = f->channels;
- if (z > channels) z = channels;
- while (n < len) {
- int k = f->channel_buffer_end - f->channel_buffer_start;
- if (n+k >= len) k = len - n;
- if (k)
- convert_samples_short(channels, buffer, n, f->channels, f->channel_buffers, f->channel_buffer_start, k);
- n += k;
- f->channel_buffer_start += k;
- if (n == len) break;
- if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;
- }
- return n;
-}
-
-#ifndef STB_VORBIS_NO_STDIO
-int stb_vorbis_decode_filename(char *filename, int *channels, short **output)
-{
- int data_len, offset, total, limit, error;
- short *data;
- stb_vorbis *v = stb_vorbis_open_filename(filename, &error, NULL);
- if (v == NULL) return -1;
- limit = v->channels * 4096;
- *channels = v->channels;
- offset = data_len = 0;
- total = limit;
- data = (short *) malloc(total * sizeof(*data));
- if (data == NULL) {
- stb_vorbis_close(v);
- return -2;
- }
- for (;;) {
- int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset);
- if (n == 0) break;
- data_len += n;
- offset += n * v->channels;
- if (offset + limit > total) {
- short *data2;
- total *= 2;
- data2 = (short *) realloc(data, total * sizeof(*data));
- if (data2 == NULL) {
- free(data);
- stb_vorbis_close(v);
- return -2;
- }
- data = data2;
- }
- }
- *output = data;
- return data_len;
-}
-#endif // NO_STDIO
-
-int stb_vorbis_decode_memory(uint8 *mem, int len, int *channels, short **output)
-{
- int data_len, offset, total, limit, error;
- short *data;
- stb_vorbis *v = stb_vorbis_open_memory(mem, len, &error, NULL);
- if (v == NULL) return -1;
- limit = v->channels * 4096;
- *channels = v->channels;
- offset = data_len = 0;
- total = limit;
- data = (short *) malloc(total * sizeof(*data));
- if (data == NULL) {
- stb_vorbis_close(v);
- return -2;
- }
- for (;;) {
- int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset);
- if (n == 0) break;
- data_len += n;
- offset += n * v->channels;
- if (offset + limit > total) {
- short *data2;
- total *= 2;
- data2 = (short *) realloc(data, total * sizeof(*data));
- if (data2 == NULL) {
- free(data);
- stb_vorbis_close(v);
- return -2;
- }
- data = data2;
- }
- }
- *output = data;
- return data_len;
-}
-#endif
-
-int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats)
-{
- float **outputs;
- int len = num_floats / channels;
- int n=0;
- int z = f->channels;
- if (z > channels) z = channels;
- while (n < len) {
- int i,j;
- int k = f->channel_buffer_end - f->channel_buffer_start;
- if (n+k >= len) k = len - n;
- for (j=0; j < k; ++j) {
- for (i=0; i < z; ++i)
- *buffer++ = f->channel_buffers[i][f->channel_buffer_start+j];
- for ( ; i < channels; ++i)
- *buffer++ = 0;
- }
- n += k;
- f->channel_buffer_start += k;
- if (n == len) break;
- if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;
- }
- return n;
-}
-
-int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples)
-{
- float **outputs;
- int n=0;
- int z = f->channels;
- if (z > channels) z = channels;
- while (n < num_samples) {
- int i;
- int k = f->channel_buffer_end - f->channel_buffer_start;
- if (n+k >= num_samples) k = num_samples - n;
- if (k) {
- for (i=0; i < z; ++i)
- memcpy(buffer[i]+n, f->channel_buffers+f->channel_buffer_start, sizeof(float)*k);
- for ( ; i < channels; ++i)
- memset(buffer[i]+n, 0, sizeof(float) * k);
- }
- n += k;
- f->channel_buffer_start += k;
- if (n == num_samples) break;
- if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;
- }
- return n;
-}
-#endif // STB_VORBIS_NO_PULLDATA_API
-
-#endif // STB_VORBIS_HEADER_ONLY
diff --git a/src/SFML/Audio/stb_vorbis/stb_vorbis.h b/src/SFML/Audio/stb_vorbis/stb_vorbis.h
deleted file mode 100755
index e2355e6..0000000
--- a/src/SFML/Audio/stb_vorbis/stb_vorbis.h
+++ /dev/null
@@ -1,357 +0,0 @@
-// Ogg Vorbis I audio decoder -- version 0.99994
-//
-// Written in April 2007 by Sean Barrett, sponsored by RAD Game Tools.
-//
-// Placed in the public domain April 2007 by the author: no copyright is
-// claimed, and you may use it for any purpose you like.
-//
-// No warranty for any purpose is expressed or implied by the author (nor
-// by RAD Game Tools). Report bugs and send enhancements to the author.
-//
-// Get the latest version and other information at:
-// http://nothings.org/stb_vorbis/
-
-
-// Todo:
-//
-// - seeking (note you can seek yourself using the pushdata API)
-//
-// Limitations:
-//
-// - floor 0 not supported (used in old ogg vorbis files)
-// - lossless sample-truncation at beginning ignored
-// - cannot concatenate multiple vorbis streams
-// - sample positions are 32-bit, limiting seekable 192Khz
-// files to around 6 hours (Ogg supports 64-bit)
-//
-// All of these limitations may be removed in future versions.
-
-
-//////////////////////////////////////////////////////////////////////////////
-//
-// HEADER BEGINS HERE
-//
-
-#ifndef STB_VORBIS_INCLUDE_STB_VORBIS_H
-#define STB_VORBIS_INCLUDE_STB_VORBIS_H
-
-#if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO)
-#define STB_VORBIS_NO_STDIO 1
-#endif
-
-#ifndef STB_VORBIS_NO_STDIO
-#include <stdio.h>
-#endif
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/////////// THREAD SAFETY
-
-// Individual stb_vorbis* handles are not thread-safe; you cannot decode from
-// them from multiple threads at the same time. However, you can have multiple
-// stb_vorbis* handles and decode from them independently in multiple thrads.
-
-
-/////////// MEMORY ALLOCATION
-
-// normally stb_vorbis uses malloc() to allocate memory at startup,
-// and alloca() to allocate temporary memory during a frame on the
-// stack. (Memory consumption will depend on the amount of setup
-// data in the file and how you set the compile flags for speed
-// vs. size. In my test files the maximal-size usage is ~150KB.)
-//
-// You can modify the wrapper functions in the source (setup_malloc,
-// setup_temp_malloc, temp_malloc) to change this behavior, or you
-// can use a simpler allocation model: you pass in a buffer from
-// which stb_vorbis will allocate _all_ its memory (including the
-// temp memory). "open" may fail with a VORBIS_outofmem if you
-// do not pass in enough data; there is no way to determine how
-// much you do need except to succeed (at which point you can
-// query get_info to find the exact amount required. yes I know
-// this is lame).
-//
-// If you pass in a non-NULL buffer of the type below, allocation
-// will occur from it as described above. Otherwise just pass NULL
-// to use malloc()/alloca()
-
-typedef struct
-{
- char *alloc_buffer;
- int alloc_buffer_length_in_bytes;
-} stb_vorbis_alloc;
-
-
-/////////// FUNCTIONS USEABLE WITH ALL INPUT MODES
-
-typedef struct stb_vorbis stb_vorbis;
-
-typedef struct
-{
- unsigned int sample_rate;
- int channels;
-
- unsigned int setup_memory_required;
- unsigned int setup_temp_memory_required;
- unsigned int temp_memory_required;
-
- int max_frame_size;
-} stb_vorbis_info;
-
-// get general information about the file
-extern stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f);
-
-// get the last error detected (clears it, too)
-extern int stb_vorbis_get_error(stb_vorbis *f);
-
-// close an ogg vorbis file and free all memory in use
-extern void stb_vorbis_close(stb_vorbis *f);
-
-// this function returns the offset (in samples) from the beginning of the
-// file that will be returned by the next decode, if it is known, or -1
-// otherwise. after a flush_pushdata() call, this may take a while before
-// it becomes valid again.
-// NOT WORKING YET after a seek with PULLDATA API
-extern int stb_vorbis_get_sample_offset(stb_vorbis *f);
-
-// returns the current seek point within the file, or offset from the beginning
-// of the memory buffer. In pushdata mode it returns 0.
-extern unsigned int stb_vorbis_get_file_offset(stb_vorbis *f);
-
-/////////// PUSHDATA API
-
-#ifndef STB_VORBIS_NO_PUSHDATA_API
-
-// this API allows you to get blocks of data from any source and hand
-// them to stb_vorbis. you have to buffer them; stb_vorbis will tell
-// you how much it used, and you have to give it the rest next time;
-// and stb_vorbis may not have enough data to work with and you will
-// need to give it the same data again PLUS more. Note that the Vorbis
-// specification does not bound the size of an individual frame.
-
-extern stb_vorbis *stb_vorbis_open_pushdata(
- unsigned char *datablock, int datablock_length_in_bytes,
- int *datablock_memory_consumed_in_bytes,
- int *error,
- stb_vorbis_alloc *alloc_buffer);
-// create a vorbis decoder by passing in the initial data block containing
-// the ogg&vorbis headers (you don't need to do parse them, just provide
-// the first N bytes of the file--you're told if it's not enough, see below)
-// on success, returns an stb_vorbis *, does not set error, returns the amount of
-// data parsed/consumed on this call in *datablock_memory_consumed_in_bytes;
-// on failure, returns NULL on error and sets *error, does not change *datablock_memory_consumed
-// if returns NULL and *error is VORBIS_need_more_data, then the input block was
-// incomplete and you need to pass in a larger block from the start of the file
-
-extern int stb_vorbis_decode_frame_pushdata(
- stb_vorbis *f, unsigned char *datablock, int datablock_length_in_bytes,
- int *channels, // place to write number of float * buffers
- float ***output, // place to write float ** array of float * buffers
- int *samples // place to write number of output samples
- );
-// decode a frame of audio sample data if possible from the passed-in data block
-//
-// return value: number of bytes we used from datablock
-// possible cases:
-// 0 bytes used, 0 samples output (need more data)
-// N bytes used, 0 samples output (resynching the stream, keep going)
-// N bytes used, M samples output (one frame of data)
-// note that after opening a file, you will ALWAYS get one N-bytes,0-sample
-// frame, because Vorbis always "discards" the first frame.
-//
-// Note that on resynch, stb_vorbis will rarely consume all of the buffer,
-// instead only datablock_length_in_bytes-3 or less. This is because it wants
-// to avoid missing parts of a page header if they cross a datablock boundary,
-// without writing state-machiney code to record a partial detection.
-//
-// The number of channels returned are stored in *channels (which can be
-// NULL--it is always the same as the number of channels reported by
-// get_info). *output will contain an array of float* buffers, one per
-// channel. In other words, (*output)[0][0] contains the first sample from
-// the first channel, and (*output)[1][0] contains the first sample from
-// the second channel.
-
-extern void stb_vorbis_flush_pushdata(stb_vorbis *f);
-// inform stb_vorbis that your next datablock will not be contiguous with
-// previous ones (e.g. you've seeked in the data); future attempts to decode
-// frames will cause stb_vorbis to resynchronize (as noted above), and
-// once it sees a valid Ogg page (typically 4-8KB, as large as 64KB), it
-// will begin decoding the _next_ frame.
-//
-// if you want to seek using pushdata, you need to seek in your file, then
-// call stb_vorbis_flush_pushdata(), then start calling decoding, then once
-// decoding is returning you data, call stb_vorbis_get_sample_offset, and
-// if you don't like the result, seek your file again and repeat.
-#endif
-
-
-////////// PULLING INPUT API
-
-#ifndef STB_VORBIS_NO_PULLDATA_API
-// This API assumes stb_vorbis is allowed to pull data from a source--
-// either a block of memory containing the _entire_ vorbis stream, or a
-// FILE * that you or it create, or possibly some other reading mechanism
-// if you go modify the source to replace the FILE * case with some kind
-// of callback to your code. (But if you don't support seeking, you may
-// just want to go ahead and use pushdata.)
-
-#if !defined(STB_VORBIS_NO_STDIO) && !defined(STB_VORBIS_NO_INTEGER_CONVERSION)
-extern int stb_vorbis_decode_filename(char *filename, int *channels, short **output);
-#endif
-extern int stb_vorbis_decode_memory(unsigned char *mem, int len, int *channels, short **output);
-// decode an entire file and output the data interleaved into a malloc()ed
-// buffer stored in *output. The return value is the number of samples
-// decoded, or -1 if the file could not be opened or was not an ogg vorbis file.
-// When you're done with it, just free() the pointer returned in *output.
-
-extern stb_vorbis * stb_vorbis_open_memory(unsigned char *data, int len,
- int *error, stb_vorbis_alloc *alloc_buffer);
-// create an ogg vorbis decoder from an ogg vorbis stream in memory (note
-// this must be the entire stream!). on failure, returns NULL and sets *error
-
-#ifndef STB_VORBIS_NO_STDIO
-extern stb_vorbis * stb_vorbis_open_filename(char *filename,
- int *error, stb_vorbis_alloc *alloc_buffer);
-// create an ogg vorbis decoder from a filename via fopen(). on failure,
-// returns NULL and sets *error (possibly to VORBIS_file_open_failure).
-
-extern stb_vorbis * stb_vorbis_open_file(FILE *f, int close_handle_on_close,
- int *error, stb_vorbis_alloc *alloc_buffer);
-// create an ogg vorbis decoder from an open FILE *, looking for a stream at
-// the _current_ seek point (ftell). on failure, returns NULL and sets *error.
-// note that stb_vorbis must "own" this stream; if you seek it in between
-// calls to stb_vorbis, it will become confused. Morever, if you attempt to
-// perform stb_vorbis_seek_*() operations on this file, it will assume it
-// owns the _entire_ rest of the file after the start point. Use the next
-// function, stb_vorbis_open_file_section(), to limit it.
-
-extern stb_vorbis * stb_vorbis_open_file_section(FILE *f, int close_handle_on_close,
- int *error, stb_vorbis_alloc *alloc_buffer, unsigned int len);
-// create an ogg vorbis decoder from an open FILE *, looking for a stream at
-// the _current_ seek point (ftell); the stream will be of length 'len' bytes.
-// on failure, returns NULL and sets *error. note that stb_vorbis must "own"
-// this stream; if you seek it in between calls to stb_vorbis, it will become
-// confused.
-#endif
-
-extern int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number);
-extern int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number);
-// NOT WORKING YET
-// these functions seek in the Vorbis file to (approximately) 'sample_number'.
-// after calling seek_frame(), the next call to get_frame_*() will include
-// the specified sample. after calling stb_vorbis_seek(), the next call to
-// stb_vorbis_get_samples_* will start with the specified sample. If you
-// do not need to seek to EXACTLY the target sample when using get_samples_*,
-// you can also use seek_frame().
-
-extern void stb_vorbis_seek_start(stb_vorbis *f);
-// this function is equivalent to stb_vorbis_seek(f,0), but it
-// actually works
-
-extern unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f);
-extern float stb_vorbis_stream_length_in_seconds(stb_vorbis *f);
-// these functions return the total length of the vorbis stream
-
-extern int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output);
-// decode the next frame and return the number of samples. the number of
-// channels returned are stored in *channels (which can be NULL--it is always
-// the same as the number of channels reported by get_info). *output will
-// contain an array of float* buffers, one per channel. These outputs will
-// be overwritten on the next call to stb_vorbis_get_frame_*.
-//
-// You generally should not intermix calls to stb_vorbis_get_frame_*()
-// and stb_vorbis_get_samples_*(), since the latter calls the former.
-
-#ifndef STB_VORBIS_NO_INTEGER_CONVERSION
-extern int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts);
-extern int stb_vorbis_get_frame_short (stb_vorbis *f, int num_c, short **buffer, int num_samples);
-#endif
-// decode the next frame and return the number of samples per channel. the
-// data is coerced to the number of channels you request according to the
-// channel coercion rules (see below). You must pass in the size of your
-// buffer(s) so that stb_vorbis will not overwrite the end of the buffer.
-// The maximum buffer size needed can be gotten from get_info(); however,
-// the Vorbis I specification implies an absolute maximum of 4096 samples
-// per channel. Note that for interleaved data, you pass in the number of
-// shorts (the size of your array), but the return value is the number of
-// samples per channel, not the total number of samples.
-
-// Channel coercion rules:
-// Let M be the number of channels requested, and N the number of channels present,
-// and Cn be the nth channel; let stereo L be the sum of all L and center channels,
-// and stereo R be the sum of all R and center channels (channel assignment from the
-// vorbis spec).
-// M N output
-// 1 k sum(Ck) for all k
-// 2 * stereo L, stereo R
-// k l k > l, the first l channels, then 0s
-// k l k <= l, the first k channels
-// Note that this is not _good_ surround etc. mixing at all! It's just so
-// you get something useful.
-
-extern int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats);
-extern int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples);
-// gets num_samples samples, not necessarily on a frame boundary--this requires
-// buffering so you have to supply the buffers. DOES NOT APPLY THE COERCION RULES.
-// Returns the number of samples stored per channel; it may be less than requested
-// at the end of the file. If there are no more samples in the file, returns 0.
-
-#ifndef STB_VORBIS_NO_INTEGER_CONVERSION
-extern int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts);
-extern int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int num_samples);
-#endif
-// gets num_samples samples, not necessarily on a frame boundary--this requires
-// buffering so you have to supply the buffers. Applies the coercion rules above
-// to produce 'channels' channels. Returns the number of samples stored per channel;
-// it may be less than requested at the end of the file. If there are no more
-// samples in the file, returns 0.
-
-#endif
-
-//////// ERROR CODES
-
-enum STBVorbisError
-{
- VORBIS__no_error,
-
- VORBIS_need_more_data=1, // not a real error
-
- VORBIS_invalid_api_mixing, // can't mix API modes
- VORBIS_outofmem, // not enough memory
- VORBIS_feature_not_supported, // uses floor 0
- VORBIS_too_many_channels, // STB_VORBIS_MAX_CHANNELS is too small
- VORBIS_file_open_failure, // fopen() failed
- VORBIS_seek_without_length, // can't seek in unknown-length file
-
- VORBIS_unexpected_eof=10, // file is truncated?
- VORBIS_seek_invalid, // seek past EOF
-
- // decoding errors (corrupt/invalid stream) -- you probably
- // don't care about the exact details of these
-
- // vorbis errors:
- VORBIS_invalid_setup=20,
- VORBIS_invalid_stream,
-
- // ogg errors:
- VORBIS_missing_capture_pattern=30,
- VORBIS_invalid_stream_structure_version,
- VORBIS_continued_packet_flag_invalid,
- VORBIS_incorrect_stream_serial_number,
- VORBIS_invalid_first_page,
- VORBIS_bad_packet_type,
- VORBIS_cant_find_last_page,
- VORBIS_seek_failed
-};
-
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // STB_VORBIS_INCLUDE_STB_VORBIS_H
-//
-// HEADER ENDS HERE
-//
-//////////////////////////////////////////////////////////////////////////////
diff --git a/src/SFML/CMakeLists.txt b/src/SFML/CMakeLists.txt
new file mode 100644
index 0000000..a3fb4d9
--- /dev/null
+++ b/src/SFML/CMakeLists.txt
@@ -0,0 +1,45 @@
+
+# include the SFML specific macros
+include(${PROJECT_SOURCE_DIR}/cmake/Macros.cmake)
+
+# let CMake know about our additional libraries paths (on Windows and OS X)
+if (WINDOWS)
+ set(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} "${PROJECT_SOURCE_DIR}/extlibs/headers")
+ if(COMPILER_GCC)
+ if(ARCH_32BITS)
+ set(CMAKE_LIBRARY_PATH ${CMAKE_LIBRARY_PATH} "${PROJECT_SOURCE_DIR}/extlibs/libs-mingw/x86")
+ set(CMAKE_LIBRARY_PATH ${CMAKE_LIBRARY_PATH} "${PROJECT_SOURCE_DIR}/extlibs/bin/x86")
+ elseif(ARCH_64BITS)
+ set(CMAKE_LIBRARY_PATH ${CMAKE_LIBRARY_PATH} "${PROJECT_SOURCE_DIR}/extlibs/libs-mingw/x64")
+ set(CMAKE_LIBRARY_PATH ${CMAKE_LIBRARY_PATH} "${PROJECT_SOURCE_DIR}/extlibs/bin/x64")
+ endif()
+ elseif(COMPILER_MSVC)
+ if(ARCH_32BITS)
+ set(CMAKE_LIBRARY_PATH ${CMAKE_LIBRARY_PATH} "${PROJECT_SOURCE_DIR}/extlibs/libs-msvc/x86")
+ elseif(ARCH_64BITS)
+ set(CMAKE_LIBRARY_PATH ${CMAKE_LIBRARY_PATH} "${PROJECT_SOURCE_DIR}/extlibs/libs-msvc/x64")
+ endif()
+ endif()
+elseif(MACOSX)
+ set(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} "${PROJECT_SOURCE_DIR}/extlibs/headers")
+ set(CMAKE_LIBRARY_PATH ${CMAKE_LIBRARY_PATH} "${PROJECT_SOURCE_DIR}/extlibs/libs-osx/lib/")
+endif()
+
+# add the SFML sources path
+include_directories(${PROJECT_SOURCE_DIR}/src)
+
+# define the path of our additional CMake modules
+set(CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake/Modules/")
+
+# set the output directory for SFML libraries
+set(LIBRARY_OUTPUT_PATH "${PROJECT_BINARY_DIR}/lib")
+
+# add the modules subdirectories
+add_subdirectory(System)
+add_subdirectory(Window)
+add_subdirectory(Network)
+add_subdirectory(Graphics)
+add_subdirectory(Audio)
+if(WINDOWS)
+ add_subdirectory(Main)
+endif()
diff --git a/src/SFML/Graphics/CMakeLists.txt b/src/SFML/Graphics/CMakeLists.txt
new file mode 100644
index 0000000..ba74b71
--- /dev/null
+++ b/src/SFML/Graphics/CMakeLists.txt
@@ -0,0 +1,135 @@
+
+set(INCROOT ${PROJECT_SOURCE_DIR}/include/SFML/Graphics)
+set(SRCROOT ${PROJECT_SOURCE_DIR}/src/SFML/Graphics)
+
+# all source files
+set(SRC
+ ${INCROOT}/BlendMode.hpp
+ ${SRCROOT}/Color.cpp
+ ${INCROOT}/Color.hpp
+ ${INCROOT}/Export.hpp
+ ${SRCROOT}/Font.cpp
+ ${INCROOT}/Font.hpp
+ ${INCROOT}/Glyph.hpp
+ ${SRCROOT}/GLCheck.cpp
+ ${SRCROOT}/GLCheck.hpp
+ ${SRCROOT}/Image.cpp
+ ${INCROOT}/Image.hpp
+ ${SRCROOT}/ImageLoader.cpp
+ ${SRCROOT}/ImageLoader.hpp
+ ${INCROOT}/PrimitiveType.hpp
+ ${INCROOT}/Rect.hpp
+ ${INCROOT}/Rect.inl
+ ${SRCROOT}/RenderStates.cpp
+ ${INCROOT}/RenderStates.hpp
+ ${SRCROOT}/RenderTexture.cpp
+ ${INCROOT}/RenderTexture.hpp
+ ${SRCROOT}/RenderTarget.cpp
+ ${INCROOT}/RenderTarget.hpp
+ ${SRCROOT}/RenderWindow.cpp
+ ${INCROOT}/RenderWindow.hpp
+ ${SRCROOT}/Shader.cpp
+ ${INCROOT}/Shader.hpp
+ ${SRCROOT}/Texture.cpp
+ ${INCROOT}/Texture.hpp
+ ${SRCROOT}/TextureSaver.cpp
+ ${SRCROOT}/TextureSaver.hpp
+ ${SRCROOT}/Transform.cpp
+ ${INCROOT}/Transform.hpp
+ ${SRCROOT}/Transformable.cpp
+ ${INCROOT}/Transformable.hpp
+ ${SRCROOT}/View.cpp
+ ${INCROOT}/View.hpp
+ ${SRCROOT}/Vertex.cpp
+ ${INCROOT}/Vertex.hpp
+)
+source_group("" FILES ${SRC})
+
+# drawables sources
+set(DRAWABLES_SRC
+ ${INCROOT}/Drawable.hpp
+ ${SRCROOT}/Shape.cpp
+ ${INCROOT}/Shape.hpp
+ ${SRCROOT}/CircleShape.cpp
+ ${INCROOT}/CircleShape.hpp
+ ${SRCROOT}/RectangleShape.cpp
+ ${INCROOT}/RectangleShape.hpp
+ ${SRCROOT}/ConvexShape.cpp
+ ${INCROOT}/ConvexShape.hpp
+ ${SRCROOT}/Sprite.cpp
+ ${INCROOT}/Sprite.hpp
+ ${SRCROOT}/Text.cpp
+ ${INCROOT}/Text.hpp
+ ${SRCROOT}/VertexArray.cpp
+ ${INCROOT}/VertexArray.hpp
+)
+source_group("drawables" FILES ${DRAWABLES_SRC})
+
+# render-texture sources
+set(RENDER_TEXTURE_SRC
+ ${SRCROOT}/RenderTextureImpl.cpp
+ ${SRCROOT}/RenderTextureImpl.hpp
+ ${SRCROOT}/RenderTextureImplFBO.cpp
+ ${SRCROOT}/RenderTextureImplFBO.hpp
+ ${SRCROOT}/RenderTextureImplDefault.cpp
+ ${SRCROOT}/RenderTextureImplDefault.hpp
+)
+source_group("render texture" FILES ${RENDER_TEXTURE_SRC})
+
+# stb_image sources
+set(STB_SRC
+ ${SRCROOT}/stb_image/stb_image.h
+ ${SRCROOT}/stb_image/stb_image_write.h
+)
+source_group("stb_image" FILES ${STB_SRC})
+
+# let CMake know about our additional graphics libraries paths (on Windows and OSX)
+if(WINDOWS OR MACOSX)
+ set(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} "${PROJECT_SOURCE_DIR}/extlibs/headers/jpeg")
+endif()
+
+if(WINDOWS)
+ set(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} "${PROJECT_SOURCE_DIR}/extlibs/headers/libfreetype/windows")
+ set(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} "${PROJECT_SOURCE_DIR}/extlibs/headers/libfreetype/windows/freetype")
+elseif(MACOSX)
+ set(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} "${PROJECT_SOURCE_DIR}/extlibs/headers/libfreetype/osx")
+ set(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} "${PROJECT_SOURCE_DIR}/extlibs/headers/libfreetype/osx/freetype2")
+ set(CMAKE_LIBRARY_PATH ${CMAKE_LIBRARY_PATH} "${PROJECT_SOURCE_DIR}/extlibs/libs-osx/Frameworks")
+endif()
+
+# find external libraries
+find_package(OpenGL REQUIRED)
+find_package(Freetype REQUIRED)
+find_package(GLEW REQUIRED)
+find_package(JPEG REQUIRED)
+if(LINUX)
+ find_package(X11 REQUIRED)
+endif()
+
+# add include paths of external libraries
+include_directories(${FREETYPE_INCLUDE_DIRS} ${GLEW_INCLUDE_PATH} ${JPEG_INCLUDE_DIR} ${OPENGL_INCLUDE_DIR})
+
+# build the list of libraries to link
+# GL and X11 are only needed for shared build, as they are already linked by sfml-window
+set(GRAPHICS_EXT_LIBS ${FREETYPE_LIBRARY} ${GLEW_LIBRARY} ${JPEG_LIBRARY})
+if(BUILD_SHARED_LIBS)
+ set(GRAPHICS_EXT_LIBS ${GRAPHICS_EXT_LIBS} ${OPENGL_gl_LIBRARY})
+ if(LINUX)
+ set(GRAPHICS_EXT_LIBS ${GRAPHICS_EXT_LIBS} ${X11_LIBRARIES})
+ endif()
+endif()
+
+# add preprocessor symbols
+add_definitions(-DGLEW_STATIC -DSTBI_FAILURE_USERMSG)
+
+# ImageLoader.cpp must be compiled with the -fno-strict-aliasing
+# when gcc is used; otherwise saving PNGs may crash in stb_image_write
+if(COMPILER_GCC)
+ set_source_files_properties(${SRCROOT}/ImageLoader.cpp PROPERTIES COMPILE_FLAGS -fno-strict-aliasing)
+endif()
+
+# define the sfml-graphics target
+sfml_add_library(sfml-graphics
+ SOURCES ${SRC} ${DRAWABLES_SRC} ${RENDER_TEXTURE_SRC} ${STB_SRC}
+ DEPENDS sfml-window sfml-system
+ EXTERNAL_LIBS ${GRAPHICS_EXT_LIBS})
diff --git a/src/SFML/Graphics/CircleShape.cpp b/src/SFML/Graphics/CircleShape.cpp
new file mode 100644
index 0000000..23e9e77
--- /dev/null
+++ b/src/SFML/Graphics/CircleShape.cpp
@@ -0,0 +1,84 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Graphics/CircleShape.hpp>
+#include <cmath>
+
+
+namespace sf
+{
+////////////////////////////////////////////////////////////
+CircleShape::CircleShape(float radius, unsigned int pointCount) :
+m_radius (radius),
+m_pointCount(pointCount)
+{
+ update();
+}
+
+
+////////////////////////////////////////////////////////////
+void CircleShape::setRadius(float radius)
+{
+ m_radius = radius;
+ update();
+}
+
+
+////////////////////////////////////////////////////////////
+float CircleShape::getRadius() const
+{
+ return m_radius;
+}
+
+
+////////////////////////////////////////////////////////////
+void CircleShape::setPointCount(unsigned int count)
+{
+ m_pointCount = count;
+ update();
+}
+
+////////////////////////////////////////////////////////////
+unsigned int CircleShape::getPointCount() const
+{
+ return m_pointCount;
+}
+
+
+////////////////////////////////////////////////////////////
+Vector2f CircleShape::getPoint(unsigned int index) const
+{
+ static const float pi = 3.141592654f;
+
+ float angle = index * 2 * pi / m_pointCount - pi / 2;
+ float x = std::cos(angle) * m_radius;
+ float y = std::sin(angle) * m_radius;
+
+ return Vector2f(m_radius + x, m_radius + y);
+}
+
+} // namespace sf
diff --git a/src/SFML/Graphics/Color.cpp b/src/SFML/Graphics/Color.cpp
index 48b043d..d016a9d 100755..100644
--- a/src/SFML/Graphics/Color.cpp
+++ b/src/SFML/Graphics/Color.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -42,11 +42,10 @@ const Color Color::Blue(0, 0, 255);
const Color Color::Yellow(255, 255, 0);
const Color Color::Magenta(255, 0, 255);
const Color Color::Cyan(0, 255, 255);
+const Color Color::Transparent(0, 0, 0, 0);
////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
Color::Color() :
r(0),
g(0),
@@ -58,85 +57,64 @@ a(255)
////////////////////////////////////////////////////////////
-/// Construct the color from its 4 RGBA components
-////////////////////////////////////////////////////////////
-Color::Color(Uint8 R, Uint8 G, Uint8 B, Uint8 A) :
-r(R),
-g(G),
-b(B),
-a(A)
+Color::Color(Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha) :
+r(red),
+g(green),
+b(blue),
+a(alpha)
{
}
////////////////////////////////////////////////////////////
-/// Operator += overload to add a color
-////////////////////////////////////////////////////////////
-Color& Color::operator +=(const Color& Other)
+bool operator ==(const Color& left, const Color& right)
{
- r = static_cast<Uint8>(std::min(r + Other.r, 255));
- g = static_cast<Uint8>(std::min(g + Other.g, 255));
- b = static_cast<Uint8>(std::min(b + Other.b, 255));
- a = static_cast<Uint8>(std::min(a + Other.a, 255));
-
- return *this;
+ return (left.r == right.r) &&
+ (left.g == right.g) &&
+ (left.b == right.b) &&
+ (left.a == right.a);
}
////////////////////////////////////////////////////////////
-/// Operator *= overload to modulate a color
-////////////////////////////////////////////////////////////
-Color& Color::operator *=(const Color& Other)
+bool operator !=(const Color& left, const Color& right)
{
- r = static_cast<Uint8>(r * Other.r / 255);
- g = static_cast<Uint8>(g * Other.g / 255);
- b = static_cast<Uint8>(b * Other.b / 255);
- a = static_cast<Uint8>(a * Other.a / 255);
-
- return *this;
+ return !(left == right);
}
////////////////////////////////////////////////////////////
-/// Compare two colors (for equality)
-////////////////////////////////////////////////////////////
-bool Color::operator ==(const Color& Other) const
+Color operator +(const Color& left, const Color& right)
{
- return (r == Other.r) && (g == Other.g) && (b == Other.b) && (a == Other.a);
+ return Color(static_cast<Uint8>(std::min(left.r + right.r, 255)),
+ static_cast<Uint8>(std::min(left.g + right.g, 255)),
+ static_cast<Uint8>(std::min(left.b + right.b, 255)),
+ static_cast<Uint8>(std::min(left.a + right.a, 255)));
}
////////////////////////////////////////////////////////////
-/// Compare two colors (for difference)
-////////////////////////////////////////////////////////////
-bool Color::operator !=(const Color& Other) const
+Color operator *(const Color& left, const Color& right)
{
- return (r != Other.r) || (g != Other.g) || (b != Other.b) || (a != Other.a);
+ return Color(static_cast<Uint8>(left.r * right.r / 255),
+ static_cast<Uint8>(left.g * right.g / 255),
+ static_cast<Uint8>(left.b * right.b / 255),
+ static_cast<Uint8>(left.a * right.a / 255));
}
////////////////////////////////////////////////////////////
-/// Operator + overload to add two colors
-////////////////////////////////////////////////////////////
-Color operator +(const Color& Color1, const Color& Color2)
+Color& operator +=(Color& left, const Color& right)
{
- Color c = Color1;
- c += Color2;
-
- return c;
+ return left = left + right;
}
////////////////////////////////////////////////////////////
-/// Operator * overload to modulate two colors
-////////////////////////////////////////////////////////////
-Color operator *(const Color& Color1, const Color& Color2)
+Color& operator *=(Color& left, const Color& right)
{
- Color c = Color1;
- c *= Color2;
-
- return c;
+ return left = left * right;
}
} // namespace sf
diff --git a/src/SFML/System/Unix/Mutex.cpp b/src/SFML/Graphics/ConvexShape.cpp
index 9614361..a5ad0e5 100755..100644
--- a/src/SFML/System/Unix/Mutex.cpp
+++ b/src/SFML/Graphics/ConvexShape.cpp
@@ -1,68 +1,69 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/System/Unix/Mutex.hpp>
-
-
-namespace sf
-{
-////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
-Mutex::Mutex()
-{
- pthread_mutex_init(&myMutex, NULL);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Destructor
-////////////////////////////////////////////////////////////
-Mutex::~Mutex()
-{
- pthread_mutex_destroy(&myMutex);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Lock the mutex
-////////////////////////////////////////////////////////////
-void Mutex::Lock()
-{
- pthread_mutex_lock(&myMutex);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Unlock the mutex
-////////////////////////////////////////////////////////////
-void Mutex::Unlock()
-{
- pthread_mutex_unlock(&myMutex);
-}
-
-} // namespace sf
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Graphics/ConvexShape.hpp>
+
+
+namespace sf
+{
+////////////////////////////////////////////////////////////
+ConvexShape::ConvexShape(unsigned int pointCount)
+{
+ setPointCount(pointCount);
+}
+
+
+////////////////////////////////////////////////////////////
+void ConvexShape::setPointCount(unsigned int count)
+{
+ m_points.resize(count);
+ update();
+}
+
+
+////////////////////////////////////////////////////////////
+unsigned int ConvexShape::getPointCount() const
+{
+ return static_cast<unsigned int>(m_points.size());
+}
+
+
+////////////////////////////////////////////////////////////
+void ConvexShape::setPoint(unsigned int index, const Vector2f& point)
+{
+ m_points[index] = point;
+ update();
+}
+
+
+////////////////////////////////////////////////////////////
+Vector2f ConvexShape::getPoint(unsigned int index) const
+{
+ return m_points[index];
+}
+
+} // namespace sf
diff --git a/src/SFML/Graphics/Drawable.cpp b/src/SFML/Graphics/Drawable.cpp
deleted file mode 100755
index 7ff5d09..0000000
--- a/src/SFML/Graphics/Drawable.cpp
+++ /dev/null
@@ -1,402 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Graphics/Drawable.hpp>
-#include <SFML/Graphics/GraphicsContext.hpp>
-#include <SFML/Window/Window.hpp>
-#include <math.h>
-
-
-namespace sf
-{
-////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
-Drawable::Drawable(const Vector2f& Position, const Vector2f& Scale, float Rotation, const Color& Col) :
-myPosition (Position),
-myScale (Scale),
-myCenter (0, 0),
-myRotation (Rotation),
-myColor (Col),
-myBlendMode (Blend::Alpha),
-myNeedUpdate (true),
-myInvNeedUpdate(true)
-{
-
-}
-
-
-////////////////////////////////////////////////////////////
-/// Virtual destructor
-////////////////////////////////////////////////////////////
-Drawable::~Drawable()
-{
- // Nothing to do
-}
-
-
-////////////////////////////////////////////////////////////
-/// Set the position of the object (take 2 values)
-////////////////////////////////////////////////////////////
-void Drawable::SetPosition(float X, float Y)
-{
- SetX(X);
- SetY(Y);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Set the position of the object (take a 2D vector)
-////////////////////////////////////////////////////////////
-void Drawable::SetPosition(const Vector2f& Position)
-{
- SetX(Position.x);
- SetY(Position.y);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Set the X position of the object
-////////////////////////////////////////////////////////////
-void Drawable::SetX(float X)
-{
- myPosition.x = X;
- myNeedUpdate = true;
- myInvNeedUpdate = true;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Set the Y position of the object
-////////////////////////////////////////////////////////////
-void Drawable::SetY(float Y)
-{
- myPosition.y = Y;
- myNeedUpdate = true;
- myInvNeedUpdate = true;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Set the scale of the object (take 2 values)
-////////////////////////////////////////////////////////////
-void Drawable::SetScale(float ScaleX, float ScaleY)
-{
- SetScaleX(ScaleX);
- SetScaleY(ScaleY);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Set the scale of the object (take a 2D vector)
-////////////////////////////////////////////////////////////
-void Drawable::SetScale(const Vector2f& Scale)
-{
- SetScaleX(Scale.x);
- SetScaleY(Scale.y);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Set the X scale factor of the object
-////////////////////////////////////////////////////////////
-void Drawable::SetScaleX(float FactorX)
-{
- if (FactorX > 0)
- {
- myScale.x = FactorX;
- myNeedUpdate = true;
- myInvNeedUpdate = true;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Set the Y scale factor of the object
-////////////////////////////////////////////////////////////
-void Drawable::SetScaleY(float FactorY)
-{
- if (FactorY > 0)
- {
- myScale.y = FactorY;
- myNeedUpdate = true;
- myInvNeedUpdate = true;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Set the center of the object, in coordinates relative to the
-/// top-left of the object (take 2 values).
-/// The default center is (0, 0)
-////////////////////////////////////////////////////////////
-void Drawable::SetCenter(float CenterX, float CenterY)
-{
- myCenter.x = CenterX;
- myCenter.y = CenterY;
- myNeedUpdate = true;
- myInvNeedUpdate = true;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Set the center of the object, in coordinates relative to the
-/// top-left of the object (take a 2D vector).
-/// The default center is (0, 0)
-////////////////////////////////////////////////////////////
-void Drawable::SetCenter(const Vector2f& Center)
-{
- SetCenter(Center.x, Center.y);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Set the orientation of the object
-////////////////////////////////////////////////////////////
-void Drawable::SetRotation(float Rotation)
-{
- myRotation = static_cast<float>(fmod(Rotation, 360));
- if (myRotation < 0)
- myRotation += 360.f;
- myNeedUpdate = true;
- myInvNeedUpdate = true;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Set the color of the object.
-/// The default color is white
-////////////////////////////////////////////////////////////
-void Drawable::SetColor(const Color& Col)
-{
- myColor = Col;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Set the blending mode for the object.
-/// The default blend mode is Blend::Alpha
-////////////////////////////////////////////////////////////
-void Drawable::SetBlendMode(Blend::Mode Mode)
-{
- myBlendMode = Mode;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the position of the object
-////////////////////////////////////////////////////////////
-const Vector2f& Drawable::GetPosition() const
-{
- return myPosition;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the current scale of the object
-////////////////////////////////////////////////////////////
-const Vector2f& Drawable::GetScale() const
-{
- return myScale;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the center of the object
-////////////////////////////////////////////////////////////
-const Vector2f& Drawable::GetCenter() const
-{
- return myCenter;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the orientation of the object
-////////////////////////////////////////////////////////////
-float Drawable::GetRotation() const
-{
- return myRotation;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the color of the object
-////////////////////////////////////////////////////////////
-const Color& Drawable::GetColor() const
-{
- return myColor;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the current blending mode
-////////////////////////////////////////////////////////////
-Blend::Mode Drawable::GetBlendMode() const
-{
- return myBlendMode;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Move the object of a given offset (take 2 values)
-///
-////////////////////////////////////////////////////////////
-void Drawable::Move(float OffsetX, float OffsetY)
-{
- SetX(myPosition.x + OffsetX);
- SetY(myPosition.y + OffsetY);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Move the object of a given offset (take a 2D vector)
-////////////////////////////////////////////////////////////
-void Drawable::Move(const Vector2f& Offset)
-{
- Move(Offset.x, Offset.y);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Scale the object (take 2 values)
-////////////////////////////////////////////////////////////
-void Drawable::Scale(float FactorX, float FactorY)
-{
- SetScaleX(myScale.x * FactorX);
- SetScaleY(myScale.y * FactorY);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Scale the object (take a 2D vector)
-////////////////////////////////////////////////////////////
-void Drawable::Scale(const Vector2f& Factor)
-{
- Scale(Factor.x, Factor.y);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Rotate the object
-////////////////////////////////////////////////////////////
-void Drawable::Rotate(float Angle)
-{
- SetRotation(myRotation + Angle);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Transform a point from global coordinates into local coordinates
-/// (ie it applies the inverse of object's center, translation, rotation and scale to the point)
-////////////////////////////////////////////////////////////
-sf::Vector2f Drawable::TransformToLocal(const sf::Vector2f& Point) const
-{
- return GetInverseMatrix().Transform(Point);
-}
-
-////////////////////////////////////////////////////////////
-/// Transform a point from local coordinates into global coordinates
-/// (ie it applies the object's center, translation, rotation and scale to the point)
-////////////////////////////////////////////////////////////
-sf::Vector2f Drawable::TransformToGlobal(const sf::Vector2f& Point) const
-{
- return GetMatrix().Transform(Point);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the transform matrix of the drawable
-////////////////////////////////////////////////////////////
-const Matrix3& Drawable::GetMatrix() const
-{
- // First recompute it if needed
- if (myNeedUpdate)
- {
- myMatrix.SetFromTransformations(myCenter, myPosition, myRotation, myScale);
- myNeedUpdate = false;
- }
-
- return myMatrix;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the inverse transform matrix of the drawable
-////////////////////////////////////////////////////////////
-const Matrix3& Drawable::GetInverseMatrix() const
-{
- // First recompute it if needed
- if (myInvNeedUpdate)
- {
- myInvMatrix = GetMatrix().GetInverse();
- myInvNeedUpdate = false;
- }
-
- return myInvMatrix;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Draw the object into the specified window
-////////////////////////////////////////////////////////////
-void Drawable::Draw(RenderTarget& Target) const
-{
- // Save the current modelview matrix and set the new one
- GLCheck(glMatrixMode(GL_MODELVIEW));
- GLCheck(glPushMatrix());
- GLCheck(glMultMatrixf(GetMatrix().Get4x4Elements()));
-
- // Setup alpha-blending
- if (myBlendMode == Blend::None)
- {
- GLCheck(glDisable(GL_BLEND));
- }
- else
- {
- GLCheck(glEnable(GL_BLEND));
-
- switch (myBlendMode)
- {
- case Blend::Alpha : GLCheck(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)); break;
- case Blend::Add : GLCheck(glBlendFunc(GL_SRC_ALPHA, GL_ONE)); break;
- case Blend::Multiply : GLCheck(glBlendFunc(GL_DST_COLOR, GL_ZERO)); break;
- default : break;
- }
- }
-
- // Set color
- GLCheck(glColor4f(myColor.r / 255.f, myColor.g / 255.f, myColor.b / 255.f, myColor.a / 255.f));
-
- // Let the derived class render the object geometry
- Render(Target);
-
- // Restore the previous modelview matrix
- GLCheck(glMatrixMode(GL_MODELVIEW));
- GLCheck(glPopMatrix());
-}
-
-} // namespace sf
diff --git a/src/SFML/Graphics/Font.cpp b/src/SFML/Graphics/Font.cpp
index 36c4c28..8afe57e 100755..100644
--- a/src/SFML/Graphics/Font.cpp
+++ b/src/SFML/Graphics/Font.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -26,167 +26,574 @@
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Font.hpp>
-#include <SFML/Graphics/FontLoader.hpp>
-#include <iostream>
+#include <SFML/Graphics/GLCheck.hpp>
+#include <SFML/System/InputStream.hpp>
+#include <SFML/System/Err.hpp>
+#include <ft2build.h>
+#include FT_FREETYPE_H
+#include FT_GLYPH_H
+#include FT_OUTLINE_H
+#include FT_BITMAP_H
+#include <cstdlib>
+#include <cstring>
+
+
+namespace
+{
+ // FreeType callbacks that operate on a sf::InputStream
+ unsigned long read(FT_Stream rec, unsigned long offset, unsigned char* buffer, unsigned long count)
+ {
+ sf::InputStream* stream = static_cast<sf::InputStream*>(rec->descriptor.pointer);
+ if (static_cast<unsigned long>(stream->seek(offset)) == offset)
+ {
+ if (count > 0)
+ return static_cast<unsigned long>(stream->read(reinterpret_cast<char*>(buffer), count));
+ else
+ return 0;
+ }
+ else
+ return count > 0 ? 0 : 1; // error code is 0 if we're reading, or nonzero if we're seeking
+ }
+ void close(FT_Stream)
+ {
+ }
+}
namespace sf
{
////////////////////////////////////////////////////////////
-// Static member data
-////////////////////////////////////////////////////////////
-Uint32 Font::ourDefaultCharset[] =
+Font::Font() :
+m_library (NULL),
+m_face (NULL),
+m_streamRec(NULL),
+m_refCount (NULL)
{
- // Printable characters in ASCII range
- 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F,
- 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
- 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F,
- 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F,
- 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F,
- 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E,
- // Printable characters in extended ASCII range
- 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0x2A, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF,
- 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBF,
- 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF,
- 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF,
- 0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF,
- 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE,
-
- // To make it a valid string
- 0x00
-};
+}
////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
-Font::Font() :
-myCharSize(0)
+Font::Font(const Font& copy) :
+m_library (copy.m_library),
+m_face (copy.m_face),
+m_streamRec (copy.m_streamRec),
+m_refCount (copy.m_refCount),
+m_pages (copy.m_pages),
+m_pixelBuffer(copy.m_pixelBuffer)
{
+ // Note: as FreeType doesn't provide functions for copying/cloning,
+ // we must share all the FreeType pointers
+ if (m_refCount)
+ (*m_refCount)++;
}
////////////////////////////////////////////////////////////
-/// Load the font from a file
+Font::~Font()
+{
+ cleanup();
+}
+
+
////////////////////////////////////////////////////////////
-bool Font::LoadFromFile(const std::string& Filename, unsigned int CharSize, const Unicode::Text& Charset)
+bool Font::loadFromFile(const std::string& filename)
{
- // Clear the previous character map
- myGlyphs.clear();
+ // Cleanup the previous resources
+ cleanup();
+ m_refCount = new int(1);
+
+ // Initialize FreeType
+ // Note: we initialize FreeType for every font instance in order to avoid having a single
+ // global manager that would create a lot of issues regarding creation and destruction order.
+ FT_Library library;
+ if (FT_Init_FreeType(&library) != 0)
+ {
+ err() << "Failed to load font \"" << filename << "\" (failed to initialize FreeType)" << std::endl;
+ return false;
+ }
+ m_library = library;
- // Always add these special characters
- Unicode::UTF32String UTFCharset = Charset;
- if (UTFCharset.find(L' ') != Unicode::UTF32String::npos) UTFCharset += L' ';
- if (UTFCharset.find(L'\n') != Unicode::UTF32String::npos) UTFCharset += L'\n';
- if (UTFCharset.find(L'\v') != Unicode::UTF32String::npos) UTFCharset += L'\v';
- if (UTFCharset.find(L'\t') != Unicode::UTF32String::npos) UTFCharset += L'\t';
+ // Load the new font face from the specified file
+ FT_Face face;
+ if (FT_New_Face(static_cast<FT_Library>(m_library), filename.c_str(), 0, &face) != 0)
+ {
+ err() << "Failed to load font \"" << filename << "\" (failed to create the font face)" << std::endl;
+ return false;
+ }
- return priv::FontLoader::GetInstance().LoadFontFromFile(Filename, CharSize, UTFCharset, *this);
+ // Select the unicode character map
+ if (FT_Select_Charmap(face, FT_ENCODING_UNICODE) != 0)
+ {
+ err() << "Failed to load font \"" << filename << "\" (failed to set the Unicode character set)" << std::endl;
+ return false;
+ }
+
+ // Store the loaded font in our ugly void* :)
+ m_face = face;
+
+ return true;
}
////////////////////////////////////////////////////////////
-/// Load the font from a file in memory
-////////////////////////////////////////////////////////////
-bool Font::LoadFromMemory(const char* Data, std::size_t SizeInBytes, unsigned int CharSize, const Unicode::Text& Charset)
+bool Font::loadFromMemory(const void* data, std::size_t sizeInBytes)
{
- // Clear the previous character map
- myGlyphs.clear();
+ // Cleanup the previous resources
+ cleanup();
+ m_refCount = new int(1);
+
+ // Initialize FreeType
+ // Note: we initialize FreeType for every font instance in order to avoid having a single
+ // global manager that would create a lot of issues regarding creation and destruction order.
+ FT_Library library;
+ if (FT_Init_FreeType(&library) != 0)
+ {
+ err() << "Failed to load font from memory (failed to initialize FreeType)" << std::endl;
+ return false;
+ }
+ m_library = library;
- // Check parameters
- if (!Data || (SizeInBytes == 0))
+ // Load the new font face from the specified file
+ FT_Face face;
+ if (FT_New_Memory_Face(static_cast<FT_Library>(m_library), reinterpret_cast<const FT_Byte*>(data), static_cast<FT_Long>(sizeInBytes), 0, &face) != 0)
{
- std::cerr << "Failed to load font from memory, no data provided" << std::endl;
+ err() << "Failed to load font from memory (failed to create the font face)" << std::endl;
return false;
}
- // Always add these special characters
- Unicode::UTF32String UTFCharset = Charset;
- if (UTFCharset.find(L' ') != Unicode::UTF32String::npos) UTFCharset += L' ';
- if (UTFCharset.find(L'\n') != Unicode::UTF32String::npos) UTFCharset += L'\n';
- if (UTFCharset.find(L'\v') != Unicode::UTF32String::npos) UTFCharset += L'\v';
- if (UTFCharset.find(L'\t') != Unicode::UTF32String::npos) UTFCharset += L'\t';
+ // Select the unicode character map
+ if (FT_Select_Charmap(face, FT_ENCODING_UNICODE) != 0)
+ {
+ err() << "Failed to load font from memory (failed to set the Unicode character set)" << std::endl;
+ return false;
+ }
+
+ // Store the loaded font in our ugly void* :)
+ m_face = face;
- return priv::FontLoader::GetInstance().LoadFontFromMemory(Data, SizeInBytes, CharSize, UTFCharset, *this);
+ return true;
}
////////////////////////////////////////////////////////////
-/// Get the base size of characters in the font;
-/// All glyphs dimensions are based on this value
+bool Font::loadFromStream(InputStream& stream)
+{
+ // Cleanup the previous resources
+ cleanup();
+ m_refCount = new int(1);
+
+ // Initialize FreeType
+ // Note: we initialize FreeType for every font instance in order to avoid having a single
+ // global manager that would create a lot of issues regarding creation and destruction order.
+ FT_Library library;
+ if (FT_Init_FreeType(&library) != 0)
+ {
+ err() << "Failed to load font from stream (failed to initialize FreeType)" << std::endl;
+ return false;
+ }
+ m_library = library;
+
+ // Make sure that the stream's reading position is at the beginning
+ stream.seek(0);
+
+ // Prepare a wrapper for our stream, that we'll pass to FreeType callbacks
+ FT_StreamRec* rec = new FT_StreamRec;
+ std::memset(rec, 0, sizeof(*rec));
+ rec->base = NULL;
+ rec->size = static_cast<unsigned long>(stream.getSize());
+ rec->pos = 0;
+ rec->descriptor.pointer = &stream;
+ rec->read = &read;
+ rec->close = &close;
+
+ // Setup the FreeType callbacks that will read our stream
+ FT_Open_Args args;
+ args.flags = FT_OPEN_STREAM;
+ args.stream = rec;
+ args.driver = 0;
+
+ // Load the new font face from the specified stream
+ FT_Face face;
+ if (FT_Open_Face(static_cast<FT_Library>(m_library), &args, 0, &face) != 0)
+ {
+ err() << "Failed to load font from stream (failed to create the font face)" << std::endl;
+ return false;
+ }
+
+ // Select the unicode character map
+ if (FT_Select_Charmap(face, FT_ENCODING_UNICODE) != 0)
+ {
+ err() << "Failed to load font from stream (failed to set the Unicode character set)" << std::endl;
+ return false;
+ }
+
+ // Store the loaded font in our ugly void* :)
+ m_face = face;
+ m_streamRec = rec;
+
+ return true;
+}
+
+
////////////////////////////////////////////////////////////
-unsigned int Font::GetCharacterSize() const
+const Glyph& Font::getGlyph(Uint32 codePoint, unsigned int characterSize, bool bold) const
{
- return myCharSize;
+ // Get the page corresponding to the character size
+ GlyphTable& glyphs = m_pages[characterSize].glyphs;
+
+ // Build the key by combining the code point and the bold flag
+ Uint32 key = ((bold ? 1 : 0) << 31) | codePoint;
+
+ // Search the glyph into the cache
+ GlyphTable::const_iterator it = glyphs.find(key);
+ if (it != glyphs.end())
+ {
+ // Found: just return it
+ return it->second;
+ }
+ else
+ {
+ // Not found: we have to load it
+ Glyph glyph = loadGlyph(codePoint, characterSize, bold);
+ return glyphs.insert(std::make_pair(key, glyph)).first->second;
+ }
}
////////////////////////////////////////////////////////////
-/// Get the description of a glyph (character)
-/// given by its unicode value
+int Font::getKerning(Uint32 first, Uint32 second, unsigned int characterSize) const
+{
+ // Special case where first or second is 0 (null character)
+ if (first == 0 || second == 0)
+ return 0;
+
+ FT_Face face = static_cast<FT_Face>(m_face);
+
+ if (face && FT_HAS_KERNING(face) && setCurrentSize(characterSize))
+ {
+ // Convert the characters to indices
+ FT_UInt index1 = FT_Get_Char_Index(face, first);
+ FT_UInt index2 = FT_Get_Char_Index(face, second);
+
+ // Get the kerning vector
+ FT_Vector kerning;
+ FT_Get_Kerning(face, index1, index2, FT_KERNING_DEFAULT, &kerning);
+
+ // Return the X advance
+ return kerning.x >> 6;
+ }
+ else
+ {
+ // Invalid font, or no kerning
+ return 0;
+ }
+}
+
+
////////////////////////////////////////////////////////////
-const Glyph& Font::GetGlyph(Uint32 CodePoint) const
+int Font::getLineSpacing(unsigned int characterSize) const
{
- std::map<Uint32, Glyph>::const_iterator It = myGlyphs.find(CodePoint);
- if (It != myGlyphs.end())
+ FT_Face face = static_cast<FT_Face>(m_face);
+
+ if (face && setCurrentSize(characterSize))
{
- // Valid glyph
- return It->second;
+ return (face->size->metrics.height >> 6);
}
else
{
- // Invalid glyph -- return an invalid glyph
- static const Glyph InvalidGlyph;
- return InvalidGlyph;
+ return 0;
}
}
////////////////////////////////////////////////////////////
-/// Get the image containing the rendered characters (glyphs)
+const Texture& Font::getTexture(unsigned int characterSize) const
+{
+ return m_pages[characterSize].texture;
+}
+
+
////////////////////////////////////////////////////////////
-const Image& Font::GetImage() const
+Font& Font::operator =(const Font& right)
{
- return myTexture;
+ Font temp(right);
+
+ std::swap(m_library, temp.m_library);
+ std::swap(m_face, temp.m_face);
+ std::swap(m_pages, temp.m_pages);
+ std::swap(m_pixelBuffer, temp.m_pixelBuffer);
+ std::swap(m_refCount, temp.m_refCount);
+
+ return *this;
}
////////////////////////////////////////////////////////////
-/// Get the SFML default built-in font (Arial)
+void Font::cleanup()
+{
+ // Check if we must destroy the FreeType pointers
+ if (m_refCount)
+ {
+ // Decrease the reference counter
+ (*m_refCount)--;
+
+ // Free the resources only if we are the last owner
+ if (*m_refCount == 0)
+ {
+ // Delete the reference counter
+ delete m_refCount;
+
+ // Destroy the font face
+ if (m_face)
+ FT_Done_Face(static_cast<FT_Face>(m_face));
+
+ // Destroy the stream rec instance, if any (must be done after FT_Done_Face!)
+ if (m_streamRec)
+ delete static_cast<FT_StreamRec*>(m_streamRec);
+
+ // Close the library
+ if (m_library)
+ FT_Done_FreeType(static_cast<FT_Library>(m_library));
+ }
+ }
+
+ // Reset members
+ m_library = NULL;
+ m_face = NULL;
+ m_streamRec = NULL;
+ m_refCount = NULL;
+ m_pages.clear();
+ m_pixelBuffer.clear();
+}
+
+
////////////////////////////////////////////////////////////
-const Font& Font::GetDefaultFont()
+Glyph Font::loadGlyph(Uint32 codePoint, unsigned int characterSize, bool bold) const
{
-#if defined(SFML_SYSTEM_WINDOWS) && defined(SFML_DYNAMIC)
+ // The glyph to return
+ Glyph glyph;
+
+ // First, transform our ugly void* to a FT_Face
+ FT_Face face = static_cast<FT_Face>(m_face);
+ if (!face)
+ return glyph;
+
+ // Set the character size
+ if (!setCurrentSize(characterSize))
+ return glyph;
+
+ // Load the glyph corresponding to the code point
+ if (FT_Load_Char(face, codePoint, FT_LOAD_TARGET_NORMAL) != 0)
+ return glyph;
+
+ // Retrieve the glyph
+ FT_Glyph glyphDesc;
+ if (FT_Get_Glyph(face->glyph, &glyphDesc) != 0)
+ return glyph;
+
+ // Apply bold if necessary -- first technique using outline (highest quality)
+ FT_Pos weight = 1 << 6;
+ bool outline = (glyphDesc->format == FT_GLYPH_FORMAT_OUTLINE);
+ if (bold && outline)
+ {
+ FT_OutlineGlyph outlineGlyph = (FT_OutlineGlyph)glyphDesc;
+ FT_Outline_Embolden(&outlineGlyph->outline, weight);
+ }
- // On Windows dynamic build, the default font causes a crash at global exit.
- // This is a temporary workaround that turns the crash into a memory leak.
- // Note that this bug doesn't exist anymore in SFML 2.
- static Font* DefaultFontPtr = new Font;
- Font& DefaultFont = *DefaultFontPtr;
+ // Convert the glyph to a bitmap (i.e. rasterize it)
+ FT_Glyph_To_Bitmap(&glyphDesc, FT_RENDER_MODE_NORMAL, 0, 1);
+ FT_BitmapGlyph bitmapGlyph = (FT_BitmapGlyph)glyphDesc;
+ FT_Bitmap& bitmap = bitmapGlyph->bitmap;
-#else
+ // Apply bold if necessary -- fallback technique using bitmap (lower quality)
+ if (bold && !outline)
+ {
+ FT_Bitmap_Embolden(static_cast<FT_Library>(m_library), &bitmap, weight, weight);
+ }
- static Font DefaultFont;
+ // Compute the glyph's advance offset
+ glyph.advance = glyphDesc->advance.x >> 16;
+ if (bold)
+ glyph.advance += weight >> 6;
+
+ int width = bitmap.width;
+ int height = bitmap.rows;
+ if ((width > 0) && (height > 0))
+ {
+ // Leave a small padding around characters, so that filtering doesn't
+ // pollute them with pixels from neighbours
+ const unsigned int padding = 1;
+
+ // Get the glyphs page corresponding to the character size
+ Page& page = m_pages[characterSize];
+
+ // Find a good position for the new glyph into the texture
+ glyph.textureRect = findGlyphRect(page, width + 2 * padding, height + 2 * padding);
+
+ // Compute the glyph's bounding box
+ glyph.bounds.left = bitmapGlyph->left - padding;
+ glyph.bounds.top = -bitmapGlyph->top - padding;
+ glyph.bounds.width = width + 2 * padding;
+ glyph.bounds.height = height + 2 * padding;
+
+ // Extract the glyph's pixels from the bitmap
+ m_pixelBuffer.resize(width * height * 4, 255);
+ const Uint8* pixels = bitmap.buffer;
+ if (bitmap.pixel_mode == FT_PIXEL_MODE_MONO)
+ {
+ // Pixels are 1 bit monochrome values
+ for (int y = 0; y < height; ++y)
+ {
+ for (int x = 0; x < width; ++x)
+ {
+ // The color channels remain white, just fill the alpha channel
+ std::size_t index = (x + y * width) * 4 + 3;
+ m_pixelBuffer[index] = ((pixels[x / 8]) & (1 << (7 - (x % 8)))) ? 255 : 0;
+ }
+ pixels += bitmap.pitch;
+ }
+ }
+ else
+ {
+ // Pixels are 8 bits gray levels
+ for (int y = 0; y < height; ++y)
+ {
+ for (int x = 0; x < width; ++x)
+ {
+ // The color channels remain white, just fill the alpha channel
+ std::size_t index = (x + y * width) * 4 + 3;
+ m_pixelBuffer[index] = pixels[x];
+ }
+ pixels += bitmap.pitch;
+ }
+ }
+
+ // Write the pixels to the texture
+ unsigned int x = glyph.textureRect.left + padding;
+ unsigned int y = glyph.textureRect.top + padding;
+ unsigned int w = glyph.textureRect.width - 2 * padding;
+ unsigned int h = glyph.textureRect.height - 2 * padding;
+ page.texture.update(&m_pixelBuffer[0], w, h, x, y);
+ }
-#endif
+ // Delete the FT glyph
+ FT_Done_Glyph(glyphDesc);
- // Get the raw data of the Arial font file into an array, so that we can load it into the font
- static const char DefaultFontData[] =
+ // Force an OpenGL flush, so that the font's texture will appear updated
+ // in all contexts immediately (solves problems in multi-threaded apps)
+ glCheck(glFlush());
+
+ // Done :)
+ return glyph;
+}
+
+
+////////////////////////////////////////////////////////////
+IntRect Font::findGlyphRect(Page& page, unsigned int width, unsigned int height) const
+{
+ // Find the line that fits well the glyph
+ Row* row = NULL;
+ float bestRatio = 0;
+ for (std::vector<Row>::iterator it = page.rows.begin(); it != page.rows.end() && !row; ++it)
{
- #include <SFML/Graphics/Arial.hpp>
- };
+ float ratio = static_cast<float>(height) / it->height;
+
+ // Ignore rows that are either too small or too high
+ if ((ratio < 0.7f) || (ratio > 1.f))
+ continue;
+
+ // Check if there's enough horizontal space left in the row
+ if (width > page.texture.getSize().x - it->width)
+ continue;
+
+ // Make sure that this new row is the best found so far
+ if (ratio < bestRatio)
+ continue;
+
+ // The current row passed all the tests: we can select it
+ row = &*it;
+ bestRatio = ratio;
+ }
+
+ // If we didn't find a matching row, create a new one (10% taller than the glyph)
+ if (!row)
+ {
+ int rowHeight = height + height / 10;
+ while (page.nextRow + rowHeight >= page.texture.getSize().y)
+ {
+ // Not enough space: resize the texture if possible
+ unsigned int textureWidth = page.texture.getSize().x;
+ unsigned int textureHeight = page.texture.getSize().y;
+ if ((textureWidth * 2 <= Texture::getMaximumSize()) && (textureHeight * 2 <= Texture::getMaximumSize()))
+ {
+ // Make the texture 2 times bigger
+ Image newImage;
+ newImage.create(textureWidth * 2, textureHeight * 2, Color(255, 255, 255, 0));
+ newImage.copy(page.texture.copyToImage(), 0, 0);
+ page.texture.loadFromImage(newImage);
+ }
+ else
+ {
+ // Oops, we've reached the maximum texture size...
+ err() << "Failed to add a new character to the font: the maximum texture size has been reached" << std::endl;
+ return IntRect(0, 0, 2, 2);
+ }
+ }
+
+ // We can now create the new row
+ page.rows.push_back(Row(page.nextRow, rowHeight));
+ page.nextRow += rowHeight;
+ row = &page.rows.back();
+ }
+
+ // Find the glyph's rectangle on the selected row
+ IntRect rect(row->width, row->top, width, height);
- // Load the default font on first call
- static bool DefaultFontLoaded = false;
- if (!DefaultFontLoaded)
+ // Update the row informations
+ row->width += width;
+
+ return rect;
+}
+
+
+////////////////////////////////////////////////////////////
+bool Font::setCurrentSize(unsigned int characterSize) const
+{
+ // FT_Set_Pixel_Sizes is an expensive function, so we must call it
+ // only when necessary to avoid killing performances
+
+ FT_Face face = static_cast<FT_Face>(m_face);
+ FT_UShort currentSize = face->size->metrics.x_ppem;
+
+ if (currentSize != characterSize)
{
- DefaultFont.LoadFromMemory(DefaultFontData, sizeof(DefaultFontData), 30);
- DefaultFontLoaded = true;
+ return FT_Set_Pixel_Sizes(face, 0, characterSize) == 0;
}
+ else
+ {
+ return true;
+ }
+}
- return DefaultFont;
+
+////////////////////////////////////////////////////////////
+Font::Page::Page() :
+nextRow(3)
+{
+ // Make sure that the texture is initialized by default
+ sf::Image image;
+ image.create(128, 128, Color(255, 255, 255, 0));
+
+ // Reserve a 2x2 white square for texturing underlines
+ for (int x = 0; x < 2; ++x)
+ for (int y = 0; y < 2; ++y)
+ image.setPixel(x, y, Color(255, 255, 255, 255));
+
+ // Create the texture
+ texture.loadFromImage(image);
+ texture.setSmooth(true);
}
} // namespace sf
diff --git a/src/SFML/Graphics/FontLoader.cpp b/src/SFML/Graphics/FontLoader.cpp
deleted file mode 100755
index 0f6e67b..0000000
--- a/src/SFML/Graphics/FontLoader.cpp
+++ /dev/null
@@ -1,419 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Graphics/FontLoader.hpp>
-#include <SFML/Graphics/Color.hpp>
-#include <SFML/Graphics/Font.hpp>
-#include <SFML/Graphics/Image.hpp>
-#include <SFML/Graphics/GraphicsContext.hpp>
-#include FT_GLYPH_H
-#include <iostream>
-#include <map>
-#include <vector>
-#include <math.h>
-
-
-namespace
-{
- ////////////////////////////////////////////////////////////
- // Functor to sort glyphs by size
- ////////////////////////////////////////////////////////////
- struct SizeCompare
- {
- bool operator ()(FT_BitmapGlyph Glyph1, FT_BitmapGlyph Glyph2) const
- {
- return Glyph2->bitmap.rows < Glyph1->bitmap.rows;
- }
- };
-}
-
-namespace sf
-{
-namespace priv
-{
-////////////////////////////////////////////////////////////
-/// Get the unique instance of the class
-////////////////////////////////////////////////////////////
-FontLoader& FontLoader::GetInstance()
-{
- static FontLoader Instance;
-
- return Instance;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
-FontLoader::FontLoader()
-{
- // Initialize FreeType library
- FT_Error Error = FT_Init_FreeType(&myLibrary);
- if (Error)
- {
- std::cerr << "Failed to initialize FreeType library (error code : " << Error << ")" << std::endl;
- return;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Destructor
-////////////////////////////////////////////////////////////
-FontLoader::~FontLoader()
-{
- // Shutdown FreeType library
- if (myLibrary)
- FT_Done_FreeType(myLibrary);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Load a font from a file
-////////////////////////////////////////////////////////////
-bool FontLoader::LoadFontFromFile(const std::string& Filename, unsigned int CharSize, const Unicode::UTF32String& Charset, Font& LoadedFont)
-{
- // Check if Freetype is correctly initialized
- if (!myLibrary)
- {
- std::cerr << "Failed to load font \"" << Filename << "\", FreeType has not been initialized" << std::endl;
- return false;
- }
-
- // Create a new font face from the specified file
- FT_Face FontFace;
- FT_Error Error = FT_New_Face(myLibrary, Filename.c_str(), 0, &FontFace);
- if (Error)
- {
- std::cerr << "Failed to load font \"" << Filename << "\" (" << GetErrorDesc(Error) << ")" << std::endl;
- return false;
- }
-
- // Create the bitmap font
- Error = CreateBitmapFont(FontFace, CharSize, Charset, LoadedFont);
- if (Error)
- std::cerr << "Failed to load font \"" << Filename << "\" (" << GetErrorDesc(Error) << ")" << std::endl;
-
- // Delete the font
- FT_Done_Face(FontFace);
-
- return Error == 0;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Load the font from a file in memory
-////////////////////////////////////////////////////////////
-bool FontLoader::LoadFontFromMemory(const char* Data, std::size_t SizeInBytes, unsigned int CharSize, const Unicode::UTF32String& Charset, Font& LoadedFont)
-{
- // Check if Freetype is correctly initialized
- if (!myLibrary)
- {
- std::cerr << "Failed to load font from memory, FreeType has not been initialized" << std::endl;
- return false;
- }
-
- // Create a new font face from the specified memory data
- FT_Face FontFace;
- FT_Error Error = FT_New_Memory_Face(myLibrary, reinterpret_cast<const FT_Byte*>(Data), static_cast<FT_Long>(SizeInBytes), 0, &FontFace);
- if (Error)
- {
- std::cerr << "Failed to load font from memory (" << GetErrorDesc(Error) << ")" << std::endl;
- return false;
- }
-
- // Create the bitmap font
- Error = CreateBitmapFont(FontFace, CharSize, Charset, LoadedFont);
- if (Error)
- std::cerr << "Failed to load font from memory (" << GetErrorDesc(Error) << ")" << std::endl;
-
- // Delete the font
- FT_Done_Face(FontFace);
-
- return Error == 0;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Create a bitmap font from a font face and a characters set
-////////////////////////////////////////////////////////////
-FT_Error FontLoader::CreateBitmapFont(FT_Face FontFace, unsigned int CharSize, const Unicode::UTF32String& Charset, Font& LoadedFont)
-{
- // Make sure we have a valid context
- priv::GraphicsContext Ctx;
-
- // Let's find how many characters to put in each row to make them fit into a squared texture
- GLint MaxSize;
- GLCheck(glGetIntegerv(GL_MAX_TEXTURE_SIZE, &MaxSize));
- int NbChars = static_cast<int>(sqrt(static_cast<double>(Charset.length())) * 0.75);
-
- // Clamp the character size to make sure we won't create a texture too big
- if (NbChars * CharSize >= static_cast<unsigned int>(MaxSize))
- CharSize = MaxSize / NbChars;
-
- // Initialize the dimensions
- unsigned int Left = 0;
- unsigned int Top = 0;
- unsigned int TexWidth = Image::GetValidTextureSize(CharSize * NbChars);
- unsigned int TexHeight = CharSize * NbChars;
- std::vector<unsigned int> Tops(TexWidth, 0);
-
- // Create a pixel buffer for rendering every glyph
- std::vector<Uint8> GlyphsBuffer(TexWidth * TexHeight * 4);
-
- // Setup the font size
- FT_Error Error = FT_Set_Pixel_Sizes(FontFace, CharSize, CharSize);
- if (Error)
- return Error;
-
- // Select the unicode character map
- Error = FT_Select_Charmap(FontFace, FT_ENCODING_UNICODE);
- if (Error)
- return Error;
-
- // Render all glyphs and sort them by size to optimize texture space
- typedef std::multimap<FT_BitmapGlyph, Uint32, SizeCompare> GlyphTable;
- GlyphTable Glyphs;
- for (std::size_t i = 0; i < Charset.length(); ++i)
- {
- // Load the glyph corresponding to the current character
- Error = FT_Load_Char(FontFace, Charset[i], FT_LOAD_TARGET_NORMAL);
- if (Error)
- return Error;
-
- // Convert the glyph to a bitmap (ie. rasterize it)
- FT_Glyph Glyph;
- Error = FT_Get_Glyph(FontFace->glyph, &Glyph);
- if (Error)
- return Error;
- FT_Glyph_To_Bitmap(&Glyph, FT_RENDER_MODE_NORMAL, 0, 1);
- FT_BitmapGlyph BitmapGlyph = (FT_BitmapGlyph)Glyph;
-
- // Add it to the sorted table of glyphs
- Glyphs.insert(std::make_pair(BitmapGlyph, Charset[i]));
- }
-
- // Copy the rendered glyphs into the texture
- unsigned int MaxHeight = 0;
- std::map<Uint32, IntRect> Coords;
- for (GlyphTable::const_iterator i = Glyphs.begin(); i != Glyphs.end(); ++i)
- {
- // Get the bitmap of the current glyph
- Glyph& CurGlyph = LoadedFont.myGlyphs[i->second];
- FT_BitmapGlyph BitmapGlyph = i->first;
- FT_Bitmap& Bitmap = BitmapGlyph->bitmap;
-
- // Make sure we don't go over the texture width
- if (Left + Bitmap.width + 1 >= TexWidth)
- Left = 0;
-
- // Compute the top coordinate
- Top = Tops[Left];
- for (int x = 0; x < Bitmap.width + 1; ++x)
- Top = std::max(Top, Tops[Left + x]);
- Top++;
-
- // Make sure we don't go over the texture height -- resize it if we need more space
- if (Top + Bitmap.rows + 1 >= TexHeight)
- {
- TexHeight *= 2;
- GlyphsBuffer.resize(TexWidth * TexHeight * 4);
- }
-
- // Store the character's position and size
- CurGlyph.Rectangle.Left = BitmapGlyph->left;
- CurGlyph.Rectangle.Top = -BitmapGlyph->top;
- CurGlyph.Rectangle.Right = CurGlyph.Rectangle.Left + Bitmap.width;
- CurGlyph.Rectangle.Bottom = Bitmap.rows - BitmapGlyph->top;
- CurGlyph.Advance = BitmapGlyph->root.advance.x >> 16;
-
- // Texture size may change, so let the texture coordinates be calculated later
- Coords[i->second] = IntRect(Left + 1, Top + 1, Left + Bitmap.width + 1, Top + Bitmap.rows + 1);
-
- // Draw the glyph into our bitmap font
- const Uint8* Pixels = Bitmap.buffer;
- for (int y = 0; y < Bitmap.rows; ++y)
- {
- for (int x = 0; x < Bitmap.width; ++x)
- {
- std::size_t Index = x + Left + 1 + (y + Top + 1) * TexWidth;
- GlyphsBuffer[Index * 4 + 0] = 255;
- GlyphsBuffer[Index * 4 + 1] = 255;
- GlyphsBuffer[Index * 4 + 2] = 255;
- GlyphsBuffer[Index * 4 + 3] = Pixels[x];
- }
- Pixels += Bitmap.pitch;
- }
-
- // Update the rendering coordinates
- for (int x = 0; x < Bitmap.width + 1; ++x)
- Tops[Left + x] = Top + Bitmap.rows;
- Left += Bitmap.width + 1;
- if (Top + Bitmap.rows > MaxHeight)
- MaxHeight = Top + Bitmap.rows;
-
- // Delete the glyph
- FT_Done_Glyph((FT_Glyph)BitmapGlyph);
- }
-
- // Create the font's texture
- TexHeight = MaxHeight + 1;
- GlyphsBuffer.resize(TexWidth * TexHeight * 4);
- LoadedFont.myTexture.LoadFromPixels(TexWidth, TexHeight, &GlyphsBuffer[0]);
-
- // Now that the texture is created, we can precompute texture coordinates
- for (std::size_t i = 0; i < Charset.size(); ++i)
- {
- Uint32 CurChar = Charset[i];
- LoadedFont.myGlyphs[CurChar].TexCoords = LoadedFont.myTexture.GetTexCoords(Coords[CurChar]);
- }
-
- // Update the character size (it may have been changed by the function)
- LoadedFont.myCharSize = CharSize;
-
- return 0;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get a description from a FT error code
-////////////////////////////////////////////////////////////
-std::string FontLoader::GetErrorDesc(FT_Error Error)
-{
- switch (Error)
- {
- // Generic errors
- case FT_Err_Cannot_Open_Resource : return "cannot open resource";
- case FT_Err_Unknown_File_Format : return "unknown file format";
- case FT_Err_Invalid_File_Format : return "broken file";
- case FT_Err_Invalid_Version : return "invalid FreeType version";
- case FT_Err_Lower_Module_Version : return "module version is too low";
- case FT_Err_Invalid_Argument : return "invalid argument";
- case FT_Err_Unimplemented_Feature : return "unimplemented feature";
- case FT_Err_Invalid_Table : return "broken table";
- case FT_Err_Invalid_Offset : return "broken offset within table";
-
- // Glyph / character errors
- case FT_Err_Invalid_Glyph_Index : return "invalid glyph index";
- case FT_Err_Invalid_Character_Code : return "invalid character code";
- case FT_Err_Invalid_Glyph_Format : return "unsupported glyph image format";
- case FT_Err_Cannot_Render_Glyph : return "cannot render this glyph format";
- case FT_Err_Invalid_Outline : return "invalid outline";
- case FT_Err_Invalid_Composite : return "invalid composite glyph";
- case FT_Err_Too_Many_Hints : return "too many hints";
- case FT_Err_Invalid_Pixel_Size : return "invalid pixel size";
-
- // Handle errors
- case FT_Err_Invalid_Handle : return "invalid object handle";
- case FT_Err_Invalid_Library_Handle : return "invalid library handle";
- case FT_Err_Invalid_Driver_Handle : return "invalid module handle";
- case FT_Err_Invalid_Face_Handle : return "invalid face handle";
- case FT_Err_Invalid_Size_Handle : return "invalid size handle";
- case FT_Err_Invalid_Slot_Handle : return "invalid glyph slot handle";
- case FT_Err_Invalid_CharMap_Handle : return "invalid charmap handle";
- case FT_Err_Invalid_Cache_Handle : return "invalid cache manager handle";
- case FT_Err_Invalid_Stream_Handle : return "invalid stream handle";
-
- // Driver errors
- case FT_Err_Too_Many_Drivers : return "too many modules";
- case FT_Err_Too_Many_Extensions : return "too many extensions";
-
- // Memory errors
- case FT_Err_Out_Of_Memory : return "out of memory";
- case FT_Err_Unlisted_Object : return "unlisted object";
-
- // Stream errors
- case FT_Err_Cannot_Open_Stream : return "cannot open stream";
- case FT_Err_Invalid_Stream_Seek : return "invalid stream seek";
- case FT_Err_Invalid_Stream_Skip : return "invalid stream skip";
- case FT_Err_Invalid_Stream_Read : return "invalid stream read";
- case FT_Err_Invalid_Stream_Operation : return "invalid stream operation";
- case FT_Err_Invalid_Frame_Operation : return "invalid frame operation";
- case FT_Err_Nested_Frame_Access : return "nested frame access";
- case FT_Err_Invalid_Frame_Read : return "invalid frame read";
-
- // Raster errors
- case FT_Err_Raster_Uninitialized : return "raster uninitialized";
- case FT_Err_Raster_Corrupted : return "raster corrupted";
- case FT_Err_Raster_Overflow : return "raster overflow";
- case FT_Err_Raster_Negative_Height : return "negative height while rastering";
-
- // Cache errors
- case FT_Err_Too_Many_Caches : return "too many registered caches";
-
- // TrueType and SFNT errors
- case FT_Err_Invalid_Opcode : return "invalid opcode";
- case FT_Err_Too_Few_Arguments : return "too few arguments";
- case FT_Err_Stack_Overflow : return "stack overflow";
- case FT_Err_Code_Overflow : return "code overflow";
- case FT_Err_Bad_Argument : return "bad argument";
- case FT_Err_Divide_By_Zero : return "division by zero";
- case FT_Err_Invalid_Reference : return "invalid reference";
- case FT_Err_Debug_OpCode : return "found debug opcode";
- case FT_Err_ENDF_In_Exec_Stream : return "found ENDF opcode in execution stream";
- case FT_Err_Nested_DEFS : return "nested DEFS";
- case FT_Err_Invalid_CodeRange : return "invalid code range";
- case FT_Err_Execution_Too_Long : return "execution context too long";
- case FT_Err_Too_Many_Function_Defs : return "too many function definitions";
- case FT_Err_Too_Many_Instruction_Defs : return "too many instruction definitions";
- case FT_Err_Table_Missing : return "SFNT font table missing";
- case FT_Err_Horiz_Header_Missing : return "horizontal header (hhea) table missing";
- case FT_Err_Locations_Missing : return "locations (loca) table missing";
- case FT_Err_Name_Table_Missing : return "name table missing";
- case FT_Err_CMap_Table_Missing : return "character map (cmap) table missing";
- case FT_Err_Hmtx_Table_Missing : return "horizontal metrics (hmtx) table missing";
- case FT_Err_Post_Table_Missing : return "PostScript (post) table missing";
- case FT_Err_Invalid_Horiz_Metrics : return "invalid horizontal metrics";
- case FT_Err_Invalid_CharMap_Format : return "invalid character map (cmap) format";
- case FT_Err_Invalid_PPem : return "invalid ppem value";
- case FT_Err_Invalid_Vert_Metrics : return "invalid vertical metrics";
- case FT_Err_Could_Not_Find_Context : return "could not find context";
- case FT_Err_Invalid_Post_Table_Format : return "invalid PostScript (post) table format";
- case FT_Err_Invalid_Post_Table : return "invalid PostScript (post) table";
-
- // CCF, CID and Type 1 errors
- case FT_Err_Syntax_Error : return "opcode syntax error";
- case FT_Err_Stack_Underflow : return "argument stack underflow";
- case FT_Err_Ignore : return "ignore";
-
- // BDF errors
- case FT_Err_Missing_Startfont_Field : return "`STARTFONT' field missing";
- case FT_Err_Missing_Font_Field : return "`FONT' field missing";
- case FT_Err_Missing_Size_Field : return "`SIZE' field missing";
- case FT_Err_Missing_Chars_Field : return "`CHARS' field missing";
- case FT_Err_Missing_Startchar_Field : return "`STARTCHAR' field missing";
- case FT_Err_Missing_Encoding_Field : return "`ENCODING' field missing";
- case FT_Err_Missing_Bbx_Field : return "`BBX' field missing";
- }
-
- return "unknown error";
-}
-
-} // namespace priv
-
-} // namespace sf
-
diff --git a/src/SFML/Graphics/GLCheck.cpp b/src/SFML/Graphics/GLCheck.cpp
new file mode 100644
index 0000000..4743c8a
--- /dev/null
+++ b/src/SFML/Graphics/GLCheck.cpp
@@ -0,0 +1,130 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Graphics/GLCheck.hpp>
+#include <SFML/System/Err.hpp>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+void glCheckError(const char* file, unsigned int line)
+{
+ // Get the last error
+ GLenum errorCode = glGetError();
+
+ if (errorCode != GL_NO_ERROR)
+ {
+ std::string fileString(file);
+ std::string error = "unknown error";
+ std::string description = "no description";
+
+ // Decode the error code
+ switch (errorCode)
+ {
+ case GL_INVALID_ENUM :
+ {
+ error = "GL_INVALID_ENUM";
+ description = "an unacceptable value has been specified for an enumerated argument";
+ break;
+ }
+
+ case GL_INVALID_VALUE :
+ {
+ error = "GL_INVALID_VALUE";
+ description = "a numeric argument is out of range";
+ break;
+ }
+
+ case GL_INVALID_OPERATION :
+ {
+ error = "GL_INVALID_OPERATION";
+ description = "the specified operation is not allowed in the current state";
+ break;
+ }
+
+ case GL_STACK_OVERFLOW :
+ {
+ error = "GL_STACK_OVERFLOW";
+ description = "this command would cause a stack overflow";
+ break;
+ }
+
+ case GL_STACK_UNDERFLOW :
+ {
+ error = "GL_STACK_UNDERFLOW";
+ description = "this command would cause a stack underflow";
+ break;
+ }
+
+ case GL_OUT_OF_MEMORY :
+ {
+ error = "GL_OUT_OF_MEMORY";
+ description = "there is not enough memory left to execute the command";
+ break;
+ }
+
+ case GL_INVALID_FRAMEBUFFER_OPERATION_EXT :
+ {
+ error = "GL_INVALID_FRAMEBUFFER_OPERATION_EXT";
+ description = "the object bound to FRAMEBUFFER_BINDING_EXT is not \"framebuffer complete\"";
+ break;
+ }
+ }
+
+ // Log the error
+ err() << "An internal OpenGL call failed in "
+ << fileString.substr(fileString.find_last_of("\\/") + 1) << " (" << line << ") : "
+ << error << ", " << description
+ << std::endl;
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void ensureGlewInit()
+{
+ static bool initialized = false;
+ if (!initialized)
+ {
+ GLenum status = glewInit();
+ if (status == GLEW_OK)
+ {
+ initialized = true;
+ }
+ else
+ {
+ err() << "Failed to initialize GLEW, " << glewGetErrorString(status) << std::endl;
+ }
+ }
+}
+
+} // namespace priv
+
+} // namespace sf
diff --git a/src/SFML/Window/Cocoa/Joystick.cpp b/src/SFML/Graphics/GLCheck.hpp
index f65ac73..72e505e 100755..100644
--- a/src/SFML/Window/Cocoa/Joystick.cpp
+++ b/src/SFML/Graphics/GLCheck.hpp
@@ -1,77 +1,75 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Window/Joystick.hpp>
-
-
-namespace sf
-{
-namespace priv
-{
-////////////////////////////////////////////////////////////
-/// Initialize the instance and bind it to a physical joystick
-////////////////////////////////////////////////////////////
-void Joystick::Initialize(unsigned int Index)
-{
- // Reset the joystick state
-
- // Initialize the Index-th available joystick
-}
-
-
-////////////////////////////////////////////////////////////
-/// Update the current joystick and return its new state
-////////////////////////////////////////////////////////////
-JoystickState Joystick::UpdateState()
-{
- // Fill a JoystickState instance with the current joystick state
- JoystickState s;
- return s;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Check if the joystick supports the given axis
-////////////////////////////////////////////////////////////
-bool Joystick::HasAxis(Joy::Axis Axis) const
-{
- return false;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the number of buttons supported by the joystick
-////////////////////////////////////////////////////////////
-unsigned int Joystick::GetButtonsCount() const
-{
- // Return number of supported buttons
- return 0;
-}
-
-} // namespace priv
-
-} // namespace sf
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_GLCHECK_HPP
+#define SFML_GLCHECK_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Config.hpp>
+#include <GL/glew.h>
+#include <string>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// Let's define a macro to quickly check every OpenGL API calls
+////////////////////////////////////////////////////////////
+#ifdef SFML_DEBUG
+
+ // In debug mode, perform a test on every OpenGL call
+ #define glCheck(call) ((call), sf::priv::glCheckError(__FILE__, __LINE__))
+
+#else
+
+ // Else, we don't add any overhead
+ #define glCheck(call) (call)
+
+#endif
+
+////////////////////////////////////////////////////////////
+/// \brief Check the last OpenGL error
+///
+/// \param file Source file where the call is located
+/// \param line Line number of the source file where the call is located
+///
+////////////////////////////////////////////////////////////
+void glCheckError(const char* file, unsigned int line);
+
+////////////////////////////////////////////////////////////
+/// \brief Make sure that GLEW is initialized
+///
+////////////////////////////////////////////////////////////
+void ensureGlewInit();
+
+} // namespace priv
+
+} // namespace sf
+
+
+#endif // SFML_GLCHECK_HPP
diff --git a/src/SFML/Graphics/GraphicsContext.cpp b/src/SFML/Graphics/GraphicsContext.cpp
deleted file mode 100755
index edb8b16..0000000
--- a/src/SFML/Graphics/GraphicsContext.cpp
+++ /dev/null
@@ -1,94 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Graphics/GraphicsContext.hpp>
-#include <SFML/Window/Context.hpp>
-
-
-namespace
-{
- ////////////////////////////////////////////////////////////
- // One time initialization of 3rd party libraries.
- // We use a global function with a static boolean rather
- // than directly a global boolean, to avoid the randomness
- // of global variables initializations across compile units.
- ////////////////////////////////////////////////////////////
- void InitGraphicsLibs()
- {
- static bool InitDone = false;
- if (!InitDone)
- {
- // Initialize GLEW
- glewInit();
-
- InitDone = true;
- }
- }
-
-}
-
-
-namespace sf
-{
-namespace priv
-{
-////////////////////////////////////////////////////////////
-/// Default constructor, activate the global context
-/// if no other context is bound to the current thread
-////////////////////////////////////////////////////////////
-GraphicsContext::GraphicsContext()
-{
- // Activate the global context
- if (!Context::IsContextActive())
- {
- Context::GetGlobal().SetActive(true);
- myActivated = true;
- }
- else
- {
- myActivated = false;
- }
-
- // Make sure third party libraries are initialized
- InitGraphicsLibs();
-}
-
-
-////////////////////////////////////////////////////////////
-/// Destructor, deactivate the global context
-/// if no other context was previously bound to the current thread
-////////////////////////////////////////////////////////////
-GraphicsContext::~GraphicsContext()
-{
- // Deactivate the global context
- if (myActivated)
- Context::GetGlobal().SetActive(false);
-}
-
-} // namespace priv
-
-} // namespace sf
diff --git a/src/SFML/Graphics/GraphicsContext.hpp b/src/SFML/Graphics/GraphicsContext.hpp
deleted file mode 100755
index 2fa77a3..0000000
--- a/src/SFML/Graphics/GraphicsContext.hpp
+++ /dev/null
@@ -1,176 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-#ifndef SFML_GRAPHICSCONTEXT_HPP
-#define SFML_GRAPHICSCONTEXT_HPP
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Config.hpp>
-#include <SFML/System/NonCopyable.hpp>
-#include <SFML/Graphics/GLEW/glew.h>
-#include <iostream>
-#include <string>
-
-
-namespace sf
-{
-class Context;
-
-namespace priv
-{
-////////////////////////////////////////////////////////////
-/// RAII class ensuring a valid shared OpenGL context is bound
-/// to the current thread for all the lifetime of the instance.
-/// It also ensures all third party libraries (like GLEW)
-/// are properly initialized
-/// This class is for internal use only, it is required
-/// to solve tricky problems involving multi-threading
-////////////////////////////////////////////////////////////
-class GraphicsContext : NonCopyable
-{
-public :
-
- ////////////////////////////////////////////////////////////
- /// Default constructor, activate the global context
- /// if no other context is bound to the current thread
- ///
- ////////////////////////////////////////////////////////////
- GraphicsContext();
-
- ////////////////////////////////////////////////////////////
- /// Destructor, deactivate the global context
- /// if no other context was previously bound to the current thread
- ///
- ////////////////////////////////////////////////////////////
- ~GraphicsContext();
-
-private :
-
- ////////////////////////////////////////////////////////////
- // Member data
- ////////////////////////////////////////////////////////////
- bool myActivated; ///< Keep track of the activation state of the global context
-};
-
-} // namespace priv
-
-
-////////////////////////////////////////////////////////////
-/// Let's define a macro to quickly check every OpenGL
-/// API calls
-////////////////////////////////////////////////////////////
-#ifdef SFML_DEBUG
-
- // In debug mode, perform a test on every OpenGL call
- #define GLCheck(Func) ((Func), GLCheckError(__FILE__, __LINE__))
-
-#else
-
- // Else, we don't add any overhead
- #define GLCheck(Func) (Func)
-
-#endif
-
-
-////////////////////////////////////////////////////////////
-/// Check the last OpenGL error
-///
-////////////////////////////////////////////////////////////
-inline void GLCheckError(const std::string& File, unsigned int Line)
-{
- // Get the last error
- GLenum ErrorCode = glGetError();
-
- if (ErrorCode != GL_NO_ERROR)
- {
- std::string Error = "unknown error";
- std::string Desc = "no description";
-
- // Decode the error code
- switch (ErrorCode)
- {
- case GL_INVALID_ENUM :
- {
- Error = "GL_INVALID_ENUM";
- Desc = "an unacceptable value has been specified for an enumerated argument";
- break;
- }
-
- case GL_INVALID_VALUE :
- {
- Error = "GL_INVALID_VALUE";
- Desc = "a numeric argument is out of range";
- break;
- }
-
- case GL_INVALID_OPERATION :
- {
- Error = "GL_INVALID_OPERATION";
- Desc = "the specified operation is not allowed in the current state";
- break;
- }
-
- case GL_STACK_OVERFLOW :
- {
- Error = "GL_STACK_OVERFLOW";
- Desc = "this command would cause a stack overflow";
- break;
- }
-
- case GL_STACK_UNDERFLOW :
- {
- Error = "GL_STACK_UNDERFLOW";
- Desc = "this command would cause a stack underflow";
- break;
- }
-
- case GL_OUT_OF_MEMORY :
- {
- Error = "GL_OUT_OF_MEMORY";
- Desc = "there is not enough memory left to execute the command";
- break;
- }
-
- case GL_INVALID_FRAMEBUFFER_OPERATION_EXT :
- {
- Error = "GL_INVALID_FRAMEBUFFER_OPERATION_EXT";
- Desc = "the object bound to FRAMEBUFFER_BINDING_EXT is not \"framebuffer complete\"";
- break;
- }
- }
-
- // Log the error
- std::cerr << "An internal OpenGL call failed in "
- << File.substr(File.find_last_of("\\/") + 1) << " (" << Line << ") : "
- << Error << ", " << Desc
- << std::endl;
- }
-}
-
-} // namespace sf
-
-
-#endif // SFML_GRAPHICSCONTEXT_HPP
diff --git a/src/SFML/Graphics/Image.cpp b/src/SFML/Graphics/Image.cpp
index 14346fb..50f49ba 100755..100644
--- a/src/SFML/Graphics/Image.cpp
+++ b/src/SFML/Graphics/Image.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -27,749 +27,286 @@
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Image.hpp>
#include <SFML/Graphics/ImageLoader.hpp>
-#include <SFML/Graphics/RenderWindow.hpp>
-#include <SFML/Graphics/GraphicsContext.hpp>
+#include <SFML/System/Err.hpp>
#include <algorithm>
-#include <iostream>
-#include <vector>
-#include <string.h>
+#include <cstring>
namespace sf
{
////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
Image::Image() :
-myWidth (0),
-myHeight (0),
-myTextureWidth (0),
-myTextureHeight (0),
-myTexture (0),
-myIsSmooth (true),
-myNeedTextureUpdate(false),
-myNeedArrayUpdate (false)
+m_size(0, 0)
{
}
////////////////////////////////////////////////////////////
-/// Copy constructor
-////////////////////////////////////////////////////////////
-Image::Image(const Image& Copy) :
-Resource<Image> (Copy),
-myWidth (Copy.myWidth),
-myHeight (Copy.myHeight),
-myTextureWidth (Copy.myTextureWidth),
-myTextureHeight (Copy.myTextureHeight),
-myTexture (0),
-myIsSmooth (Copy.myIsSmooth),
-myPixels (Copy.myPixels),
-myNeedTextureUpdate(false),
-myNeedArrayUpdate (false)
+void Image::create(unsigned int width, unsigned int height, const Color& color)
{
- CreateTexture();
-}
+ if (width && height)
+ {
+ // Assign the new size
+ m_size.x = width;
+ m_size.y = height;
+ // Resize the pixel buffer
+ m_pixels.resize(width * height * 4);
-////////////////////////////////////////////////////////////
-/// Construct an empty image
-////////////////////////////////////////////////////////////
-Image::Image(unsigned int Width, unsigned int Height, const Color& Col) :
-myWidth (0),
-myHeight (0),
-myTextureWidth (0),
-myTextureHeight (0),
-myTexture (0),
-myIsSmooth (true),
-myNeedTextureUpdate(false),
-myNeedArrayUpdate (false)
-{
- Create(Width, Height, Col);
+ // Fill it with the specified color
+ Uint8* ptr = &m_pixels[0];
+ Uint8* end = ptr + m_pixels.size();
+ while (ptr < end)
+ {
+ *ptr++ = color.r;
+ *ptr++ = color.g;
+ *ptr++ = color.b;
+ *ptr++ = color.a;
+ }
+ }
+ else
+ {
+ // Create an empty image
+ m_size.x = 0;
+ m_size.y = 0;
+ m_pixels.clear();
+ }
}
////////////////////////////////////////////////////////////
-/// Construct the image from pixels in memory
-////////////////////////////////////////////////////////////
-Image::Image(unsigned int Width, unsigned int Height, const Uint8* Data) :
-myWidth (0),
-myHeight (0),
-myTextureWidth (0),
-myTextureHeight (0),
-myTexture (0),
-myIsSmooth (true),
-myNeedTextureUpdate(false),
-myNeedArrayUpdate (false)
+void Image::create(unsigned int width, unsigned int height, const Uint8* pixels)
{
- LoadFromPixels(Width, Height, Data);
+ if (pixels && width && height)
+ {
+ // Assign the new size
+ m_size.x = width;
+ m_size.y = height;
+
+ // Copy the pixels
+ std::size_t size = width * height * 4;
+ m_pixels.resize(size);
+ std::memcpy(&m_pixels[0], pixels, size); // faster than vector::assign
+ }
+ else
+ {
+ // Create an empty image
+ m_size.x = 0;
+ m_size.y = 0;
+ m_pixels.clear();
+ }
}
////////////////////////////////////////////////////////////
-/// Destructor
-////////////////////////////////////////////////////////////
-Image::~Image()
+bool Image::loadFromFile(const std::string& filename)
{
- // Destroy the OpenGL texture
- DestroyTexture();
+ return priv::ImageLoader::getInstance().loadImageFromFile(filename, m_pixels, m_size);
}
////////////////////////////////////////////////////////////
-/// Load the image from a file
-////////////////////////////////////////////////////////////
-bool Image::LoadFromFile(const std::string& Filename)
+bool Image::loadFromMemory(const void* data, std::size_t size)
{
- // Let the image loader load the image into our pixel array
- bool Success = priv::ImageLoader::GetInstance().LoadImageFromFile(Filename, myPixels, myWidth, myHeight);
-
- if (Success)
- {
- // Loading succeeded : we can create the texture
- if (CreateTexture())
- return true;
- }
-
- // Oops... something failed
- Reset();
-
- return false;
+ return priv::ImageLoader::getInstance().loadImageFromMemory(data, size, m_pixels, m_size);
}
////////////////////////////////////////////////////////////
-/// Load the image from a file in memory
-////////////////////////////////////////////////////////////
-bool Image::LoadFromMemory(const char* Data, std::size_t SizeInBytes)
+bool Image::loadFromStream(InputStream& stream)
{
- // Check parameters
- if (!Data || (SizeInBytes == 0))
- {
- std::cerr << "Failed to image font from memory, no data provided" << std::endl;
- return false;
- }
-
- // Let the image loader load the image into our pixel array
- bool Success = priv::ImageLoader::GetInstance().LoadImageFromMemory(Data, SizeInBytes, myPixels, myWidth, myHeight);
-
- if (Success)
- {
- // Loading succeeded : we can create the texture
- if (CreateTexture())
- return true;
- }
-
- // Oops... something failed
- Reset();
-
- return false;
+ return priv::ImageLoader::getInstance().loadImageFromStream(stream, m_pixels, m_size);
}
////////////////////////////////////////////////////////////
-/// Load the image directly from an array of pixels
-////////////////////////////////////////////////////////////
-bool Image::LoadFromPixels(unsigned int Width, unsigned int Height, const Uint8* Data)
+bool Image::saveToFile(const std::string& filename) const
{
- if (Data)
- {
- // Store the texture dimensions
- myWidth = Width;
- myHeight = Height;
-
- // Fill the pixel buffer with the specified raw data
- const Color* Ptr = reinterpret_cast<const Color*>(Data);
- myPixels.assign(Ptr, Ptr + Width * Height);
-
- // We can create the texture
- if (CreateTexture())
- {
- return true;
- }
- else
- {
- // Oops... something failed
- Reset();
- return false;
- }
- }
- else
- {
- // No data provided : create a white image
- return Create(Width, Height, Color(255, 255, 255, 255));
- }
+ return priv::ImageLoader::getInstance().saveImageToFile(filename, m_pixels, m_size);
}
////////////////////////////////////////////////////////////
-/// Save the content of the image to a file
-////////////////////////////////////////////////////////////
-bool Image::SaveToFile(const std::string& Filename) const
+Vector2u Image::getSize() const
{
- // Check if the array of pixels needs to be updated
- EnsureArrayUpdate();
-
- // Let the image loader save our pixel array into the image
- return priv::ImageLoader::GetInstance().SaveImageToFile(Filename, myPixels, myWidth, myHeight);
+ return m_size;
}
////////////////////////////////////////////////////////////
-/// Create an empty image
-////////////////////////////////////////////////////////////
-bool Image::Create(unsigned int Width, unsigned int Height, Color Col)
+void Image::createMaskFromColor(const Color& color, Uint8 alpha)
{
- // Store the texture dimensions
- myWidth = Width;
- myHeight = Height;
-
- // Recreate the pixel buffer and fill it with the specified color
- myPixels.clear();
- myPixels.resize(Width * Height, Col);
-
- // We can create the texture
- if (CreateTexture())
- {
- return true;
- }
- else
+ // Make sure that the image is not empty
+ if (!m_pixels.empty())
{
- // Oops... something failed
- Reset();
- return false;
+ // Replace the alpha of the pixels that match the transparent color
+ Uint8* ptr = &m_pixels[0];
+ Uint8* end = ptr + m_pixels.size();
+ while (ptr < end)
+ {
+ if ((ptr[0] == color.r) && (ptr[1] == color.g) && (ptr[2] == color.b) && (ptr[3] == color.a))
+ ptr[3] = alpha;
+ ptr += 4;
+ }
}
}
////////////////////////////////////////////////////////////
-/// Create transparency mask from a specified colorkey
-////////////////////////////////////////////////////////////
-void Image::CreateMaskFromColor(Color ColorKey, Uint8 Alpha)
-{
- // Check if the array of pixels needs to be updated
- EnsureArrayUpdate();
-
- // Calculate the new color (old color with no alpha)
- Color NewColor(ColorKey.r, ColorKey.g, ColorKey.b, Alpha);
-
- // Replace the old color by the new one
- std::replace(myPixels.begin(), myPixels.end(), ColorKey, NewColor);
-
- // The texture will need to be updated
- myNeedTextureUpdate = true;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Copy pixels from another image onto this one.
-/// This function does a slow pixel copy and should only
-/// be used at initialization time
-////////////////////////////////////////////////////////////
-void Image::Copy(const Image& Source, unsigned int DestX, unsigned int DestY, const IntRect& SourceRect, bool ApplyAlpha)
+void Image::copy(const Image& source, unsigned int destX, unsigned int destY, const IntRect& sourceRect, bool applyAlpha)
{
- // Make sure both images are valid
- if ((Source.myWidth == 0) || (Source.myHeight == 0) || (myWidth == 0) || (myHeight == 0))
+ // Make sure that both images are valid
+ if ((source.m_size.x == 0) || (source.m_size.y == 0) || (m_size.x == 0) || (m_size.y == 0))
return;
- // Make sure both images have up-to-date arrays
- EnsureArrayUpdate();
- Source.EnsureArrayUpdate();
-
// Adjust the source rectangle
- IntRect SrcRect = SourceRect;
- if (SrcRect.GetWidth() == 0 || (SrcRect.GetHeight() == 0))
+ IntRect srcRect = sourceRect;
+ if (srcRect.width == 0 || (srcRect.height == 0))
{
- SrcRect.Left = 0;
- SrcRect.Top = 0;
- SrcRect.Right = Source.myWidth;
- SrcRect.Bottom = Source.myHeight;
+ srcRect.left = 0;
+ srcRect.top = 0;
+ srcRect.width = source.m_size.x;
+ srcRect.height = source.m_size.y;
}
else
{
- if (SrcRect.Left < 0) SrcRect.Left = 0;
- if (SrcRect.Top < 0) SrcRect.Top = 0;
- if (SrcRect.Right > static_cast<int>(Source.myWidth)) SrcRect.Right = Source.myWidth;
- if (SrcRect.Bottom > static_cast<int>(Source.myHeight)) SrcRect.Bottom = Source.myHeight;
+ if (srcRect.left < 0) srcRect.left = 0;
+ if (srcRect.top < 0) srcRect.top = 0;
+ if (srcRect.width > static_cast<int>(source.m_size.x)) srcRect.width = source.m_size.x;
+ if (srcRect.height > static_cast<int>(source.m_size.y)) srcRect.height = source.m_size.y;
}
// Then find the valid bounds of the destination rectangle
- int Width = SrcRect.GetWidth();
- int Height = SrcRect.GetHeight();
- if (DestX + Width > myWidth) Width = myWidth - DestX;
- if (DestY + Height > myHeight) Height = myHeight - DestY;
+ int width = srcRect.width;
+ int height = srcRect.height;
+ if (destX + width > m_size.x) width = m_size.x - destX;
+ if (destY + height > m_size.y) height = m_size.y - destY;
// Make sure the destination area is valid
- if ((Width <= 0) || (Height <= 0))
+ if ((width <= 0) || (height <= 0))
return;
// Precompute as much as possible
- int Pitch = Width * 4;
- int Rows = Height;
- int SrcStride = Source.myWidth * 4;
- int DstStride = myWidth * 4;
- const Uint8* SrcPixels = Source.GetPixelsPtr() + (SrcRect.Left + SrcRect.Top * Source.myWidth) * 4;
- Uint8* DstPixels = reinterpret_cast<Uint8*>(&myPixels[0]) + (DestX + DestY * myWidth) * 4;
+ int pitch = width * 4;
+ int rows = height;
+ int srcStride = source.m_size.x * 4;
+ int dstStride = m_size.x * 4;
+ const Uint8* srcPixels = &source.m_pixels[0] + (srcRect.left + srcRect.top * source.m_size.x) * 4;
+ Uint8* dstPixels = &m_pixels[0] + (destX + destY * m_size.x) * 4;
// Copy the pixels
- if (ApplyAlpha)
+ if (applyAlpha)
{
// Interpolation using alpha values, pixel by pixel (slower)
- for (int i = 0; i < Rows; ++i)
+ for (int i = 0; i < rows; ++i)
{
- for (int j = 0; j < Width; ++j)
+ for (int j = 0; j < width; ++j)
{
// Get a direct pointer to the components of the current pixel
- const Uint8* Src = SrcPixels + j * 4;
- Uint8* Dst = DstPixels + j * 4;
-
- // Interpolate RGB components using the alpha value of the source pixel
- Uint8 Alpha = Src[3];
- Dst[0] = (Src[0] * Alpha + Dst[0] * (255 - Alpha)) / 255;
- Dst[1] = (Src[1] * Alpha + Dst[1] * (255 - Alpha)) / 255;
- Dst[2] = (Src[2] * Alpha + Dst[2] * (255 - Alpha)) / 255;
+ const Uint8* src = srcPixels + j * 4;
+ Uint8* dst = dstPixels + j * 4;
+
+ // Interpolate RGBA components using the alpha value of the source pixel
+ Uint8 alpha = src[3];
+ dst[0] = (src[0] * alpha + dst[0] * (255 - alpha)) / 255;
+ dst[1] = (src[1] * alpha + dst[1] * (255 - alpha)) / 255;
+ dst[2] = (src[2] * alpha + dst[2] * (255 - alpha)) / 255;
+ dst[3] = alpha + dst[3] * (255 - alpha) / 255;
}
- SrcPixels += SrcStride;
- DstPixels += DstStride;
+ srcPixels += srcStride;
+ dstPixels += dstStride;
}
}
else
{
// Optimized copy ignoring alpha values, row by row (faster)
- for (int i = 0; i < Rows; ++i)
+ for (int i = 0; i < rows; ++i)
{
- memcpy(DstPixels, SrcPixels, Pitch);
- SrcPixels += SrcStride;
- DstPixels += DstStride;
+ std::memcpy(dstPixels, srcPixels, pitch);
+ srcPixels += srcStride;
+ dstPixels += dstStride;
}
}
-
- // The texture will need an update
- myNeedTextureUpdate = true;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Create the image from the current contents of the
-/// given window
-////////////////////////////////////////////////////////////
-bool Image::CopyScreen(RenderWindow& Window, const IntRect& SourceRect)
-{
- // Adjust the source rectangle
- IntRect SrcRect = SourceRect;
- if (SrcRect.GetWidth() == 0 || (SrcRect.GetHeight() == 0))
- {
- SrcRect.Left = 0;
- SrcRect.Top = 0;
- SrcRect.Right = Window.GetWidth();
- SrcRect.Bottom = Window.GetHeight();
- }
- else
- {
- if (SrcRect.Left < 0) SrcRect.Left = 0;
- if (SrcRect.Top < 0) SrcRect.Top = 0;
- if (SrcRect.Right > static_cast<int>(Window.GetWidth())) SrcRect.Right = Window.GetWidth();
- if (SrcRect.Bottom > static_cast<int>(Window.GetHeight())) SrcRect.Bottom = Window.GetHeight();
- }
-
- // Store the texture dimensions
- myWidth = SrcRect.GetWidth();
- myHeight = SrcRect.GetHeight();
-
- // We can then create the texture
- if (Window.SetActive() && CreateTexture())
- {
- GLint PreviousTexture;
- GLCheck(glGetIntegerv(GL_TEXTURE_BINDING_2D, &PreviousTexture));
-
- GLCheck(glBindTexture(GL_TEXTURE_2D, myTexture));
- GLCheck(glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, SrcRect.Left, SrcRect.Top, myWidth, myHeight));
-
- GLCheck(glBindTexture(GL_TEXTURE_2D, PreviousTexture));
-
- myNeedTextureUpdate = false;
- myNeedArrayUpdate = true;
-
- return true;
- }
- else
- {
- Reset();
- return false;
- }
}
////////////////////////////////////////////////////////////
-/// Change the color of a pixel
-////////////////////////////////////////////////////////////
-void Image::SetPixel(unsigned int X, unsigned int Y, const Color& Col)
+void Image::setPixel(unsigned int x, unsigned int y, const Color& color)
{
- // First check if the array of pixels needs to be updated
- EnsureArrayUpdate();
-
- // Check if pixel is whithin the image bounds
- if ((X >= myWidth) || (Y >= myHeight))
- {
- std::cerr << "Cannot set pixel (" << X << "," << Y << ") for image "
- << "(width = " << myWidth << ", height = " << myHeight << ")" << std::endl;
- return;
- }
-
- myPixels[X + Y * myWidth] = Col;
-
- // The texture will need to be updated
- myNeedTextureUpdate = true;
+ Uint8* pixel = &m_pixels[(x + y * m_size.x) * 4];
+ *pixel++ = color.r;
+ *pixel++ = color.g;
+ *pixel++ = color.b;
+ *pixel++ = color.a;
}
////////////////////////////////////////////////////////////
-/// Get a pixel from the image
-////////////////////////////////////////////////////////////
-const Color& Image::GetPixel(unsigned int X, unsigned int Y) const
+Color Image::getPixel(unsigned int x, unsigned int y) const
{
- // First check if the array of pixels needs to be updated
- EnsureArrayUpdate();
-
- // Check if pixel is whithin the image bounds
- if ((X >= myWidth) || (Y >= myHeight))
- {
- std::cerr << "Cannot get pixel (" << X << "," << Y << ") for image "
- << "(width = " << myWidth << ", height = " << myHeight << ")" << std::endl;
- return Color::Black;
- }
-
- return myPixels[X + Y * myWidth];
+ const Uint8* pixel = &m_pixels[(x + y * m_size.x) * 4];
+ return Color(pixel[0], pixel[1], pixel[2], pixel[3]);
}
////////////////////////////////////////////////////////////
-/// Get a read-only pointer to the array of pixels (RGBA 8 bits integers components)
-/// Array size is GetWidth() x GetHeight() x 4
-/// This pointer becomes invalid if you reload or resize the image
-////////////////////////////////////////////////////////////
-const Uint8* Image::GetPixelsPtr() const
+const Uint8* Image::getPixelsPtr() const
{
- // First check if the array of pixels needs to be updated
- EnsureArrayUpdate();
-
- if (!myPixels.empty())
+ if (!m_pixels.empty())
{
- return reinterpret_cast<const Uint8*>(&myPixels[0]);
+ return &m_pixels[0];
}
else
{
- std::cerr << "Trying to access the pixels of an empty image" << std::endl;
+ err() << "Trying to access the pixels of an empty image" << std::endl;
return NULL;
}
}
////////////////////////////////////////////////////////////
-/// Bind the image for rendering
-////////////////////////////////////////////////////////////
-void Image::Bind() const
+void Image::flipHorizontally()
{
- // First check if the texture needs to be updated
- EnsureTextureUpdate();
-
- // Bind it
- if (myTexture)
+ if (!m_pixels.empty())
{
- GLCheck(glEnable(GL_TEXTURE_2D));
- GLCheck(glBindTexture(GL_TEXTURE_2D, myTexture));
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Enable or disable image smoothing filter
-////////////////////////////////////////////////////////////
-void Image::SetSmooth(bool Smooth)
-{
- if (Smooth != myIsSmooth)
- {
- myIsSmooth = Smooth;
-
- if (myTexture)
- {
- // Make sure we have a valid context
- priv::GraphicsContext Ctx;
-
- GLint PreviousTexture;
- GLCheck(glGetIntegerv(GL_TEXTURE_BINDING_2D, &PreviousTexture));
-
- GLCheck(glBindTexture(GL_TEXTURE_2D, myTexture));
- GLCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, myIsSmooth ? GL_LINEAR : GL_NEAREST));
- GLCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, myIsSmooth ? GL_LINEAR : GL_NEAREST));
-
- GLCheck(glBindTexture(GL_TEXTURE_2D, PreviousTexture));
- }
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Return the width of the image
-////////////////////////////////////////////////////////////
-unsigned int Image::GetWidth() const
-{
- return myWidth;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Return the height of the image
-////////////////////////////////////////////////////////////
-unsigned int Image::GetHeight() const
-{
- return myHeight;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Tells whether the smooth filtering is enabled or not
-////////////////////////////////////////////////////////////
-bool Image::IsSmooth() const
-{
- return myIsSmooth;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Convert a subrect expressed in pixels, into float
-/// texture coordinates
-////////////////////////////////////////////////////////////
-FloatRect Image::GetTexCoords(const IntRect& Rect) const
-{
- float Width = static_cast<float>(myTextureWidth);
- float Height = static_cast<float>(myTextureHeight);
-
- return FloatRect(Rect.Left / Width,
- Rect.Top / Height,
- Rect.Right / Width,
- Rect.Bottom / Height);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get a valid texture size according to hardware support
-////////////////////////////////////////////////////////////
-unsigned int Image::GetValidTextureSize(unsigned int Size)
-{
- // Make sure we have a valid context
- priv::GraphicsContext Ctx;
-
- if (glewIsSupported("GL_ARB_texture_non_power_of_two") != 0)
- {
- // If hardware supports NPOT textures, then just return the unmodified size
- return Size;
- }
- else
- {
- // If hardware doesn't support NPOT textures, we calculate the nearest power of two
- unsigned int PowerOfTwo = 1;
- while (PowerOfTwo < Size)
- PowerOfTwo *= 2;
-
- return PowerOfTwo;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Assignment operator
-////////////////////////////////////////////////////////////
-Image& Image::operator =(const Image& Other)
-{
- Image Temp(Other);
-
- std::swap(myWidth, Temp.myWidth);
- std::swap(myHeight, Temp.myHeight);
- std::swap(myTextureWidth, Temp.myTextureWidth);
- std::swap(myTextureHeight, Temp.myTextureHeight);
- std::swap(myTexture, Temp.myTexture);
- std::swap(myIsSmooth, Temp.myIsSmooth);
- std::swap(myNeedArrayUpdate, Temp.myNeedArrayUpdate);
- std::swap(myNeedTextureUpdate, Temp.myNeedTextureUpdate);
- myPixels.swap(Temp.myPixels);
-
- return *this;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Create the OpenGL texture
-////////////////////////////////////////////////////////////
-bool Image::CreateTexture()
-{
- // Check if texture parameters are valid before creating it
- if (!myWidth || !myHeight)
- return false;
-
- // Make sure we have a valid context
- priv::GraphicsContext Ctx;
-
- // Adjust internal texture dimensions depending on NPOT textures support
- unsigned int TextureWidth = GetValidTextureSize(myWidth);
- unsigned int TextureHeight = GetValidTextureSize(myHeight);
-
- // Check the maximum texture size
- GLint MaxSize;
- GLCheck(glGetIntegerv(GL_MAX_TEXTURE_SIZE, &MaxSize));
- if ((TextureWidth > static_cast<unsigned int>(MaxSize)) || (TextureHeight > static_cast<unsigned int>(MaxSize)))
- {
- std::cerr << "Failed to create image, its internal size is too high (" << TextureWidth << "x" << TextureHeight << ")" << std::endl;
- return false;
- }
-
- // Destroy the previous OpenGL texture if it already exists with another size
- if ((TextureWidth != myTextureWidth) || (TextureHeight != myTextureHeight))
- {
- DestroyTexture();
- myTextureWidth = TextureWidth;
- myTextureHeight = TextureHeight;
- }
-
- // Create the OpenGL texture
- if (!myTexture)
- {
- GLint PreviousTexture;
- GLCheck(glGetIntegerv(GL_TEXTURE_BINDING_2D, &PreviousTexture));
-
- GLuint Texture = 0;
- GLCheck(glGenTextures(1, &Texture));
- GLCheck(glBindTexture(GL_TEXTURE_2D, Texture));
- GLCheck(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, myTextureWidth, myTextureHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL));
- GLCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP));
- GLCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP));
- GLCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, myIsSmooth ? GL_LINEAR : GL_NEAREST));
- GLCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, myIsSmooth ? GL_LINEAR : GL_NEAREST));
- myTexture = static_cast<unsigned int>(Texture);
-
- GLCheck(glBindTexture(GL_TEXTURE_2D, PreviousTexture));
- }
-
- myNeedTextureUpdate = true;
-
- return true;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Make sure the texture in video memory is updated with the
-/// array of pixels
-////////////////////////////////////////////////////////////
-void Image::EnsureTextureUpdate() const
-{
- if (myNeedTextureUpdate)
- {
- // Copy the pixels
- if (myTexture && !myPixels.empty())
+ std::vector<Uint8> before = m_pixels;
+ for (unsigned int y = 0; y < m_size.y; ++y)
{
- GLint PreviousTexture;
- GLCheck(glGetIntegerv(GL_TEXTURE_BINDING_2D, &PreviousTexture));
-
- // Update the texture with the pixels array in RAM
- GLCheck(glBindTexture(GL_TEXTURE_2D, myTexture));
- GLCheck(glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, myWidth, myHeight, GL_RGBA, GL_UNSIGNED_BYTE, &myPixels[0]));
+ const Uint8* source = &before[y * m_size.x * 4];
+ Uint8* dest = &m_pixels[(y + 1) * m_size.x * 4 - 4];
+ for (unsigned int x = 0; x < m_size.x; ++x)
+ {
+ dest[0] = source[0];
+ dest[1] = source[1];
+ dest[2] = source[2];
+ dest[3] = source[3];
- GLCheck(glBindTexture(GL_TEXTURE_2D, PreviousTexture));
+ source += 4;
+ dest -= 4;
+ }
}
-
- myNeedTextureUpdate = false;
}
}
////////////////////////////////////////////////////////////
-/// Make sure the array of pixels is updated with the
-/// texture in video memory
-////////////////////////////////////////////////////////////
-void Image::EnsureArrayUpdate() const
+void Image::flipVertically()
{
- if (myNeedArrayUpdate)
+ if (!m_pixels.empty())
{
- // Save the previous texture
- GLint PreviousTexture;
- GLCheck(glGetIntegerv(GL_TEXTURE_BINDING_2D, &PreviousTexture));
-
- // Resize the destination array of pixels
- myPixels.resize(myWidth * myHeight);
-
- if ((myWidth == myTextureWidth) && (myHeight == myTextureHeight))
- {
- // Texture and array have the same size, we can use a direct copy
+ std::vector<Uint8> before = m_pixels;
+ const Uint8* source = &before[m_size.x * (m_size.y - 1) * 4];
+ Uint8* dest = &m_pixels[0];
+ std::size_t rowSize = m_size.x * 4;
- // Copy pixels from texture to array
- GLCheck(glBindTexture(GL_TEXTURE_2D, myTexture));
- GLCheck(glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, &myPixels[0]));
- }
- else
+ for (unsigned int y = 0; y < m_size.y; ++y)
{
- // Texture and array don't have the same size, we have to use a slower algorithm
-
- // All the pixels will first be copied to a temporary array
- std::vector<Color> AllPixels(myTextureWidth * myTextureHeight);
- GLCheck(glBindTexture(GL_TEXTURE_2D, myTexture));
- GLCheck(glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, &AllPixels[0]));
-
- // The we copy the useful pixels from the temporary array to the final one
- const Color* Src = &AllPixels[0];
- Color* Dst = &myPixels[0];
- for (unsigned int i = 0; i < myHeight; ++i)
- {
- std::copy(Src, Src + myWidth, Dst);
- Src += myTextureWidth;
- Dst += myWidth;
- }
+ std::memcpy(dest, source, rowSize);
+ source -= rowSize;
+ dest += rowSize;
}
-
- // Restore the previous texture
- GLCheck(glBindTexture(GL_TEXTURE_2D, PreviousTexture));
-
- myNeedArrayUpdate = false;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Reset the image attributes
-////////////////////////////////////////////////////////////
-void Image::Reset()
-{
- DestroyTexture();
-
- myWidth = 0;
- myHeight = 0;
- myTextureWidth = 0;
- myTextureHeight = 0;
- myTexture = 0;
- myIsSmooth = true;
- myNeedTextureUpdate = false;
- myNeedArrayUpdate = false;
- myPixels.clear();
-}
-
-
-////////////////////////////////////////////////////////////
-/// Destroy the OpenGL texture
-////////////////////////////////////////////////////////////
-void Image::DestroyTexture()
-{
- // Destroy the internal texture
- if (myTexture)
- {
- // Make sure we have a valid context
- priv::GraphicsContext Ctx;
-
- GLuint Texture = static_cast<GLuint>(myTexture);
- GLCheck(glDeleteTextures(1, &Texture));
- myTexture = 0;
- myNeedTextureUpdate = false;
- myNeedArrayUpdate = false;
}
}
diff --git a/src/SFML/Graphics/ImageLoader.cpp b/src/SFML/Graphics/ImageLoader.cpp
index a3f83bf..340c5c8 100755..100644
--- a/src/SFML/Graphics/ImageLoader.cpp
+++ b/src/SFML/Graphics/ImageLoader.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -26,25 +26,44 @@
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/ImageLoader.hpp>
+#include <SFML/System/InputStream.hpp>
+#include <SFML/System/Err.hpp>
+#include <SFML/Graphics/stb_image/stb_image.h>
+#define STB_IMAGE_WRITE_IMPLEMENTATION
+#include <SFML/Graphics/stb_image/stb_image_write.h>
extern "C"
{
- #include <SFML/Graphics/libjpeg/jpeglib.h>
- #include <SFML/Graphics/libjpeg/jerror.h>
+ #include <jpeglib.h>
+ #include <jerror.h>
}
-#include <SFML/Graphics/libpng/png.h>
-#include <SFML/Graphics/SOIL/SOIL.h>
-#include <iostream>
+#include <cctype>
namespace
{
- ////////////////////////////////////////////////////////////
- /// Error callback for PNG writing
- ////////////////////////////////////////////////////////////
- void PngErrorHandler(png_structp Png, png_const_charp Message)
+ // Convert a string to lower case
+ std::string toLower(std::string str)
{
- std::cerr << "Failed to write PNG image. Reason : " << Message << std::endl;
- longjmp(Png->jmpbuf, 1);
+ for (std::string::iterator i = str.begin(); i != str.end(); ++i)
+ *i = static_cast<char>(std::tolower(*i));
+ return str;
+ }
+
+ // stb_image callbacks that operate on a sf::InputStream
+ int read(void* user, char* data, int size)
+ {
+ sf::InputStream* stream = static_cast<sf::InputStream*>(user);
+ return static_cast<int>(stream->read(data, size));
+ }
+ void skip(void* user, unsigned int size)
+ {
+ sf::InputStream* stream = static_cast<sf::InputStream*>(user);
+ stream->seek(stream->tell() + size);
+ }
+ int eof(void* user)
+ {
+ sf::InputStream* stream = static_cast<sf::InputStream*>(user);
+ return stream->tell() >= stream->getSize();
}
}
@@ -54,9 +73,7 @@ namespace sf
namespace priv
{
////////////////////////////////////////////////////////////
-/// Get the unique instance of the class
-////////////////////////////////////////////////////////////
-ImageLoader& ImageLoader::GetInstance()
+ImageLoader& ImageLoader::getInstance()
{
static ImageLoader Instance;
@@ -65,8 +82,6 @@ ImageLoader& ImageLoader::GetInstance()
////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
ImageLoader::ImageLoader()
{
// Nothing to do
@@ -74,8 +89,6 @@ ImageLoader::ImageLoader()
////////////////////////////////////////////////////////////
-/// Destructor
-////////////////////////////////////////////////////////////
ImageLoader::~ImageLoader()
{
// Nothing to do
@@ -83,36 +96,34 @@ ImageLoader::~ImageLoader()
////////////////////////////////////////////////////////////
-/// Load pixels from an image file
-////////////////////////////////////////////////////////////
-bool ImageLoader::LoadImageFromFile(const std::string& Filename, std::vector<Color>& Pixels, unsigned int& Width, unsigned int& Height)
+bool ImageLoader::loadImageFromFile(const std::string& filename, std::vector<Uint8>& pixels, Vector2u& size)
{
// Clear the array (just in case)
- Pixels.clear();
+ pixels.clear();
// Load the image and get a pointer to the pixels in memory
- int ImgWidth, ImgHeight, ImgChannels;
- unsigned char* PixelsPtr = SOIL_load_image(Filename.c_str(), &ImgWidth, &ImgHeight, &ImgChannels, SOIL_LOAD_RGBA);
+ int width, height, channels;
+ unsigned char* ptr = stbi_load(filename.c_str(), &width, &height, &channels, STBI_rgb_alpha);
- if (PixelsPtr)
+ if (ptr && width && height)
{
// Assign the image properties
- Width = ImgWidth;
- Height = ImgHeight;
+ size.x = width;
+ size.y = height;
// Copy the loaded pixels to the pixel buffer
- Pixels.resize(Width * Height);
- memcpy(&Pixels[0], PixelsPtr, Width * Height * 4);
+ pixels.resize(width * height * 4);
+ memcpy(&pixels[0], ptr, pixels.size());
// Free the loaded pixels (they are now in our own pixel buffer)
- SOIL_free_image_data(PixelsPtr);
+ stbi_image_free(ptr);
return true;
}
else
{
// Error, failed to load the image
- std::cerr << "Failed to load image \"" << Filename << "\". Reason : " << SOIL_last_result() << std::endl;
+ err() << "Failed to load image \"" << filename << "\". Reason : " << stbi_failure_reason() << std::endl;
return false;
}
@@ -120,38 +131,88 @@ bool ImageLoader::LoadImageFromFile(const std::string& Filename, std::vector<Col
////////////////////////////////////////////////////////////
-/// Load pixels from an image file in memory
+bool ImageLoader::loadImageFromMemory(const void* data, std::size_t dataSize, std::vector<Uint8>& pixels, Vector2u& size)
+{
+ // Check input parameters
+ if (data && dataSize)
+ {
+ // Clear the array (just in case)
+ pixels.clear();
+
+ // Load the image and get a pointer to the pixels in memory
+ int width, height, channels;
+ const unsigned char* buffer = static_cast<const unsigned char*>(data);
+ unsigned char* ptr = stbi_load_from_memory(buffer, static_cast<int>(dataSize), &width, &height, &channels, STBI_rgb_alpha);
+
+ if (ptr && width && height)
+ {
+ // Assign the image properties
+ size.x = width;
+ size.y = height;
+
+ // Copy the loaded pixels to the pixel buffer
+ pixels.resize(width * height * 4);
+ memcpy(&pixels[0], ptr, pixels.size());
+
+ // Free the loaded pixels (they are now in our own pixel buffer)
+ stbi_image_free(ptr);
+
+ return true;
+ }
+ else
+ {
+ // Error, failed to load the image
+ err() << "Failed to load image from memory. Reason : " << stbi_failure_reason() << std::endl;
+
+ return false;
+ }
+ }
+ else
+ {
+ err() << "Failed to load image from memory, no data provided" << std::endl;
+ return false;
+ }
+}
+
+
////////////////////////////////////////////////////////////
-bool ImageLoader::LoadImageFromMemory(const char* Data, std::size_t SizeInBytes, std::vector<Color>& Pixels, unsigned int& Width, unsigned int& Height)
+bool ImageLoader::loadImageFromStream(InputStream& stream, std::vector<Uint8>& pixels, Vector2u& size)
{
// Clear the array (just in case)
- Pixels.clear();
+ pixels.clear();
+
+ // Make sure that the stream's reading position is at the beginning
+ stream.seek(0);
+
+ // Setup the stb_image callbacks
+ stbi_io_callbacks callbacks;
+ callbacks.read = &read;
+ callbacks.skip = &skip;
+ callbacks.eof = &eof;
// Load the image and get a pointer to the pixels in memory
- const unsigned char* Buffer = reinterpret_cast<const unsigned char*>(Data);
- int Size = static_cast<int>(SizeInBytes);
- int ImgWidth, ImgHeight, ImgChannels;
- unsigned char* PixelsPtr = SOIL_load_image_from_memory(Buffer, Size, &ImgWidth, &ImgHeight, &ImgChannels, SOIL_LOAD_RGBA);
+ int width, height, channels;
+ unsigned char* ptr = stbi_load_from_callbacks(&callbacks, &stream, &width, &height, &channels, STBI_rgb_alpha);
- if (PixelsPtr)
+ if (ptr && width && height)
{
// Assign the image properties
- Width = ImgWidth;
- Height = ImgHeight;
+ size.x = width;
+ size.y = height;
// Copy the loaded pixels to the pixel buffer
- Pixels.resize(Width * Height);
- memcpy(&Pixels[0], PixelsPtr, Width * Height * 4);
+ pixels.resize(width * height * 4);
+ memcpy(&pixels[0], ptr, pixels.size());
// Free the loaded pixels (they are now in our own pixel buffer)
- SOIL_free_image_data(PixelsPtr);
+ stbi_image_free(ptr);
return true;
}
else
{
// Error, failed to load the image
- std::cerr << "Failed to load image from memory. Reason : " << SOIL_last_result() << std::endl;
+ err() << "Failed to load image from stream. Reason : " << stbi_failure_reason() << std::endl;
return false;
}
@@ -159,170 +220,98 @@ bool ImageLoader::LoadImageFromMemory(const char* Data, std::size_t SizeInBytes,
////////////////////////////////////////////////////////////
-/// Save pixels to an image file
-////////////////////////////////////////////////////////////
-bool ImageLoader::SaveImageToFile(const std::string& Filename, const std::vector<Color>& Pixels, unsigned int Width, unsigned int Height)
+bool ImageLoader::saveImageToFile(const std::string& filename, const std::vector<Uint8>& pixels, const Vector2u& size)
{
- // Deduce the image type from its extension
- int Type = -1;
- if (Filename.size() > 3)
+ // Make sure the image is not empty
+ if (!pixels.empty() && (size.x > 0) && (size.y > 0))
{
- std::string Extension = Filename.substr(Filename.size() - 3);
- if (Extension == "bmp" || Extension == "BMP") Type = SOIL_SAVE_TYPE_BMP;
- else if (Extension == "tga" || Extension == "TGA") Type = SOIL_SAVE_TYPE_TGA;
- else if (Extension == "dds" || Extension == "DDS") Type = SOIL_SAVE_TYPE_DDS;
-
- // Special handling for PNG and JPG -- not handled by SOIL
- else if (Extension == "png" || Extension == "PNG") return WritePng(Filename, Pixels, Width, Height);
- else if (Extension == "jpg" || Extension == "JPG") return WriteJpg(Filename, Pixels, Width, Height);
+ // Deduce the image type from its extension
+ if (filename.size() > 3)
+ {
+ // Extract the extension
+ std::string extension = filename.substr(filename.size() - 3);
+
+ if (toLower(extension) == "bmp")
+ {
+ // BMP format
+ if (stbi_write_bmp(filename.c_str(), size.x, size.y, 4, &pixels[0]))
+ return true;
+ }
+ else if (toLower(extension) == "tga")
+ {
+ // TGA format
+ if (stbi_write_tga(filename.c_str(), size.x, size.y, 4, &pixels[0]))
+ return true;
+ }
+ else if(toLower(extension) == "png")
+ {
+ // PNG format
+ if (stbi_write_png(filename.c_str(), size.x, size.y, 4, &pixels[0], 0))
+ return true;
+ }
+ else if (toLower(extension) == "jpg")
+ {
+ // JPG format
+ if (writeJpg(filename, pixels, size.x, size.y))
+ return true;
+ }
+ }
}
- if (Type == -1)
- {
- // Error, incompatible type
- std::cerr << "Failed to save image \"" << Filename << "\". Reason : this image format is not supported" << std::endl;
- return false;
- }
-
- // Finally save the image
- const unsigned char* PixelsPtr = reinterpret_cast<const unsigned char*>(&Pixels[0]);
- if (!SOIL_save_image(Filename.c_str(), Type, static_cast<int>(Width), static_cast<int>(Height), 4, PixelsPtr))
- {
- // Error, failed to save the image
- std::cerr << "Failed to save image \"" << Filename << "\". Reason : " << SOIL_last_result() << std::endl;
- return false;
- }
-
- return true;
+ err() << "Failed to save image \"" << filename << "\"" << std::endl;
+ return false;
}
////////////////////////////////////////////////////////////
-/// Save a JPG image file
-////////////////////////////////////////////////////////////
-bool ImageLoader::WriteJpg(const std::string& Filename, const std::vector<Color>& Pixels, unsigned int Width, unsigned int Height)
+bool ImageLoader::writeJpg(const std::string& filename, const std::vector<Uint8>& pixels, unsigned int width, unsigned int height)
{
// Open the file to write in
- FILE* File = fopen(Filename.c_str(), "wb");
- if (!File)
- {
- std::cerr << "Failed to save image file \"" << Filename << "\". Reason : cannot open file" << std::endl;
+ FILE* file = fopen(filename.c_str(), "wb");
+ if (!file)
return false;
- }
// Initialize the error handler
- jpeg_compress_struct CompressInfo;
- jpeg_error_mgr ErrorManager;
- CompressInfo.err = jpeg_std_error(&ErrorManager);
+ jpeg_compress_struct compressInfos;
+ jpeg_error_mgr errorManager;
+ compressInfos.err = jpeg_std_error(&errorManager);
// Initialize all the writing and compression infos
- jpeg_create_compress(&CompressInfo);
- CompressInfo.image_width = Width;
- CompressInfo.image_height = Height;
- CompressInfo.input_components = 3;
- CompressInfo.in_color_space = JCS_RGB;
- jpeg_stdio_dest(&CompressInfo, File);
- jpeg_set_defaults(&CompressInfo);
- jpeg_set_quality(&CompressInfo, 90, TRUE);
+ jpeg_create_compress(&compressInfos);
+ compressInfos.image_width = width;
+ compressInfos.image_height = height;
+ compressInfos.input_components = 3;
+ compressInfos.in_color_space = JCS_RGB;
+ jpeg_stdio_dest(&compressInfos, file);
+ jpeg_set_defaults(&compressInfos);
+ jpeg_set_quality(&compressInfos, 90, TRUE);
// Get rid of the aplha channel
- std::vector<Uint8> PixelsBuffer(Width * Height * 3);
- for (std::size_t i = 0; i < Pixels.size(); ++i)
+ std::vector<Uint8> buffer(width * height * 3);
+ for (std::size_t i = 0; i < width * height; ++i)
{
- PixelsBuffer[i * 3 + 0] = Pixels[i].r;
- PixelsBuffer[i * 3 + 1] = Pixels[i].g;
- PixelsBuffer[i * 3 + 2] = Pixels[i].b;
+ buffer[i * 3 + 0] = pixels[i * 4 + 0];
+ buffer[i * 3 + 1] = pixels[i * 4 + 1];
+ buffer[i * 3 + 2] = pixels[i * 4 + 2];
}
- Uint8* PixelsPtr = &PixelsBuffer[0];
+ Uint8* ptr = &buffer[0];
// Start compression
- jpeg_start_compress(&CompressInfo, TRUE);
+ jpeg_start_compress(&compressInfos, TRUE);
// Write each row of the image
- while (CompressInfo.next_scanline < CompressInfo.image_height)
+ while (compressInfos.next_scanline < compressInfos.image_height)
{
- JSAMPROW RowPointer = PixelsPtr + (CompressInfo.next_scanline * Width * 3);
- jpeg_write_scanlines(&CompressInfo, &RowPointer, 1);
+ JSAMPROW rawPointer = ptr + (compressInfos.next_scanline * width * 3);
+ jpeg_write_scanlines(&compressInfos, &rawPointer, 1);
}
// Finish compression
- jpeg_finish_compress(&CompressInfo);
- jpeg_destroy_compress(&CompressInfo);
+ jpeg_finish_compress(&compressInfos);
+ jpeg_destroy_compress(&compressInfos);
// Close the file
- fclose(File);
-
- return true;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Save a PNG image file
-////////////////////////////////////////////////////////////
-bool ImageLoader::WritePng(const std::string& Filename, const std::vector<Color>& Pixels, unsigned int Width, unsigned int Height)
-{
- // Open the file to write in
- FILE* File = fopen(Filename.c_str(), "wb");
- if (!File)
- {
- std::cerr << "Failed to save image file \"" << Filename << "\". Reason : cannot open file" << std::endl;
- return false;
- }
-
- // Create the main PNG structure
- png_structp Png = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, &PngErrorHandler, NULL);
- if (!Png)
- {
- fclose(File);
- std::cerr << "Failed to save image file \"" << Filename << "\". Reason : cannot allocate PNG write structure" << std::endl;
- return false;
- }
-
- // Initialize the image informations
- png_infop PngInfo = png_create_info_struct(Png);
- if (!PngInfo)
- {
- fclose(File);
- png_destroy_write_struct(&Png, NULL);
- std::cerr << "Failed to save image file \"" << Filename << "\". Reason : cannot allocate PNG info structure" << std::endl;
- return false;
- }
-
- // For proper error handling...
- if (setjmp(Png->jmpbuf))
- {
- png_destroy_write_struct(&Png, &PngInfo);
- return false;
- }
-
- // Link the file to the PNG structure
- png_init_io(Png, File);
-
- // Set the image informations
- png_set_IHDR(Png, PngInfo, Width, Height, 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
-
- // Write the header
- png_write_info(Png, PngInfo);
-
- // Get the pointers to the pixels rows into an array
- png_byte* PixelsPtr = (png_byte*)&Pixels[0];
- std::vector<png_byte*> RowPointers(Height);
- for (unsigned int i = 0; i < Height; ++i)
- {
- RowPointers[i] = PixelsPtr;
- PixelsPtr += Width * 4;
- }
-
- // Write pixels row by row
- png_set_rows(Png, PngInfo, &RowPointers[0]);
- png_write_png(Png, PngInfo, PNG_TRANSFORM_IDENTITY, NULL);
-
- // Finish writing the file
- png_write_end(Png, PngInfo);
-
- // Cleanup resources
- png_destroy_write_struct(&Png, &PngInfo);
- fclose(File);
+ fclose(file);
return true;
}
diff --git a/src/SFML/Graphics/ImageLoader.hpp b/src/SFML/Graphics/ImageLoader.hpp
index d3a6242..08f652b 100755..100644
--- a/src/SFML/Graphics/ImageLoader.hpp
+++ b/src/SFML/Graphics/ImageLoader.hpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -28,111 +28,109 @@
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
-#include <SFML/Graphics/Color.hpp>
#include <SFML/System/NonCopyable.hpp>
+#include <SFML/System/Vector2.hpp>
#include <string>
#include <vector>
namespace sf
{
+class InputStream;
+
namespace priv
{
////////////////////////////////////////////////////////////
-/// ImageLoader load and save images from files ;
-/// Supported formats are : bmp, dds, jpg, png, tga, psd
+/// \brief Load/save image files
+///
////////////////////////////////////////////////////////////
class ImageLoader : NonCopyable
{
public :
////////////////////////////////////////////////////////////
- /// Get the unique instance of the class
+ /// \brief Get the unique instance of the class
///
/// \return Reference to the ImageLoader instance
///
////////////////////////////////////////////////////////////
- static ImageLoader& GetInstance();
+ static ImageLoader& getInstance();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Load an image from a file on disk
+ ///
+ /// \param filename Path of image file to load
+ /// \param pixels Array of pixels to fill with loaded image
+ /// \param size Size of loaded image, in pixels
+ ///
+ /// \return True if loading was successful
+ ///
+ ////////////////////////////////////////////////////////////
+ bool loadImageFromFile(const std::string& filename, std::vector<Uint8>& pixels, Vector2u& size);
////////////////////////////////////////////////////////////
- /// Load pixels from an image file
+ /// \brief Load an image from a file in memory
///
- /// \param Filename : Path of image file to load
- /// \param Pixels : Array of pixels to fill with loaded image
- /// \param Width : Width of loaded image, in pixels
- /// \param Height : Height of loaded image, in pixels
+ /// \param data Pointer to the file data in memory
+ /// \param dataSize Size of the data to load, in bytes
+ /// \param pixels Array of pixels to fill with loaded image
+ /// \param size Size of loaded image, in pixels
///
/// \return True if loading was successful
///
////////////////////////////////////////////////////////////
- bool LoadImageFromFile(const std::string& Filename, std::vector<Color>& Pixels, unsigned int& Width, unsigned int& Height);
+ bool loadImageFromMemory(const void* data, std::size_t dataSize, std::vector<Uint8>& pixels, Vector2u& size);
////////////////////////////////////////////////////////////
- /// Load pixels from an image file in memory
+ /// \brief Load an image from a custom stream
///
- /// \param Data : Pointer to the file data in memory
- /// \param SizeInBytes : Size of the data to load, in bytes
- /// \param Pixels : Array of pixels to fill with loaded image
- /// \param Width : Width of loaded image, in pixels
- /// \param Height : Height of loaded image, in pixels
+ /// \param stream Source stream to read from
+ /// \param pixels Array of pixels to fill with loaded image
+ /// \param size Size of loaded image, in pixels
///
/// \return True if loading was successful
///
////////////////////////////////////////////////////////////
- bool LoadImageFromMemory(const char* Data, std::size_t SizeInBytes, std::vector<Color>& Pixels, unsigned int& Width, unsigned int& Height);
+ bool loadImageFromStream(InputStream& stream, std::vector<Uint8>& pixels, Vector2u& size);
////////////////////////////////////////////////////////////
- /// Save pixels to an image file
+ /// \bref Save an array of pixels as an image file
///
- /// \param Filename : Path of image file to save
- /// \param Pixels : Array of pixels to save to image
- /// \param Width : Width of image to save, in pixels
- /// \param Height : Height of image to save, in pixels
+ /// \param filename Path of image file to save
+ /// \param pixels Array of pixels to save to image
+ /// \param size Size of image to save, in pixels
///
/// \return True if saving was successful
///
////////////////////////////////////////////////////////////
- bool SaveImageToFile(const std::string& Filename, const std::vector<Color>& Pixels, unsigned int Width, unsigned int Height);
+ bool saveImageToFile(const std::string& filename, const std::vector<Uint8>& pixels, const Vector2u& size);
private :
////////////////////////////////////////////////////////////
- /// Default constructor
+ /// \brief Default constructor
///
////////////////////////////////////////////////////////////
ImageLoader();
////////////////////////////////////////////////////////////
- /// Destructor
+ /// \brief Destructor
///
////////////////////////////////////////////////////////////
~ImageLoader();
////////////////////////////////////////////////////////////
- /// Save a JPG image file
- ///
- /// \param Filename : Path of image file to save
- /// \param Pixels : Array of pixels to save to image
- /// \param Width : Width of image to save, in pixels
- /// \param Height : Height of image to save, in pixels
- ///
- /// \return True if saving was successful
- ///
- ////////////////////////////////////////////////////////////
- bool WriteJpg(const std::string& Filename, const std::vector<Color>& Pixels, unsigned int Width, unsigned int Height);
-
- ////////////////////////////////////////////////////////////
- /// Save a PNG image file
+ /// \brief Save an image file in JPEG format
///
- /// \param Filename : Path of image file to save
- /// \param Pixels : Array of pixels to save to image
- /// \param Width : Width of image to save, in pixels
- /// \param Height : Height of image to save, in pixels
+ /// \param filename Path of image file to save
+ /// \param pixels Array of pixels to save to image
+ /// \param width Width of image to save, in pixels
+ /// \param height Height of image to save, in pixels
///
/// \return True if saving was successful
///
////////////////////////////////////////////////////////////
- bool WritePng(const std::string& Filename, const std::vector<Color>& Pixels, unsigned int Width, unsigned int Height);
+ bool writeJpg(const std::string& filename, const std::vector<Uint8>& pixels, unsigned int width, unsigned int height);
};
} // namespace priv
diff --git a/src/SFML/Graphics/Makefile b/src/SFML/Graphics/Makefile
deleted file mode 100755
index 4de224d..0000000
--- a/src/SFML/Graphics/Makefile
+++ /dev/null
@@ -1,47 +0,0 @@
-SRC = $(wildcard *.cpp)
-SRCGLEW = $(wildcard ./GLEW/*.c)
-SRCJPEG = $(wildcard ./libjpeg/*.c)
-SRCPNG = $(wildcard ./libpng/*.c)
-SRCSOIL = $(wildcard ./SOIL/*.c)
-SRCZLIB = $(wildcard ./zlib/*.c)
-OBJ = $(SRC:.cpp=.o)
-OBJGLEW = $(SRCGLEW:.c=.o)
-OBJJPEG = $(SRCJPEG:.c=.o)
-OBJPNG = $(SRCPNG:.c=.o)
-OBJSOIL = $(SRCSOIL:.c=.o)
-OBJZLIB = $(SRCZLIB:.c=.o)
-
-ifeq ($(STATIC), yes)
- LIB = libsfml-graphics-s.a
- LIBNAME = $(LIBPATH)/$(LIB)
- INSTALL =
-else
- LIB = libsfml-graphics.so
- LIBNAME = $(LIBPATH)/$(LIB).$(VERSION)
- INSTALL = && $(LN) $(LNFLAGS) $(LIB).$(VERSION) $(DESTLIBDIR)/$(LIB)
-endif
-
-all: $(LIB)
-
-libsfml-graphics-s.a: $(OBJ) $(OBJGLEW) $(OBJJPEG) $(OBJPNG) $(OBJSOIL) $(OBJZLIB)
- $(AR) $(ARFLAGS) $(LIBNAME) $(OBJ) $(OBJGLEW) $(OBJJPEG) $(OBJPNG) $(OBJSOIL) $(OBJZLIB)
-
-libsfml-graphics.so: $(OBJ) $(OBJGLEW) $(OBJJPEG) $(OBJPNG) $(OBJSOIL) $(OBJZLIB)
- $(CPP) $(LDFLAGS) -Wl,-soname,$(LIB).$(VERSION) -o $(LIBNAME) $(OBJ) $(OBJGLEW) $(OBJJPEG) $(OBJPNG) $(OBJSOIL) $(OBJZLIB) -lfreetype -lX11 -lGL
-
-$(OBJ): %.o: %.cpp
- $(CPP) -o $@ -c $< $(CFLAGS) -I/usr/include/freetype2
-
-$(OBJGLEW) $(OBJJPEG) $(OBJPNG) $(OBJSOIL) $(OBJZLIB): %.o: %.c
- $(CC) -o $@ -c $< $(CFLAGSEXT) -DSTBI_FAILURE_USERMSG
-
-.PHONY: clean mrproper
-
-clean:
- @rm -rf $(OBJ) $(OBJGLEW) $(OBJJPEG) $(OBJPNG) $(OBJSOIL) $(OBJZLIB)
-
-mrproper: clean
- @rm -rf $(LIBNAME)
-
-install:
- @($(CP) $(LIBNAME) $(DESTLIBDIR) $(INSTALL))
diff --git a/src/SFML/Graphics/PostFX.cpp b/src/SFML/Graphics/PostFX.cpp
deleted file mode 100755
index cc5e698..0000000
--- a/src/SFML/Graphics/PostFX.cpp
+++ /dev/null
@@ -1,506 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Graphics/PostFX.hpp>
-#include <SFML/Graphics/RenderWindow.hpp>
-#include <SFML/Graphics/GraphicsContext.hpp>
-#include <fstream>
-#include <iostream>
-#include <set>
-#include <sstream>
-
-
-namespace sf
-{
-////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
-PostFX::PostFX() :
-myShaderProgram(0)
-{
- // No filtering on frame buffer
- myFrameBuffer.SetSmooth(false);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Copy constructor
-////////////////////////////////////////////////////////////
-PostFX::PostFX(const PostFX& Copy) :
-Drawable (Copy),
-myShaderProgram (0),
-myTextures (Copy.myTextures),
-myFragmentShader(Copy.myFragmentShader),
-myFrameBuffer (Copy.myFrameBuffer)
-{
- // No filtering on frame buffer
- myFrameBuffer.SetSmooth(false);
-
- // Create the shaders and the program
- if (Copy.myShaderProgram)
- CreateProgram();
-}
-
-
-////////////////////////////////////////////////////////////
-/// Destructor
-////////////////////////////////////////////////////////////
-PostFX::~PostFX()
-{
- // Destroy effect program
- if (myShaderProgram)
- {
- // Make sure we have a valid context
- priv::GraphicsContext Ctx;
-
- GLCheck(glDeleteObjectARB(myShaderProgram));
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Load the effect from a file
-////////////////////////////////////////////////////////////
-bool PostFX::LoadFromFile(const std::string& Filename)
-{
- // Open the file
- std::ifstream File(Filename.c_str());
- if (!File)
- {
- std::cerr << "Failed to open effect file \"" << Filename << "\"" << std::endl;
- return false;
- }
-
- // Apply the preprocessing pass to the fragment shader code
- myFragmentShader = PreprocessEffect(File);
-
- // Create the shaders and the program
- CreateProgram();
-
- return myShaderProgram != 0;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Load the effect from a text in memory
-////////////////////////////////////////////////////////////
-bool PostFX::LoadFromMemory(const std::string& Effect)
-{
- // Open a stream and copy the effect code
- std::istringstream Stream(Effect.c_str());
-
- // Apply the preprocessing pass to the fragment shader code
- myFragmentShader = PreprocessEffect(Stream);
-
- // Create the shaders and the program
- CreateProgram();
-
- return myShaderProgram != 0;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Change a parameter of the effect (1 float)
-////////////////////////////////////////////////////////////
-void PostFX::SetParameter(const std::string& Name, float X)
-{
- if (myShaderProgram)
- {
- // Enable program
- GLCheck(glUseProgramObjectARB(myShaderProgram));
-
- // Get parameter location and assign it new values
- GLint Location = glGetUniformLocationARB(myShaderProgram, Name.c_str());
- if (Location != -1)
- GLCheck(glUniform1fARB(Location, X));
- else
- std::cerr << "Parameter \"" << Name << "\" not found in post-effect" << std::endl;
-
- // Disable program
- GLCheck(glUseProgramObjectARB(0));
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Change a parameter of the effect (2 floats)
-////////////////////////////////////////////////////////////
-void PostFX::SetParameter(const std::string& Name, float X, float Y)
-{
- if (myShaderProgram)
- {
- // Enable program
- GLCheck(glUseProgramObjectARB(myShaderProgram));
-
- // Get parameter location and assign it new values
- GLint Location = glGetUniformLocationARB(myShaderProgram, Name.c_str());
- if (Location != -1)
- GLCheck(glUniform2fARB(Location, X, Y));
- else
- std::cerr << "Parameter \"" << Name << "\" not found in post-effect" << std::endl;
-
- // Disable program
- GLCheck(glUseProgramObjectARB(0));
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Change a parameter of the effect (3 floats)
-////////////////////////////////////////////////////////////
-void PostFX::SetParameter(const std::string& Name, float X, float Y, float Z)
-{
- if (myShaderProgram)
- {
- // Enable program
- GLCheck(glUseProgramObjectARB(myShaderProgram));
-
- // Get parameter location and assign it new values
- GLint Location = glGetUniformLocationARB(myShaderProgram, Name.c_str());
- if (Location != -1)
- GLCheck(glUniform3fARB(Location, X, Y, Z));
- else
- std::cerr << "Parameter \"" << Name << "\" not found in post-effect" << std::endl;
-
- // Disable program
- GLCheck(glUseProgramObjectARB(0));
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Change a parameter of the effect (4 floats)
-////////////////////////////////////////////////////////////
-void PostFX::SetParameter(const std::string& Name, float X, float Y, float Z, float W)
-{
- if (myShaderProgram)
- {
- // Enable program
- GLCheck(glUseProgramObjectARB(myShaderProgram));
-
- // Get parameter location and assign it new values
- GLint Location = glGetUniformLocationARB(myShaderProgram, Name.c_str());
- if (Location != -1)
- GLCheck(glUniform4fARB(Location, X, Y, Z, W));
- else
- std::cerr << "Parameter \"" << Name << "\" not found in post-effect" << std::endl;
-
- // Disable program
- GLCheck(glUseProgramObjectARB(0));
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Set a texture parameter
-////////////////////////////////////////////////////////////
-void PostFX::SetTexture(const std::string& Name, Image* Texture)
-{
- // Check that the current texture unit is available
- GLint MaxUnits;
- GLCheck(glGetIntegerv(GL_MAX_TEXTURE_COORDS_ARB, &MaxUnits));
- if (myTextures.size() >= static_cast<std::size_t>(MaxUnits))
- {
- std::cerr << "Impossible to use texture \"" << Name << "\" for post-effect : all available texture units are used" << std::endl;
- return;
- }
-
- // Make sure the given name is a valid variable in the effect
- int Location = glGetUniformLocationARB(myShaderProgram, Name.c_str());
- if (Location == -1)
- {
- std::cerr << "Texture \"" << Name << "\" not found in post-effect" << std::endl;
- return;
- }
-
- // Store the texture for later use
- myTextures[Name] = Texture ? Texture : &myFrameBuffer;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Assignment operator
-////////////////////////////////////////////////////////////
-PostFX& PostFX::operator =(const PostFX& Other)
-{
- PostFX Temp(Other);
-
- std::swap(myShaderProgram, Temp.myShaderProgram);
- std::swap(myTextures, Temp.myTextures);
- std::swap(myFragmentShader, Temp.myFragmentShader);
- std::swap(myFrameBuffer, Temp.myFrameBuffer);
-
- return *this;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Tell whether or not the system supports post-effects
-////////////////////////////////////////////////////////////
-bool PostFX::CanUsePostFX()
-{
- // Make sure we have a valid context
- priv::GraphicsContext Ctx;
-
- return glewIsSupported("GL_ARB_shading_language_100") != 0 &&
- glewIsSupported("GL_ARB_shader_objects") != 0 &&
- glewIsSupported("GL_ARB_vertex_shader") != 0 &&
- glewIsSupported("GL_ARB_fragment_shader") != 0;
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see Drawable::Render
-////////////////////////////////////////////////////////////
-void PostFX::Render(RenderTarget& Target) const
-{
- // Check that we have a valid program
- if (!myShaderProgram)
- return;
-
- // Copy the current framebuffer pixels to our frame buffer texture
- // The ugly cast is temporary until PostFx are rewritten :)
- myFrameBuffer.CopyScreen((RenderWindow&)Target);
-
- // Enable program
- GLCheck(glUseProgramObjectARB(myShaderProgram));
-
- // Bind textures
- TextureTable::const_iterator ItTex = myTextures.begin();
- for (std::size_t i = 0; i < myTextures.size(); ++i)
- {
- int Location = glGetUniformLocationARB(myShaderProgram, ItTex->first.c_str());
- GLCheck(glUniform1iARB(Location, static_cast<GLint>(i)));
- GLCheck(glActiveTextureARB(static_cast<GLenum>(GL_TEXTURE0_ARB + i)));
- ItTex->second->Bind();
- ItTex++;
- }
-
- // Compute the texture coordinates (in case the texture is larger than the screen, or flipped)
- IntRect FrameBufferRect(0, 0, myFrameBuffer.GetWidth(), myFrameBuffer.GetHeight());
- FloatRect TexCoords = myFrameBuffer.GetTexCoords(FrameBufferRect);
-
- // Render a fullscreen quad using the effect on our framebuffer
- FloatRect Screen = Target.GetView().GetRect();
- glBegin(GL_QUADS);
- glTexCoord2f(TexCoords.Left, TexCoords.Top); glVertex2f(Screen.Left, Screen.Bottom);
- glTexCoord2f(TexCoords.Right, TexCoords.Top); glVertex2f(Screen.Right, Screen.Bottom);
- glTexCoord2f(TexCoords.Right, TexCoords.Bottom); glVertex2f(Screen.Right, Screen.Top);
- glTexCoord2f(TexCoords.Left, TexCoords.Bottom); glVertex2f(Screen.Left, Screen.Top);
- glEnd();
-
- // Disable program
- GLCheck(glUseProgramObjectARB(0));
-
- // Disable texture units
- for (std::size_t i = 0; i < myTextures.size(); ++i)
- {
- GLCheck(glActiveTextureARB(static_cast<GLenum>(GL_TEXTURE0_ARB + i)));
- GLCheck(glBindTexture(GL_TEXTURE_2D, 0));
- }
- GLCheck(glActiveTextureARB(GL_TEXTURE0_ARB));
-}
-
-
-////////////////////////////////////////////////////////////
-/// Preprocess a SFML effect file
-/// to convert it to a valid GLSL fragment shader
-////////////////////////////////////////////////////////////
-std::string PostFX::PreprocessEffect(std::istream& File)
-{
- // Initialize output string
- std::set<std::string> myTextures;
- std::string Out = "";
-
- // Variable declarations
- std::string Line;
- while (std::getline(File, Line) && (Line.substr(0, 6) != "effect"))
- {
- // Remove the ending '\r', if any
- if (!Line.empty() && (Line[Line.size() - 1] == '\r'))
- Line.erase(Line.size() - 1);
-
- // Skip empty lines
- if (Line == "")
- continue;
-
- // Extract variables type and name and convert them
- std::string Type, Name;
- std::istringstream iss(Line);
- if (!(iss >> Type >> Name))
- {
- std::cerr << "Post-effect error : invalid declaration (should be \"[type][name]\")" << std::endl
- << "> " << Line << std::endl;
- return "";
- }
-
- if (Type == "texture")
- {
- // Textures need some checking and conversion
- if (myTextures.find(Name) != myTextures.end())
- {
- std::cerr << "Post-effect error : texture \"" << Name << "\" already exists" << std::endl;
- return "";
- }
-
- Out += "uniform sampler2D " + Name + ";\n";
- myTextures.insert(Name);
- }
- else
- {
- // Other types are just copied to output with "uniform" prefix
- Out += "uniform " + Type + " " + Name + ";\n";
- }
- }
-
- // Effect code
- Out += "void main()\n";
- while (std::getline(File, Line))
- {
- // Replace any texture lookup "T(" by "texture2D(T, "
- for (std::set<std::string>::const_iterator i = myTextures.begin(); i != myTextures.end(); ++i)
- {
- std::string::size_type Pos = Line.find(*i);
- if (Pos != std::string::npos)
- Line.replace(Pos, i->size() + 1, "texture2D(" + *i + ", ");
- }
-
- // Replace "_in" by "gl_TexCoord[0].xy"
- for (std::string::size_type Pos = Line.find("_in"); Pos != std::string::npos; Pos = Line.find("_in"))
- Line.replace(Pos, 3, "gl_TexCoord[0].xy");
-
- // Replace "_out" by "gl_FragColor"
- for (std::string::size_type Pos = Line.find("_out"); Pos != std::string::npos; Pos = Line.find("_out"))
- Line.replace(Pos, 4, "gl_FragColor");
-
- // Write modified line to output string
- Out += Line + "\n";
- }
-
- return Out;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Create the program and attach the shaders
-////////////////////////////////////////////////////////////
-void PostFX::CreateProgram()
-{
- // Make sure we have a valid context
- priv::GraphicsContext Ctx;
-
- // Check that we can use post-FX !
- if (!CanUsePostFX())
- {
- std::cerr << "Failed to create a PostFX : your system doesn't support effects" << std::endl;
- return;
- }
-
- // Destroy effect program if it was already created
- if (myShaderProgram)
- GLCheck(glDeleteObjectARB(myShaderProgram));
-
- // Define vertex shader source (we provide it directly as it doesn't have to change)
- static const std::string VertexShaderSrc =
- "void main()"
- "{"
- " gl_TexCoord[0] = gl_MultiTexCoord0;"
- " gl_Position = ftransform();"
- "}";
-
- // Create the program
- myShaderProgram = glCreateProgramObjectARB();
-
- // Create the shaders
- GLhandleARB VertexShader = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB);
- GLhandleARB FragmentShader = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);
-
- // Compile them
- const char* VertexSrc = VertexShaderSrc.c_str();
- const char* FragmentSrc = myFragmentShader.c_str();
- GLCheck(glShaderSourceARB(VertexShader, 1, &VertexSrc, NULL));
- GLCheck(glShaderSourceARB(FragmentShader, 1, &FragmentSrc, NULL));
- GLCheck(glCompileShaderARB(VertexShader));
- GLCheck(glCompileShaderARB(FragmentShader));
-
- // Check the compile logs
- GLint Success;
- GLCheck(glGetObjectParameterivARB(VertexShader, GL_OBJECT_COMPILE_STATUS_ARB, &Success));
- if (Success == GL_FALSE)
- {
- char CompileLog[1024];
- GLCheck(glGetInfoLogARB(VertexShader, sizeof(CompileLog), 0, CompileLog));
- std::cerr << "Failed to compile post-effect :" << std::endl
- << CompileLog << std::endl;
- GLCheck(glDeleteObjectARB(VertexShader));
- GLCheck(glDeleteObjectARB(FragmentShader));
- GLCheck(glDeleteObjectARB(myShaderProgram));
- myShaderProgram = 0;
- return;
- }
- GLCheck(glGetObjectParameterivARB(FragmentShader, GL_OBJECT_COMPILE_STATUS_ARB, &Success));
- if (Success == GL_FALSE)
- {
- char CompileLog[1024];
- GLCheck(glGetInfoLogARB(FragmentShader, sizeof(CompileLog), 0, CompileLog));
- std::cerr << "Failed to compile post-effect :" << std::endl
- << CompileLog << std::endl;
- GLCheck(glDeleteObjectARB(VertexShader));
- GLCheck(glDeleteObjectARB(FragmentShader));
- GLCheck(glDeleteObjectARB(myShaderProgram));
- myShaderProgram = 0;
- return;
- }
-
- // Attach the shaders to the program
- GLCheck(glAttachObjectARB(myShaderProgram, VertexShader));
- GLCheck(glAttachObjectARB(myShaderProgram, FragmentShader));
-
- // We can now delete the shaders
- GLCheck(glDeleteObjectARB(VertexShader));
- GLCheck(glDeleteObjectARB(FragmentShader));
-
- // Link the program
- GLCheck(glLinkProgramARB(myShaderProgram));
-
- // Get link log
- GLCheck(glGetObjectParameterivARB(myShaderProgram, GL_OBJECT_LINK_STATUS_ARB, &Success));
- if (Success == GL_FALSE)
- {
- // Oops... link errors
- char LinkLog[1024];
- GLCheck(glGetInfoLogARB(myShaderProgram, sizeof(LinkLog), 0, LinkLog));
- std::cerr << "Failed to link post-effect :" << std::endl
- << LinkLog << std::endl;
- GLCheck(glDeleteObjectARB(myShaderProgram));
- myShaderProgram = 0;
- return;
- }
-}
-
-} // namespace sf
diff --git a/src/SFML/Graphics/RectangleShape.cpp b/src/SFML/Graphics/RectangleShape.cpp
new file mode 100644
index 0000000..39154c0
--- /dev/null
+++ b/src/SFML/Graphics/RectangleShape.cpp
@@ -0,0 +1,76 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Graphics/RectangleShape.hpp>
+#include <cmath>
+
+
+namespace sf
+{
+////////////////////////////////////////////////////////////
+RectangleShape::RectangleShape(const Vector2f& size)
+{
+ setSize(size);
+}
+
+
+////////////////////////////////////////////////////////////
+void RectangleShape::setSize(const Vector2f& size)
+{
+ m_size = size;
+ update();
+}
+
+
+////////////////////////////////////////////////////////////
+const Vector2f& RectangleShape::getSize() const
+{
+ return m_size;
+}
+
+
+////////////////////////////////////////////////////////////
+unsigned int RectangleShape::getPointCount() const
+{
+ return 4;
+}
+
+
+////////////////////////////////////////////////////////////
+Vector2f RectangleShape::getPoint(unsigned int index) const
+{
+ switch (index)
+ {
+ default:
+ case 0: return Vector2f(0, 0);
+ case 1: return Vector2f(m_size.x, 0);
+ case 2: return Vector2f(m_size.x, m_size.y);
+ case 3: return Vector2f(0, m_size.y);
+ }
+}
+
+} // namespace sf
diff --git a/src/SFML/Graphics/RenderStates.cpp b/src/SFML/Graphics/RenderStates.cpp
new file mode 100644
index 0000000..95ca8c1
--- /dev/null
+++ b/src/SFML/Graphics/RenderStates.cpp
@@ -0,0 +1,98 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Graphics/RenderStates.hpp>
+#include <cstddef>
+
+
+namespace sf
+{
+////////////////////////////////////////////////////////////
+const RenderStates RenderStates::Default;
+
+
+////////////////////////////////////////////////////////////
+RenderStates::RenderStates() :
+blendMode(BlendAlpha),
+transform(),
+texture (NULL),
+shader (NULL)
+{
+}
+
+
+////////////////////////////////////////////////////////////
+RenderStates::RenderStates(const Transform& theTransform) :
+blendMode(BlendAlpha),
+transform(theTransform),
+texture (NULL),
+shader (NULL)
+{
+}
+
+
+////////////////////////////////////////////////////////////
+RenderStates::RenderStates(BlendMode theBlendMode) :
+blendMode(theBlendMode),
+transform(),
+texture (NULL),
+shader (NULL)
+{
+}
+
+
+////////////////////////////////////////////////////////////
+RenderStates::RenderStates(const Texture* theTexture) :
+blendMode(BlendAlpha),
+transform(),
+texture (theTexture),
+shader (NULL)
+{
+}
+
+
+////////////////////////////////////////////////////////////
+RenderStates::RenderStates(const Shader* theShader) :
+blendMode(BlendAlpha),
+transform(),
+texture (NULL),
+shader (theShader)
+{
+}
+
+
+////////////////////////////////////////////////////////////
+RenderStates::RenderStates(BlendMode theBlendMode, const Transform& theTransform,
+ const Texture* theTexture, const Shader* theShader) :
+blendMode(theBlendMode),
+transform(theTransform),
+texture (theTexture),
+shader (theShader)
+{
+}
+
+} // namespace sf
diff --git a/src/SFML/Graphics/RenderTarget.cpp b/src/SFML/Graphics/RenderTarget.cpp
index 2dca866..a2316cf 100755..100644
--- a/src/SFML/Graphics/RenderTarget.cpp
+++ b/src/SFML/Graphics/RenderTarget.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -27,165 +27,429 @@
////////////////////////////////////////////////////////////
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Graphics/Drawable.hpp>
-#include <SFML/Graphics/GraphicsContext.hpp>
+#include <SFML/Graphics/Shader.hpp>
+#include <SFML/Graphics/Texture.hpp>
+#include <SFML/Graphics/VertexArray.hpp>
+#include <SFML/Graphics/GLCheck.hpp>
+#include <SFML/System/Err.hpp>
#include <iostream>
namespace sf
{
////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
RenderTarget::RenderTarget() :
-myCurrentView (&myDefaultView),
-myPreserveStates(false),
-myIsDrawing (false)
+m_defaultView(),
+m_view (),
+m_cache ()
{
+ m_cache.glStatesSet = false;
+}
+
+////////////////////////////////////////////////////////////
+RenderTarget::~RenderTarget()
+{
}
////////////////////////////////////////////////////////////
-/// Destructor
+void RenderTarget::clear(const Color& color)
+{
+ if (activate(true))
+ {
+ glCheck(glClearColor(color.r / 255.f, color.g / 255.f, color.b / 255.f, color.a / 255.f));
+ glCheck(glClear(GL_COLOR_BUFFER_BIT));
+ }
+}
+
+
////////////////////////////////////////////////////////////
-RenderTarget::~RenderTarget()
+void RenderTarget::setView(const View& view)
+{
+ m_view = view;
+ m_cache.viewChanged = true;
+}
+
+
+////////////////////////////////////////////////////////////
+const View& RenderTarget::getView() const
{
- // Nothing to do
+ return m_view;
}
////////////////////////////////////////////////////////////
-/// Clear the entire target with a single color
+const View& RenderTarget::getDefaultView() const
+{
+ return m_defaultView;
+}
+
+
////////////////////////////////////////////////////////////
-void RenderTarget::Clear(const Color& FillColor)
+IntRect RenderTarget::getViewport(const View& view) const
{
- if (Activate(true))
- {
- // Clear the frame buffer
- GLCheck(glClearColor(FillColor.r / 255.f, FillColor.g / 255.f, FillColor.b / 255.f, FillColor.a / 255.f));
- GLCheck(glClear(GL_COLOR_BUFFER_BIT));
+ float width = static_cast<float>(getSize().x);
+ float height = static_cast<float>(getSize().y);
+ const FloatRect& viewport = view.getViewport();
- Activate(false);
- }
+ return IntRect(static_cast<int>(0.5f + width * viewport.left),
+ static_cast<int>(0.5f + height * viewport.top),
+ static_cast<int>(width * viewport.width),
+ static_cast<int>(height * viewport.height));
+}
+
+
+////////////////////////////////////////////////////////////
+Vector2f RenderTarget::mapPixelToCoords(const Vector2i& point) const
+{
+ return mapPixelToCoords(point, getView());
+}
+
+
+////////////////////////////////////////////////////////////
+Vector2f RenderTarget::mapPixelToCoords(const Vector2i& point, const View& view) const
+{
+ // First, convert from viewport coordinates to homogeneous coordinates
+ Vector2f normalized;
+ IntRect viewport = getViewport(view);
+ normalized.x = -1.f + 2.f * (point.x - viewport.left) / viewport.width;
+ normalized.y = 1.f - 2.f * (point.y - viewport.top) / viewport.height;
+
+ // Then transform by the inverse of the view matrix
+ return view.getInverseTransform().transformPoint(normalized);
}
+////////////////////////////////////////////////////////////
+Vector2i RenderTarget::mapCoordsToPixel(const Vector2f& point) const
+{
+ return mapCoordsToPixel(point, getView());
+}
+
+////////////////////////////////////////////////////////////
+Vector2i RenderTarget::mapCoordsToPixel(const Vector2f& point, const View& view) const
+{
+ // First, transform the point by the view matrix
+ Vector2f normalized = view.getTransform().transformPoint(point);
+
+ // Then convert to viewport coordinates
+ Vector2i pixel;
+ IntRect viewport = getViewport(view);
+ pixel.x = static_cast<int>(( normalized.x + 1.f) / 2.f * viewport.width + viewport.left);
+ pixel.y = static_cast<int>((-normalized.y + 1.f) / 2.f * viewport.height + viewport.top);
+
+ return pixel;
+}
////////////////////////////////////////////////////////////
-/// Draw something on the window
+void RenderTarget::draw(const Drawable& drawable, const RenderStates& states)
+{
+ drawable.draw(*this, states);
+}
+
+
////////////////////////////////////////////////////////////
-void RenderTarget::Draw(const Drawable& Object)
+void RenderTarget::draw(const Vertex* vertices, unsigned int vertexCount,
+ PrimitiveType type, const RenderStates& states)
{
- // Check whether we are called from the outside or from a previous call to Draw
- if (!myIsDrawing)
+ // Nothing to draw?
+ if (!vertices || (vertexCount == 0))
+ return;
+
+ if (activate(true))
{
- myIsDrawing = true;
+ // First set the persistent OpenGL states if it's the very first call
+ if (!m_cache.glStatesSet)
+ resetGLStates();
- // Set our target as the current target for rendering
- if (Activate(true))
+ // Check if the vertex count is low enough so that we can pre-transform them
+ bool useVertexCache = (vertexCount <= StatesCache::VertexCacheSize);
+ if (useVertexCache)
{
- // Save the current render states and set the SFML ones
- if (myPreserveStates)
+ // Pre-transform the vertices and store them into the vertex cache
+ for (unsigned int i = 0; i < vertexCount; ++i)
{
- GLCheck(glPushAttrib(GL_COLOR_BUFFER_BIT | GL_CURRENT_BIT | GL_ENABLE_BIT |
- GL_TEXTURE_BIT | GL_TRANSFORM_BIT | GL_VIEWPORT_BIT));
- GLCheck(glMatrixMode(GL_MODELVIEW)); GLCheck(glPushMatrix());
- GLCheck(glMatrixMode(GL_PROJECTION)); GLCheck(glPushMatrix());
- SetRenderStates();
+ Vertex& vertex = m_cache.vertexCache[i];
+ vertex.position = states.transform * vertices[i].position;
+ vertex.color = vertices[i].color;
+ vertex.texCoords = vertices[i].texCoords;
}
- // Set the window viewport and transform matrices
- GLCheck(glViewport(0, 0, GetWidth(), GetHeight()));
- GLCheck(glMatrixMode(GL_PROJECTION)); GLCheck(glLoadMatrixf(myCurrentView->GetMatrix().Get4x4Elements()));
- GLCheck(glMatrixMode(GL_MODELVIEW)); GLCheck(glLoadIdentity());
+ // Since vertices are transformed, we must use an identity transform to render them
+ if (!m_cache.useVertexCache)
+ applyTransform(Transform::Identity);
+ }
+ else
+ {
+ applyTransform(states.transform);
+ }
- // Let the object draw itself
- Object.Draw(*this);
+ // Apply the view
+ if (m_cache.viewChanged)
+ applyCurrentView();
- // Restore render states
- if (myPreserveStates)
- {
- GLCheck(glMatrixMode(GL_PROJECTION)); GLCheck(glPopMatrix());
- GLCheck(glMatrixMode(GL_MODELVIEW)); GLCheck(glPopMatrix());
- GLCheck(glPopAttrib());
- }
+ // Apply the blend mode
+ if (states.blendMode != m_cache.lastBlendMode)
+ applyBlendMode(states.blendMode);
+
+ // Apply the texture
+ Uint64 textureId = states.texture ? states.texture->m_cacheId : 0;
+ if (textureId != m_cache.lastTextureId)
+ applyTexture(states.texture);
+
+ // Apply the shader
+ if (states.shader)
+ applyShader(states.shader);
- // Deactivate rendering on this target
- Activate(false);
+ // If we pre-transform the vertices, we must use our internal vertex cache
+ if (useVertexCache)
+ {
+ // ... and if we already used it previously, we don't need to set the pointers again
+ if (!m_cache.useVertexCache)
+ vertices = m_cache.vertexCache;
+ else
+ vertices = NULL;
+ }
+
+ // Setup the pointers to the vertices' components
+ if (vertices)
+ {
+ const char* data = reinterpret_cast<const char*>(vertices);
+ glCheck(glVertexPointer(2, GL_FLOAT, sizeof(Vertex), data + 0));
+ glCheck(glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(Vertex), data + 8));
+ glCheck(glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), data + 12));
}
- myIsDrawing = false;
+ // Find the OpenGL primitive type
+ static const GLenum modes[] = {GL_POINTS, GL_LINES, GL_LINE_STRIP, GL_TRIANGLES,
+ GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN, GL_QUADS};
+ GLenum mode = modes[type];
+
+ // Draw the primitives
+ glCheck(glDrawArrays(mode, 0, vertexCount));
+
+ // Unbind the shader, if any
+ if (states.shader)
+ applyShader(NULL);
+
+ // Update the cache
+ m_cache.useVertexCache = useVertexCache;
}
- else
+}
+
+
+////////////////////////////////////////////////////////////
+void RenderTarget::pushGLStates()
+{
+ if (activate(true))
{
- // We are already called from a previous Draw : we don't need to set the states again, just draw the object
- Object.Draw(*this);
+#ifdef SFML_DEBUG
+ // make sure that the user didn't leave an unchecked OpenGL error
+ GLenum error = glGetError();
+ if (error != GL_NO_ERROR)
+ {
+ err() << "OpenGL error (" << error << ") detected in user code, "
+ << "you should check for errors with glGetError()"
+ << std::endl;
+ }
+#endif
+
+ glCheck(glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS));
+ glCheck(glPushAttrib(GL_ALL_ATTRIB_BITS));
+ glCheck(glMatrixMode(GL_MODELVIEW));
+ glCheck(glPushMatrix());
+ glCheck(glMatrixMode(GL_PROJECTION));
+ glCheck(glPushMatrix());
+ glCheck(glMatrixMode(GL_TEXTURE));
+ glCheck(glPushMatrix());
}
+
+ resetGLStates();
}
////////////////////////////////////////////////////////////
-/// Change the current active view
-////////////////////////////////////////////////////////////
-void RenderTarget::SetView(const View& NewView)
+void RenderTarget::popGLStates()
{
- myCurrentView = &NewView;
+ if (activate(true))
+ {
+ glCheck(glMatrixMode(GL_PROJECTION));
+ glCheck(glPopMatrix());
+ glCheck(glMatrixMode(GL_MODELVIEW));
+ glCheck(glPopMatrix());
+ glCheck(glMatrixMode(GL_TEXTURE));
+ glCheck(glPopMatrix());
+ glCheck(glPopClientAttrib());
+ glCheck(glPopAttrib());
+ }
}
////////////////////////////////////////////////////////////
-/// Get the current view
-////////////////////////////////////////////////////////////
-const View& RenderTarget::GetView() const
+void RenderTarget::resetGLStates()
{
- return *myCurrentView;
+ if (activate(true))
+ {
+ // Make sure that GLEW is initialized
+ priv::ensureGlewInit();
+
+ // Define the default OpenGL states
+ glCheck(glDisable(GL_CULL_FACE));
+ glCheck(glDisable(GL_LIGHTING));
+ glCheck(glDisable(GL_DEPTH_TEST));
+ glCheck(glDisable(GL_ALPHA_TEST));
+ glCheck(glEnable(GL_TEXTURE_2D));
+ glCheck(glEnable(GL_BLEND));
+ glCheck(glMatrixMode(GL_MODELVIEW));
+ glCheck(glEnableClientState(GL_VERTEX_ARRAY));
+ glCheck(glEnableClientState(GL_COLOR_ARRAY));
+ glCheck(glEnableClientState(GL_TEXTURE_COORD_ARRAY));
+ m_cache.glStatesSet = true;
+
+ // Apply the default SFML states
+ applyBlendMode(BlendAlpha);
+ applyTransform(Transform::Identity);
+ applyTexture(NULL);
+ if (Shader::isAvailable())
+ applyShader(NULL);
+ m_cache.useVertexCache = false;
+
+ // Set the default view
+ setView(getView());
+ }
}
////////////////////////////////////////////////////////////
-/// Get the default view of the window for read / write
-////////////////////////////////////////////////////////////
-View& RenderTarget::GetDefaultView()
+void RenderTarget::initialize()
{
- return myDefaultView;
+ // Setup the default and current views
+ m_defaultView.reset(FloatRect(0, 0, static_cast<float>(getSize().x), static_cast<float>(getSize().y)));
+ m_view = m_defaultView;
+
+ // Set GL states only on first draw, so that we don't pollute user's states
+ m_cache.glStatesSet = false;
}
////////////////////////////////////////////////////////////
-/// Tell SFML to preserve external OpenGL states, at the expense of
-/// more CPU charge. Use this function if you don't want SFML
-/// to mess up your own OpenGL states (if any).
-/// Don't enable state preservation if not needed, as it will allow
-/// SFML to do internal optimizations and improve performances.
-/// This parameter is false by default
+void RenderTarget::applyCurrentView()
+{
+ // Set the viewport
+ IntRect viewport = getViewport(m_view);
+ int top = getSize().y - (viewport.top + viewport.height);
+ glCheck(glViewport(viewport.left, top, viewport.width, viewport.height));
+
+ // Set the projection matrix
+ glCheck(glMatrixMode(GL_PROJECTION));
+ glCheck(glLoadMatrixf(m_view.getTransform().getMatrix()));
+
+ // Go back to model-view mode
+ glCheck(glMatrixMode(GL_MODELVIEW));
+
+ m_cache.viewChanged = false;
+}
+
+
////////////////////////////////////////////////////////////
-void RenderTarget::PreserveOpenGLStates(bool Preserve)
+void RenderTarget::applyBlendMode(BlendMode mode)
{
- myPreserveStates = Preserve;
+ switch (mode)
+ {
+ // glBlendFuncSeparateEXT is used when available to avoid an incorrect alpha value when the target
+ // is a RenderTexture -- in this case the alpha value must be written directly to the target buffer
+
+ // Alpha blending
+ default :
+ case BlendAlpha :
+ if (GLEW_EXT_blend_func_separate)
+ glCheck(glBlendFuncSeparateEXT(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA));
+ else
+ glCheck(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
+ break;
+
+ // Additive blending
+ case BlendAdd :
+ if (GLEW_EXT_blend_func_separate)
+ glCheck(glBlendFuncSeparateEXT(GL_SRC_ALPHA, GL_ONE, GL_ONE, GL_ONE));
+ else
+ glCheck(glBlendFunc(GL_SRC_ALPHA, GL_ONE));
+ break;
+
+ // Multiplicative blending
+ case BlendMultiply :
+ glCheck(glBlendFunc(GL_DST_COLOR, GL_ZERO));
+ break;
+
+ // No blending
+ case BlendNone :
+ glCheck(glBlendFunc(GL_ONE, GL_ZERO));
+ break;
+ }
+
+ m_cache.lastBlendMode = mode;
}
////////////////////////////////////////////////////////////
-/// Called by the derived class when it's ready to be initialized
+void RenderTarget::applyTransform(const Transform& transform)
+{
+ // No need to call glMatrixMode(GL_MODELVIEW), it is always the
+ // current mode (for optimization purpose, since it's the most used)
+ glCheck(glLoadMatrixf(transform.getMatrix()));
+}
+
+
////////////////////////////////////////////////////////////
-void RenderTarget::Initialize()
+void RenderTarget::applyTexture(const Texture* texture)
{
- // Set the default rendering states
- SetRenderStates();
+ Texture::bind(texture, Texture::Pixels);
- // Setup the default view
- myDefaultView.SetFromRect(FloatRect(0, 0, static_cast<float>(GetWidth()), static_cast<float>(GetHeight())));
- SetView(myDefaultView);
+ m_cache.lastTextureId = texture ? texture->m_cacheId : 0;
}
////////////////////////////////////////////////////////////
-/// Set the OpenGL render states needed for the SFML rendering
-////////////////////////////////////////////////////////////
-void RenderTarget::SetRenderStates()
+void RenderTarget::applyShader(const Shader* shader)
{
- GLCheck(glDisable(GL_ALPHA_TEST));
- GLCheck(glDisable(GL_DEPTH_TEST));
- GLCheck(glDisable(GL_LIGHTING));
+ Shader::bind(shader);
}
} // namespace sf
+
+
+////////////////////////////////////////////////////////////
+// Render states caching strategies
+//
+// * View
+// If SetView was called since last draw, the projection
+// matrix is updated. We don't need more, the view doesn't
+// change frequently.
+//
+// * Transform
+// The transform matrix is usually expensive because each
+// entity will most likely use a different transform. This can
+// lead, in worst case, to changing it every 4 vertices.
+// To avoid that, when the vertex count is low enough, we
+// pre-transform them and therefore use an identity transform
+// to render them.
+//
+// * Blending mode
+// It's a simple integral value, so we can easily check
+// whether the value to apply is the same as before or not.
+//
+// * Texture
+// Storing the pointer or OpenGL ID of the last used texture
+// is not enough; if the sf::Texture instance is destroyed,
+// both the pointer and the OpenGL ID might be recycled in
+// a new texture instance. We need to use our own unique
+// identifier system to ensure consistent caching.
+//
+// * Shader
+// Shaders are very hard to optimize, because they have
+// parameters that can be hard (if not impossible) to track,
+// like matrices or textures. The only optimization that we
+// do is that we avoid setting a null shader if there was
+// already none for the previous draw.
+//
+////////////////////////////////////////////////////////////
diff --git a/src/SFML/Graphics/RenderTexture.cpp b/src/SFML/Graphics/RenderTexture.cpp
new file mode 100644
index 0000000..845b0b6
--- /dev/null
+++ b/src/SFML/Graphics/RenderTexture.cpp
@@ -0,0 +1,155 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Graphics/RenderTexture.hpp>
+#include <SFML/Graphics/RenderTextureImplFBO.hpp>
+#include <SFML/Graphics/RenderTextureImplDefault.hpp>
+#include <SFML/System/Err.hpp>
+
+
+namespace sf
+{
+////////////////////////////////////////////////////////////
+RenderTexture::RenderTexture() :
+m_impl(NULL)
+{
+
+}
+
+
+////////////////////////////////////////////////////////////
+RenderTexture::~RenderTexture()
+{
+ delete m_impl;
+}
+
+
+////////////////////////////////////////////////////////////
+bool RenderTexture::create(unsigned int width, unsigned int height, bool depthBuffer)
+{
+ // Create the texture
+ if (!m_texture.create(width, height))
+ {
+ err() << "Impossible to create render texture (failed to create the target texture)" << std::endl;
+ return false;
+ }
+
+ // We disable smoothing by default for render textures
+ setSmooth(false);
+
+ // Create the implementation
+ delete m_impl;
+ if (priv::RenderTextureImplFBO::isAvailable())
+ {
+ // Use frame-buffer object (FBO)
+ m_impl = new priv::RenderTextureImplFBO;
+ }
+ else
+ {
+ // Use default implementation
+ m_impl = new priv::RenderTextureImplDefault;
+ }
+
+ // Initialize the render texture
+ if (!m_impl->create(width, height, m_texture.m_texture, depthBuffer))
+ return false;
+
+ // We can now initialize the render target part
+ RenderTarget::initialize();
+
+ return true;
+}
+
+
+////////////////////////////////////////////////////////////
+void RenderTexture::setSmooth(bool smooth)
+{
+ m_texture.setSmooth(smooth);
+}
+
+
+////////////////////////////////////////////////////////////
+bool RenderTexture::isSmooth() const
+{
+ return m_texture.isSmooth();
+}
+
+
+////////////////////////////////////////////////////////////
+void RenderTexture::setRepeated(bool repeated)
+{
+ m_texture.setRepeated(repeated);
+}
+
+
+////////////////////////////////////////////////////////////
+bool RenderTexture::isRepeated() const
+{
+ return m_texture.isRepeated();
+}
+
+
+////////////////////////////////////////////////////////////
+bool RenderTexture::setActive(bool active)
+{
+ return m_impl && m_impl->activate(active);
+}
+
+
+////////////////////////////////////////////////////////////
+void RenderTexture::display()
+{
+ // Update the target texture
+ if (setActive(true))
+ {
+ m_impl->updateTexture(m_texture.m_texture);
+ m_texture.m_pixelsFlipped = true;
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+Vector2u RenderTexture::getSize() const
+{
+ return m_texture.getSize();
+}
+
+
+////////////////////////////////////////////////////////////
+const Texture& RenderTexture::getTexture() const
+{
+ return m_texture;
+}
+
+
+////////////////////////////////////////////////////////////
+bool RenderTexture::activate(bool active)
+{
+ return setActive(active);
+}
+
+} // namespace sf
diff --git a/src/SFML/Graphics/RenderTextureImpl.cpp b/src/SFML/Graphics/RenderTextureImpl.cpp
new file mode 100644
index 0000000..cf26dbe
--- /dev/null
+++ b/src/SFML/Graphics/RenderTextureImpl.cpp
@@ -0,0 +1,43 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Graphics/RenderTextureImpl.hpp>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+RenderTextureImpl::~RenderTextureImpl()
+{
+ // Nothing to do
+}
+
+} // namespace priv
+
+} // namespace sf
diff --git a/src/SFML/Graphics/RenderTextureImpl.hpp b/src/SFML/Graphics/RenderTextureImpl.hpp
new file mode 100644
index 0000000..f9402c4
--- /dev/null
+++ b/src/SFML/Graphics/RenderTextureImpl.hpp
@@ -0,0 +1,89 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_RENDERTEXTUREIMPL_HPP
+#define SFML_RENDERTEXTUREIMPL_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/System/NonCopyable.hpp>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief Abstract base class for render-texture implementations
+///
+////////////////////////////////////////////////////////////
+class RenderTextureImpl : NonCopyable
+{
+public :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Destructor
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual ~RenderTextureImpl();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Create the render texture implementation
+ ///
+ /// \param width Width of the texture to render to
+ /// \param height Height of the texture to render to
+ /// \param textureId OpenGL identifier of the target texture
+ /// \param depthBuffer Is a depth buffer requested?
+ ///
+ /// \return True if creation has been successful
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual bool create(unsigned int width, unsigned int height, unsigned int textureId, bool depthBuffer) = 0;
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Activate or deactivate the render texture for rendering
+ ///
+ /// \param active True to activate, false to deactivate
+ ///
+ /// \return True on success, false on failure
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual bool activate(bool active) = 0;
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Update the pixels of the target texture
+ ///
+ /// \param textureId OpenGL identifier of the target texture
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual void updateTexture(unsigned int textureId) = 0;
+};
+
+} // namespace priv
+
+} // namespace sf
+
+
+#endif // SFML_RENDERTEXTUREIMPL_HPP
diff --git a/src/SFML/Graphics/RenderTextureImplDefault.cpp b/src/SFML/Graphics/RenderTextureImplDefault.cpp
new file mode 100644
index 0000000..aeb6dc0
--- /dev/null
+++ b/src/SFML/Graphics/RenderTextureImplDefault.cpp
@@ -0,0 +1,91 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Graphics/RenderTextureImplDefault.hpp>
+#include <SFML/Graphics/GLCheck.hpp>
+#include <SFML/Graphics/TextureSaver.hpp>
+#include <SFML/Window/Context.hpp>
+#include <SFML/System/Err.hpp>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+RenderTextureImplDefault::RenderTextureImplDefault() :
+m_context(0),
+m_width (0),
+m_height (0)
+{
+
+}
+
+
+////////////////////////////////////////////////////////////
+RenderTextureImplDefault::~RenderTextureImplDefault()
+{
+ // Destroy the context
+ delete m_context;
+}
+
+
+////////////////////////////////////////////////////////////
+bool RenderTextureImplDefault::create(unsigned int width, unsigned int height, unsigned int, bool depthBuffer)
+{
+ // Store the dimensions
+ m_width = width;
+ m_height = height;
+
+ // Create the in-memory OpenGL context
+ m_context = new Context(ContextSettings(depthBuffer ? 32 : 0), width, height);
+
+ return true;
+}
+
+
+////////////////////////////////////////////////////////////
+bool RenderTextureImplDefault::activate(bool active)
+{
+ return m_context->setActive(active);
+}
+
+
+////////////////////////////////////////////////////////////
+void RenderTextureImplDefault::updateTexture(unsigned int textureId)
+{
+ // Make sure that the current texture binding will be preserved
+ priv::TextureSaver save;
+
+ // Copy the rendered pixels to the texture
+ glCheck(glBindTexture(GL_TEXTURE_2D, textureId));
+ glCheck(glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, m_width, m_height));
+}
+
+} // namespace priv
+
+} // namespace sf
diff --git a/src/SFML/Graphics/RenderTextureImplDefault.hpp b/src/SFML/Graphics/RenderTextureImplDefault.hpp
new file mode 100644
index 0000000..8e321f6
--- /dev/null
+++ b/src/SFML/Graphics/RenderTextureImplDefault.hpp
@@ -0,0 +1,107 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_RENDERTEXTUREIMPLDEFAULT_HPP
+#define SFML_RENDERTEXTUREIMPLDEFAULT_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Graphics/RenderTextureImpl.hpp>
+#include <SFML/Window/GlResource.hpp>
+#include <SFML/Window/Context.hpp>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief Default specialization of RenderTextureImpl,
+/// using a in-memory context
+///
+////////////////////////////////////////////////////////////
+class RenderTextureImplDefault : public RenderTextureImpl, GlResource
+{
+public :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Default constructor
+ ///
+ ////////////////////////////////////////////////////////////
+ RenderTextureImplDefault();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Destructor
+ ///
+ ////////////////////////////////////////////////////////////
+ ~RenderTextureImplDefault();
+
+private :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Create the render texture implementation
+ ///
+ /// \param width Width of the texture to render to
+ /// \param height Height of the texture to render to
+ /// \param textureId OpenGL identifier of the target texture
+ /// \param depthBuffer Is a depth buffer requested?
+ ///
+ /// \return True if creation has been successful
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual bool create(unsigned int width, unsigned int height, unsigned int textureId, bool depthBuffer);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Activate or deactivate the render texture for rendering
+ ///
+ /// \param active True to activate, false to deactivate
+ ///
+ /// \return True on success, false on failure
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual bool activate(bool active);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Update the pixels of the target texture
+ ///
+ /// \param textureId OpenGL identifier of the target texture
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual void updateTexture(unsigned textureId);
+
+ ////////////////////////////////////////////////////////////
+ // Member data
+ ////////////////////////////////////////////////////////////
+ Context* m_context; ///< P-Buffer based context
+ unsigned int m_width; ///< Width of the P-Buffer
+ unsigned int m_height; ///< Height of the P-Buffer
+};
+
+} // namespace priv
+
+} // namespace sf
+
+
+#endif // SFML_RENDERTEXTUREIMPLDEFAULT_HPP
diff --git a/src/SFML/Graphics/RenderTextureImplFBO.cpp b/src/SFML/Graphics/RenderTextureImplFBO.cpp
new file mode 100644
index 0000000..0e92e0e
--- /dev/null
+++ b/src/SFML/Graphics/RenderTextureImplFBO.cpp
@@ -0,0 +1,146 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Graphics/RenderTextureImplFBO.hpp>
+#include <SFML/Graphics/Texture.hpp>
+#include <SFML/Graphics/GLCheck.hpp>
+#include <SFML/System/Err.hpp>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+RenderTextureImplFBO::RenderTextureImplFBO() :
+m_frameBuffer(0),
+m_depthBuffer(0)
+{
+
+}
+
+
+////////////////////////////////////////////////////////////
+RenderTextureImplFBO::~RenderTextureImplFBO()
+{
+ ensureGlContext();
+
+ // Destroy the depth buffer
+ if (m_depthBuffer)
+ {
+ GLuint depthBuffer = static_cast<GLuint>(m_depthBuffer);
+ glCheck(glDeleteRenderbuffersEXT(1, &depthBuffer));
+ }
+
+ // Destroy the frame buffer
+ if (m_frameBuffer)
+ {
+ GLuint frameBuffer = static_cast<GLuint>(m_frameBuffer);
+ glCheck(glDeleteFramebuffersEXT(1, &frameBuffer));
+ }
+
+ // Delete the context
+ delete m_context;
+}
+
+
+////////////////////////////////////////////////////////////
+bool RenderTextureImplFBO::isAvailable()
+{
+ ensureGlContext();
+
+ // Make sure that GLEW is initialized
+ priv::ensureGlewInit();
+
+ return GLEW_EXT_framebuffer_object != 0;
+}
+
+
+////////////////////////////////////////////////////////////
+bool RenderTextureImplFBO::create(unsigned int width, unsigned int height, unsigned int textureId, bool depthBuffer)
+{
+ // Create the context
+ m_context = new Context;
+
+ // Create the framebuffer object
+ GLuint frameBuffer = 0;
+ glCheck(glGenFramebuffersEXT(1, &frameBuffer));
+ m_frameBuffer = static_cast<unsigned int>(frameBuffer);
+ if (!m_frameBuffer)
+ {
+ err() << "Impossible to create render texture (failed to create the frame buffer object)" << std::endl;
+ return false;
+ }
+ glCheck(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_frameBuffer));
+
+ // Create the depth buffer if requested
+ if (depthBuffer)
+ {
+ GLuint depth = 0;
+ glCheck(glGenRenderbuffersEXT(1, &depth));
+ m_depthBuffer = static_cast<unsigned int>(depth);
+ if (!m_depthBuffer)
+ {
+ err() << "Impossible to create render texture (failed to create the attached depth buffer)" << std::endl;
+ return false;
+ }
+ glCheck(glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, m_depthBuffer));
+ glCheck(glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, width, height));
+ glCheck(glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_depthBuffer));
+ }
+
+ // Link the texture to the frame buffer
+ glCheck(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, textureId, 0));
+
+ // A final check, just to be sure...
+ if (glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT) != GL_FRAMEBUFFER_COMPLETE_EXT)
+ {
+ glCheck(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
+ err() << "Impossible to create render texture (failed to link the target texture to the frame buffer)" << std::endl;
+ return false;
+ }
+
+ return true;
+}
+
+
+////////////////////////////////////////////////////////////
+bool RenderTextureImplFBO::activate(bool active)
+{
+ return m_context->setActive(active);
+}
+
+
+////////////////////////////////////////////////////////////
+void RenderTextureImplFBO::updateTexture(unsigned int)
+{
+ glFlush();
+}
+
+} // namespace priv
+
+} // namespace sf
diff --git a/src/SFML/Graphics/RenderTextureImplFBO.hpp b/src/SFML/Graphics/RenderTextureImplFBO.hpp
new file mode 100644
index 0000000..200a834
--- /dev/null
+++ b/src/SFML/Graphics/RenderTextureImplFBO.hpp
@@ -0,0 +1,115 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_RENDERTEXTUREIMPLFBO_HPP
+#define SFML_RENDERTEXTUREIMPLFBO_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Graphics/RenderTextureImpl.hpp>
+#include <SFML/Window/Context.hpp>
+#include <SFML/Window/GlResource.hpp>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief Specialization of RenderTextureImpl using the
+/// FrameBuffer Object OpenGL extension
+///
+////////////////////////////////////////////////////////////
+class RenderTextureImplFBO : public RenderTextureImpl, GlResource
+{
+public :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Default constructor
+ ///
+ ////////////////////////////////////////////////////////////
+ RenderTextureImplFBO();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Destructor
+ ///
+ ////////////////////////////////////////////////////////////
+ ~RenderTextureImplFBO();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Check whether the system supports FBOs or not
+ ///
+ /// \return True if FBO render textures are supported
+ ///
+ ////////////////////////////////////////////////////////////
+ static bool isAvailable();
+
+private :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Create the render texture implementation
+ ///
+ /// \param width Width of the texture to render to
+ /// \param height Height of the texture to render to
+ /// \param textureId OpenGL identifier of the target texture
+ /// \param depthBuffer Is a depth buffer requested?
+ ///
+ /// \return True if creation has been successful
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual bool create(unsigned int width, unsigned int height, unsigned int textureId, bool depthBuffer);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Activate or deactivate the render texture for rendering
+ ///
+ /// \param active True to activate, false to deactivate
+ ///
+ /// \return True on success, false on failure
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual bool activate(bool active);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Update the pixels of the target texture
+ ///
+ /// \param textureId OpenGL identifier of the target texture
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual void updateTexture(unsigned textureId);
+
+ ////////////////////////////////////////////////////////////
+ // Member data
+ ////////////////////////////////////////////////////////////
+ Context* m_context; ///< Needs a separate OpenGL context for not messing up the other ones
+ unsigned int m_frameBuffer; ///< OpenGL frame buffer object
+ unsigned int m_depthBuffer; ///< Optional depth buffer attached to the frame buffer
+};
+
+} // namespace priv
+
+} // namespace sf
+
+
+#endif // SFML_RENDERTEXTUREIMPLFBO_HPP
diff --git a/src/SFML/Graphics/RenderWindow.cpp b/src/SFML/Graphics/RenderWindow.cpp
index bb1d62c..de9babf 100755..100644
--- a/src/SFML/Graphics/RenderWindow.cpp
+++ b/src/SFML/Graphics/RenderWindow.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -26,17 +26,12 @@
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/RenderWindow.hpp>
-#include <SFML/Graphics/Drawable.hpp>
-#include <SFML/Graphics/Image.hpp>
-#include <SFML/Graphics/GraphicsContext.hpp>
-#include <iostream>
+#include <SFML/Graphics/GLCheck.hpp>
namespace sf
{
////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
RenderWindow::RenderWindow()
{
// Nothing to do
@@ -44,26 +39,22 @@ RenderWindow::RenderWindow()
////////////////////////////////////////////////////////////
-/// Construct the window
-////////////////////////////////////////////////////////////
-RenderWindow::RenderWindow(VideoMode Mode, const std::string& Title, unsigned long WindowStyle, const WindowSettings& Params)
+RenderWindow::RenderWindow(VideoMode mode, const String& title, Uint32 style, const ContextSettings& settings)
{
- Create(Mode, Title, WindowStyle, Params);
+ // Don't call the base class constructor because it contains virtual function calls
+ create(mode, title, style, settings);
}
////////////////////////////////////////////////////////////
-/// Construct the window from an existing control
-////////////////////////////////////////////////////////////
-RenderWindow::RenderWindow(WindowHandle Handle, const WindowSettings& Params)
+RenderWindow::RenderWindow(WindowHandle handle, const ContextSettings& settings)
{
- Create(Handle, Params);
+ // Don't call the base class constructor because it contains virtual function calls
+ create(handle, settings);
}
////////////////////////////////////////////////////////////
-/// Destructor
-////////////////////////////////////////////////////////////
RenderWindow::~RenderWindow()
{
// Nothing to do
@@ -71,97 +62,56 @@ RenderWindow::~RenderWindow()
////////////////////////////////////////////////////////////
-/// /see RenderTarget::Activate
-////////////////////////////////////////////////////////////
-bool RenderWindow::Activate(bool Active)
-{
- // For performances and consistency reasons, we only handle activation
- if (Active)
- return SetActive();
- else
- return true;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the width of the rendering region of the window
-////////////////////////////////////////////////////////////
-unsigned int RenderWindow::GetWidth() const
+bool RenderWindow::activate(bool active)
{
- return sf::Window::GetWidth();
+ return setActive(active);
}
////////////////////////////////////////////////////////////
-/// Get the height of the rendering region of the window
-////////////////////////////////////////////////////////////
-unsigned int RenderWindow::GetHeight() const
+Vector2u RenderWindow::getSize() const
{
- return sf::Window::GetHeight();
+ return Window::getSize();
}
////////////////////////////////////////////////////////////
-/// Save the content of the window to an image
-////////////////////////////////////////////////////////////
-Image RenderWindow::Capture() const
+Image RenderWindow::capture() const
{
- // Get the window dimensions
- const unsigned int Width = GetWidth();
- const unsigned int Height = GetHeight();
-
- // Set our window as the current target for rendering
- if (SetActive())
- {
- // Make sure we have a valid context
- priv::GraphicsContext Ctx;
-
- // Get pixels from the backbuffer
- std::vector<Uint8> Pixels(Width * Height * 4);
- Uint8* PixelsPtr = &Pixels[0];
- GLCheck(glReadPixels(0, 0, Width, Height, GL_RGBA, GL_UNSIGNED_BYTE, PixelsPtr));
-
- // Flip the pixels
- unsigned int Pitch = Width * 4;
- for (unsigned int y = 0; y < Height / 2; ++y)
- std::swap_ranges(PixelsPtr + y * Pitch, PixelsPtr + (y + 1) * Pitch, PixelsPtr + (Height - y - 1) * Pitch);
-
- // Create an image from the pixel buffer and return it
- return Image(Width, Height, PixelsPtr);
- }
- else
+ Image image;
+ if (setActive())
{
- return Image(Width, Height, Color::White);
+ int width = static_cast<int>(getSize().x);
+ int height = static_cast<int>(getSize().y);
+
+ // copy rows one by one and flip them (OpenGL's origin is bottom while SFML's origin is top)
+ std::vector<Uint8> pixels(width * height * 4);
+ for (int i = 0; i < height; ++i)
+ {
+ Uint8* ptr = &pixels[i * width * 4];
+ glCheck(glReadPixels(0, height - i - 1, width, 1, GL_RGBA, GL_UNSIGNED_BYTE, ptr));
+ }
+
+ image.create(width, height, &pixels[0]);
}
+
+ return image;
}
////////////////////////////////////////////////////////////
-/// Convert a point in window coordinates into view coordinates
-////////////////////////////////////////////////////////////
-sf::Vector2f RenderWindow::ConvertCoords(unsigned int WindowX, unsigned int WindowY, const View* TargetView) const
+void RenderWindow::onCreate()
{
- // Use the current view if none has been passed
- if (!TargetView)
- TargetView = &GetView();
-
- float Left = TargetView->GetCenter().x - TargetView->GetHalfSize().x;
- float Top = TargetView->GetCenter().y - TargetView->GetHalfSize().y;
- float Right = TargetView->GetCenter().x + TargetView->GetHalfSize().x;
- float Bottom = TargetView->GetCenter().y + TargetView->GetHalfSize().y;
-
- return sf::Vector2f(Left + WindowX * (Right - Left) / GetWidth(),
- Top + WindowY * (Bottom - Top) / GetHeight());
+ // Just initialize the render target part
+ RenderTarget::initialize();
}
////////////////////////////////////////////////////////////
-/// Called after the window has been created
-////////////////////////////////////////////////////////////
-void RenderWindow::OnCreate()
+void RenderWindow::onResize()
{
- // We can now initialize the render target part
- RenderTarget::Initialize();
+ // Update the current view (recompute the viewport, which is stored in relative coordinates)
+ setView(getView());
}
} // namespace sf
diff --git a/src/SFML/Graphics/Shader.cpp b/src/SFML/Graphics/Shader.cpp
new file mode 100644
index 0000000..eb292b7
--- /dev/null
+++ b/src/SFML/Graphics/Shader.cpp
@@ -0,0 +1,593 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Graphics/Shader.hpp>
+#include <SFML/Graphics/Texture.hpp>
+#include <SFML/Graphics/GLCheck.hpp>
+#include <SFML/System/InputStream.hpp>
+#include <SFML/System/Err.hpp>
+#include <fstream>
+#include <vector>
+
+
+namespace
+{
+ // Retrieve the maximum number of texture units available
+ GLint getMaxTextureUnits()
+ {
+ GLint maxUnits;
+ glCheck(glGetIntegerv(GL_MAX_TEXTURE_COORDS_ARB, &maxUnits));
+ return maxUnits;
+ }
+
+ // Read the contents of a file into an array of char
+ bool getFileContents(const std::string& filename, std::vector<char>& buffer)
+ {
+ std::ifstream file(filename.c_str(), std::ios_base::binary);
+ if (file)
+ {
+ file.seekg(0, std::ios_base::end);
+ std::streamsize size = file.tellg();
+ if (size > 0)
+ {
+ file.seekg(0, std::ios_base::beg);
+ buffer.resize(static_cast<std::size_t>(size));
+ file.read(&buffer[0], size);
+ }
+ buffer.push_back('\0');
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ // Read the contents of a stream into an array of char
+ bool getStreamContents(sf::InputStream& stream, std::vector<char>& buffer)
+ {
+ bool success = true;
+ sf::Int64 size = stream.getSize();
+ if (size > 0)
+ {
+ buffer.resize(static_cast<std::size_t>(size));
+ stream.seek(0);
+ sf::Int64 read = stream.read(&buffer[0], size);
+ success = (read == size);
+ }
+ buffer.push_back('\0');
+ return success;
+ }
+}
+
+
+namespace sf
+{
+////////////////////////////////////////////////////////////
+Shader::CurrentTextureType Shader::CurrentTexture;
+
+
+////////////////////////////////////////////////////////////
+Shader::Shader() :
+m_shaderProgram (0),
+m_currentTexture(-1),
+m_textures (),
+m_params ()
+{
+}
+
+
+////////////////////////////////////////////////////////////
+Shader::~Shader()
+{
+ ensureGlContext();
+
+ // Destroy effect program
+ if (m_shaderProgram)
+ glCheck(glDeleteObjectARB(m_shaderProgram));
+}
+
+
+////////////////////////////////////////////////////////////
+bool Shader::loadFromFile(const std::string& filename, Type type)
+{
+ // Read the file
+ std::vector<char> shader;
+ if (!getFileContents(filename, shader))
+ {
+ err() << "Failed to open shader file \"" << filename << "\"" << std::endl;
+ return false;
+ }
+
+ // Compile the shader program
+ if (type == Vertex)
+ return compile(&shader[0], NULL);
+ else
+ return compile(NULL, &shader[0]);
+}
+
+
+////////////////////////////////////////////////////////////
+bool Shader::loadFromFile(const std::string& vertexShaderFilename, const std::string& fragmentShaderFilename)
+{
+ // Read the vertex shader file
+ std::vector<char> vertexShader;
+ if (!getFileContents(vertexShaderFilename, vertexShader))
+ {
+ err() << "Failed to open vertex shader file \"" << vertexShaderFilename << "\"" << std::endl;
+ return false;
+ }
+
+ // Read the fragment shader file
+ std::vector<char> fragmentShader;
+ if (!getFileContents(fragmentShaderFilename, fragmentShader))
+ {
+ err() << "Failed to open fragment shader file \"" << fragmentShaderFilename << "\"" << std::endl;
+ return false;
+ }
+
+ // Compile the shader program
+ return compile(&vertexShader[0], &fragmentShader[0]);
+}
+
+
+////////////////////////////////////////////////////////////
+bool Shader::loadFromMemory(const std::string& shader, Type type)
+{
+ // Compile the shader program
+ if (type == Vertex)
+ return compile(shader.c_str(), NULL);
+ else
+ return compile(NULL, shader.c_str());
+}
+
+
+////////////////////////////////////////////////////////////
+bool Shader::loadFromMemory(const std::string& vertexShader, const std::string& fragmentShader)
+{
+ // Compile the shader program
+ return compile(vertexShader.c_str(), fragmentShader.c_str());
+}
+
+
+////////////////////////////////////////////////////////////
+bool Shader::loadFromStream(InputStream& stream, Type type)
+{
+ // Read the shader code from the stream
+ std::vector<char> shader;
+ if (!getStreamContents(stream, shader))
+ {
+ err() << "Failed to read shader from stream" << std::endl;
+ return false;
+ }
+
+ // Compile the shader program
+ if (type == Vertex)
+ return compile(&shader[0], NULL);
+ else
+ return compile(NULL, &shader[0]);
+}
+
+
+////////////////////////////////////////////////////////////
+bool Shader::loadFromStream(InputStream& vertexShaderStream, InputStream& fragmentShaderStream)
+{
+ // Read the vertex shader code from the stream
+ std::vector<char> vertexShader;
+ if (!getStreamContents(vertexShaderStream, vertexShader))
+ {
+ err() << "Failed to read vertex shader from stream" << std::endl;
+ return false;
+ }
+
+ // Read the fragment shader code from the stream
+ std::vector<char> fragmentShader;
+ if (!getStreamContents(fragmentShaderStream, fragmentShader))
+ {
+ err() << "Failed to read fragment shader from stream" << std::endl;
+ return false;
+ }
+
+ // Compile the shader program
+ return compile(&vertexShader[0], &fragmentShader[0]);
+}
+
+
+////////////////////////////////////////////////////////////
+void Shader::setParameter(const std::string& name, float x)
+{
+ if (m_shaderProgram)
+ {
+ ensureGlContext();
+
+ // Enable program
+ GLhandleARB program = glGetHandleARB(GL_PROGRAM_OBJECT_ARB);
+ glCheck(glUseProgramObjectARB(m_shaderProgram));
+
+ // Get parameter location and assign it new values
+ GLint location = getParamLocation(name);
+ if (location != -1)
+ glCheck(glUniform1fARB(location, x));
+
+ // Disable program
+ glCheck(glUseProgramObjectARB(program));
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void Shader::setParameter(const std::string& name, float x, float y)
+{
+ if (m_shaderProgram)
+ {
+ ensureGlContext();
+
+ // Enable program
+ GLhandleARB program = glGetHandleARB(GL_PROGRAM_OBJECT_ARB);
+ glCheck(glUseProgramObjectARB(m_shaderProgram));
+
+ // Get parameter location and assign it new values
+ GLint location = getParamLocation(name);
+ if (location != -1)
+ glCheck(glUniform2fARB(location, x, y));
+
+ // Disable program
+ glCheck(glUseProgramObjectARB(program));
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void Shader::setParameter(const std::string& name, float x, float y, float z)
+{
+ if (m_shaderProgram)
+ {
+ ensureGlContext();
+
+ // Enable program
+ GLhandleARB program = glGetHandleARB(GL_PROGRAM_OBJECT_ARB);
+ glCheck(glUseProgramObjectARB(m_shaderProgram));
+
+ // Get parameter location and assign it new values
+ GLint location = getParamLocation(name);
+ if (location != -1)
+ glCheck(glUniform3fARB(location, x, y, z));
+
+ // Disable program
+ glCheck(glUseProgramObjectARB(program));
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void Shader::setParameter(const std::string& name, float x, float y, float z, float w)
+{
+ if (m_shaderProgram)
+ {
+ ensureGlContext();
+
+ // Enable program
+ GLhandleARB program = glGetHandleARB(GL_PROGRAM_OBJECT_ARB);
+ glCheck(glUseProgramObjectARB(m_shaderProgram));
+
+ // Get parameter location and assign it new values
+ GLint location = getParamLocation(name);
+ if (location != -1)
+ glCheck(glUniform4fARB(location, x, y, z, w));
+
+ // Disable program
+ glCheck(glUseProgramObjectARB(program));
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void Shader::setParameter(const std::string& name, const Vector2f& v)
+{
+ setParameter(name, v.x, v.y);
+}
+
+
+////////////////////////////////////////////////////////////
+void Shader::setParameter(const std::string& name, const Vector3f& v)
+{
+ setParameter(name, v.x, v.y, v.z);
+}
+
+
+////////////////////////////////////////////////////////////
+void Shader::setParameter(const std::string& name, const Color& color)
+{
+ setParameter(name, color.r / 255.f, color.g / 255.f, color.b / 255.f, color.a / 255.f);
+}
+
+
+////////////////////////////////////////////////////////////
+void Shader::setParameter(const std::string& name, const sf::Transform& transform)
+{
+ if (m_shaderProgram)
+ {
+ ensureGlContext();
+
+ // Enable program
+ GLhandleARB program = glGetHandleARB(GL_PROGRAM_OBJECT_ARB);
+ glCheck(glUseProgramObjectARB(m_shaderProgram));
+
+ // Get parameter location and assign it new values
+ GLint location = getParamLocation(name);
+ if (location != -1)
+ glCheck(glUniformMatrix4fvARB(location, 1, GL_FALSE, transform.getMatrix()));
+
+ // Disable program
+ glCheck(glUseProgramObjectARB(program));
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void Shader::setParameter(const std::string& name, const Texture& texture)
+{
+ if (m_shaderProgram)
+ {
+ ensureGlContext();
+
+ // Find the location of the variable in the shader
+ int location = getParamLocation(name);
+ if (location != -1)
+ {
+ // Store the location -> texture mapping
+ TextureTable::iterator it = m_textures.find(location);
+ if (it == m_textures.end())
+ {
+ // New entry, make sure there are enough texture units
+ static const GLint maxUnits = getMaxTextureUnits();
+ if (m_textures.size() + 1 >= static_cast<std::size_t>(maxUnits))
+ {
+ err() << "Impossible to use texture \"" << name << "\" for shader: all available texture units are used" << std::endl;
+ return;
+ }
+
+ m_textures[location] = &texture;
+ }
+ else
+ {
+ // Location already used, just replace the texture
+ it->second = &texture;
+ }
+ }
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void Shader::setParameter(const std::string& name, CurrentTextureType)
+{
+ if (m_shaderProgram)
+ {
+ ensureGlContext();
+
+ // Find the location of the variable in the shader
+ m_currentTexture = getParamLocation(name);
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void Shader::bind(const Shader* shader)
+{
+ ensureGlContext();
+
+ if (shader && shader->m_shaderProgram)
+ {
+ // Enable the program
+ glCheck(glUseProgramObjectARB(shader->m_shaderProgram));
+
+ // Bind the textures
+ shader->bindTextures();
+
+ // Bind the current texture
+ if (shader->m_currentTexture != -1)
+ glCheck(glUniform1iARB(shader->m_currentTexture, 0));
+ }
+ else
+ {
+ // Bind no shader
+ glCheck(glUseProgramObjectARB(0));
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+bool Shader::isAvailable()
+{
+ ensureGlContext();
+
+ // Make sure that GLEW is initialized
+ priv::ensureGlewInit();
+
+ return GLEW_ARB_shading_language_100 &&
+ GLEW_ARB_shader_objects &&
+ GLEW_ARB_vertex_shader &&
+ GLEW_ARB_fragment_shader;
+}
+
+
+////////////////////////////////////////////////////////////
+bool Shader::compile(const char* vertexShaderCode, const char* fragmentShaderCode)
+{
+ ensureGlContext();
+
+ // First make sure that we can use shaders
+ if (!isAvailable())
+ {
+ err() << "Failed to create a shader: your system doesn't support shaders "
+ << "(you should test Shader::isAvailable() before trying to use the Shader class)" << std::endl;
+ return false;
+ }
+
+ // Destroy the shader if it was already created
+ if (m_shaderProgram)
+ glCheck(glDeleteObjectARB(m_shaderProgram));
+
+ // Reset the internal state
+ m_currentTexture = -1;
+ m_textures.clear();
+ m_params.clear();
+
+ // Create the program
+ m_shaderProgram = glCreateProgramObjectARB();
+
+ // Create the vertex shader if needed
+ if (vertexShaderCode)
+ {
+ // Create and compile the shader
+ GLhandleARB vertexShader = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB);
+ glCheck(glShaderSourceARB(vertexShader, 1, &vertexShaderCode, NULL));
+ glCheck(glCompileShaderARB(vertexShader));
+
+ // Check the compile log
+ GLint success;
+ glCheck(glGetObjectParameterivARB(vertexShader, GL_OBJECT_COMPILE_STATUS_ARB, &success));
+ if (success == GL_FALSE)
+ {
+ char log[1024];
+ glCheck(glGetInfoLogARB(vertexShader, sizeof(log), 0, log));
+ err() << "Failed to compile vertex shader:" << std::endl
+ << log << std::endl;
+ glCheck(glDeleteObjectARB(vertexShader));
+ glCheck(glDeleteObjectARB(m_shaderProgram));
+ m_shaderProgram = 0;
+ return false;
+ }
+
+ // Attach the shader to the program, and delete it (not needed anymore)
+ glCheck(glAttachObjectARB(m_shaderProgram, vertexShader));
+ glCheck(glDeleteObjectARB(vertexShader));
+ }
+
+ // Create the fragment shader if needed
+ if (fragmentShaderCode)
+ {
+ // Create and compile the shader
+ GLhandleARB fragmentShader = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);
+ glCheck(glShaderSourceARB(fragmentShader, 1, &fragmentShaderCode, NULL));
+ glCheck(glCompileShaderARB(fragmentShader));
+
+ // Check the compile log
+ GLint success;
+ glCheck(glGetObjectParameterivARB(fragmentShader, GL_OBJECT_COMPILE_STATUS_ARB, &success));
+ if (success == GL_FALSE)
+ {
+ char log[1024];
+ glCheck(glGetInfoLogARB(fragmentShader, sizeof(log), 0, log));
+ err() << "Failed to compile fragment shader:" << std::endl
+ << log << std::endl;
+ glCheck(glDeleteObjectARB(fragmentShader));
+ glCheck(glDeleteObjectARB(m_shaderProgram));
+ m_shaderProgram = 0;
+ return false;
+ }
+
+ // Attach the shader to the program, and delete it (not needed anymore)
+ glCheck(glAttachObjectARB(m_shaderProgram, fragmentShader));
+ glCheck(glDeleteObjectARB(fragmentShader));
+ }
+
+ // Link the program
+ glCheck(glLinkProgramARB(m_shaderProgram));
+
+ // Check the link log
+ GLint success;
+ glCheck(glGetObjectParameterivARB(m_shaderProgram, GL_OBJECT_LINK_STATUS_ARB, &success));
+ if (success == GL_FALSE)
+ {
+ char log[1024];
+ glCheck(glGetInfoLogARB(m_shaderProgram, sizeof(log), 0, log));
+ err() << "Failed to link shader:" << std::endl
+ << log << std::endl;
+ glCheck(glDeleteObjectARB(m_shaderProgram));
+ m_shaderProgram = 0;
+ return false;
+ }
+
+ // Force an OpenGL flush, so that the shader will appear updated
+ // in all contexts immediately (solves problems in multi-threaded apps)
+ glCheck(glFlush());
+
+ return true;
+}
+
+
+////////////////////////////////////////////////////////////
+void Shader::bindTextures() const
+{
+ TextureTable::const_iterator it = m_textures.begin();
+ for (std::size_t i = 0; i < m_textures.size(); ++i)
+ {
+ GLint index = static_cast<GLsizei>(i + 1);
+ glCheck(glUniform1iARB(it->first, index));
+ glCheck(glActiveTextureARB(GL_TEXTURE0_ARB + index));
+ Texture::bind(it->second);
+ ++it;
+ }
+
+ // Make sure that the texture unit which is left active is the number 0
+ glCheck(glActiveTextureARB(GL_TEXTURE0_ARB));
+}
+
+
+////////////////////////////////////////////////////////////
+int Shader::getParamLocation(const std::string& name)
+{
+ // Check the cache
+ ParamTable::const_iterator it = m_params.find(name);
+ if (it != m_params.end())
+ {
+ // Already in cache, return it
+ return it->second;
+ }
+ else
+ {
+ // Not in cache, request the location from OpenGL
+ int location = glGetUniformLocationARB(m_shaderProgram, name.c_str());
+ if (location != -1)
+ {
+ // Location found: add it to the cache
+ m_params.insert(std::make_pair(name, location));
+ }
+ else
+ {
+ // Error: location not found
+ err() << "Parameter \"" << name << "\" not found in shader" << std::endl;
+ }
+
+ return location;
+ }
+}
+
+} // namespace sf
diff --git a/src/SFML/Graphics/Shape.cpp b/src/SFML/Graphics/Shape.cpp
index ca613f0..16524f5 100755..100644
--- a/src/SFML/Graphics/Shape.cpp
+++ b/src/SFML/Graphics/Shape.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -26,400 +26,280 @@
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Shape.hpp>
-#include <SFML/Graphics/GraphicsContext.hpp>
-#include <math.h>
+#include <SFML/Graphics/RenderTarget.hpp>
+#include <SFML/Graphics/Texture.hpp>
+#include <SFML/System/Err.hpp>
+#include <cmath>
-namespace sf
-{
-////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
-Shape::Shape() :
-myOutline (0.f),
-myIsFillEnabled (true),
-myIsOutlineEnabled(true),
-myIsCompiled (false)
+namespace
{
- // Put a placeholder for the center of the shape
- myPoints.push_back(Point());
+ // Compute the normal of a segment
+ sf::Vector2f computeNormal(const sf::Vector2f& p1, const sf::Vector2f& p2)
+ {
+ sf::Vector2f normal(p1.y - p2.y, p2.x - p1.x);
+ float length = std::sqrt(normal.x * normal.x + normal.y * normal.y);
+ if (length != 0.f)
+ normal /= length;
+ return normal;
+ }
+
+ // Compute the dot product of two vectors
+ float dotProduct(const sf::Vector2f& p1, const sf::Vector2f& p2)
+ {
+ return p1.x * p2.x + p1.y * p2.y;
+ }
}
+namespace sf
+{
////////////////////////////////////////////////////////////
-/// Add a point to the shape
-////////////////////////////////////////////////////////////
-void Shape::AddPoint(float X, float Y, const Color& Col, const Color& OutlineCol)
+Shape::~Shape()
{
- AddPoint(Vector2f(X, Y), Col, OutlineCol);
}
////////////////////////////////////////////////////////////
-/// Add a point to the shape
-////////////////////////////////////////////////////////////
-void Shape::AddPoint(const Vector2f& Position, const Color& Col, const Color& OutlineCol)
+void Shape::setTexture(const Texture* texture, bool resetRect)
{
- myPoints.push_back(Point(Position, Col, OutlineCol));
- myIsCompiled = false;
+ if (texture)
+ {
+ // Recompute the texture area if requested, or if there was no texture & rect before
+ if (resetRect || (!m_texture && (m_textureRect == sf::IntRect())))
+ setTextureRect(IntRect(0, 0, texture->getSize().x, texture->getSize().y));
+ }
+
+ // Assign the new texture
+ m_texture = texture;
}
////////////////////////////////////////////////////////////
-/// Get the number of points composing the shape
-////////////////////////////////////////////////////////////
-unsigned int Shape::GetNbPoints() const
+const Texture* Shape::getTexture() const
{
- return static_cast<unsigned int>(myPoints.size() - 1);
+ return m_texture;
}
////////////////////////////////////////////////////////////
-/// Enable or disable filling the shape.
-/// Fill is enabled by default
-////////////////////////////////////////////////////////////
-void Shape::EnableFill(bool Enable)
+void Shape::setTextureRect(const IntRect& rect)
{
- myIsFillEnabled = Enable;
+ m_textureRect = rect;
+ updateTexCoords();
}
////////////////////////////////////////////////////////////
-/// Enable or disable drawing the shape outline.
-/// Outline is enabled by default
-////////////////////////////////////////////////////////////
-void Shape::EnableOutline(bool Enable)
+const IntRect& Shape::getTextureRect() const
{
- myIsOutlineEnabled = Enable;
+ return m_textureRect;
}
////////////////////////////////////////////////////////////
-/// Set the position of a point
-////////////////////////////////////////////////////////////
-void Shape::SetPointPosition(unsigned int Index, const Vector2f& Position)
+void Shape::setFillColor(const Color& color)
{
- myPoints[Index + 1].Position = Position;
- myIsCompiled = false;
+ m_fillColor = color;
+ updateFillColors();
}
////////////////////////////////////////////////////////////
-/// Set the position of a point
-////////////////////////////////////////////////////////////
-void Shape::SetPointPosition(unsigned int Index, float X, float Y)
+const Color& Shape::getFillColor() const
{
- SetPointPosition(Index, Vector2f(X, Y));
+ return m_fillColor;
}
////////////////////////////////////////////////////////////
-/// Set the color of a point
-////////////////////////////////////////////////////////////
-void Shape::SetPointColor(unsigned int Index, const Color& Col)
+void Shape::setOutlineColor(const Color& color)
{
- myPoints[Index + 1].Col = Col;
- myIsCompiled = false;
+ m_outlineColor = color;
+ updateOutlineColors();
}
////////////////////////////////////////////////////////////
-/// Set the outline color of a point
-////////////////////////////////////////////////////////////
-void Shape::SetPointOutlineColor(unsigned int Index, const Color& OutlineCol)
+const Color& Shape::getOutlineColor() const
{
- myPoints[Index + 1].OutlineCol = OutlineCol;
- myIsCompiled = false;
+ return m_outlineColor;
}
////////////////////////////////////////////////////////////
-/// Change the width of the shape outline
-////////////////////////////////////////////////////////////
-void Shape::SetOutlineWidth(float Width)
+void Shape::setOutlineThickness(float thickness)
{
- myOutline = Width;
+ m_outlineThickness = thickness;
+ update(); // recompute everything because the whole shape must be offset
}
////////////////////////////////////////////////////////////
-/// Get the position of a point
-////////////////////////////////////////////////////////////
-const Vector2f& Shape::GetPointPosition(unsigned int Index) const
+float Shape::getOutlineThickness() const
{
- return myPoints[Index + 1].Position;
+ return m_outlineThickness;
}
////////////////////////////////////////////////////////////
-/// Get the color of a point
-////////////////////////////////////////////////////////////
-const Color& Shape::GetPointColor(unsigned int Index) const
+FloatRect Shape::getLocalBounds() const
{
- return myPoints[Index + 1].Col;
+ return m_bounds;
}
////////////////////////////////////////////////////////////
-/// Get the outline color of a point
-////////////////////////////////////////////////////////////
-const Color& Shape::GetPointOutlineColor(unsigned int Index) const
+FloatRect Shape::getGlobalBounds() const
{
- return myPoints[Index + 1].OutlineCol;
+ return getTransform().transformRect(getLocalBounds());
}
////////////////////////////////////////////////////////////
-/// Get the width of the shape outline
-////////////////////////////////////////////////////////////
-float Shape::GetOutlineWidth() const
+Shape::Shape() :
+m_texture (NULL),
+m_textureRect (),
+m_fillColor (255, 255, 255),
+m_outlineColor (255, 255, 255),
+m_outlineThickness(0),
+m_vertices (TrianglesFan),
+m_outlineVertices (TrianglesStrip),
+m_insideBounds (),
+m_bounds ()
{
- return myOutline;
}
////////////////////////////////////////////////////////////
-/// Create a shape made of a single line
-////////////////////////////////////////////////////////////
-Shape Shape::Line(float P1X, float P1Y, float P2X, float P2Y, float Thickness, const Color& Col, float Outline, const Color& OutlineCol)
+void Shape::update()
{
- Vector2f P1(P1X, P1Y);
- Vector2f P2(P2X, P2Y);
-
- // Compute the extrusion direction
- Vector2f Normal;
- ComputeNormal(P1, P2, Normal);
- Normal *= Thickness / 2;
-
- // Create the shape's points
- Shape S;
- S.AddPoint(P1 - Normal, Col, OutlineCol);
- S.AddPoint(P2 - Normal, Col, OutlineCol);
- S.AddPoint(P2 + Normal, Col, OutlineCol);
- S.AddPoint(P1 + Normal, Col, OutlineCol);
- S.SetOutlineWidth(Outline);
-
- // Compile it
- S.Compile();
-
- return S;
-}
+ // Get the total number of points of the shape
+ unsigned int count = getPointCount();
+ if (count < 3)
+ {
+ m_vertices.resize(0);
+ m_outlineVertices.resize(0);
+ return;
+ }
+ m_vertices.resize(count + 2); // + 2 for center and repeated first point
-////////////////////////////////////////////////////////////
-/// Create a shape made of a single line (use vectors)
-////////////////////////////////////////////////////////////
-Shape Shape::Line(const Vector2f& P1, const Vector2f& P2, float Thickness, const Color& Col, float Outline, const Color& OutlineCol)
-{
- return Shape::Line(P1.x, P1.y, P2.x, P2.y, Thickness, Col, Outline, OutlineCol);
-}
+ // Position
+ for (unsigned int i = 0; i < count; ++i)
+ m_vertices[i + 1].position = getPoint(i);
+ m_vertices[count + 1].position = m_vertices[1].position;
+ // Update the bounding rectangle
+ m_vertices[0] = m_vertices[1]; // so that the result of getBounds() is correct
+ m_insideBounds = m_vertices.getBounds();
-////////////////////////////////////////////////////////////
-/// Create a shape made of a single rectangle
-////////////////////////////////////////////////////////////
-Shape Shape::Rectangle(float P1X, float P1Y, float P2X, float P2Y, const Color& Col, float Outline, const Color& OutlineCol)
-{
- // Create the shape's points
- Shape S;
- S.AddPoint(Vector2f(P1X, P1Y), Col, OutlineCol);
- S.AddPoint(Vector2f(P2X, P1Y), Col, OutlineCol);
- S.AddPoint(Vector2f(P2X, P2Y), Col, OutlineCol);
- S.AddPoint(Vector2f(P1X, P2Y), Col, OutlineCol);
- S.SetOutlineWidth(Outline);
-
- // Compile it
- S.Compile();
-
- return S;
-}
+ // Compute the center and make it the first vertex
+ m_vertices[0].position.x = m_insideBounds.left + m_insideBounds.width / 2;
+ m_vertices[0].position.y = m_insideBounds.top + m_insideBounds.height / 2;
+ // Color
+ updateFillColors();
-////////////////////////////////////////////////////////////
-/// Create a shape made of a single rectangle (use vectors)
-////////////////////////////////////////////////////////////
-Shape Shape::Rectangle(const Vector2f& P1, const Vector2f& P2, const Color& Col, float Outline, const Color& OutlineCol)
-{
- return Shape::Rectangle(P1.x, P1.y, P2.x, P2.y, Col, Outline, OutlineCol);
+ // Texture coordinates
+ updateTexCoords();
+
+ // Outline
+ updateOutline();
}
////////////////////////////////////////////////////////////
-/// Create a shape made of a single circle
-////////////////////////////////////////////////////////////
-Shape Shape::Circle(float X, float Y, float Radius, const Color& Col, float Outline, const Color& OutlineCol)
+void Shape::draw(RenderTarget& target, RenderStates states) const
{
- static const int NbSegments = 40;
+ states.transform *= getTransform();
- // Create the points set
- Shape S;
- Vector2f Center(X, Y);
- for (int i = 0; i < NbSegments; ++i)
- {
- float Angle = i * 2 * 3.141592654f / NbSegments;
- Vector2f Offset(cos(Angle), sin(Angle));
+ // Render the inside
+ states.texture = m_texture;
+ target.draw(m_vertices, states);
- S.AddPoint(Center + Offset * Radius, Col, OutlineCol);
+ // Render the outline
+ if (m_outlineThickness != 0)
+ {
+ states.texture = NULL;
+ target.draw(m_outlineVertices, states);
}
-
- // Compile it
- S.SetOutlineWidth(Outline);
- S.Compile();
-
- return S;
}
////////////////////////////////////////////////////////////
-/// Create a shape made of a single circle (use vectors)
-////////////////////////////////////////////////////////////
-Shape Shape::Circle(const Vector2f& Center, float Radius, const Color& Col, float Outline, const Color& OutlineCol)
+void Shape::updateFillColors()
{
- return Shape::Circle(Center.x, Center.y, Radius, Col, Outline, OutlineCol);
+ for (unsigned int i = 0; i < m_vertices.getVertexCount(); ++i)
+ m_vertices[i].color = m_fillColor;
}
////////////////////////////////////////////////////////////
-/// /see Drawable::Render
-////////////////////////////////////////////////////////////
-void Shape::Render(RenderTarget&) const
+void Shape::updateTexCoords()
{
- // Make sure the shape has at least 3 points (4 if we count the center)
- if (myPoints.size() < 4)
- return;
-
- // Make sure the shape is compiled
- if (!myIsCompiled)
- const_cast<Shape*>(this)->Compile();
-
- // Shapes only use color, no texture
- GLCheck(glDisable(GL_TEXTURE_2D));
-
- // Draw the shape
- if (myIsFillEnabled)
+ for (unsigned int i = 0; i < m_vertices.getVertexCount(); ++i)
{
- glBegin(GL_TRIANGLE_FAN);
- {
- for (std::vector<Point>::const_iterator i = myPoints.begin(); i != myPoints.end(); ++i)
- {
- Color PointColor = i->Col * GetColor();
- glColor4f(PointColor.r / 255.f, PointColor.g / 255.f, PointColor.b / 255.f, PointColor.a / 255.f);
- glVertex2f(i->Position.x, i->Position.y);
- }
-
- // Close the shape by duplicating the first point at the end
- Color PointColor = myPoints[1].Col * GetColor();
- glColor4f(PointColor.r / 255.f, PointColor.g / 255.f, PointColor.b / 255.f, PointColor.a / 255.f);
- glVertex2f(myPoints[1].Position.x, myPoints[1].Position.y);
- }
- glEnd();
- }
-
- // Draw the outline
- if (myIsOutlineEnabled)
- {
- glBegin(GL_TRIANGLE_STRIP);
- {
- for (std::size_t i = 1; i < myPoints.size(); ++i)
- {
- Color PointColor = myPoints[i].OutlineCol * GetColor();
- glColor4f(PointColor.r / 255.f, PointColor.g / 255.f, PointColor.b / 255.f, PointColor.a / 255.f);
- glVertex2f(myPoints[i].Position.x, myPoints[i].Position.y);
- glColor4f(PointColor.r / 255.f, PointColor.g / 255.f, PointColor.b / 255.f, PointColor.a / 255.f);
- glVertex2f(myPoints[i].Position.x + myPoints[i].Normal.x * myOutline, myPoints[i].Position.y + myPoints[i].Normal.y * myOutline);
- }
-
- // Close the shape by duplicating the first point at the end
- Color PointColor = myPoints[1].OutlineCol * GetColor();
- glColor4f(PointColor.r / 255.f, PointColor.g / 255.f, PointColor.b / 255.f, PointColor.a / 255.f);
- glVertex2f(myPoints[1].Position.x, myPoints[1].Position.y);
- glColor4f(PointColor.r / 255.f, PointColor.g / 255.f, PointColor.b / 255.f, PointColor.a / 255.f);
- glVertex2f(myPoints[1].Position.x + myPoints[1].Normal.x * myOutline, myPoints[1].Position.y + myPoints[1].Normal.y * myOutline);
- }
- glEnd();
+ float xratio = (m_vertices[i].position.x - m_insideBounds.left) / m_insideBounds.width;
+ float yratio = (m_vertices[i].position.y - m_insideBounds.top) / m_insideBounds.height;
+ m_vertices[i].texCoords.x = m_textureRect.left + m_textureRect.width * xratio;
+ m_vertices[i].texCoords.y = m_textureRect.top + m_textureRect.height * yratio;
}
}
////////////////////////////////////////////////////////////
-/// Compile the shape : compute its center and its outline
-////////////////////////////////////////////////////////////
-void Shape::Compile()
+void Shape::updateOutline()
{
- // Compute the center
- float NbPoints = static_cast<float>(myPoints.size() - 1);
- float R = 0, G = 0, B = 0, A = 0;
- Point Center(Vector2f(0, 0), Color(0, 0, 0, 0));
- for (std::size_t i = 1; i < myPoints.size(); ++i)
- {
- Center.Position += myPoints[i].Position / NbPoints;
- R += myPoints[i].Col.r / NbPoints;
- G += myPoints[i].Col.g / NbPoints;
- B += myPoints[i].Col.b / NbPoints;
- A += myPoints[i].Col.a / NbPoints;
- }
- Center.Col.r = static_cast<Uint8>(R);
- Center.Col.g = static_cast<Uint8>(G);
- Center.Col.b = static_cast<Uint8>(B);
- Center.Col.a = static_cast<Uint8>(A);
- myPoints[0] = Center;
-
- // Compute the outline
- for (std::size_t i = 1; i < myPoints.size(); ++i)
+ unsigned int count = m_vertices.getVertexCount() - 2;
+ m_outlineVertices.resize((count + 1) * 2);
+
+ for (unsigned int i = 0; i < count; ++i)
{
+ unsigned int index = i + 1;
+
// Get the two segments shared by the current point
- Point& P0 = (i == 1) ? myPoints[myPoints.size() - 1] : myPoints[i - 1];
- Point& P1 = myPoints[i];
- Point& P2 = (i == myPoints.size() - 1) ? myPoints[1] : myPoints[i + 1];
+ Vector2f p0 = (i == 0) ? m_vertices[count].position : m_vertices[index - 1].position;
+ Vector2f p1 = m_vertices[index].position;
+ Vector2f p2 = m_vertices[index + 1].position;
// Compute their normal
- Vector2f Normal1, Normal2;
- if (!ComputeNormal(P0.Position, P1.Position, Normal1) || !ComputeNormal(P1.Position, P2.Position, Normal2))
- continue;
-
- // Add them to get the extrusion direction
- float Factor = 1.f + (Normal1.x * Normal2.x + Normal1.y * Normal2.y);
- P1.Normal = (Normal1 + Normal2) / Factor;
-
- // Make sure it points towards the outside of the shape
- float Dot = (P1.Position.x - Center.Position.x) * P1.Normal.x + (P1.Position.y - Center.Position.y) * P1.Normal.y;
- if (Dot < 0)
- P1.Normal = -P1.Normal;
+ Vector2f n1 = computeNormal(p0, p1);
+ Vector2f n2 = computeNormal(p1, p2);
+
+ // Make sure that the normals point towards the outside of the shape
+ // (this depends on the order in which the points were defined)
+ if (dotProduct(n1, m_vertices[0].position - p1) > 0)
+ n1 = -n1;
+ if (dotProduct(n2, m_vertices[0].position - p1) > 0)
+ n2 = -n2;
+
+ // Combine them to get the extrusion direction
+ float factor = 1.f + (n1.x * n2.x + n1.y * n2.y);
+ Vector2f normal = (n1 + n2) / factor;
+
+ // Update the outline points
+ m_outlineVertices[i * 2 + 0].position = p1;
+ m_outlineVertices[i * 2 + 1].position = p1 + normal * m_outlineThickness;
}
- myIsCompiled = true;
-}
-
+ // Duplicate the first point at the end, to close the outline
+ m_outlineVertices[count * 2 + 0].position = m_outlineVertices[0].position;
+ m_outlineVertices[count * 2 + 1].position = m_outlineVertices[1].position;
-////////////////////////////////////////////////////////////
-/// Compute the normal of a given 2D segment
-////////////////////////////////////////////////////////////
-bool Shape::ComputeNormal(const Vector2f& P1, const Vector2f& P2, Vector2f& Normal)
-{
- Normal.x = P1.y - P2.y;
- Normal.y = P2.x - P1.x;
+ // Update outline colors
+ updateOutlineColors();
- float Len = sqrt(Normal.x * Normal.x + Normal.y * Normal.y);
- if (Len == 0.f)
- return false;
-
- Normal.x /= Len;
- Normal.y /= Len;
-
- return true;
+ // Update the shape's bounds
+ m_bounds = m_outlineVertices.getBounds();
}
////////////////////////////////////////////////////////////
-/// Default constructor for Point
-////////////////////////////////////////////////////////////
-Shape::Point::Point(const Vector2f& Pos, const Color& C, const Color& OutlineC) :
-Position (Pos),
-Normal (0.f, 0.f),
-Col (C),
-OutlineCol(OutlineC)
+void Shape::updateOutlineColors()
{
-
+ for (unsigned int i = 0; i < m_outlineVertices.getVertexCount(); ++i)
+ m_outlineVertices[i].color = m_outlineColor;
}
} // namespace sf
diff --git a/src/SFML/Graphics/Sprite.cpp b/src/SFML/Graphics/Sprite.cpp
index 375bd5e..d5df41e 100755..100644
--- a/src/SFML/Graphics/Sprite.cpp
+++ b/src/SFML/Graphics/Sprite.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -26,201 +26,149 @@
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Sprite.hpp>
-#include <SFML/Graphics/Image.hpp>
-#include <SFML/Graphics/GraphicsContext.hpp>
+#include <SFML/Graphics/Texture.hpp>
+#include <SFML/Graphics/RenderTarget.hpp>
+#include <cstdlib>
namespace sf
{
////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
Sprite::Sprite() :
-mySubRect (0, 0, 1, 1),
-myIsFlippedX(false),
-myIsFlippedY(false)
+m_texture (NULL),
+m_textureRect()
{
-
}
////////////////////////////////////////////////////////////
-/// Construct the sprite from a source image
-////////////////////////////////////////////////////////////
-Sprite::Sprite(const Image& Img, const Vector2f& Position, const Vector2f& Scale, float Rotation, const Color& Col) :
-Drawable (Position, Scale, Rotation, Col),
-mySubRect (0, 0, 1, 1),
-myIsFlippedX(false),
-myIsFlippedY(false)
+Sprite::Sprite(const Texture& texture) :
+m_texture (NULL),
+m_textureRect()
{
- SetImage(Img);
+ setTexture(texture);
}
////////////////////////////////////////////////////////////
-/// Set the image of the sprite
-////////////////////////////////////////////////////////////
-void Sprite::SetImage(const Image& Img)
+Sprite::Sprite(const Texture& texture, const IntRect& rectangle) :
+m_texture (NULL),
+m_textureRect()
{
- // If there was no source image before and the new image is valid, adjust the source rectangle
- if (!myImage && (Img.GetWidth() > 0) && (Img.GetHeight() > 0))
- {
- SetSubRect(IntRect(0, 0, Img.GetWidth(), Img.GetHeight()));
- }
-
- // Assign the new image
- myImage = &Img;
+ setTexture(texture);
+ setTextureRect(rectangle);
}
////////////////////////////////////////////////////////////
-/// Set the sub-rectangle of the sprite inside the source image
-////////////////////////////////////////////////////////////
-void Sprite::SetSubRect(const IntRect& SubRect)
+void Sprite::setTexture(const Texture& texture, bool resetRect)
{
- mySubRect = SubRect;
+ // Recompute the texture area if requested, or if there was no valid texture & rect before
+ if (resetRect || (!m_texture && (m_textureRect == sf::IntRect())))
+ setTextureRect(IntRect(0, 0, texture.getSize().x, texture.getSize().y));
+
+ // Assign the new texture
+ m_texture = &texture;
}
////////////////////////////////////////////////////////////
-/// Resize the sprite (by changing its scale factors) (take 2 values).
-/// The default size is defined by the subrect
-////////////////////////////////////////////////////////////
-void Sprite::Resize(float Width, float Height)
+void Sprite::setTextureRect(const IntRect& rectangle)
{
- int LocalWidth = mySubRect.GetWidth();
- int LocalHeight = mySubRect.GetHeight();
-
- if ((LocalWidth > 0) && (LocalHeight > 0))
- SetScale(Width / LocalWidth, Height / LocalHeight);
+ if (rectangle != m_textureRect)
+ {
+ m_textureRect = rectangle;
+ updatePositions();
+ updateTexCoords();
+ }
}
////////////////////////////////////////////////////////////
-/// Resize the object (by changing its scale factors) (take a 2D vector)
-/// The default size is defined by the subrect
-////////////////////////////////////////////////////////////
-void Sprite::Resize(const Vector2f& Size)
+void Sprite::setColor(const Color& color)
{
- Resize(Size.x, Size.y);
+ // Update the vertices' color
+ m_vertices[0].color = color;
+ m_vertices[1].color = color;
+ m_vertices[2].color = color;
+ m_vertices[3].color = color;
}
////////////////////////////////////////////////////////////
-/// Flip the sprite horizontally
-////////////////////////////////////////////////////////////
-void Sprite::FlipX(bool Flipped)
+const Texture* Sprite::getTexture() const
{
- myIsFlippedX = Flipped;
+ return m_texture;
}
////////////////////////////////////////////////////////////
-/// Flip the sprite vertically
-////////////////////////////////////////////////////////////
-void Sprite::FlipY(bool Flipped)
+const IntRect& Sprite::getTextureRect() const
{
- myIsFlippedY = Flipped;
+ return m_textureRect;
}
////////////////////////////////////////////////////////////
-/// Get the source image of the sprite
-////////////////////////////////////////////////////////////
-const Image* Sprite::GetImage() const
+const Color& Sprite::getColor() const
{
- return myImage;
+ return m_vertices[0].color;
}
////////////////////////////////////////////////////////////
-/// Get the sub-rectangle of the sprite inside the source image
-////////////////////////////////////////////////////////////
-const IntRect& Sprite::GetSubRect() const
+FloatRect Sprite::getLocalBounds() const
{
- return mySubRect;
+ float width = static_cast<float>(std::abs(m_textureRect.width));
+ float height = static_cast<float>(std::abs(m_textureRect.height));
+
+ return FloatRect(0.f, 0.f, width, height);
}
////////////////////////////////////////////////////////////
-/// Get the sprite size
-////////////////////////////////////////////////////////////
-Vector2f Sprite::GetSize() const
+FloatRect Sprite::getGlobalBounds() const
{
- return Vector2f(mySubRect.GetWidth() * GetScale().x, mySubRect.GetHeight() * GetScale().y);
+ return getTransform().transformRect(getLocalBounds());
}
////////////////////////////////////////////////////////////
-/// Get the color of a given pixel in the sprite
-/// (point is in local coordinates)
-////////////////////////////////////////////////////////////
-Color Sprite::GetPixel(unsigned int X, unsigned int Y) const
+void Sprite::draw(RenderTarget& target, RenderStates states) const
{
- if (myImage)
+ if (m_texture)
{
- unsigned int ImageX = mySubRect.Left + X;
- unsigned int ImageY = mySubRect.Top + Y;
-
- if (myIsFlippedX) ImageX = mySubRect.GetWidth() - ImageX - 1;
- if (myIsFlippedY) ImageY = mySubRect.GetHeight() - ImageY - 1;
-
- return myImage->GetPixel(ImageX, ImageY) * GetColor();
- }
- else
- {
- return GetColor();
+ states.transform *= getTransform();
+ states.texture = m_texture;
+ target.draw(m_vertices, 4, Quads, states);
}
}
////////////////////////////////////////////////////////////
-/// /see sfDrawable::Render
-////////////////////////////////////////////////////////////
-void Sprite::Render(RenderTarget&) const
+void Sprite::updatePositions()
{
- // Get the sprite size
- float Width = static_cast<float>(mySubRect.GetWidth());
- float Height = static_cast<float>(mySubRect.GetHeight());
+ FloatRect bounds = getLocalBounds();
- // Check if the image is valid
- if (myImage && (myImage->GetWidth() > 0) && (myImage->GetHeight() > 0))
- {
- // Use the "offset trick" to get pixel-perfect rendering
- // see http://www.opengl.org/resources/faq/technical/transformations.htm#tran0030
- GLCheck(glTranslatef(0.375f, 0.375f, 0.f));
-
- // Bind the texture
- myImage->Bind();
-
- // Calculate the texture coordinates
- FloatRect TexCoords = myImage->GetTexCoords(mySubRect);
- FloatRect Rect(myIsFlippedX ? TexCoords.Right : TexCoords.Left,
- myIsFlippedY ? TexCoords.Bottom : TexCoords.Top,
- myIsFlippedX ? TexCoords.Left : TexCoords.Right,
- myIsFlippedY ? TexCoords.Top : TexCoords.Bottom);
-
- // Draw the sprite's triangles
- glBegin(GL_QUADS);
- glTexCoord2f(Rect.Left, Rect.Top); glVertex2f(0, 0);
- glTexCoord2f(Rect.Left, Rect.Bottom); glVertex2f(0, Height);
- glTexCoord2f(Rect.Right, Rect.Bottom); glVertex2f(Width, Height);
- glTexCoord2f(Rect.Right, Rect.Top); glVertex2f(Width, 0) ;
- glEnd();
- }
- else
- {
- // Disable texturing
- GLCheck(glDisable(GL_TEXTURE_2D));
-
- // Draw the sprite's triangles
- glBegin(GL_QUADS);
- glVertex2f(0, 0);
- glVertex2f(0, Height);
- glVertex2f(Width, Height);
- glVertex2f(Width, 0);
- glEnd();
- }
+ m_vertices[0].position = Vector2f(0, 0);
+ m_vertices[1].position = Vector2f(0, bounds.height);
+ m_vertices[2].position = Vector2f(bounds.width, bounds.height);
+ m_vertices[3].position = Vector2f(bounds.width, 0);
+}
+
+
+////////////////////////////////////////////////////////////
+void Sprite::updateTexCoords()
+{
+ float left = static_cast<float>(m_textureRect.left);
+ float right = left + m_textureRect.width;
+ float top = static_cast<float>(m_textureRect.top);
+ float bottom = top + m_textureRect.height;
+
+ m_vertices[0].texCoords = Vector2f(left, top);
+ m_vertices[1].texCoords = Vector2f(left, bottom);
+ m_vertices[2].texCoords = Vector2f(right, bottom);
+ m_vertices[3].texCoords = Vector2f(right, top);
}
} // namespace sf
diff --git a/src/SFML/Graphics/String.cpp b/src/SFML/Graphics/String.cpp
deleted file mode 100755
index 89cfc30..0000000
--- a/src/SFML/Graphics/String.cpp
+++ /dev/null
@@ -1,412 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Graphics/String.hpp>
-#include <SFML/Graphics/Image.hpp>
-#include <SFML/Graphics/GraphicsContext.hpp>
-#include <locale>
-
-
-namespace sf
-{
-////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
-String::String() :
-myFont (&Font::GetDefaultFont()),
-mySize (30.f),
-myStyle (Regular),
-myNeedRectUpdate(true)
-{
-
-}
-
-
-////////////////////////////////////////////////////////////
-/// Construct the string from any kind of text
-////////////////////////////////////////////////////////////
-String::String(const Unicode::Text& Text, const Font& CharFont, float Size) :
-myFont (&CharFont),
-mySize (Size),
-myStyle (Regular),
-myNeedRectUpdate(true)
-{
- SetText(Text);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Set the text (from any kind of string)
-////////////////////////////////////////////////////////////
-void String::SetText(const Unicode::Text& Text)
-{
- myNeedRectUpdate = true;
- myText = Text;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Set the font of the string
-////////////////////////////////////////////////////////////
-void String::SetFont(const Font& CharFont)
-{
- if (myFont != &CharFont)
- {
- myNeedRectUpdate = true;
- myFont = &CharFont;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Set the size of the string
-////////////////////////////////////////////////////////////
-void String::SetSize(float Size)
-{
- if (mySize != Size)
- {
- myNeedRectUpdate = true;
- mySize = Size;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Set the style of the text
-/// The default style is Regular
-////////////////////////////////////////////////////////////
-void String::SetStyle(unsigned long TextStyle)
-{
- if (myStyle != TextStyle)
- {
- myNeedRectUpdate = true;
- myStyle = TextStyle;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the text (the returned text can be converted implicitely to any kind of string)
-////////////////////////////////////////////////////////////
-const Unicode::Text& String::GetText() const
-{
- return myText;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the font used by the string
-////////////////////////////////////////////////////////////
-const Font& String::GetFont() const
-{
- return *myFont;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the size of the characters
-////////////////////////////////////////////////////////////
-float String::GetSize() const
-{
- return mySize;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the style of the text
-////////////////////////////////////////////////////////////
-unsigned long String::GetStyle() const
-{
- return myStyle;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Return the visual position of the Index-th character of the string,
-/// in coordinates relative to the string
-/// (note : translation, center, rotation and scale are not applied)
-////////////////////////////////////////////////////////////
-sf::Vector2f String::GetCharacterPos(std::size_t Index) const
-{
- // First get the UTF32 representation of the text
- const Unicode::UTF32String& Text = myText;
-
- // Adjust the index if it's out of range
- if (Index > Text.length())
- Index = Text.length();
-
- // The final size is based on the text size
- float FactorX = mySize / myFont->GetCharacterSize();
- float AdvanceY = mySize;
-
- // Compute the position
- sf::Vector2f Position;
- for (std::size_t i = 0; i < Index; ++i)
- {
- // Get the current character and its corresponding glyph
- Uint32 CurChar = Text[i];
- const Glyph& CurGlyph = myFont->GetGlyph(CurChar);
- float AdvanceX = CurGlyph.Advance * FactorX;
-
- switch (CurChar)
- {
- // Handle special characters
- case L' ' : Position.x += AdvanceX; break;
- case L'\t' : Position.x += AdvanceX * 4; break;
- case L'\v' : Position.y += AdvanceY * 4; break;
- case L'\n' : Position.y += AdvanceY; Position.x = 0; break;
-
- // Regular character : just add its advance value
- default : Position.x += AdvanceX; break;
- }
- }
-
- return Position;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the string rectangle on screen
-////////////////////////////////////////////////////////////
-FloatRect String::GetRect() const
-{
- if (myNeedRectUpdate)
- const_cast<String*>(this)->RecomputeRect();
-
- FloatRect Rect;
- Rect.Left = (myBaseRect.Left - GetCenter().x) * GetScale().x + GetPosition().x;
- Rect.Top = (myBaseRect.Top - GetCenter().y) * GetScale().y + GetPosition().y;
- Rect.Right = (myBaseRect.Right - GetCenter().x) * GetScale().x + GetPosition().x;
- Rect.Bottom = (myBaseRect.Bottom - GetCenter().y) * GetScale().y + GetPosition().y;
-
- return Rect;
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see sfDrawable::Render
-////////////////////////////////////////////////////////////
-void String::Render(RenderTarget&) const
-{
- // First get the internal UTF-32 string of the text
- const Unicode::UTF32String& Text = myText;
-
- // No text, no rendering :)
- if (Text.empty())
- return;
-
- // Set the scaling factor to get the actual size
- float CharSize = static_cast<float>(myFont->GetCharacterSize());
- float Factor = mySize / CharSize;
- GLCheck(glScalef(Factor, Factor, 1.f));
-
- // Bind the font texture
- myFont->GetImage().Bind();
-
- // Initialize the rendering coordinates
- float X = 0.f;
- float Y = CharSize;
-
- // Holds the lines to draw later, for underlined style
- std::vector<float> UnderlineCoords;
- UnderlineCoords.reserve(16);
-
- // Compute the shearing to apply if we're using the italic style
- float ItalicCoeff = (myStyle & Italic) ? 0.208f : 0.f; // 12 degrees
-
- // Draw one quad for each character
- glBegin(GL_QUADS);
- for (std::size_t i = 0; i < Text.size(); ++i)
- {
- // Get the current character and its corresponding glyph
- Uint32 CurChar = Text[i];
- const Glyph& CurGlyph = myFont->GetGlyph(CurChar);
- int Advance = CurGlyph.Advance;
- const IntRect& Rect = CurGlyph.Rectangle;
- const FloatRect& Coord = CurGlyph.TexCoords;
-
- // If we're using the underlined style and there's a new line,
- // we keep track of the previous line to draw it later
- if ((CurChar == L'\n') && (myStyle & Underlined))
- {
- UnderlineCoords.push_back(X);
- UnderlineCoords.push_back(Y + 2);
- }
-
- // Handle special characters
- switch (CurChar)
- {
- case L' ' : X += Advance; continue;
- case L'\n' : Y += CharSize; X = 0; continue;
- case L'\t' : X += Advance * 4; continue;
- case L'\v' : Y += CharSize * 4; continue;
- }
-
- // Draw a textured quad for the current character
- glTexCoord2f(Coord.Left, Coord.Top); glVertex2f(X + Rect.Left - ItalicCoeff * Rect.Top, Y + Rect.Top);
- glTexCoord2f(Coord.Left, Coord.Bottom); glVertex2f(X + Rect.Left - ItalicCoeff * Rect.Bottom, Y + Rect.Bottom);
- glTexCoord2f(Coord.Right, Coord.Bottom); glVertex2f(X + Rect.Right - ItalicCoeff * Rect.Bottom, Y + Rect.Bottom);
- glTexCoord2f(Coord.Right, Coord.Top); glVertex2f(X + Rect.Right - ItalicCoeff * Rect.Top, Y + Rect.Top);
-
- // If we're using the bold style, we must render the character 4 more times,
- // slightly offseted, to simulate a higher weight
- if (myStyle & Bold)
- {
- static const float OffsetsX[] = {-0.5f, 0.5f, 0.f, 0.f};
- static const float OffsetsY[] = {0.f, 0.f, -0.5f, 0.5f};
-
- for (int j = 0; j < 4; ++j)
- {
- glTexCoord2f(Coord.Left, Coord.Top); glVertex2f(X + OffsetsX[j] + Rect.Left - ItalicCoeff * Rect.Top, Y + OffsetsY[j] + Rect.Top);
- glTexCoord2f(Coord.Left, Coord.Bottom); glVertex2f(X + OffsetsX[j] + Rect.Left - ItalicCoeff * Rect.Bottom, Y + OffsetsY[j] + Rect.Bottom);
- glTexCoord2f(Coord.Right, Coord.Bottom); glVertex2f(X + OffsetsX[j] + Rect.Right - ItalicCoeff * Rect.Bottom, Y + OffsetsY[j] + Rect.Bottom);
- glTexCoord2f(Coord.Right, Coord.Top); glVertex2f(X + OffsetsX[j] + Rect.Right - ItalicCoeff * Rect.Top, Y + OffsetsY[j] + Rect.Top);
- }
- }
-
- // Advance to the next character
- X += Advance;
- }
- glEnd();
-
- // Draw the underlines if needed
- if (myStyle & Underlined)
- {
- // Compute the line thickness
- float Thickness = (myStyle & Bold) ? 3.f : 2.f;
-
- // Add the last line (which was not finished with a \n)
- UnderlineCoords.push_back(X);
- UnderlineCoords.push_back(Y + 2);
-
- // Draw the underlines as quads
- GLCheck(glDisable(GL_TEXTURE_2D));
- glBegin(GL_QUADS);
- for (std::size_t i = 0; i < UnderlineCoords.size(); i += 2)
- {
- glVertex2f(0, UnderlineCoords[i + 1]);
- glVertex2f(0, UnderlineCoords[i + 1] + Thickness);
- glVertex2f(UnderlineCoords[i], UnderlineCoords[i + 1] + Thickness);
- glVertex2f(UnderlineCoords[i], UnderlineCoords[i + 1]);
- }
- glEnd();
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Recompute the bounding rectangle of the text
-////////////////////////////////////////////////////////////
-void String::RecomputeRect()
-{
- // First get the internal UTF-32 string of the text
- const Unicode::UTF32String& Text = myText;
-
- // Reset the "need update" state
- myNeedRectUpdate = false;
-
- // No text, empty box :)
- if (Text.empty())
- {
- myBaseRect = FloatRect(0, 0, 0, 0);
- return;
- }
-
- // Initial values
- float CurWidth = 0;
- float CurHeight = 0;
- float Width = 0;
- float Height = 0;
- float Factor = mySize / myFont->GetCharacterSize();
-
- // Go through each character
- for (std::size_t i = 0; i < Text.size(); ++i)
- {
- // Get the current character and its corresponding glyph
- Uint32 CurChar = Text[i];
- const Glyph& CurGlyph = myFont->GetGlyph(CurChar);
- float Advance = CurGlyph.Advance * Factor;
- const IntRect& Rect = CurGlyph.Rectangle;
-
- // Handle special characters
- switch (CurChar)
- {
- case L' ' : CurWidth += Advance; continue;
- case L'\t' : CurWidth += Advance * 4; continue;
- case L'\v' : Height += mySize * 4; CurHeight = 0; continue;
-
- case L'\n' :
- Height += mySize;
- CurHeight = 0;
- if (CurWidth > Width)
- Width = CurWidth;
- CurWidth = 0;
- continue;
- }
-
- // Advance to the next character
- CurWidth += Advance;
-
- // Update the maximum height
- float CharHeight = (myFont->GetCharacterSize() + Rect.Bottom) * Factor;
- if (CharHeight > CurHeight)
- CurHeight = CharHeight;
- }
-
- // Update the last line
- if (CurWidth > Width)
- Width = CurWidth;
- Height += CurHeight;
-
- // Add a slight width / height if we're using the bold style
- if (myStyle & Bold)
- {
- Width += 1 * Factor;
- Height += 1 * Factor;
- }
-
- // Add a slight width if we're using the italic style
- if (myStyle & Italic)
- {
- Width += 0.208f * mySize;
- }
-
- // Add a slight height if we're using the underlined style
- if (myStyle & Underlined)
- {
- if (CurHeight < mySize + 4 * Factor)
- Height += 4 * Factor;
- }
-
- // Finally update the rectangle
- myBaseRect.Left = 0;
- myBaseRect.Top = 0;
- myBaseRect.Right = Width;
- myBaseRect.Bottom = Height;
-}
-
-} // namespace sf
diff --git a/src/SFML/Graphics/Text.cpp b/src/SFML/Graphics/Text.cpp
new file mode 100644
index 0000000..ec64822
--- /dev/null
+++ b/src/SFML/Graphics/Text.cpp
@@ -0,0 +1,346 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Graphics/Text.hpp>
+#include <SFML/Graphics/Texture.hpp>
+#include <SFML/Graphics/RenderTarget.hpp>
+#include <cassert>
+
+
+namespace sf
+{
+////////////////////////////////////////////////////////////
+Text::Text() :
+m_string (),
+m_font (NULL),
+m_characterSize(30),
+m_style (Regular),
+m_color (255, 255, 255),
+m_vertices (Quads),
+m_bounds ()
+{
+
+}
+
+
+////////////////////////////////////////////////////////////
+Text::Text(const String& string, const Font& font, unsigned int characterSize) :
+m_string (string),
+m_font (&font),
+m_characterSize(characterSize),
+m_style (Regular),
+m_color (255, 255, 255),
+m_vertices (Quads),
+m_bounds ()
+{
+ updateGeometry();
+}
+
+
+////////////////////////////////////////////////////////////
+void Text::setString(const String& string)
+{
+ m_string = string;
+ updateGeometry();
+}
+
+
+////////////////////////////////////////////////////////////
+void Text::setFont(const Font& font)
+{
+ if (m_font != &font)
+ {
+ m_font = &font;
+ updateGeometry();
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void Text::setCharacterSize(unsigned int size)
+{
+ if (m_characterSize != size)
+ {
+ m_characterSize = size;
+ updateGeometry();
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void Text::setStyle(Uint32 style)
+{
+ if (m_style != style)
+ {
+ m_style = style;
+ updateGeometry();
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void Text::setColor(const Color& color)
+{
+ if (color != m_color)
+ {
+ m_color = color;
+ for (unsigned int i = 0; i < m_vertices.getVertexCount(); ++i)
+ m_vertices[i].color = m_color;
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+const String& Text::getString() const
+{
+ return m_string;
+}
+
+
+////////////////////////////////////////////////////////////
+const Font* Text::getFont() const
+{
+ return m_font;
+}
+
+
+////////////////////////////////////////////////////////////
+unsigned int Text::getCharacterSize() const
+{
+ return m_characterSize;
+}
+
+
+////////////////////////////////////////////////////////////
+Uint32 Text::getStyle() const
+{
+ return m_style;
+}
+
+
+////////////////////////////////////////////////////////////
+const Color& Text::getColor() const
+{
+ return m_color;
+}
+
+
+////////////////////////////////////////////////////////////
+Vector2f Text::findCharacterPos(std::size_t index) const
+{
+ // Make sure that we have a valid font
+ if (!m_font)
+ return Vector2f();
+
+ // Adjust the index if it's out of range
+ if (index > m_string.getSize())
+ index = m_string.getSize();
+
+ // Precompute the variables needed by the algorithm
+ bool bold = (m_style & Bold) != 0;
+ float hspace = static_cast<float>(m_font->getGlyph(L' ', m_characterSize, bold).advance);
+ float vspace = static_cast<float>(m_font->getLineSpacing(m_characterSize));
+
+ // Compute the position
+ Vector2f position;
+ Uint32 prevChar = 0;
+ for (std::size_t i = 0; i < index; ++i)
+ {
+ Uint32 curChar = m_string[i];
+
+ // Apply the kerning offset
+ position.x += static_cast<float>(m_font->getKerning(prevChar, curChar, m_characterSize));
+ prevChar = curChar;
+
+ // Handle special characters
+ switch (curChar)
+ {
+ case L' ' : position.x += hspace; continue;
+ case L'\t' : position.x += hspace * 4; continue;
+ case L'\n' : position.y += vspace; position.x = 0; continue;
+ case L'\v' : position.y += vspace * 4; continue;
+ }
+
+ // For regular characters, add the advance offset of the glyph
+ position.x += static_cast<float>(m_font->getGlyph(curChar, m_characterSize, bold).advance);
+ }
+
+ // Transform the position to global coordinates
+ position = getTransform().transformPoint(position);
+
+ return position;
+}
+
+
+////////////////////////////////////////////////////////////
+FloatRect Text::getLocalBounds() const
+{
+ return m_bounds;
+}
+
+
+////////////////////////////////////////////////////////////
+FloatRect Text::getGlobalBounds() const
+{
+ return getTransform().transformRect(getLocalBounds());
+}
+
+
+////////////////////////////////////////////////////////////
+void Text::draw(RenderTarget& target, RenderStates states) const
+{
+ if (m_font)
+ {
+ states.transform *= getTransform();
+ states.texture = &m_font->getTexture(m_characterSize);
+ target.draw(m_vertices, states);
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void Text::updateGeometry()
+{
+ // Clear the previous geometry
+ m_vertices.clear();
+ m_bounds = FloatRect();
+
+ // No font: nothing to draw
+ if (!m_font)
+ return;
+
+ // No text: nothing to draw
+ if (m_string.isEmpty())
+ return;
+
+ // Compute values related to the text style
+ bool bold = (m_style & Bold) != 0;
+ bool underlined = (m_style & Underlined) != 0;
+ float italic = (m_style & Italic) ? 0.208f : 0.f; // 12 degrees
+ float underlineOffset = m_characterSize * 0.1f;
+ float underlineThickness = m_characterSize * (bold ? 0.1f : 0.07f);
+
+ // Precompute the variables needed by the algorithm
+ float hspace = static_cast<float>(m_font->getGlyph(L' ', m_characterSize, bold).advance);
+ float vspace = static_cast<float>(m_font->getLineSpacing(m_characterSize));
+ float x = 0.f;
+ float y = static_cast<float>(m_characterSize);
+
+ // Create one quad for each character
+ float minY = static_cast<float>(m_characterSize);
+ Uint32 prevChar = 0;
+ for (std::size_t i = 0; i < m_string.getSize(); ++i)
+ {
+ Uint32 curChar = m_string[i];
+
+ // Apply the kerning offset
+ x += static_cast<float>(m_font->getKerning(prevChar, curChar, m_characterSize));
+ prevChar = curChar;
+
+ // If we're using the underlined style and there's a new line, draw a line
+ if (underlined && (curChar == L'\n'))
+ {
+ float top = y + underlineOffset;
+ float bottom = top + underlineThickness;
+
+ m_vertices.append(Vertex(Vector2f(0, top), m_color, Vector2f(1, 1)));
+ m_vertices.append(Vertex(Vector2f(x, top), m_color, Vector2f(1, 1)));
+ m_vertices.append(Vertex(Vector2f(x, bottom), m_color, Vector2f(1, 1)));
+ m_vertices.append(Vertex(Vector2f(0, bottom), m_color, Vector2f(1, 1)));
+ }
+
+ // Handle special characters
+ switch (curChar)
+ {
+ case L' ' :
+ x += hspace;
+ continue;
+
+ case L'\t' :
+ x += hspace * 4;
+ continue;
+
+ case L'\n' :
+ if (x > m_bounds.width)
+ m_bounds.width = x;
+ y += vspace;
+ x = 0;
+ continue;
+
+ case L'\v' :
+ y += vspace * 4;
+ continue;
+ }
+
+ // Extract the current glyph's description
+ const Glyph& glyph = m_font->getGlyph(curChar, m_characterSize, bold);
+
+ int left = glyph.bounds.left;
+ int top = glyph.bounds.top;
+ int right = glyph.bounds.left + glyph.bounds.width;
+ int bottom = glyph.bounds.top + glyph.bounds.height;
+
+ float u1 = static_cast<float>(glyph.textureRect.left);
+ float v1 = static_cast<float>(glyph.textureRect.top);
+ float u2 = static_cast<float>(glyph.textureRect.left + glyph.textureRect.width);
+ float v2 = static_cast<float>(glyph.textureRect.top + glyph.textureRect.height);
+
+ // Add a quad for the current character
+ m_vertices.append(Vertex(Vector2f(x + left - italic * top, y + top), m_color, Vector2f(u1, v1)));
+ m_vertices.append(Vertex(Vector2f(x + right - italic * top, y + top), m_color, Vector2f(u2, v1)));
+ m_vertices.append(Vertex(Vector2f(x + right - italic * bottom, y + bottom), m_color, Vector2f(u2, v2)));
+ m_vertices.append(Vertex(Vector2f(x + left - italic * bottom, y + bottom), m_color, Vector2f(u1, v2)));
+
+ // Advance to the next character
+ x += glyph.advance;
+
+ // Update the minimum Y coordinate
+ if (y + top < minY)
+ minY = y + top;
+ }
+
+ // If we're using the underlined style, add the last line
+ if (underlined)
+ {
+ float top = y + underlineOffset;
+ float bottom = top + underlineThickness;
+
+ m_vertices.append(Vertex(Vector2f(0, top), m_color, Vector2f(1, 1)));
+ m_vertices.append(Vertex(Vector2f(x, top), m_color, Vector2f(1, 1)));
+ m_vertices.append(Vertex(Vector2f(x, bottom), m_color, Vector2f(1, 1)));
+ m_vertices.append(Vertex(Vector2f(0, bottom), m_color, Vector2f(1, 1)));
+ }
+
+ // Update the bounding rectangle
+ m_bounds.left = 0;
+ m_bounds.top = minY;
+ if (x > m_bounds.width)
+ m_bounds.width = x;
+ m_bounds.height = y - minY;
+}
+
+} // namespace sf
diff --git a/src/SFML/Graphics/Texture.cpp b/src/SFML/Graphics/Texture.cpp
new file mode 100644
index 0000000..7b5fdb2
--- /dev/null
+++ b/src/SFML/Graphics/Texture.cpp
@@ -0,0 +1,545 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Graphics/Texture.hpp>
+#include <SFML/Graphics/Image.hpp>
+#include <SFML/Graphics/GLCheck.hpp>
+#include <SFML/Graphics/TextureSaver.hpp>
+#include <SFML/Window/Window.hpp>
+#include <SFML/System/Mutex.hpp>
+#include <SFML/System/Lock.hpp>
+#include <SFML/System/Err.hpp>
+#include <cassert>
+#include <cstring>
+
+
+namespace
+{
+ // Thread-safe unique identifier generator,
+ // is used for states cache (see RenderTarget)
+ sf::Uint64 getUniqueId()
+ {
+ static sf::Uint64 id = 1; // start at 1, zero is "no texture"
+ static sf::Mutex mutex;
+
+ sf::Lock lock(mutex);
+ return id++;
+ }
+}
+
+
+namespace sf
+{
+////////////////////////////////////////////////////////////
+Texture::Texture() :
+m_size (0, 0),
+m_actualSize (0, 0),
+m_texture (0),
+m_isSmooth (false),
+m_isRepeated (false),
+m_pixelsFlipped(false),
+m_cacheId (getUniqueId())
+{
+
+}
+
+
+////////////////////////////////////////////////////////////
+Texture::Texture(const Texture& copy) :
+m_size (0, 0),
+m_actualSize (0, 0),
+m_texture (0),
+m_isSmooth (copy.m_isSmooth),
+m_isRepeated (copy.m_isRepeated),
+m_pixelsFlipped(false),
+m_cacheId (getUniqueId())
+{
+ if (copy.m_texture)
+ loadFromImage(copy.copyToImage());
+}
+
+
+////////////////////////////////////////////////////////////
+Texture::~Texture()
+{
+ // Destroy the OpenGL texture
+ if (m_texture)
+ {
+ ensureGlContext();
+
+ GLuint texture = static_cast<GLuint>(m_texture);
+ glCheck(glDeleteTextures(1, &texture));
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+bool Texture::create(unsigned int width, unsigned int height)
+{
+ // Check if texture parameters are valid before creating it
+ if ((width == 0) || (height == 0))
+ {
+ err() << "Failed to create texture, invalid size (" << width << "x" << height << ")" << std::endl;
+ return false;
+ }
+
+ // Compute the internal texture dimensions depending on NPOT textures support
+ Vector2u actualSize(getValidSize(width), getValidSize(height));
+
+ // Check the maximum texture size
+ unsigned int maxSize = getMaximumSize();
+ if ((actualSize.x > maxSize) || (actualSize.y > maxSize))
+ {
+ err() << "Failed to create texture, its internal size is too high "
+ << "(" << actualSize.x << "x" << actualSize.y << ", "
+ << "maximum is " << maxSize << "x" << maxSize << ")"
+ << std::endl;
+ return false;
+ }
+
+ // All the validity checks passed, we can store the new texture settings
+ m_size.x = width;
+ m_size.y = height;
+ m_actualSize = actualSize;
+ m_pixelsFlipped = false;
+
+ ensureGlContext();
+
+ // Create the OpenGL texture if it doesn't exist yet
+ if (!m_texture)
+ {
+ GLuint texture;
+ glCheck(glGenTextures(1, &texture));
+ m_texture = static_cast<unsigned int>(texture);
+ }
+
+ // Make sure that the current texture binding will be preserved
+ priv::TextureSaver save;
+
+ // Initialize the texture
+ glCheck(glBindTexture(GL_TEXTURE_2D, m_texture));
+ glCheck(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, m_actualSize.x, m_actualSize.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL));
+ glCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, m_isRepeated ? GL_REPEAT : GL_CLAMP_TO_EDGE));
+ glCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, m_isRepeated ? GL_REPEAT : GL_CLAMP_TO_EDGE));
+ glCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, m_isSmooth ? GL_LINEAR : GL_NEAREST));
+ glCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, m_isSmooth ? GL_LINEAR : GL_NEAREST));
+ m_cacheId = getUniqueId();
+
+ return true;
+}
+
+
+////////////////////////////////////////////////////////////
+bool Texture::loadFromFile(const std::string& filename, const IntRect& area)
+{
+ Image image;
+ return image.loadFromFile(filename) && loadFromImage(image, area);
+}
+
+
+////////////////////////////////////////////////////////////
+bool Texture::loadFromMemory(const void* data, std::size_t size, const IntRect& area)
+{
+ Image image;
+ return image.loadFromMemory(data, size) && loadFromImage(image, area);
+}
+
+
+////////////////////////////////////////////////////////////
+bool Texture::loadFromStream(InputStream& stream, const IntRect& area)
+{
+ Image image;
+ return image.loadFromStream(stream) && loadFromImage(image, area);
+}
+
+
+////////////////////////////////////////////////////////////
+bool Texture::loadFromImage(const Image& image, const IntRect& area)
+{
+ // Retrieve the image size
+ int width = static_cast<int>(image.getSize().x);
+ int height = static_cast<int>(image.getSize().y);
+
+ // Load the entire image if the source area is either empty or contains the whole image
+ if (area.width == 0 || (area.height == 0) ||
+ ((area.left <= 0) && (area.top <= 0) && (area.width >= width) && (area.height >= height)))
+ {
+ // Load the entire image
+ if (create(image.getSize().x, image.getSize().y))
+ {
+ update(image);
+
+ // Force an OpenGL flush, so that the texture will appear updated
+ // in all contexts immediately (solves problems in multi-threaded apps)
+ glCheck(glFlush());
+
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+ }
+ else
+ {
+ // Load a sub-area of the image
+
+ // Adjust the rectangle to the size of the image
+ IntRect rectangle = area;
+ if (rectangle.left < 0) rectangle.left = 0;
+ if (rectangle.top < 0) rectangle.top = 0;
+ if (rectangle.left + rectangle.width > width) rectangle.width = width - rectangle.left;
+ if (rectangle.top + rectangle.height > height) rectangle.height = height - rectangle.top;
+
+ // Create the texture and upload the pixels
+ if (create(rectangle.width, rectangle.height))
+ {
+ // Make sure that the current texture binding will be preserved
+ priv::TextureSaver save;
+
+ // Copy the pixels to the texture, row by row
+ const Uint8* pixels = image.getPixelsPtr() + 4 * (rectangle.left + (width * rectangle.top));
+ glCheck(glBindTexture(GL_TEXTURE_2D, m_texture));
+ for (int i = 0; i < rectangle.height; ++i)
+ {
+ glCheck(glTexSubImage2D(GL_TEXTURE_2D, 0, 0, i, rectangle.width, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixels));
+ pixels += 4 * width;
+ }
+
+ // Force an OpenGL flush, so that the texture will appear updated
+ // in all contexts immediately (solves problems in multi-threaded apps)
+ glCheck(glFlush());
+
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+Vector2u Texture::getSize() const
+{
+ return m_size;
+}
+
+
+////////////////////////////////////////////////////////////
+Image Texture::copyToImage() const
+{
+ // Easy case: empty texture
+ if (!m_texture)
+ return Image();
+
+ ensureGlContext();
+
+ // Make sure that the current texture binding will be preserved
+ priv::TextureSaver save;
+
+ // Create an array of pixels
+ std::vector<Uint8> pixels(m_size.x * m_size.y * 4);
+
+ if ((m_size == m_actualSize) && !m_pixelsFlipped)
+ {
+ // Texture is not padded nor flipped, we can use a direct copy
+ glCheck(glBindTexture(GL_TEXTURE_2D, m_texture));
+ glCheck(glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, &pixels[0]));
+ }
+ else
+ {
+ // Texture is either padded or flipped, we have to use a slower algorithm
+
+ // All the pixels will first be copied to a temporary array
+ std::vector<Uint8> allPixels(m_actualSize.x * m_actualSize.y * 4);
+ glCheck(glBindTexture(GL_TEXTURE_2D, m_texture));
+ glCheck(glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, &allPixels[0]));
+
+ // Then we copy the useful pixels from the temporary array to the final one
+ const Uint8* src = &allPixels[0];
+ Uint8* dst = &pixels[0];
+ int srcPitch = m_actualSize.x * 4;
+ int dstPitch = m_size.x * 4;
+
+ // Handle the case where source pixels are flipped vertically
+ if (m_pixelsFlipped)
+ {
+ src += srcPitch * (m_size.y - 1);
+ srcPitch = -srcPitch;
+ }
+
+ for (unsigned int i = 0; i < m_size.y; ++i)
+ {
+ std::memcpy(dst, src, dstPitch);
+ src += srcPitch;
+ dst += dstPitch;
+ }
+ }
+
+ // Create the image
+ Image image;
+ image.create(m_size.x, m_size.y, &pixels[0]);
+
+ return image;
+}
+
+
+////////////////////////////////////////////////////////////
+void Texture::update(const Uint8* pixels)
+{
+ // Update the whole texture
+ update(pixels, m_size.x, m_size.y, 0, 0);
+}
+
+
+////////////////////////////////////////////////////////////
+void Texture::update(const Uint8* pixels, unsigned int width, unsigned int height, unsigned int x, unsigned int y)
+{
+ assert(x + width <= m_size.x);
+ assert(y + height <= m_size.y);
+
+ if (pixels && m_texture)
+ {
+ ensureGlContext();
+
+ // Make sure that the current texture binding will be preserved
+ priv::TextureSaver save;
+
+ // Copy pixels from the given array to the texture
+ glCheck(glBindTexture(GL_TEXTURE_2D, m_texture));
+ glCheck(glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels));
+ m_pixelsFlipped = false;
+ m_cacheId = getUniqueId();
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void Texture::update(const Image& image)
+{
+ // Update the whole texture
+ update(image.getPixelsPtr(), image.getSize().x, image.getSize().y, 0, 0);
+}
+
+
+////////////////////////////////////////////////////////////
+void Texture::update(const Image& image, unsigned int x, unsigned int y)
+{
+ update(image.getPixelsPtr(), image.getSize().x, image.getSize().y, x, y);
+}
+
+
+////////////////////////////////////////////////////////////
+void Texture::update(const Window& window)
+{
+ update(window, 0, 0);
+}
+
+
+////////////////////////////////////////////////////////////
+void Texture::update(const Window& window, unsigned int x, unsigned int y)
+{
+ assert(x + window.getSize().x <= m_size.x);
+ assert(y + window.getSize().y <= m_size.y);
+
+ if (m_texture && window.setActive(true))
+ {
+ // Make sure that the current texture binding will be preserved
+ priv::TextureSaver save;
+
+ // Copy pixels from the back-buffer to the texture
+ glCheck(glBindTexture(GL_TEXTURE_2D, m_texture));
+ glCheck(glCopyTexSubImage2D(GL_TEXTURE_2D, 0, x, y, 0, 0, window.getSize().x, window.getSize().y));
+ m_pixelsFlipped = true;
+ m_cacheId = getUniqueId();
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void Texture::setSmooth(bool smooth)
+{
+ if (smooth != m_isSmooth)
+ {
+ m_isSmooth = smooth;
+
+ if (m_texture)
+ {
+ ensureGlContext();
+
+ // Make sure that the current texture binding will be preserved
+ priv::TextureSaver save;
+
+ glCheck(glBindTexture(GL_TEXTURE_2D, m_texture));
+ glCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, m_isSmooth ? GL_LINEAR : GL_NEAREST));
+ glCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, m_isSmooth ? GL_LINEAR : GL_NEAREST));
+ }
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+bool Texture::isSmooth() const
+{
+ return m_isSmooth;
+}
+
+
+////////////////////////////////////////////////////////////
+void Texture::setRepeated(bool repeated)
+{
+ if (repeated != m_isRepeated)
+ {
+ m_isRepeated = repeated;
+
+ if (m_texture)
+ {
+ ensureGlContext();
+
+ // Make sure that the current texture binding will be preserved
+ priv::TextureSaver save;
+
+ glCheck(glBindTexture(GL_TEXTURE_2D, m_texture));
+ glCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, m_isRepeated ? GL_REPEAT : GL_CLAMP_TO_EDGE));
+ glCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, m_isRepeated ? GL_REPEAT : GL_CLAMP_TO_EDGE));
+ }
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+bool Texture::isRepeated() const
+{
+ return m_isRepeated;
+}
+
+
+////////////////////////////////////////////////////////////
+void Texture::bind(const Texture* texture, CoordinateType coordinateType)
+{
+ ensureGlContext();
+
+ if (texture && texture->m_texture)
+ {
+ // Bind the texture
+ glCheck(glBindTexture(GL_TEXTURE_2D, texture->m_texture));
+
+ // Check if we need to define a special texture matrix
+ if ((coordinateType == Pixels) || texture->m_pixelsFlipped)
+ {
+ GLfloat matrix[16] = {1.f, 0.f, 0.f, 0.f,
+ 0.f, 1.f, 0.f, 0.f,
+ 0.f, 0.f, 1.f, 0.f,
+ 0.f, 0.f, 0.f, 1.f};
+
+ // If non-normalized coordinates (= pixels) are requested, we need to
+ // setup scale factors that convert the range [0 .. size] to [0 .. 1]
+ if (coordinateType == Pixels)
+ {
+ matrix[0] = 1.f / texture->m_actualSize.x;
+ matrix[5] = 1.f / texture->m_actualSize.y;
+ }
+
+ // If pixels are flipped we must invert the Y axis
+ if (texture->m_pixelsFlipped)
+ {
+ matrix[5] = -matrix[5];
+ matrix[13] = static_cast<float>(texture->m_size.y / texture->m_actualSize.y);
+ }
+
+ // Load the matrix
+ glCheck(glMatrixMode(GL_TEXTURE));
+ glCheck(glLoadMatrixf(matrix));
+
+ // Go back to model-view mode (sf::RenderTarget relies on it)
+ glCheck(glMatrixMode(GL_MODELVIEW));
+ }
+ }
+ else
+ {
+ // Bind no texture
+ glCheck(glBindTexture(GL_TEXTURE_2D, 0));
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+unsigned int Texture::getMaximumSize()
+{
+ ensureGlContext();
+
+ GLint size;
+ glCheck(glGetIntegerv(GL_MAX_TEXTURE_SIZE, &size));
+
+ return static_cast<unsigned int>(size);
+}
+
+
+////////////////////////////////////////////////////////////
+Texture& Texture::operator =(const Texture& right)
+{
+ Texture temp(right);
+
+ std::swap(m_size, temp.m_size);
+ std::swap(m_actualSize, temp.m_actualSize);
+ std::swap(m_texture, temp.m_texture);
+ std::swap(m_isSmooth, temp.m_isSmooth);
+ std::swap(m_isRepeated, temp.m_isRepeated);
+ std::swap(m_pixelsFlipped, temp.m_pixelsFlipped);
+ m_cacheId = getUniqueId();
+
+ return *this;
+}
+
+
+////////////////////////////////////////////////////////////
+unsigned int Texture::getValidSize(unsigned int size)
+{
+ ensureGlContext();
+
+ // Make sure that GLEW is initialized
+ priv::ensureGlewInit();
+
+ if (GLEW_ARB_texture_non_power_of_two)
+ {
+ // If hardware supports NPOT textures, then just return the unmodified size
+ return size;
+ }
+ else
+ {
+ // If hardware doesn't support NPOT textures, we calculate the nearest power of two
+ unsigned int powerOfTwo = 1;
+ while (powerOfTwo < size)
+ powerOfTwo *= 2;
+
+ return powerOfTwo;
+ }
+}
+
+} // namespace sf
diff --git a/src/SFML/Graphics/Matrix3.cpp b/src/SFML/Graphics/TextureSaver.cpp
index 7de4b0f..1037fd3 100755..100644
--- a/src/SFML/Graphics/Matrix3.cpp
+++ b/src/SFML/Graphics/TextureSaver.cpp
@@ -1,40 +1,50 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Graphics/Matrix3.hpp>
-
-
-namespace sf
-{
-////////////////////////////////////////////////////////////
-// Static member data
-////////////////////////////////////////////////////////////
-const Matrix3 Matrix3::Identity(1, 0, 0,
- 0, 1, 0,
- 0, 0, 1);
-
-} // namespace sf
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Graphics/TextureSaver.hpp>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+TextureSaver::TextureSaver()
+{
+ glCheck(glGetIntegerv(GL_TEXTURE_BINDING_2D, &m_textureBinding));
+}
+
+
+////////////////////////////////////////////////////////////
+TextureSaver::~TextureSaver()
+{
+ glCheck(glBindTexture(GL_TEXTURE_2D, m_textureBinding));
+}
+
+} // namespace priv
+
+} // namespace sf
diff --git a/src/SFML/System/Win32/Platform.hpp b/src/SFML/Graphics/TextureSaver.hpp
index ae27ec4..1c23d04 100755..100644
--- a/src/SFML/System/Win32/Platform.hpp
+++ b/src/SFML/Graphics/TextureSaver.hpp
@@ -1,69 +1,75 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-#ifndef SFML_PLATFORMWIN32_HPP
-#define SFML_PLATFORMWIN32_HPP
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Config.hpp>
-#include <vector>
-
-
-namespace sf
-{
-namespace priv
-{
-////////////////////////////////////////////////////////////
-/// Win32 implementation of Platform.
-/// Gives access to various global system functions
-////////////////////////////////////////////////////////////
-class Platform
-{
-public :
-
- ////////////////////////////////////////////////////////////
- /// Get the current system time
- ///
- /// \return System time, in seconds
- ///
- ////////////////////////////////////////////////////////////
- static double GetSystemTime();
-
- ////////////////////////////////////////////////////////////
- /// Suspend the execution of the current thread for a specified time
- ///
- /// \param Time : Time to sleep, in seconds
- ///
- ////////////////////////////////////////////////////////////
- static void Sleep(float Time);
-};
-
-} // namespace priv
-
-} // namespace sf
-
-
-#endif // SFML_PLATFORMWIN32_HPP
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_TEXTURESAVER_HPP
+#define SFML_TEXTURESAVER_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Graphics/GLCheck.hpp>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief Automatic wrapper for saving and restoring the current texture binding
+///
+////////////////////////////////////////////////////////////
+class TextureSaver
+{
+public :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Default constructor
+ ///
+ /// The current texture binding is saved.
+ ///
+ ////////////////////////////////////////////////////////////
+ TextureSaver();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Destructor
+ ///
+ /// The previous texture binding is restored.
+ ///
+ ////////////////////////////////////////////////////////////
+ ~TextureSaver();
+
+private :
+
+ ////////////////////////////////////////////////////////////
+ // Member data
+ ////////////////////////////////////////////////////////////
+ GLint m_textureBinding; ///< Texture binding to restore
+};
+
+} // namespace priv
+
+} // namespace sf
+
+
+#endif // SFML_TEXTURESAVER_HPP
diff --git a/src/SFML/Graphics/Transform.cpp b/src/SFML/Graphics/Transform.cpp
new file mode 100644
index 0000000..6da0b51
--- /dev/null
+++ b/src/SFML/Graphics/Transform.cpp
@@ -0,0 +1,272 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Graphics/Transform.hpp>
+#include <cmath>
+
+
+namespace sf
+{
+////////////////////////////////////////////////////////////
+const Transform Transform::Identity;
+
+
+////////////////////////////////////////////////////////////
+Transform::Transform()
+{
+ // Identity matrix
+ m_matrix[0] = 1.f; m_matrix[4] = 0.f; m_matrix[8] = 0.f; m_matrix[12] = 0.f;
+ m_matrix[1] = 0.f; m_matrix[5] = 1.f; m_matrix[9] = 0.f; m_matrix[13] = 0.f;
+ m_matrix[2] = 0.f; m_matrix[6] = 0.f; m_matrix[10] = 1.f; m_matrix[14] = 0.f;
+ m_matrix[3] = 0.f; m_matrix[7] = 0.f; m_matrix[11] = 0.f; m_matrix[15] = 1.f;
+}
+
+
+////////////////////////////////////////////////////////////
+Transform::Transform(float a00, float a01, float a02,
+ float a10, float a11, float a12,
+ float a20, float a21, float a22)
+{
+ m_matrix[0] = a00; m_matrix[4] = a01; m_matrix[8] = 0.f; m_matrix[12] = a02;
+ m_matrix[1] = a10; m_matrix[5] = a11; m_matrix[9] = 0.f; m_matrix[13] = a12;
+ m_matrix[2] = 0.f; m_matrix[6] = 0.f; m_matrix[10] = 1.f; m_matrix[14] = 0.f;
+ m_matrix[3] = a20; m_matrix[7] = a21; m_matrix[11] = 0.f; m_matrix[15] = a22;
+}
+
+
+////////////////////////////////////////////////////////////
+const float* Transform::getMatrix() const
+{
+ return m_matrix;
+}
+
+
+////////////////////////////////////////////////////////////
+Transform Transform::getInverse() const
+{
+ // Compute the determinant
+ float det = m_matrix[0] * (m_matrix[15] * m_matrix[5] - m_matrix[7] * m_matrix[13]) -
+ m_matrix[1] * (m_matrix[15] * m_matrix[4] - m_matrix[7] * m_matrix[12]) +
+ m_matrix[3] * (m_matrix[13] * m_matrix[4] - m_matrix[5] * m_matrix[12]);
+
+ // Compute the inverse if the determinant is not zero
+ // (don't use an epsilon because the determinant may *really* be tiny)
+ if (det != 0.f)
+ {
+ return Transform( (m_matrix[15] * m_matrix[5] - m_matrix[7] * m_matrix[13]) / det,
+ -(m_matrix[15] * m_matrix[4] - m_matrix[7] * m_matrix[12]) / det,
+ (m_matrix[13] * m_matrix[4] - m_matrix[5] * m_matrix[12]) / det,
+ -(m_matrix[15] * m_matrix[1] - m_matrix[3] * m_matrix[13]) / det,
+ (m_matrix[15] * m_matrix[0] - m_matrix[3] * m_matrix[12]) / det,
+ -(m_matrix[13] * m_matrix[0] - m_matrix[1] * m_matrix[12]) / det,
+ (m_matrix[7] * m_matrix[1] - m_matrix[3] * m_matrix[5]) / det,
+ -(m_matrix[7] * m_matrix[0] - m_matrix[3] * m_matrix[4]) / det,
+ (m_matrix[5] * m_matrix[0] - m_matrix[1] * m_matrix[4]) / det);
+ }
+ else
+ {
+ return Identity;
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+Vector2f Transform::transformPoint(float x, float y) const
+{
+ return Vector2f(m_matrix[0] * x + m_matrix[4] * y + m_matrix[12],
+ m_matrix[1] * x + m_matrix[5] * y + m_matrix[13]);
+}
+
+
+////////////////////////////////////////////////////////////
+Vector2f Transform::transformPoint(const Vector2f& point) const
+{
+ return transformPoint(point.x, point.y);
+}
+
+
+////////////////////////////////////////////////////////////
+FloatRect Transform::transformRect(const FloatRect& rectangle) const
+{
+ // Transform the 4 corners of the rectangle
+ const Vector2f points[] =
+ {
+ transformPoint(rectangle.left, rectangle.top),
+ transformPoint(rectangle.left, rectangle.top + rectangle.height),
+ transformPoint(rectangle.left + rectangle.width, rectangle.top),
+ transformPoint(rectangle.left + rectangle.width, rectangle.top + rectangle.height)
+ };
+
+ // Compute the bounding rectangle of the transformed points
+ float left = points[0].x;
+ float top = points[0].y;
+ float right = points[0].x;
+ float bottom = points[0].y;
+ for (int i = 1; i < 4; ++i)
+ {
+ if (points[i].x < left) left = points[i].x;
+ else if (points[i].x > right) right = points[i].x;
+ if (points[i].y < top) top = points[i].y;
+ else if (points[i].y > bottom) bottom = points[i].y;
+ }
+
+ return FloatRect(left, top, right - left, bottom - top);
+}
+
+
+////////////////////////////////////////////////////////////
+Transform& Transform::combine(const Transform& transform)
+{
+ const float* a = m_matrix;
+ const float* b = transform.m_matrix;
+
+ *this = Transform(a[0] * b[0] + a[4] * b[1] + a[12] * b[3],
+ a[0] * b[4] + a[4] * b[5] + a[12] * b[7],
+ a[0] * b[12] + a[4] * b[13] + a[12] * b[15],
+ a[1] * b[0] + a[5] * b[1] + a[13] * b[3],
+ a[1] * b[4] + a[5] * b[5] + a[13] * b[7],
+ a[1] * b[12] + a[5] * b[13] + a[13] * b[15],
+ a[3] * b[0] + a[7] * b[1] + a[15] * b[3],
+ a[3] * b[4] + a[7] * b[5] + a[15] * b[7],
+ a[3] * b[12] + a[7] * b[13] + a[15] * b[15]);
+
+ return *this;
+}
+
+
+////////////////////////////////////////////////////////////
+Transform& Transform::translate(float x, float y)
+{
+ Transform translation(1, 0, x,
+ 0, 1, y,
+ 0, 0, 1);
+
+ return combine(translation);
+}
+
+
+////////////////////////////////////////////////////////////
+Transform& Transform::translate(const Vector2f& offset)
+{
+ return translate(offset.x, offset.y);
+}
+
+
+////////////////////////////////////////////////////////////
+Transform& Transform::rotate(float angle)
+{
+ float rad = angle * 3.141592654f / 180.f;
+ float cos = std::cos(rad);
+ float sin = std::sin(rad);
+
+ Transform rotation(cos, -sin, 0,
+ sin, cos, 0,
+ 0, 0, 1);
+
+ return combine(rotation);
+}
+
+
+////////////////////////////////////////////////////////////
+Transform& Transform::rotate(float angle, float centerX, float centerY)
+{
+ float rad = angle * 3.141592654f / 180.f;
+ float cos = std::cos(rad);
+ float sin = std::sin(rad);
+
+ Transform rotation(cos, -sin, centerX * (1 - cos) + centerY * sin,
+ sin, cos, centerY * (1 - cos) - centerX * sin,
+ 0, 0, 1);
+
+ return combine(rotation);
+}
+
+
+////////////////////////////////////////////////////////////
+Transform& Transform::rotate(float angle, const Vector2f& center)
+{
+ return rotate(angle, center.x, center.y);
+}
+
+
+////////////////////////////////////////////////////////////
+Transform& Transform::scale(float scaleX, float scaleY)
+{
+ Transform scaling(scaleX, 0, 0,
+ 0, scaleY, 0,
+ 0, 0, 1);
+
+ return combine(scaling);
+}
+
+
+////////////////////////////////////////////////////////////
+Transform& Transform::scale(float scaleX, float scaleY, float centerX, float centerY)
+{
+ Transform scaling(scaleX, 0, centerX * (1 - scaleX),
+ 0, scaleY, centerY * (1 - scaleY),
+ 0, 0, 1);
+
+ return combine(scaling);
+}
+
+
+////////////////////////////////////////////////////////////
+Transform& Transform::scale(const Vector2f& factors)
+{
+ return scale(factors.x, factors.y);
+}
+
+
+////////////////////////////////////////////////////////////
+Transform& Transform::scale(const Vector2f& factors, const Vector2f& center)
+{
+ return scale(factors.x, factors.y, center.x, center.y);
+}
+
+
+////////////////////////////////////////////////////////////
+Transform operator *(const Transform& left, const Transform& right)
+{
+ return Transform(left).combine(right);
+}
+
+
+////////////////////////////////////////////////////////////
+Transform& operator *=(Transform& left, const Transform& right)
+{
+ return left.combine(right);
+}
+
+
+////////////////////////////////////////////////////////////
+Vector2f operator *(const Transform& left, const Vector2f& right)
+{
+ return left.transformPoint(right);
+}
+
+} // namespace sf
diff --git a/src/SFML/Graphics/Transformable.cpp b/src/SFML/Graphics/Transformable.cpp
new file mode 100644
index 0000000..e2a830a
--- /dev/null
+++ b/src/SFML/Graphics/Transformable.cpp
@@ -0,0 +1,219 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Graphics/Transformable.hpp>
+#include <cmath>
+
+
+namespace sf
+{
+////////////////////////////////////////////////////////////
+Transformable::Transformable() :
+m_origin (0, 0),
+m_position (0, 0),
+m_rotation (0),
+m_scale (1, 1),
+m_transform (),
+m_transformNeedUpdate (true),
+m_inverseTransform (),
+m_inverseTransformNeedUpdate(true)
+{
+}
+
+
+////////////////////////////////////////////////////////////
+Transformable::~Transformable()
+{
+}
+
+
+////////////////////////////////////////////////////////////
+void Transformable::setPosition(float x, float y)
+{
+ m_position.x = x;
+ m_position.y = y;
+ m_transformNeedUpdate = true;
+ m_inverseTransformNeedUpdate = true;
+}
+
+
+////////////////////////////////////////////////////////////
+void Transformable::setPosition(const Vector2f& position)
+{
+ setPosition(position.x, position.y);
+}
+
+
+////////////////////////////////////////////////////////////
+void Transformable::setRotation(float angle)
+{
+ m_rotation = static_cast<float>(fmod(angle, 360));
+ if (m_rotation < 0)
+ m_rotation += 360.f;
+
+ m_transformNeedUpdate = true;
+ m_inverseTransformNeedUpdate = true;
+}
+
+
+////////////////////////////////////////////////////////////
+void Transformable::setScale(float factorX, float factorY)
+{
+ m_scale.x = factorX;
+ m_scale.y = factorY;
+ m_transformNeedUpdate = true;
+ m_inverseTransformNeedUpdate = true;
+}
+
+
+////////////////////////////////////////////////////////////
+void Transformable::setScale(const Vector2f& factors)
+{
+ setScale(factors.x, factors.y);
+}
+
+
+////////////////////////////////////////////////////////////
+void Transformable::setOrigin(float x, float y)
+{
+ m_origin.x = x;
+ m_origin.y = y;
+ m_transformNeedUpdate = true;
+ m_inverseTransformNeedUpdate = true;
+}
+
+
+////////////////////////////////////////////////////////////
+void Transformable::setOrigin(const Vector2f& origin)
+{
+ setOrigin(origin.x, origin.y);
+}
+
+
+////////////////////////////////////////////////////////////
+const Vector2f& Transformable::getPosition() const
+{
+ return m_position;
+}
+
+
+////////////////////////////////////////////////////////////
+float Transformable::getRotation() const
+{
+ return m_rotation;
+}
+
+
+////////////////////////////////////////////////////////////
+const Vector2f& Transformable::getScale() const
+{
+ return m_scale;
+}
+
+
+////////////////////////////////////////////////////////////
+const Vector2f& Transformable::getOrigin() const
+{
+ return m_origin;
+}
+
+
+////////////////////////////////////////////////////////////
+void Transformable::move(float offsetX, float offsetY)
+{
+ setPosition(m_position.x + offsetX, m_position.y + offsetY);
+}
+
+
+////////////////////////////////////////////////////////////
+void Transformable::move(const Vector2f& offset)
+{
+ setPosition(m_position.x + offset.x, m_position.y + offset.y);
+}
+
+
+////////////////////////////////////////////////////////////
+void Transformable::rotate(float angle)
+{
+ setRotation(m_rotation + angle);
+}
+
+
+////////////////////////////////////////////////////////////
+void Transformable::scale(float factorX, float factorY)
+{
+ setScale(m_scale.x * factorX, m_scale.y * factorY);
+}
+
+
+////////////////////////////////////////////////////////////
+void Transformable::scale(const Vector2f& factor)
+{
+ setScale(m_scale.x * factor.x, m_scale.y * factor.y);
+}
+
+
+////////////////////////////////////////////////////////////
+const Transform& Transformable::getTransform() const
+{
+ // Recompute the combined transform if needed
+ if (m_transformNeedUpdate)
+ {
+ float angle = -m_rotation * 3.141592654f / 180.f;
+ float cosine = static_cast<float>(std::cos(angle));
+ float sine = static_cast<float>(std::sin(angle));
+ float sxc = m_scale.x * cosine;
+ float syc = m_scale.y * cosine;
+ float sxs = m_scale.x * sine;
+ float sys = m_scale.y * sine;
+ float tx = -m_origin.x * sxc - m_origin.y * sys + m_position.x;
+ float ty = m_origin.x * sxs - m_origin.y * syc + m_position.y;
+
+ m_transform = Transform( sxc, sys, tx,
+ -sxs, syc, ty,
+ 0.f, 0.f, 1.f);
+ m_transformNeedUpdate = false;
+ }
+
+ return m_transform;
+}
+
+
+////////////////////////////////////////////////////////////
+const Transform& Transformable::getInverseTransform() const
+{
+ // Recompute the inverse transform if needed
+ if (m_inverseTransformNeedUpdate)
+ {
+ m_inverseTransform = getTransform().getInverse();
+ m_inverseTransformNeedUpdate = false;
+ }
+
+ return m_inverseTransform;
+}
+
+} // namespace sf
diff --git a/src/SFML/Graphics/Vertex.cpp b/src/SFML/Graphics/Vertex.cpp
new file mode 100644
index 0000000..b17a23f
--- /dev/null
+++ b/src/SFML/Graphics/Vertex.cpp
@@ -0,0 +1,77 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Graphics/Vertex.hpp>
+
+
+namespace sf
+{
+////////////////////////////////////////////////////////////
+Vertex::Vertex() :
+position (0, 0),
+color (255, 255, 255),
+texCoords(0, 0)
+{
+}
+
+
+////////////////////////////////////////////////////////////
+Vertex::Vertex(const Vector2f& thePosition) :
+position (thePosition),
+color (255, 255, 255),
+texCoords(0, 0)
+{
+}
+
+
+////////////////////////////////////////////////////////////
+Vertex::Vertex(const Vector2f& thePosition, const Color& theColor) :
+position (thePosition),
+color (theColor),
+texCoords(0, 0)
+{
+}
+
+
+////////////////////////////////////////////////////////////
+Vertex::Vertex(const Vector2f& thePosition, const Vector2f& theTexCoords) :
+position (thePosition),
+color (255, 255, 255),
+texCoords(theTexCoords)
+{
+}
+
+
+////////////////////////////////////////////////////////////
+Vertex::Vertex(const Vector2f& thePosition, const Color& theColor, const Vector2f& theTexCoords) :
+position (thePosition),
+color (theColor),
+texCoords(theTexCoords)
+{
+}
+
+} // namespace sf
diff --git a/src/SFML/Graphics/VertexArray.cpp b/src/SFML/Graphics/VertexArray.cpp
new file mode 100644
index 0000000..0c8503d
--- /dev/null
+++ b/src/SFML/Graphics/VertexArray.cpp
@@ -0,0 +1,150 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Graphics/VertexArray.hpp>
+#include <SFML/Graphics/RenderTarget.hpp>
+
+
+namespace sf
+{
+////////////////////////////////////////////////////////////
+VertexArray::VertexArray() :
+m_vertices (),
+m_primitiveType(Points)
+{
+}
+
+
+////////////////////////////////////////////////////////////
+VertexArray::VertexArray(PrimitiveType type, unsigned int vertexCount) :
+m_vertices (vertexCount),
+m_primitiveType(type)
+{
+}
+
+
+////////////////////////////////////////////////////////////
+unsigned int VertexArray::getVertexCount() const
+{
+ return static_cast<unsigned int>(m_vertices.size());
+}
+
+
+////////////////////////////////////////////////////////////
+Vertex& VertexArray::operator [](unsigned int index)
+{
+ return m_vertices[index];
+}
+
+
+////////////////////////////////////////////////////////////
+const Vertex& VertexArray::operator [](unsigned int index) const
+{
+ return m_vertices[index];
+}
+
+
+////////////////////////////////////////////////////////////
+void VertexArray::clear()
+{
+ m_vertices.clear();
+}
+
+
+////////////////////////////////////////////////////////////
+void VertexArray::resize(unsigned int vertexCount)
+{
+ m_vertices.resize(vertexCount);
+}
+
+
+////////////////////////////////////////////////////////////
+void VertexArray::append(const Vertex& vertex)
+{
+ m_vertices.push_back(vertex);
+}
+
+
+////////////////////////////////////////////////////////////
+void VertexArray::setPrimitiveType(PrimitiveType type)
+{
+ m_primitiveType = type;
+}
+
+
+////////////////////////////////////////////////////////////
+PrimitiveType VertexArray::getPrimitiveType() const
+{
+ return m_primitiveType;
+}
+
+
+////////////////////////////////////////////////////////////
+FloatRect VertexArray::getBounds() const
+{
+ if (!m_vertices.empty())
+ {
+ float left = m_vertices[0].position.x;
+ float top = m_vertices[0].position.y;
+ float right = m_vertices[0].position.x;
+ float bottom = m_vertices[0].position.y;
+
+ for (std::size_t i = 1; i < m_vertices.size(); ++i)
+ {
+ Vector2f position = m_vertices[i].position;
+
+ // Update left and right
+ if (position.x < left)
+ left = position.x;
+ else if (position.x > right)
+ right = position.x;
+
+ // Update top and bottom
+ if (position.y < top)
+ top = position.y;
+ else if (position.y > bottom)
+ bottom = position.y;
+ }
+
+ return FloatRect(left, top, right - left, bottom - top);
+ }
+ else
+ {
+ // Array is empty
+ return FloatRect();
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void VertexArray::draw(RenderTarget& target, RenderStates states) const
+{
+ if (!m_vertices.empty())
+ target.draw(&m_vertices[0], static_cast<unsigned int>(m_vertices.size()), m_primitiveType, states);
+}
+
+} // namespace sf
diff --git a/src/SFML/Graphics/View.cpp b/src/SFML/Graphics/View.cpp
index 0b2fb66..9524246 100755..100644
--- a/src/SFML/Graphics/View.cpp
+++ b/src/SFML/Graphics/View.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -26,183 +26,215 @@
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/View.hpp>
-#include <algorithm>
+#include <cmath>
namespace sf
{
////////////////////////////////////////////////////////////
-/// Construct the view from a rectangle
+View::View() :
+m_center (),
+m_size (),
+m_rotation (0),
+m_viewport (0, 0, 1, 1),
+m_transformUpdated (false),
+m_invTransformUpdated(false)
+{
+ reset(FloatRect(0, 0, 1000, 1000));
+}
+
+
////////////////////////////////////////////////////////////
-View::View(const FloatRect& ViewRect)
+View::View(const FloatRect& rectangle) :
+m_center (),
+m_size (),
+m_rotation (0),
+m_viewport (0, 0, 1, 1),
+m_transformUpdated (false),
+m_invTransformUpdated(false)
{
- SetFromRect(ViewRect);
+ reset(rectangle);
}
////////////////////////////////////////////////////////////
-/// Construct the view from its center and half-size
+View::View(const Vector2f& center, const Vector2f& size) :
+m_center (center),
+m_size (size),
+m_rotation (0),
+m_viewport (0, 0, 1, 1),
+m_transformUpdated (false),
+m_invTransformUpdated(false)
+{
+
+}
+
////////////////////////////////////////////////////////////
-View::View(const sf::Vector2f& Center, const sf::Vector2f& HalfSize) :
-myCenter (Center),
-myHalfSize (HalfSize),
-myNeedUpdate(true)
+void View::setCenter(float x, float y)
{
+ m_center.x = x;
+ m_center.y = y;
+ m_transformUpdated = false;
+ m_invTransformUpdated = false;
}
////////////////////////////////////////////////////////////
-/// Change the center of the view (take 2 values)
-////////////////////////////////////////////////////////////
-void View::SetCenter(float X, float Y)
+void View::setCenter(const Vector2f& center)
{
- myCenter.x = X;
- myCenter.y = Y;
- myNeedUpdate = true;
+ setCenter(center.x, center.y);
}
////////////////////////////////////////////////////////////
-/// Change the center of the view (take a vector)
-////////////////////////////////////////////////////////////
-void View::SetCenter(const sf::Vector2f& Center)
+void View::setSize(float width, float height)
{
- SetCenter(Center.x, Center.y);
+ m_size.x = width;
+ m_size.y = height;
+
+ m_transformUpdated = false;
+ m_invTransformUpdated = false;
}
////////////////////////////////////////////////////////////
-/// Change the half-size of the view (take 2 values)
-////////////////////////////////////////////////////////////
-void View::SetHalfSize(float HalfWidth, float HalfHeight)
+void View::setSize(const Vector2f& size)
{
- myHalfSize.x = HalfWidth;
- myHalfSize.y = HalfHeight;
- myNeedUpdate = true;
+ setSize(size.x, size.y);
}
////////////////////////////////////////////////////////////
-/// Change the half-size of the view (take a vector)
-////////////////////////////////////////////////////////////
-void View::SetHalfSize(const sf::Vector2f& HalfSize)
+void View::setRotation(float angle)
{
- SetHalfSize(HalfSize.x, HalfSize.y);
+ m_rotation = static_cast<float>(fmod(angle, 360));
+ if (m_rotation < 0)
+ m_rotation += 360.f;
+
+ m_transformUpdated = false;
+ m_invTransformUpdated = false;
}
////////////////////////////////////////////////////////////
-/// Rebuild the view from a rectangle
-////////////////////////////////////////////////////////////
-void View::SetFromRect(const FloatRect& ViewRect)
+void View::setViewport(const FloatRect& viewport)
{
- SetCenter( (ViewRect.Right + ViewRect.Left) / 2, (ViewRect.Bottom + ViewRect.Top) / 2);
- SetHalfSize((ViewRect.Right - ViewRect.Left) / 2, (ViewRect.Bottom - ViewRect.Top) / 2);
+ m_viewport = viewport;
}
////////////////////////////////////////////////////////////
-/// Get the center of the view
-////////////////////////////////////////////////////////////
-const sf::Vector2f& View::GetCenter() const
+void View::reset(const FloatRect& rectangle)
{
- return myCenter;
+ m_center.x = rectangle.left + rectangle.width / 2.f;
+ m_center.y = rectangle.top + rectangle.height / 2.f;
+ m_size.x = rectangle.width;
+ m_size.y = rectangle.height;
+ m_rotation = 0;
+
+ m_transformUpdated = false;
+ m_invTransformUpdated = false;
}
////////////////////////////////////////////////////////////
-/// Get the half-size of the view
-////////////////////////////////////////////////////////////
-const sf::Vector2f& View::GetHalfSize() const
+const Vector2f& View::getCenter() const
{
- return myHalfSize;
+ return m_center;
}
////////////////////////////////////////////////////////////
-/// Get the bounding rectangle of the view
-////////////////////////////////////////////////////////////
-const sf::FloatRect& View::GetRect() const
+const Vector2f& View::getSize() const
{
- // Recompute it if needed
- if (myNeedUpdate)
- const_cast<View*>(this)->RecomputeMatrix();
-
- return myRect;
+ return m_size;
}
////////////////////////////////////////////////////////////
-/// Move the view (take 2 values)
-////////////////////////////////////////////////////////////
-void View::Move(float OffsetX, float OffsetY)
+float View::getRotation() const
{
- myCenter.x += OffsetX;
- myCenter.y += OffsetY;
- myNeedUpdate = true;
+ return m_rotation;
}
////////////////////////////////////////////////////////////
-/// Move the view (take a vector)
+const FloatRect& View::getViewport() const
+{
+ return m_viewport;
+}
+
+
////////////////////////////////////////////////////////////
-void View::Move(const sf::Vector2f& Offset)
+void View::move(float offsetX, float offsetY)
{
- Move(Offset.x, Offset.y);
+ setCenter(m_center.x + offsetX, m_center.y + offsetY);
}
////////////////////////////////////////////////////////////
-/// Resize the view rectangle to simulate a zoom / unzoom effect
+void View::move(const Vector2f& offset)
+{
+ setCenter(m_center + offset);
+}
+
+
////////////////////////////////////////////////////////////
-void View::Zoom(float Factor)
+void View::rotate(float angle)
{
- if (Factor != 0)
- {
- myHalfSize /= Factor;
- myNeedUpdate = true;
- }
+ setRotation(m_rotation + angle);
}
////////////////////////////////////////////////////////////
-/// Get the projection matrix of the view
+void View::zoom(float factor)
+{
+ setSize(m_size.x * factor, m_size.y * factor);
+}
+
+
////////////////////////////////////////////////////////////
-const Matrix3& View::GetMatrix() const
+const Transform& View::getTransform() const
{
// Recompute the matrix if needed
- if (myNeedUpdate)
- const_cast<View*>(this)->RecomputeMatrix();
+ if (!m_transformUpdated)
+ {
+ // Rotation components
+ float angle = m_rotation * 3.141592654f / 180.f;
+ float cosine = static_cast<float>(std::cos(angle));
+ float sine = static_cast<float>(std::sin(angle));
+ float tx = -m_center.x * cosine - m_center.y * sine + m_center.x;
+ float ty = m_center.x * sine - m_center.y * cosine + m_center.y;
+
+ // Projection components
+ float a = 2.f / m_size.x;
+ float b = -2.f / m_size.y;
+ float c = -a * m_center.x;
+ float d = -b * m_center.y;
+
+ // Rebuild the projection matrix
+ m_transform = Transform( a * cosine, a * sine, a * tx + c,
+ -b * sine, b * cosine, b * ty + d,
+ 0.f, 0.f, 1.f);
+ m_transformUpdated = true;
+ }
- return myMatrix;
+ return m_transform;
}
////////////////////////////////////////////////////////////
-/// Recompute the view rectangle and the projection matrix
-////////////////////////////////////////////////////////////
-void View::RecomputeMatrix()
+const Transform& View::getInverseTransform() const
{
- // Compute the 4 corners of the view
- float Left = myCenter.x - myHalfSize.x;
- float Top = myCenter.y - myHalfSize.y;
- float Right = myCenter.x + myHalfSize.x;
- float Bottom = myCenter.y + myHalfSize.y;
-
- // Update the view rectangle - be careful, reversed views are allowed !
- myRect.Left = std::min(Left, Right);
- myRect.Top = std::min(Top, Bottom);
- myRect.Right = std::max(Left, Right);
- myRect.Bottom = std::max(Top, Bottom);
-
- // Update the projection matrix
- myMatrix(0, 0) = 2.f / (Right - Left);
- myMatrix(1, 1) = 2.f / (Top - Bottom);
- myMatrix(0, 2) = (Left + Right) / (Left - Right);
- myMatrix(1, 2) = (Bottom + Top) / (Bottom - Top);
+ // Recompute the matrix if needed
+ if (!m_invTransformUpdated)
+ {
+ m_inverseTransform = getTransform().getInverse();
+ m_invTransformUpdated = true;
+ }
- myNeedUpdate = false;
+ return m_inverseTransform;
}
} // namespace sf
diff --git a/src/SFML/Graphics/stb_image/stb_image.h b/src/SFML/Graphics/stb_image/stb_image.h
new file mode 100644
index 0000000..e6ed311
--- /dev/null
+++ b/src/SFML/Graphics/stb_image/stb_image.h
@@ -0,0 +1,4673 @@
+/* stbi-1.33 - public domain JPEG/PNG reader - http://nothings.org/stb_image.c
+ when you control the images you're loading
+ no warranty implied; use at your own risk
+
+ QUICK NOTES:
+ Primarily of interest to game developers and other people who can
+ avoid problematic images and only need the trivial interface
+
+ JPEG baseline (no JPEG progressive)
+ PNG 8-bit only
+
+ TGA (not sure what subset, if a subset)
+ BMP non-1bpp, non-RLE
+ PSD (composited view only, no extra channels)
+
+ GIF (*comp always reports as 4-channel)
+ HDR (radiance rgbE format)
+ PIC (Softimage PIC)
+
+ - decode from memory or through FILE (define STBI_NO_STDIO to remove code)
+ - decode from arbitrary I/O callbacks
+ - overridable dequantizing-IDCT, YCbCr-to-RGB conversion (define STBI_SIMD)
+
+ Latest revisions:
+ 1.33 (2011-07-14) minor fixes suggested by Dave Moore
+ 1.32 (2011-07-13) info support for all filetypes (SpartanJ)
+ 1.31 (2011-06-19) a few more leak fixes, bug in PNG handling (SpartanJ)
+ 1.30 (2011-06-11) added ability to load files via io callbacks (Ben Wenger)
+ 1.29 (2010-08-16) various warning fixes from Aurelien Pocheville
+ 1.28 (2010-08-01) fix bug in GIF palette transparency (SpartanJ)
+ 1.27 (2010-08-01) cast-to-uint8 to fix warnings (Laurent Gomila)
+ allow trailing 0s at end of image data (Laurent Gomila)
+ 1.26 (2010-07-24) fix bug in file buffering for PNG reported by SpartanJ
+
+ See end of file for full revision history.
+
+ TODO:
+ stbi_info support for BMP,PSD,HDR,PIC
+
+
+ ============================ Contributors =========================
+
+ Image formats Optimizations & bugfixes
+ Sean Barrett (jpeg, png, bmp) Fabian "ryg" Giesen
+ Nicolas Schulz (hdr, psd)
+ Jonathan Dummer (tga) Bug fixes & warning fixes
+ Jean-Marc Lienher (gif) Marc LeBlanc
+ Tom Seddon (pic) Christpher Lloyd
+ Thatcher Ulrich (psd) Dave Moore
+ Won Chun
+ the Horde3D community
+ Extensions, features Janez Zemva
+ Jetro Lauha (stbi_info) Jonathan Blow
+ James "moose2000" Brown (iPhone PNG) Laurent Gomila
+ Ben "Disch" Wenger (io callbacks) Aruelien Pocheville
+ Martin "SpartanJ" Golini Ryamond Barbiero
+ David Woo
+
+
+ If your name should be here but isn't, let Sean know.
+
+*/
+
+#ifndef STBI_INCLUDE_STB_IMAGE_H
+#define STBI_INCLUDE_STB_IMAGE_H
+
+// To get a header file for this, either cut and paste the header,
+// or create stb_image.h, #define STBI_HEADER_FILE_ONLY, and
+// then include stb_image.c from it.
+
+//// begin header file ////////////////////////////////////////////////////
+//
+// Limitations:
+// - no jpeg progressive support
+// - non-HDR formats support 8-bit samples only (jpeg, png)
+// - no delayed line count (jpeg) -- IJG doesn't support either
+// - no 1-bit BMP
+// - GIF always returns *comp=4
+//
+// Basic usage (see HDR discussion below):
+// int x,y,n;
+// unsigned char *data = stbi_load(filename, &x, &y, &n, 0);
+// // ... process data if not NULL ...
+// // ... x = width, y = height, n = # 8-bit components per pixel ...
+// // ... replace '0' with '1'..'4' to force that many components per pixel
+// // ... but 'n' will always be the number that it would have been if you said 0
+// stbi_image_free(data)
+//
+// Standard parameters:
+// int *x -- outputs image width in pixels
+// int *y -- outputs image height in pixels
+// int *comp -- outputs # of image components in image file
+// int req_comp -- if non-zero, # of image components requested in result
+//
+// The return value from an image loader is an 'unsigned char *' which points
+// to the pixel data. The pixel data consists of *y scanlines of *x pixels,
+// with each pixel consisting of N interleaved 8-bit components; the first
+// pixel pointed to is top-left-most in the image. There is no padding between
+// image scanlines or between pixels, regardless of format. The number of
+// components N is 'req_comp' if req_comp is non-zero, or *comp otherwise.
+// If req_comp is non-zero, *comp has the number of components that _would_
+// have been output otherwise. E.g. if you set req_comp to 4, you will always
+// get RGBA output, but you can check *comp to easily see if it's opaque.
+//
+// An output image with N components has the following components interleaved
+// in this order in each pixel:
+//
+// N=#comp components
+// 1 grey
+// 2 grey, alpha
+// 3 red, green, blue
+// 4 red, green, blue, alpha
+//
+// If image loading fails for any reason, the return value will be NULL,
+// and *x, *y, *comp will be unchanged. The function stbi_failure_reason()
+// can be queried for an extremely brief, end-user unfriendly explanation
+// of why the load failed. Define STBI_NO_FAILURE_STRINGS to avoid
+// compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly
+// more user-friendly ones.
+//
+// Paletted PNG, BMP, GIF, and PIC images are automatically depalettized.
+//
+// ===========================================================================
+//
+// iPhone PNG support:
+//
+// By default we convert iphone-formatted PNGs back to RGB; nominally they
+// would silently load as BGR, except the existing code should have just
+// failed on such iPhone PNGs. But you can disable this conversion by
+// by calling stbi_convert_iphone_png_to_rgb(0), in which case
+// you will always just get the native iphone "format" through.
+//
+// Call stbi_set_unpremultiply_on_load(1) as well to force a divide per
+// pixel to remove any premultiplied alpha *only* if the image file explicitly
+// says there's premultiplied data (currently only happens in iPhone images,
+// and only if iPhone convert-to-rgb processing is on).
+//
+// ===========================================================================
+//
+// HDR image support (disable by defining STBI_NO_HDR)
+//
+// stb_image now supports loading HDR images in general, and currently
+// the Radiance .HDR file format, although the support is provided
+// generically. You can still load any file through the existing interface;
+// if you attempt to load an HDR file, it will be automatically remapped to
+// LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1;
+// both of these constants can be reconfigured through this interface:
+//
+// stbi_hdr_to_ldr_gamma(2.2f);
+// stbi_hdr_to_ldr_scale(1.0f);
+//
+// (note, do not use _inverse_ constants; stbi_image will invert them
+// appropriately).
+//
+// Additionally, there is a new, parallel interface for loading files as
+// (linear) floats to preserve the full dynamic range:
+//
+// float *data = stbi_loadf(filename, &x, &y, &n, 0);
+//
+// If you load LDR images through this interface, those images will
+// be promoted to floating point values, run through the inverse of
+// constants corresponding to the above:
+//
+// stbi_ldr_to_hdr_scale(1.0f);
+// stbi_ldr_to_hdr_gamma(2.2f);
+//
+// Finally, given a filename (or an open file or memory block--see header
+// file for details) containing image data, you can query for the "most
+// appropriate" interface to use (that is, whether the image is HDR or
+// not), using:
+//
+// stbi_is_hdr(char *filename);
+//
+// ===========================================================================
+//
+// I/O callbacks
+//
+// I/O callbacks allow you to read from arbitrary sources, like packaged
+// files or some other source. Data read from callbacks are processed
+// through a small internal buffer (currently 128 bytes) to try to reduce
+// overhead.
+//
+// The three functions you must define are "read" (reads some bytes of data),
+// "skip" (skips some bytes of data), "eof" (reports if the stream is at the end).
+
+
+#ifndef STBI_NO_STDIO
+
+#if defined(_MSC_VER) && _MSC_VER >= 0x1400
+#define _CRT_SECURE_NO_WARNINGS // suppress bogus warnings about fopen()
+#endif
+
+#include <stdio.h>
+#endif
+
+#define STBI_VERSION 1
+
+enum
+{
+ STBI_default = 0, // only used for req_comp
+
+ STBI_grey = 1,
+ STBI_grey_alpha = 2,
+ STBI_rgb = 3,
+ STBI_rgb_alpha = 4
+};
+
+typedef unsigned char stbi_uc;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// PRIMARY API - works on images of any type
+//
+
+//
+// load image by filename, open file, or memory buffer
+//
+
+extern stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
+
+#ifndef STBI_NO_STDIO
+extern stbi_uc *stbi_load (char const *filename, int *x, int *y, int *comp, int req_comp);
+extern stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
+// for stbi_load_from_file, file pointer is left pointing immediately after image
+#endif
+
+typedef struct
+{
+ int (*read) (void *user,char *data,int size); // fill 'data' with 'size' bytes. return number of bytes actually read
+ void (*skip) (void *user,unsigned n); // skip the next 'n' bytes
+ int (*eof) (void *user); // returns nonzero if we are at end of file/data
+} stbi_io_callbacks;
+
+extern stbi_uc *stbi_load_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp);
+
+#ifndef STBI_NO_HDR
+ extern float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
+
+ #ifndef STBI_NO_STDIO
+ extern float *stbi_loadf (char const *filename, int *x, int *y, int *comp, int req_comp);
+ extern float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
+ #endif
+
+ extern float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp);
+
+ extern void stbi_hdr_to_ldr_gamma(float gamma);
+ extern void stbi_hdr_to_ldr_scale(float scale);
+
+ extern void stbi_ldr_to_hdr_gamma(float gamma);
+ extern void stbi_ldr_to_hdr_scale(float scale);
+#endif // STBI_NO_HDR
+
+// stbi_is_hdr is always defined
+extern int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user);
+extern int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len);
+#ifndef STBI_NO_STDIO
+extern int stbi_is_hdr (char const *filename);
+extern int stbi_is_hdr_from_file(FILE *f);
+#endif // STBI_NO_STDIO
+
+
+// get a VERY brief reason for failure
+// NOT THREADSAFE
+extern const char *stbi_failure_reason (void);
+
+// free the loaded image -- this is just free()
+extern void stbi_image_free (void *retval_from_stbi_load);
+
+// get image dimensions & components without fully decoding
+extern int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);
+extern int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp);
+
+#ifndef STBI_NO_STDIO
+extern int stbi_info (char const *filename, int *x, int *y, int *comp);
+extern int stbi_info_from_file (FILE *f, int *x, int *y, int *comp);
+
+#endif
+
+
+
+// for image formats that explicitly notate that they have premultiplied alpha,
+// we just return the colors as stored in the file. set this flag to force
+// unpremultiplication. results are undefined if the unpremultiply overflow.
+extern void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply);
+
+// indicate whether we should process iphone images back to canonical format,
+// or just pass them through "as-is"
+extern void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert);
+
+
+// ZLIB client - used by PNG, available for other purposes
+
+extern char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen);
+extern char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen);
+extern int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);
+
+extern char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen);
+extern int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);
+
+
+// define faster low-level operations (typically SIMD support)
+#ifdef STBI_SIMD
+typedef void (*stbi_idct_8x8)(stbi_uc *out, int out_stride, short data[64], unsigned short *dequantize);
+// compute an integer IDCT on "input"
+// input[x] = data[x] * dequantize[x]
+// write results to 'out': 64 samples, each run of 8 spaced by 'out_stride'
+// CLAMP results to 0..255
+typedef void (*stbi_YCbCr_to_RGB_run)(stbi_uc *output, stbi_uc const *y, stbi_uc const *cb, stbi_uc const *cr, int count, int step);
+// compute a conversion from YCbCr to RGB
+// 'count' pixels
+// write pixels to 'output'; each pixel is 'step' bytes (either 3 or 4; if 4, write '255' as 4th), order R,G,B
+// y: Y input channel
+// cb: Cb input channel; scale/biased to be 0..255
+// cr: Cr input channel; scale/biased to be 0..255
+
+extern void stbi_install_idct(stbi_idct_8x8 func);
+extern void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func);
+#endif // STBI_SIMD
+
+
+#ifdef __cplusplus
+}
+#endif
+
+//
+//
+//// end header file /////////////////////////////////////////////////////
+#endif // STBI_INCLUDE_STB_IMAGE_H
+
+#ifndef STBI_HEADER_FILE_ONLY
+
+#ifndef STBI_NO_HDR
+#include <math.h> // ldexp
+#include <string.h> // strcmp, strtok
+#endif
+
+#ifndef STBI_NO_STDIO
+#include <stdio.h>
+#endif
+#include <stdlib.h>
+#include <memory.h>
+#include <assert.h>
+#include <stdarg.h>
+
+#ifndef _MSC_VER
+ #ifdef __cplusplus
+ #define stbi_inline inline
+ #else
+ #define stbi_inline
+ #endif
+#else
+ #define stbi_inline __forceinline
+#endif
+
+
+// implementation:
+typedef unsigned char uint8;
+typedef unsigned short uint16;
+typedef signed short int16;
+typedef unsigned int uint32;
+typedef signed int int32;
+typedef unsigned int uint;
+
+// should produce compiler error if size is wrong
+typedef unsigned char validate_uint32[sizeof(uint32)==4 ? 1 : -1];
+
+#if defined(STBI_NO_STDIO) && !defined(STBI_NO_WRITE)
+#define STBI_NO_WRITE
+#endif
+
+#define STBI_NOTUSED(v) (void)sizeof(v)
+
+#ifdef _MSC_VER
+#define STBI_HAS_LROTL
+#endif
+
+#ifdef STBI_HAS_LROTL
+ #define stbi_lrot(x,y) _lrotl(x,y)
+#else
+ #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (32 - (y))))
+#endif
+
+///////////////////////////////////////////////
+//
+// stbi struct and start_xxx functions
+
+// stbi structure is our basic context used by all images, so it
+// contains all the IO context, plus some basic image information
+typedef struct
+{
+ uint32 img_x, img_y;
+ int img_n, img_out_n;
+
+ stbi_io_callbacks io;
+ void *io_user_data;
+
+ int read_from_callbacks;
+ int buflen;
+ uint8 buffer_start[128];
+
+ uint8 *img_buffer, *img_buffer_end;
+ uint8 *img_buffer_original;
+} stbi;
+
+
+static void refill_buffer(stbi *s);
+
+// initialize a memory-decode context
+static void start_mem(stbi *s, uint8 const *buffer, int len)
+{
+ s->io.read = NULL;
+ s->read_from_callbacks = 0;
+ s->img_buffer = s->img_buffer_original = (uint8 *) buffer;
+ s->img_buffer_end = (uint8 *) buffer+len;
+}
+
+// initialize a callback-based context
+static void start_callbacks(stbi *s, stbi_io_callbacks *c, void *user)
+{
+ s->io = *c;
+ s->io_user_data = user;
+ s->buflen = sizeof(s->buffer_start);
+ s->read_from_callbacks = 1;
+ s->img_buffer_original = s->buffer_start;
+ refill_buffer(s);
+}
+
+#ifndef STBI_NO_STDIO
+
+static int stdio_read(void *user, char *data, int size)
+{
+ return (int) fread(data,1,size,(FILE*) user);
+}
+
+static void stdio_skip(void *user, unsigned n)
+{
+ fseek((FILE*) user, n, SEEK_CUR);
+}
+
+static int stdio_eof(void *user)
+{
+ return feof((FILE*) user);
+}
+
+static stbi_io_callbacks stbi_stdio_callbacks =
+{
+ stdio_read,
+ stdio_skip,
+ stdio_eof,
+};
+
+static void start_file(stbi *s, FILE *f)
+{
+ start_callbacks(s, &stbi_stdio_callbacks, (void *) f);
+}
+
+//static void stop_file(stbi *s) { }
+
+#endif // !STBI_NO_STDIO
+
+static void stbi_rewind(stbi *s)
+{
+ // conceptually rewind SHOULD rewind to the beginning of the stream,
+ // but we just rewind to the beginning of the initial buffer, because
+ // we only use it after doing 'test', which only ever looks at at most 92 bytes
+ s->img_buffer = s->img_buffer_original;
+}
+
+static int stbi_jpeg_test(stbi *s);
+static stbi_uc *stbi_jpeg_load(stbi *s, int *x, int *y, int *comp, int req_comp);
+static int stbi_jpeg_info(stbi *s, int *x, int *y, int *comp);
+static int stbi_png_test(stbi *s);
+static stbi_uc *stbi_png_load(stbi *s, int *x, int *y, int *comp, int req_comp);
+static int stbi_png_info(stbi *s, int *x, int *y, int *comp);
+static int stbi_bmp_test(stbi *s);
+static stbi_uc *stbi_bmp_load(stbi *s, int *x, int *y, int *comp, int req_comp);
+static int stbi_tga_test(stbi *s);
+static stbi_uc *stbi_tga_load(stbi *s, int *x, int *y, int *comp, int req_comp);
+static int stbi_tga_info(stbi *s, int *x, int *y, int *comp);
+static int stbi_psd_test(stbi *s);
+static stbi_uc *stbi_psd_load(stbi *s, int *x, int *y, int *comp, int req_comp);
+static int stbi_hdr_test(stbi *s);
+static float *stbi_hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp);
+static int stbi_pic_test(stbi *s);
+static stbi_uc *stbi_pic_load(stbi *s, int *x, int *y, int *comp, int req_comp);
+static int stbi_gif_test(stbi *s);
+static stbi_uc *stbi_gif_load(stbi *s, int *x, int *y, int *comp, int req_comp);
+static int stbi_gif_info(stbi *s, int *x, int *y, int *comp);
+
+
+// this is not threadsafe
+static const char *failure_reason;
+
+const char *stbi_failure_reason(void)
+{
+ return failure_reason;
+}
+
+static int e(const char *str)
+{
+ failure_reason = str;
+ return 0;
+}
+
+// e - error
+// epf - error returning pointer to float
+// epuc - error returning pointer to unsigned char
+
+#ifdef STBI_NO_FAILURE_STRINGS
+ #define e(x,y) 0
+#elif defined(STBI_FAILURE_USERMSG)
+ #define e(x,y) e(y)
+#else
+ #define e(x,y) e(x)
+#endif
+
+#define epf(x,y) ((float *) (e(x,y)?NULL:NULL))
+#define epuc(x,y) ((unsigned char *) (e(x,y)?NULL:NULL))
+
+void stbi_image_free(void *retval_from_stbi_load)
+{
+ free(retval_from_stbi_load);
+}
+
+#ifndef STBI_NO_HDR
+static float *ldr_to_hdr(stbi_uc *data, int x, int y, int comp);
+static stbi_uc *hdr_to_ldr(float *data, int x, int y, int comp);
+#endif
+
+static unsigned char *stbi_load_main(stbi *s, int *x, int *y, int *comp, int req_comp)
+{
+ if (stbi_jpeg_test(s)) return stbi_jpeg_load(s,x,y,comp,req_comp);
+ if (stbi_png_test(s)) return stbi_png_load(s,x,y,comp,req_comp);
+ if (stbi_bmp_test(s)) return stbi_bmp_load(s,x,y,comp,req_comp);
+ if (stbi_gif_test(s)) return stbi_gif_load(s,x,y,comp,req_comp);
+ if (stbi_psd_test(s)) return stbi_psd_load(s,x,y,comp,req_comp);
+ if (stbi_pic_test(s)) return stbi_pic_load(s,x,y,comp,req_comp);
+
+ #ifndef STBI_NO_HDR
+ if (stbi_hdr_test(s)) {
+ float *hdr = stbi_hdr_load(s, x,y,comp,req_comp);
+ return hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);
+ }
+ #endif
+
+ // test tga last because it's a crappy test!
+ if (stbi_tga_test(s))
+ return stbi_tga_load(s,x,y,comp,req_comp);
+ return epuc("unknown image type", "Image not of any known type, or corrupt");
+}
+
+#ifndef STBI_NO_STDIO
+unsigned char *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp)
+{
+ FILE *f = fopen(filename, "rb");
+ unsigned char *result;
+ if (!f) return epuc("can't fopen", "Unable to open file");
+ result = stbi_load_from_file(f,x,y,comp,req_comp);
+ fclose(f);
+ return result;
+}
+
+unsigned char *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
+{
+ stbi s;
+ start_file(&s,f);
+ return stbi_load_main(&s,x,y,comp,req_comp);
+}
+#endif //!STBI_NO_STDIO
+
+unsigned char *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
+{
+ stbi s;
+ start_mem(&s,buffer,len);
+ return stbi_load_main(&s,x,y,comp,req_comp);
+}
+
+unsigned char *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)
+{
+ stbi s;
+ start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
+ return stbi_load_main(&s,x,y,comp,req_comp);
+}
+
+#ifndef STBI_NO_HDR
+
+float *stbi_loadf_main(stbi *s, int *x, int *y, int *comp, int req_comp)
+{
+ unsigned char *data;
+ #ifndef STBI_NO_HDR
+ if (stbi_hdr_test(s))
+ return stbi_hdr_load(s,x,y,comp,req_comp);
+ #endif
+ data = stbi_load_main(s, x, y, comp, req_comp);
+ if (data)
+ return ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);
+ return epf("unknown image type", "Image not of any known type, or corrupt");
+}
+
+float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
+{
+ stbi s;
+ start_mem(&s,buffer,len);
+ return stbi_loadf_main(&s,x,y,comp,req_comp);
+}
+
+float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)
+{
+ stbi s;
+ start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
+ return stbi_loadf_main(&s,x,y,comp,req_comp);
+}
+
+#ifndef STBI_NO_STDIO
+float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp)
+{
+ FILE *f = fopen(filename, "rb");
+ float *result;
+ if (!f) return epf("can't fopen", "Unable to open file");
+ result = stbi_loadf_from_file(f,x,y,comp,req_comp);
+ fclose(f);
+ return result;
+}
+
+float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
+{
+ stbi s;
+ start_file(&s,f);
+ return stbi_loadf_main(&s,x,y,comp,req_comp);
+}
+#endif // !STBI_NO_STDIO
+
+#endif // !STBI_NO_HDR
+
+// these is-hdr-or-not is defined independent of whether STBI_NO_HDR is
+// defined, for API simplicity; if STBI_NO_HDR is defined, it always
+// reports false!
+
+int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len)
+{
+ #ifndef STBI_NO_HDR
+ stbi s;
+ start_mem(&s,buffer,len);
+ return stbi_hdr_test(&s);
+ #else
+ STBI_NOTUSED(buffer);
+ STBI_NOTUSED(len);
+ return 0;
+ #endif
+}
+
+#ifndef STBI_NO_STDIO
+extern int stbi_is_hdr (char const *filename)
+{
+ FILE *f = fopen(filename, "rb");
+ int result=0;
+ if (f) {
+ result = stbi_is_hdr_from_file(f);
+ fclose(f);
+ }
+ return result;
+}
+
+extern int stbi_is_hdr_from_file(FILE *f)
+{
+ #ifndef STBI_NO_HDR
+ stbi s;
+ start_file(&s,f);
+ return stbi_hdr_test(&s);
+ #else
+ return 0;
+ #endif
+}
+#endif // !STBI_NO_STDIO
+
+extern int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user)
+{
+ #ifndef STBI_NO_HDR
+ stbi s;
+ start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
+ return stbi_hdr_test(&s);
+ #else
+ return 0;
+ #endif
+}
+
+#ifndef STBI_NO_HDR
+static float h2l_gamma_i=1.0f/2.2f, h2l_scale_i=1.0f;
+static float l2h_gamma=2.2f, l2h_scale=1.0f;
+
+void stbi_hdr_to_ldr_gamma(float gamma) { h2l_gamma_i = 1/gamma; }
+void stbi_hdr_to_ldr_scale(float scale) { h2l_scale_i = 1/scale; }
+
+void stbi_ldr_to_hdr_gamma(float gamma) { l2h_gamma = gamma; }
+void stbi_ldr_to_hdr_scale(float scale) { l2h_scale = scale; }
+#endif
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// Common code used by all image loaders
+//
+
+enum
+{
+ SCAN_load=0,
+ SCAN_type,
+ SCAN_header
+};
+
+static void refill_buffer(stbi *s)
+{
+ int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen);
+ if (n == 0) {
+ // at end of file, treat same as if from memory
+ s->read_from_callbacks = 0;
+ s->img_buffer = s->img_buffer_end-1;
+ *s->img_buffer = 0;
+ } else {
+ s->img_buffer = s->buffer_start;
+ s->img_buffer_end = s->buffer_start + n;
+ }
+}
+
+stbi_inline static int get8(stbi *s)
+{
+ if (s->img_buffer < s->img_buffer_end)
+ return *s->img_buffer++;
+ if (s->read_from_callbacks) {
+ refill_buffer(s);
+ return *s->img_buffer++;
+ }
+ return 0;
+}
+
+stbi_inline static int at_eof(stbi *s)
+{
+ if (s->io.read) {
+ if (!(s->io.eof)(s->io_user_data)) return 0;
+ // if feof() is true, check if buffer = end
+ // special case: we've only got the special 0 character at the end
+ if (s->read_from_callbacks == 0) return 1;
+ }
+
+ return s->img_buffer >= s->img_buffer_end;
+}
+
+stbi_inline static uint8 get8u(stbi *s)
+{
+ return (uint8) get8(s);
+}
+
+static void skip(stbi *s, int n)
+{
+ if (s->io.read) {
+ int blen = s->img_buffer_end - s->img_buffer;
+ if (blen < n) {
+ s->img_buffer = s->img_buffer_end;
+ (s->io.skip)(s->io_user_data, n - blen);
+ return;
+ }
+ }
+ s->img_buffer += n;
+}
+
+static int getn(stbi *s, stbi_uc *buffer, int n)
+{
+ if (s->io.read) {
+ int blen = s->img_buffer_end - s->img_buffer;
+ if (blen < n) {
+ int res, count;
+
+ memcpy(buffer, s->img_buffer, blen);
+
+ count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen);
+ res = (count == (n-blen));
+ s->img_buffer = s->img_buffer_end;
+ return res;
+ }
+ }
+
+ if (s->img_buffer+n <= s->img_buffer_end) {
+ memcpy(buffer, s->img_buffer, n);
+ s->img_buffer += n;
+ return 1;
+ } else
+ return 0;
+}
+
+static int get16(stbi *s)
+{
+ int z = get8(s);
+ return (z << 8) + get8(s);
+}
+
+static uint32 get32(stbi *s)
+{
+ uint32 z = get16(s);
+ return (z << 16) + get16(s);
+}
+
+static int get16le(stbi *s)
+{
+ int z = get8(s);
+ return z + (get8(s) << 8);
+}
+
+static uint32 get32le(stbi *s)
+{
+ uint32 z = get16le(s);
+ return z + (get16le(s) << 16);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// generic converter from built-in img_n to req_comp
+// individual types do this automatically as much as possible (e.g. jpeg
+// does all cases internally since it needs to colorspace convert anyway,
+// and it never has alpha, so very few cases ). png can automatically
+// interleave an alpha=255 channel, but falls back to this for other cases
+//
+// assume data buffer is malloced, so malloc a new one and free that one
+// only failure mode is malloc failing
+
+static uint8 compute_y(int r, int g, int b)
+{
+ return (uint8) (((r*77) + (g*150) + (29*b)) >> 8);
+}
+
+static unsigned char *convert_format(unsigned char *data, int img_n, int req_comp, uint x, uint y)
+{
+ int i,j;
+ unsigned char *good;
+
+ if (req_comp == img_n) return data;
+ assert(req_comp >= 1 && req_comp <= 4);
+
+ good = (unsigned char *) malloc(req_comp * x * y);
+ if (good == NULL) {
+ free(data);
+ return epuc("outofmem", "Out of memory");
+ }
+
+ for (j=0; j < (int) y; ++j) {
+ unsigned char *src = data + j * x * img_n ;
+ unsigned char *dest = good + j * x * req_comp;
+
+ #define COMBO(a,b) ((a)*8+(b))
+ #define CASE(a,b) case COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)
+ // convert source image with img_n components to one with req_comp components;
+ // avoid switch per pixel, so use switch per scanline and massive macros
+ switch (COMBO(img_n, req_comp)) {
+ CASE(1,2) dest[0]=src[0], dest[1]=255; break;
+ CASE(1,3) dest[0]=dest[1]=dest[2]=src[0]; break;
+ CASE(1,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=255; break;
+ CASE(2,1) dest[0]=src[0]; break;
+ CASE(2,3) dest[0]=dest[1]=dest[2]=src[0]; break;
+ CASE(2,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; break;
+ CASE(3,4) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=255; break;
+ CASE(3,1) dest[0]=compute_y(src[0],src[1],src[2]); break;
+ CASE(3,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = 255; break;
+ CASE(4,1) dest[0]=compute_y(src[0],src[1],src[2]); break;
+ CASE(4,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = src[3]; break;
+ CASE(4,3) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; break;
+ default: assert(0);
+ }
+ #undef CASE
+ }
+
+ free(data);
+ return good;
+}
+
+#ifndef STBI_NO_HDR
+static float *ldr_to_hdr(stbi_uc *data, int x, int y, int comp)
+{
+ int i,k,n;
+ float *output = (float *) malloc(x * y * comp * sizeof(float));
+ if (output == NULL) { free(data); return epf("outofmem", "Out of memory"); }
+ // compute number of non-alpha components
+ if (comp & 1) n = comp; else n = comp-1;
+ for (i=0; i < x*y; ++i) {
+ for (k=0; k < n; ++k) {
+ output[i*comp + k] = (float) pow(data[i*comp+k]/255.0f, l2h_gamma) * l2h_scale;
+ }
+ if (k < comp) output[i*comp + k] = data[i*comp+k]/255.0f;
+ }
+ free(data);
+ return output;
+}
+
+#define float2int(x) ((int) (x))
+static stbi_uc *hdr_to_ldr(float *data, int x, int y, int comp)
+{
+ int i,k,n;
+ stbi_uc *output = (stbi_uc *) malloc(x * y * comp);
+ if (output == NULL) { free(data); return epuc("outofmem", "Out of memory"); }
+ // compute number of non-alpha components
+ if (comp & 1) n = comp; else n = comp-1;
+ for (i=0; i < x*y; ++i) {
+ for (k=0; k < n; ++k) {
+ float z = (float) pow(data[i*comp+k]*h2l_scale_i, h2l_gamma_i) * 255 + 0.5f;
+ if (z < 0) z = 0;
+ if (z > 255) z = 255;
+ output[i*comp + k] = (uint8) float2int(z);
+ }
+ if (k < comp) {
+ float z = data[i*comp+k] * 255 + 0.5f;
+ if (z < 0) z = 0;
+ if (z > 255) z = 255;
+ output[i*comp + k] = (uint8) float2int(z);
+ }
+ }
+ free(data);
+ return output;
+}
+#endif
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// "baseline" JPEG/JFIF decoder (not actually fully baseline implementation)
+//
+// simple implementation
+// - channel subsampling of at most 2 in each dimension
+// - doesn't support delayed output of y-dimension
+// - simple interface (only one output format: 8-bit interleaved RGB)
+// - doesn't try to recover corrupt jpegs
+// - doesn't allow partial loading, loading multiple at once
+// - still fast on x86 (copying globals into locals doesn't help x86)
+// - allocates lots of intermediate memory (full size of all components)
+// - non-interleaved case requires this anyway
+// - allows good upsampling (see next)
+// high-quality
+// - upsampled channels are bilinearly interpolated, even across blocks
+// - quality integer IDCT derived from IJG's 'slow'
+// performance
+// - fast huffman; reasonable integer IDCT
+// - uses a lot of intermediate memory, could cache poorly
+// - load http://nothings.org/remote/anemones.jpg 3 times on 2.8Ghz P4
+// stb_jpeg: 1.34 seconds (MSVC6, default release build)
+// stb_jpeg: 1.06 seconds (MSVC6, processor = Pentium Pro)
+// IJL11.dll: 1.08 seconds (compiled by intel)
+// IJG 1998: 0.98 seconds (MSVC6, makefile provided by IJG)
+// IJG 1998: 0.95 seconds (MSVC6, makefile + proc=PPro)
+
+// huffman decoding acceleration
+#define FAST_BITS 9 // larger handles more cases; smaller stomps less cache
+
+typedef struct
+{
+ uint8 fast[1 << FAST_BITS];
+ // weirdly, repacking this into AoS is a 10% speed loss, instead of a win
+ uint16 code[256];
+ uint8 values[256];
+ uint8 size[257];
+ unsigned int maxcode[18];
+ int delta[17]; // old 'firstsymbol' - old 'firstcode'
+} huffman;
+
+typedef struct
+{
+ #ifdef STBI_SIMD
+ unsigned short dequant2[4][64];
+ #endif
+ stbi *s;
+ huffman huff_dc[4];
+ huffman huff_ac[4];
+ uint8 dequant[4][64];
+
+// sizes for components, interleaved MCUs
+ int img_h_max, img_v_max;
+ int img_mcu_x, img_mcu_y;
+ int img_mcu_w, img_mcu_h;
+
+// definition of jpeg image component
+ struct
+ {
+ int id;
+ int h,v;
+ int tq;
+ int hd,ha;
+ int dc_pred;
+
+ int x,y,w2,h2;
+ uint8 *data;
+ void *raw_data;
+ uint8 *linebuf;
+ } img_comp[4];
+
+ uint32 code_buffer; // jpeg entropy-coded buffer
+ int code_bits; // number of valid bits
+ unsigned char marker; // marker seen while filling entropy buffer
+ int nomore; // flag if we saw a marker so must stop
+
+ int scan_n, order[4];
+ int restart_interval, todo;
+} jpeg;
+
+static int build_huffman(huffman *h, int *count)
+{
+ int i,j,k=0,code;
+ // build size list for each symbol (from JPEG spec)
+ for (i=0; i < 16; ++i)
+ for (j=0; j < count[i]; ++j)
+ h->size[k++] = (uint8) (i+1);
+ h->size[k] = 0;
+
+ // compute actual symbols (from jpeg spec)
+ code = 0;
+ k = 0;
+ for(j=1; j <= 16; ++j) {
+ // compute delta to add to code to compute symbol id
+ h->delta[j] = k - code;
+ if (h->size[k] == j) {
+ while (h->size[k] == j)
+ h->code[k++] = (uint16) (code++);
+ if (code-1 >= (1 << j)) return e("bad code lengths","Corrupt JPEG");
+ }
+ // compute largest code + 1 for this size, preshifted as needed later
+ h->maxcode[j] = code << (16-j);
+ code <<= 1;
+ }
+ h->maxcode[j] = 0xffffffff;
+
+ // build non-spec acceleration table; 255 is flag for not-accelerated
+ memset(h->fast, 255, 1 << FAST_BITS);
+ for (i=0; i < k; ++i) {
+ int s = h->size[i];
+ if (s <= FAST_BITS) {
+ int c = h->code[i] << (FAST_BITS-s);
+ int m = 1 << (FAST_BITS-s);
+ for (j=0; j < m; ++j) {
+ h->fast[c+j] = (uint8) i;
+ }
+ }
+ }
+ return 1;
+}
+
+static void grow_buffer_unsafe(jpeg *j)
+{
+ do {
+ int b = j->nomore ? 0 : get8(j->s);
+ if (b == 0xff) {
+ int c = get8(j->s);
+ if (c != 0) {
+ j->marker = (unsigned char) c;
+ j->nomore = 1;
+ return;
+ }
+ }
+ j->code_buffer |= b << (24 - j->code_bits);
+ j->code_bits += 8;
+ } while (j->code_bits <= 24);
+}
+
+// (1 << n) - 1
+static uint32 bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535};
+
+// decode a jpeg huffman value from the bitstream
+stbi_inline static int decode(jpeg *j, huffman *h)
+{
+ unsigned int temp;
+ int c,k;
+
+ if (j->code_bits < 16) grow_buffer_unsafe(j);
+
+ // look at the top FAST_BITS and determine what symbol ID it is,
+ // if the code is <= FAST_BITS
+ c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1);
+ k = h->fast[c];
+ if (k < 255) {
+ int s = h->size[k];
+ if (s > j->code_bits)
+ return -1;
+ j->code_buffer <<= s;
+ j->code_bits -= s;
+ return h->values[k];
+ }
+
+ // naive test is to shift the code_buffer down so k bits are
+ // valid, then test against maxcode. To speed this up, we've
+ // preshifted maxcode left so that it has (16-k) 0s at the
+ // end; in other words, regardless of the number of bits, it
+ // wants to be compared against something shifted to have 16;
+ // that way we don't need to shift inside the loop.
+ temp = j->code_buffer >> 16;
+ for (k=FAST_BITS+1 ; ; ++k)
+ if (temp < h->maxcode[k])
+ break;
+ if (k == 17) {
+ // error! code not found
+ j->code_bits -= 16;
+ return -1;
+ }
+
+ if (k > j->code_bits)
+ return -1;
+
+ // convert the huffman code to the symbol id
+ c = ((j->code_buffer >> (32 - k)) & bmask[k]) + h->delta[k];
+ assert((((j->code_buffer) >> (32 - h->size[c])) & bmask[h->size[c]]) == h->code[c]);
+
+ // convert the id to a symbol
+ j->code_bits -= k;
+ j->code_buffer <<= k;
+ return h->values[c];
+}
+
+// combined JPEG 'receive' and JPEG 'extend', since baseline
+// always extends everything it receives.
+stbi_inline static int extend_receive(jpeg *j, int n)
+{
+ unsigned int m = 1 << (n-1);
+ unsigned int k;
+ if (j->code_bits < n) grow_buffer_unsafe(j);
+
+ #if 1
+ k = stbi_lrot(j->code_buffer, n);
+ j->code_buffer = k & ~bmask[n];
+ k &= bmask[n];
+ j->code_bits -= n;
+ #else
+ k = (j->code_buffer >> (32 - n)) & bmask[n];
+ j->code_bits -= n;
+ j->code_buffer <<= n;
+ #endif
+ // the following test is probably a random branch that won't
+ // predict well. I tried to table accelerate it but failed.
+ // maybe it's compiling as a conditional move?
+ if (k < m)
+ return (-1 << n) + k + 1;
+ else
+ return k;
+}
+
+// given a value that's at position X in the zigzag stream,
+// where does it appear in the 8x8 matrix coded as row-major?
+static uint8 dezigzag[64+15] =
+{
+ 0, 1, 8, 16, 9, 2, 3, 10,
+ 17, 24, 32, 25, 18, 11, 4, 5,
+ 12, 19, 26, 33, 40, 48, 41, 34,
+ 27, 20, 13, 6, 7, 14, 21, 28,
+ 35, 42, 49, 56, 57, 50, 43, 36,
+ 29, 22, 15, 23, 30, 37, 44, 51,
+ 58, 59, 52, 45, 38, 31, 39, 46,
+ 53, 60, 61, 54, 47, 55, 62, 63,
+ // let corrupt input sample past end
+ 63, 63, 63, 63, 63, 63, 63, 63,
+ 63, 63, 63, 63, 63, 63, 63
+};
+
+// decode one 64-entry block--
+static int decode_block(jpeg *j, short data[64], huffman *hdc, huffman *hac, int b)
+{
+ int diff,dc,k;
+ int t = decode(j, hdc);
+ if (t < 0) return e("bad huffman code","Corrupt JPEG");
+
+ // 0 all the ac values now so we can do it 32-bits at a time
+ memset(data,0,64*sizeof(data[0]));
+
+ diff = t ? extend_receive(j, t) : 0;
+ dc = j->img_comp[b].dc_pred + diff;
+ j->img_comp[b].dc_pred = dc;
+ data[0] = (short) dc;
+
+ // decode AC components, see JPEG spec
+ k = 1;
+ do {
+ int r,s;
+ int rs = decode(j, hac);
+ if (rs < 0) return e("bad huffman code","Corrupt JPEG");
+ s = rs & 15;
+ r = rs >> 4;
+ if (s == 0) {
+ if (rs != 0xf0) break; // end block
+ k += 16;
+ } else {
+ k += r;
+ // decode into unzigzag'd location
+ data[dezigzag[k++]] = (short) extend_receive(j,s);
+ }
+ } while (k < 64);
+ return 1;
+}
+
+// take a -128..127 value and clamp it and convert to 0..255
+stbi_inline static uint8 clamp(int x)
+{
+ // trick to use a single test to catch both cases
+ if ((unsigned int) x > 255) {
+ if (x < 0) return 0;
+ if (x > 255) return 255;
+ }
+ return (uint8) x;
+}
+
+#define f2f(x) (int) (((x) * 4096 + 0.5))
+#define fsh(x) ((x) << 12)
+
+// derived from jidctint -- DCT_ISLOW
+#define IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \
+ int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \
+ p2 = s2; \
+ p3 = s6; \
+ p1 = (p2+p3) * f2f(0.5411961f); \
+ t2 = p1 + p3*f2f(-1.847759065f); \
+ t3 = p1 + p2*f2f( 0.765366865f); \
+ p2 = s0; \
+ p3 = s4; \
+ t0 = fsh(p2+p3); \
+ t1 = fsh(p2-p3); \
+ x0 = t0+t3; \
+ x3 = t0-t3; \
+ x1 = t1+t2; \
+ x2 = t1-t2; \
+ t0 = s7; \
+ t1 = s5; \
+ t2 = s3; \
+ t3 = s1; \
+ p3 = t0+t2; \
+ p4 = t1+t3; \
+ p1 = t0+t3; \
+ p2 = t1+t2; \
+ p5 = (p3+p4)*f2f( 1.175875602f); \
+ t0 = t0*f2f( 0.298631336f); \
+ t1 = t1*f2f( 2.053119869f); \
+ t2 = t2*f2f( 3.072711026f); \
+ t3 = t3*f2f( 1.501321110f); \
+ p1 = p5 + p1*f2f(-0.899976223f); \
+ p2 = p5 + p2*f2f(-2.562915447f); \
+ p3 = p3*f2f(-1.961570560f); \
+ p4 = p4*f2f(-0.390180644f); \
+ t3 += p1+p4; \
+ t2 += p2+p3; \
+ t1 += p2+p4; \
+ t0 += p1+p3;
+
+#ifdef STBI_SIMD
+typedef unsigned short stbi_dequantize_t;
+#else
+typedef uint8 stbi_dequantize_t;
+#endif
+
+// .344 seconds on 3*anemones.jpg
+static void idct_block(uint8 *out, int out_stride, short data[64], stbi_dequantize_t *dequantize)
+{
+ int i,val[64],*v=val;
+ stbi_dequantize_t *dq = dequantize;
+ uint8 *o;
+ short *d = data;
+
+ // columns
+ for (i=0; i < 8; ++i,++d,++dq, ++v) {
+ // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing
+ if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0
+ && d[40]==0 && d[48]==0 && d[56]==0) {
+ // no shortcut 0 seconds
+ // (1|2|3|4|5|6|7)==0 0 seconds
+ // all separate -0.047 seconds
+ // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds
+ int dcterm = d[0] * dq[0] << 2;
+ v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;
+ } else {
+ IDCT_1D(d[ 0]*dq[ 0],d[ 8]*dq[ 8],d[16]*dq[16],d[24]*dq[24],
+ d[32]*dq[32],d[40]*dq[40],d[48]*dq[48],d[56]*dq[56])
+ // constants scaled things up by 1<<12; let's bring them back
+ // down, but keep 2 extra bits of precision
+ x0 += 512; x1 += 512; x2 += 512; x3 += 512;
+ v[ 0] = (x0+t3) >> 10;
+ v[56] = (x0-t3) >> 10;
+ v[ 8] = (x1+t2) >> 10;
+ v[48] = (x1-t2) >> 10;
+ v[16] = (x2+t1) >> 10;
+ v[40] = (x2-t1) >> 10;
+ v[24] = (x3+t0) >> 10;
+ v[32] = (x3-t0) >> 10;
+ }
+ }
+
+ for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) {
+ // no fast case since the first 1D IDCT spread components out
+ IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7])
+ // constants scaled things up by 1<<12, plus we had 1<<2 from first
+ // loop, plus horizontal and vertical each scale by sqrt(8) so together
+ // we've got an extra 1<<3, so 1<<17 total we need to remove.
+ // so we want to round that, which means adding 0.5 * 1<<17,
+ // aka 65536. Also, we'll end up with -128 to 127 that we want
+ // to encode as 0..255 by adding 128, so we'll add that before the shift
+ x0 += 65536 + (128<<17);
+ x1 += 65536 + (128<<17);
+ x2 += 65536 + (128<<17);
+ x3 += 65536 + (128<<17);
+ // tried computing the shifts into temps, or'ing the temps to see
+ // if any were out of range, but that was slower
+ o[0] = clamp((x0+t3) >> 17);
+ o[7] = clamp((x0-t3) >> 17);
+ o[1] = clamp((x1+t2) >> 17);
+ o[6] = clamp((x1-t2) >> 17);
+ o[2] = clamp((x2+t1) >> 17);
+ o[5] = clamp((x2-t1) >> 17);
+ o[3] = clamp((x3+t0) >> 17);
+ o[4] = clamp((x3-t0) >> 17);
+ }
+}
+
+#ifdef STBI_SIMD
+static stbi_idct_8x8 stbi_idct_installed = idct_block;
+
+void stbi_install_idct(stbi_idct_8x8 func)
+{
+ stbi_idct_installed = func;
+}
+#endif
+
+#define MARKER_none 0xff
+// if there's a pending marker from the entropy stream, return that
+// otherwise, fetch from the stream and get a marker. if there's no
+// marker, return 0xff, which is never a valid marker value
+static uint8 get_marker(jpeg *j)
+{
+ uint8 x;
+ if (j->marker != MARKER_none) { x = j->marker; j->marker = MARKER_none; return x; }
+ x = get8u(j->s);
+ if (x != 0xff) return MARKER_none;
+ while (x == 0xff)
+ x = get8u(j->s);
+ return x;
+}
+
+// in each scan, we'll have scan_n components, and the order
+// of the components is specified by order[]
+#define RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7)
+
+// after a restart interval, reset the entropy decoder and
+// the dc prediction
+static void reset(jpeg *j)
+{
+ j->code_bits = 0;
+ j->code_buffer = 0;
+ j->nomore = 0;
+ j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = 0;
+ j->marker = MARKER_none;
+ j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff;
+ // no more than 1<<31 MCUs if no restart_interal? that's plenty safe,
+ // since we don't even allow 1<<30 pixels
+}
+
+static int parse_entropy_coded_data(jpeg *z)
+{
+ reset(z);
+ if (z->scan_n == 1) {
+ int i,j;
+ #ifdef STBI_SIMD
+ __declspec(align(16))
+ #endif
+ short data[64];
+ int n = z->order[0];
+ // non-interleaved data, we just need to process one block at a time,
+ // in trivial scanline order
+ // number of blocks to do just depends on how many actual "pixels" this
+ // component has, independent of interleaved MCU blocking and such
+ int w = (z->img_comp[n].x+7) >> 3;
+ int h = (z->img_comp[n].y+7) >> 3;
+ for (j=0; j < h; ++j) {
+ for (i=0; i < w; ++i) {
+ if (!decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0;
+ #ifdef STBI_SIMD
+ stbi_idct_installed(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant2[z->img_comp[n].tq]);
+ #else
+ idct_block(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant[z->img_comp[n].tq]);
+ #endif
+ // every data block is an MCU, so countdown the restart interval
+ if (--z->todo <= 0) {
+ if (z->code_bits < 24) grow_buffer_unsafe(z);
+ // if it's NOT a restart, then just bail, so we get corrupt data
+ // rather than no data
+ if (!RESTART(z->marker)) return 1;
+ reset(z);
+ }
+ }
+ }
+ } else { // interleaved!
+ int i,j,k,x,y;
+ short data[64];
+ for (j=0; j < z->img_mcu_y; ++j) {
+ for (i=0; i < z->img_mcu_x; ++i) {
+ // scan an interleaved mcu... process scan_n components in order
+ for (k=0; k < z->scan_n; ++k) {
+ int n = z->order[k];
+ // scan out an mcu's worth of this component; that's just determined
+ // by the basic H and V specified for the component
+ for (y=0; y < z->img_comp[n].v; ++y) {
+ for (x=0; x < z->img_comp[n].h; ++x) {
+ int x2 = (i*z->img_comp[n].h + x)*8;
+ int y2 = (j*z->img_comp[n].v + y)*8;
+ if (!decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0;
+ #ifdef STBI_SIMD
+ stbi_idct_installed(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data, z->dequant2[z->img_comp[n].tq]);
+ #else
+ idct_block(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data, z->dequant[z->img_comp[n].tq]);
+ #endif
+ }
+ }
+ }
+ // after all interleaved components, that's an interleaved MCU,
+ // so now count down the restart interval
+ if (--z->todo <= 0) {
+ if (z->code_bits < 24) grow_buffer_unsafe(z);
+ // if it's NOT a restart, then just bail, so we get corrupt data
+ // rather than no data
+ if (!RESTART(z->marker)) return 1;
+ reset(z);
+ }
+ }
+ }
+ }
+ return 1;
+}
+
+static int process_marker(jpeg *z, int m)
+{
+ int L;
+ switch (m) {
+ case MARKER_none: // no marker found
+ return e("expected marker","Corrupt JPEG");
+
+ case 0xC2: // SOF - progressive
+ return e("progressive jpeg","JPEG format not supported (progressive)");
+
+ case 0xDD: // DRI - specify restart interval
+ if (get16(z->s) != 4) return e("bad DRI len","Corrupt JPEG");
+ z->restart_interval = get16(z->s);
+ return 1;
+
+ case 0xDB: // DQT - define quantization table
+ L = get16(z->s)-2;
+ while (L > 0) {
+ int q = get8(z->s);
+ int p = q >> 4;
+ int t = q & 15,i;
+ if (p != 0) return e("bad DQT type","Corrupt JPEG");
+ if (t > 3) return e("bad DQT table","Corrupt JPEG");
+ for (i=0; i < 64; ++i)
+ z->dequant[t][dezigzag[i]] = get8u(z->s);
+ #ifdef STBI_SIMD
+ for (i=0; i < 64; ++i)
+ z->dequant2[t][i] = z->dequant[t][i];
+ #endif
+ L -= 65;
+ }
+ return L==0;
+
+ case 0xC4: // DHT - define huffman table
+ L = get16(z->s)-2;
+ while (L > 0) {
+ uint8 *v;
+ int sizes[16],i,m=0;
+ int q = get8(z->s);
+ int tc = q >> 4;
+ int th = q & 15;
+ if (tc > 1 || th > 3) return e("bad DHT header","Corrupt JPEG");
+ for (i=0; i < 16; ++i) {
+ sizes[i] = get8(z->s);
+ m += sizes[i];
+ }
+ L -= 17;
+ if (tc == 0) {
+ if (!build_huffman(z->huff_dc+th, sizes)) return 0;
+ v = z->huff_dc[th].values;
+ } else {
+ if (!build_huffman(z->huff_ac+th, sizes)) return 0;
+ v = z->huff_ac[th].values;
+ }
+ for (i=0; i < m; ++i)
+ v[i] = get8u(z->s);
+ L -= m;
+ }
+ return L==0;
+ }
+ // check for comment block or APP blocks
+ if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) {
+ skip(z->s, get16(z->s)-2);
+ return 1;
+ }
+ return 0;
+}
+
+// after we see SOS
+static int process_scan_header(jpeg *z)
+{
+ int i;
+ int Ls = get16(z->s);
+ z->scan_n = get8(z->s);
+ if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return e("bad SOS component count","Corrupt JPEG");
+ if (Ls != 6+2*z->scan_n) return e("bad SOS len","Corrupt JPEG");
+ for (i=0; i < z->scan_n; ++i) {
+ int id = get8(z->s), which;
+ int q = get8(z->s);
+ for (which = 0; which < z->s->img_n; ++which)
+ if (z->img_comp[which].id == id)
+ break;
+ if (which == z->s->img_n) return 0;
+ z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return e("bad DC huff","Corrupt JPEG");
+ z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return e("bad AC huff","Corrupt JPEG");
+ z->order[i] = which;
+ }
+ if (get8(z->s) != 0) return e("bad SOS","Corrupt JPEG");
+ get8(z->s); // should be 63, but might be 0
+ if (get8(z->s) != 0) return e("bad SOS","Corrupt JPEG");
+
+ return 1;
+}
+
+static int process_frame_header(jpeg *z, int scan)
+{
+ stbi *s = z->s;
+ int Lf,p,i,q, h_max=1,v_max=1,c;
+ Lf = get16(s); if (Lf < 11) return e("bad SOF len","Corrupt JPEG"); // JPEG
+ p = get8(s); if (p != 8) return e("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline
+ s->img_y = get16(s); if (s->img_y == 0) return e("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG
+ s->img_x = get16(s); if (s->img_x == 0) return e("0 width","Corrupt JPEG"); // JPEG requires
+ c = get8(s);
+ if (c != 3 && c != 1) return e("bad component count","Corrupt JPEG"); // JFIF requires
+ s->img_n = c;
+ for (i=0; i < c; ++i) {
+ z->img_comp[i].data = NULL;
+ z->img_comp[i].linebuf = NULL;
+ }
+
+ if (Lf != 8+3*s->img_n) return e("bad SOF len","Corrupt JPEG");
+
+ for (i=0; i < s->img_n; ++i) {
+ z->img_comp[i].id = get8(s);
+ if (z->img_comp[i].id != i+1) // JFIF requires
+ if (z->img_comp[i].id != i) // some version of jpegtran outputs non-JFIF-compliant files!
+ return e("bad component ID","Corrupt JPEG");
+ q = get8(s);
+ z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return e("bad H","Corrupt JPEG");
+ z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return e("bad V","Corrupt JPEG");
+ z->img_comp[i].tq = get8(s); if (z->img_comp[i].tq > 3) return e("bad TQ","Corrupt JPEG");
+ }
+
+ if (scan != SCAN_load) return 1;
+
+ if ((1 << 30) / s->img_x / s->img_n < s->img_y) return e("too large", "Image too large to decode");
+
+ for (i=0; i < s->img_n; ++i) {
+ if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h;
+ if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v;
+ }
+
+ // compute interleaved mcu info
+ z->img_h_max = h_max;
+ z->img_v_max = v_max;
+ z->img_mcu_w = h_max * 8;
+ z->img_mcu_h = v_max * 8;
+ z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w;
+ z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h;
+
+ for (i=0; i < s->img_n; ++i) {
+ // number of effective pixels (e.g. for non-interleaved MCU)
+ z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max;
+ z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max;
+ // to simplify generation, we'll allocate enough memory to decode
+ // the bogus oversized data from using interleaved MCUs and their
+ // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't
+ // discard the extra data until colorspace conversion
+ z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8;
+ z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8;
+ z->img_comp[i].raw_data = malloc(z->img_comp[i].w2 * z->img_comp[i].h2+15);
+ if (z->img_comp[i].raw_data == NULL) {
+ for(--i; i >= 0; --i) {
+ free(z->img_comp[i].raw_data);
+ z->img_comp[i].data = NULL;
+ }
+ return e("outofmem", "Out of memory");
+ }
+ // align blocks for installable-idct using mmx/sse
+ z->img_comp[i].data = (uint8*) (((size_t) z->img_comp[i].raw_data + 15) & ~15);
+ z->img_comp[i].linebuf = NULL;
+ }
+
+ return 1;
+}
+
+// use comparisons since in some cases we handle more than one case (e.g. SOF)
+#define DNL(x) ((x) == 0xdc)
+#define SOI(x) ((x) == 0xd8)
+#define EOI(x) ((x) == 0xd9)
+#define SOF(x) ((x) == 0xc0 || (x) == 0xc1)
+#define SOS(x) ((x) == 0xda)
+
+static int decode_jpeg_header(jpeg *z, int scan)
+{
+ int m;
+ z->marker = MARKER_none; // initialize cached marker to empty
+ m = get_marker(z);
+ if (!SOI(m)) return e("no SOI","Corrupt JPEG");
+ if (scan == SCAN_type) return 1;
+ m = get_marker(z);
+ while (!SOF(m)) {
+ if (!process_marker(z,m)) return 0;
+ m = get_marker(z);
+ while (m == MARKER_none) {
+ // some files have extra padding after their blocks, so ok, we'll scan
+ if (at_eof(z->s)) return e("no SOF", "Corrupt JPEG");
+ m = get_marker(z);
+ }
+ }
+ if (!process_frame_header(z, scan)) return 0;
+ return 1;
+}
+
+static int decode_jpeg_image(jpeg *j)
+{
+ int m;
+ j->restart_interval = 0;
+ if (!decode_jpeg_header(j, SCAN_load)) return 0;
+ m = get_marker(j);
+ while (!EOI(m)) {
+ if (SOS(m)) {
+ if (!process_scan_header(j)) return 0;
+ if (!parse_entropy_coded_data(j)) return 0;
+ if (j->marker == MARKER_none ) {
+ // handle 0s at the end of image data from IP Kamera 9060
+ while (!at_eof(j->s)) {
+ int x = get8(j->s);
+ if (x == 255) {
+ j->marker = get8u(j->s);
+ break;
+ } else if (x != 0) {
+ return 0;
+ }
+ }
+ // if we reach eof without hitting a marker, get_marker() below will fail and we'll eventually return 0
+ }
+ } else {
+ if (!process_marker(j, m)) return 0;
+ }
+ m = get_marker(j);
+ }
+ return 1;
+}
+
+// static jfif-centered resampling (across block boundaries)
+
+typedef uint8 *(*resample_row_func)(uint8 *out, uint8 *in0, uint8 *in1,
+ int w, int hs);
+
+#define div4(x) ((uint8) ((x) >> 2))
+
+static uint8 *resample_row_1(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)
+{
+ STBI_NOTUSED(out);
+ STBI_NOTUSED(in_far);
+ STBI_NOTUSED(w);
+ STBI_NOTUSED(hs);
+ return in_near;
+}
+
+static uint8* resample_row_v_2(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)
+{
+ // need to generate two samples vertically for every one in input
+ int i;
+ STBI_NOTUSED(hs);
+ for (i=0; i < w; ++i)
+ out[i] = div4(3*in_near[i] + in_far[i] + 2);
+ return out;
+}
+
+static uint8* resample_row_h_2(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)
+{
+ // need to generate two samples horizontally for every one in input
+ int i;
+ uint8 *input = in_near;
+
+ if (w == 1) {
+ // if only one sample, can't do any interpolation
+ out[0] = out[1] = input[0];
+ return out;
+ }
+
+ out[0] = input[0];
+ out[1] = div4(input[0]*3 + input[1] + 2);
+ for (i=1; i < w-1; ++i) {
+ int n = 3*input[i]+2;
+ out[i*2+0] = div4(n+input[i-1]);
+ out[i*2+1] = div4(n+input[i+1]);
+ }
+ out[i*2+0] = div4(input[w-2]*3 + input[w-1] + 2);
+ out[i*2+1] = input[w-1];
+
+ STBI_NOTUSED(in_far);
+ STBI_NOTUSED(hs);
+
+ return out;
+}
+
+#define div16(x) ((uint8) ((x) >> 4))
+
+static uint8 *resample_row_hv_2(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)
+{
+ // need to generate 2x2 samples for every one in input
+ int i,t0,t1;
+ if (w == 1) {
+ out[0] = out[1] = div4(3*in_near[0] + in_far[0] + 2);
+ return out;
+ }
+
+ t1 = 3*in_near[0] + in_far[0];
+ out[0] = div4(t1+2);
+ for (i=1; i < w; ++i) {
+ t0 = t1;
+ t1 = 3*in_near[i]+in_far[i];
+ out[i*2-1] = div16(3*t0 + t1 + 8);
+ out[i*2 ] = div16(3*t1 + t0 + 8);
+ }
+ out[w*2-1] = div4(t1+2);
+
+ STBI_NOTUSED(hs);
+
+ return out;
+}
+
+static uint8 *resample_row_generic(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)
+{
+ // resample with nearest-neighbor
+ int i,j;
+ in_far = in_far;
+ for (i=0; i < w; ++i)
+ for (j=0; j < hs; ++j)
+ out[i*hs+j] = in_near[i];
+ return out;
+}
+
+#define float2fixed(x) ((int) ((x) * 65536 + 0.5))
+
+// 0.38 seconds on 3*anemones.jpg (0.25 with processor = Pro)
+// VC6 without processor=Pro is generating multiple LEAs per multiply!
+static void YCbCr_to_RGB_row(uint8 *out, const uint8 *y, const uint8 *pcb, const uint8 *pcr, int count, int step)
+{
+ int i;
+ for (i=0; i < count; ++i) {
+ int y_fixed = (y[i] << 16) + 32768; // rounding
+ int r,g,b;
+ int cr = pcr[i] - 128;
+ int cb = pcb[i] - 128;
+ r = y_fixed + cr*float2fixed(1.40200f);
+ g = y_fixed - cr*float2fixed(0.71414f) - cb*float2fixed(0.34414f);
+ b = y_fixed + cb*float2fixed(1.77200f);
+ r >>= 16;
+ g >>= 16;
+ b >>= 16;
+ if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; }
+ if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; }
+ if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; }
+ out[0] = (uint8)r;
+ out[1] = (uint8)g;
+ out[2] = (uint8)b;
+ out[3] = 255;
+ out += step;
+ }
+}
+
+#ifdef STBI_SIMD
+static stbi_YCbCr_to_RGB_run stbi_YCbCr_installed = YCbCr_to_RGB_row;
+
+void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func)
+{
+ stbi_YCbCr_installed = func;
+}
+#endif
+
+
+// clean up the temporary component buffers
+static void cleanup_jpeg(jpeg *j)
+{
+ int i;
+ for (i=0; i < j->s->img_n; ++i) {
+ if (j->img_comp[i].data) {
+ free(j->img_comp[i].raw_data);
+ j->img_comp[i].data = NULL;
+ }
+ if (j->img_comp[i].linebuf) {
+ free(j->img_comp[i].linebuf);
+ j->img_comp[i].linebuf = NULL;
+ }
+ }
+}
+
+typedef struct
+{
+ resample_row_func resample;
+ uint8 *line0,*line1;
+ int hs,vs; // expansion factor in each axis
+ int w_lores; // horizontal pixels pre-expansion
+ int ystep; // how far through vertical expansion we are
+ int ypos; // which pre-expansion row we're on
+} stbi_resample;
+
+static uint8 *load_jpeg_image(jpeg *z, int *out_x, int *out_y, int *comp, int req_comp)
+{
+ int n, decode_n;
+ // validate req_comp
+ if (req_comp < 0 || req_comp > 4) return epuc("bad req_comp", "Internal error");
+ z->s->img_n = 0;
+
+ // load a jpeg image from whichever source
+ if (!decode_jpeg_image(z)) { cleanup_jpeg(z); return NULL; }
+
+ // determine actual number of components to generate
+ n = req_comp ? req_comp : z->s->img_n;
+
+ if (z->s->img_n == 3 && n < 3)
+ decode_n = 1;
+ else
+ decode_n = z->s->img_n;
+
+ // resample and color-convert
+ {
+ int k;
+ uint i,j;
+ uint8 *output;
+ uint8 *coutput[4];
+
+ stbi_resample res_comp[4];
+
+ for (k=0; k < decode_n; ++k) {
+ stbi_resample *r = &res_comp[k];
+
+ // allocate line buffer big enough for upsampling off the edges
+ // with upsample factor of 4
+ z->img_comp[k].linebuf = (uint8 *) malloc(z->s->img_x + 3);
+ if (!z->img_comp[k].linebuf) { cleanup_jpeg(z); return epuc("outofmem", "Out of memory"); }
+
+ r->hs = z->img_h_max / z->img_comp[k].h;
+ r->vs = z->img_v_max / z->img_comp[k].v;
+ r->ystep = r->vs >> 1;
+ r->w_lores = (z->s->img_x + r->hs-1) / r->hs;
+ r->ypos = 0;
+ r->line0 = r->line1 = z->img_comp[k].data;
+
+ if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1;
+ else if (r->hs == 1 && r->vs == 2) r->resample = resample_row_v_2;
+ else if (r->hs == 2 && r->vs == 1) r->resample = resample_row_h_2;
+ else if (r->hs == 2 && r->vs == 2) r->resample = resample_row_hv_2;
+ else r->resample = resample_row_generic;
+ }
+
+ // can't error after this so, this is safe
+ output = (uint8 *) malloc(n * z->s->img_x * z->s->img_y + 1);
+ if (!output) { cleanup_jpeg(z); return epuc("outofmem", "Out of memory"); }
+
+ // now go ahead and resample
+ for (j=0; j < z->s->img_y; ++j) {
+ uint8 *out = output + n * z->s->img_x * j;
+ for (k=0; k < decode_n; ++k) {
+ stbi_resample *r = &res_comp[k];
+ int y_bot = r->ystep >= (r->vs >> 1);
+ coutput[k] = r->resample(z->img_comp[k].linebuf,
+ y_bot ? r->line1 : r->line0,
+ y_bot ? r->line0 : r->line1,
+ r->w_lores, r->hs);
+ if (++r->ystep >= r->vs) {
+ r->ystep = 0;
+ r->line0 = r->line1;
+ if (++r->ypos < z->img_comp[k].y)
+ r->line1 += z->img_comp[k].w2;
+ }
+ }
+ if (n >= 3) {
+ uint8 *y = coutput[0];
+ if (z->s->img_n == 3) {
+ #ifdef STBI_SIMD
+ stbi_YCbCr_installed(out, y, coutput[1], coutput[2], z->s.img_x, n);
+ #else
+ YCbCr_to_RGB_row(out, y, coutput[1], coutput[2], z->s->img_x, n);
+ #endif
+ } else
+ for (i=0; i < z->s->img_x; ++i) {
+ out[0] = out[1] = out[2] = y[i];
+ out[3] = 255; // not used if n==3
+ out += n;
+ }
+ } else {
+ uint8 *y = coutput[0];
+ if (n == 1)
+ for (i=0; i < z->s->img_x; ++i) out[i] = y[i];
+ else
+ for (i=0; i < z->s->img_x; ++i) *out++ = y[i], *out++ = 255;
+ }
+ }
+ cleanup_jpeg(z);
+ *out_x = z->s->img_x;
+ *out_y = z->s->img_y;
+ if (comp) *comp = z->s->img_n; // report original components, not output
+ return output;
+ }
+}
+
+static unsigned char *stbi_jpeg_load(stbi *s, int *x, int *y, int *comp, int req_comp)
+{
+ jpeg j;
+ j.s = s;
+ return load_jpeg_image(&j, x,y,comp,req_comp);
+}
+
+static int stbi_jpeg_test(stbi *s)
+{
+ int r;
+ jpeg j;
+ j.s = s;
+ r = decode_jpeg_header(&j, SCAN_type);
+ stbi_rewind(s);
+ return r;
+}
+
+static int stbi_jpeg_info_raw(jpeg *j, int *x, int *y, int *comp)
+{
+ if (!decode_jpeg_header(j, SCAN_header)) {
+ stbi_rewind( j->s );
+ return 0;
+ }
+ if (x) *x = j->s->img_x;
+ if (y) *y = j->s->img_y;
+ if (comp) *comp = j->s->img_n;
+ return 1;
+}
+
+static int stbi_jpeg_info(stbi *s, int *x, int *y, int *comp)
+{
+ jpeg j;
+ j.s = s;
+ return stbi_jpeg_info_raw(&j, x, y, comp);
+}
+
+// public domain zlib decode v0.2 Sean Barrett 2006-11-18
+// simple implementation
+// - all input must be provided in an upfront buffer
+// - all output is written to a single output buffer (can malloc/realloc)
+// performance
+// - fast huffman
+
+// fast-way is faster to check than jpeg huffman, but slow way is slower
+#define ZFAST_BITS 9 // accelerate all cases in default tables
+#define ZFAST_MASK ((1 << ZFAST_BITS) - 1)
+
+// zlib-style huffman encoding
+// (jpegs packs from left, zlib from right, so can't share code)
+typedef struct
+{
+ uint16 fast[1 << ZFAST_BITS];
+ uint16 firstcode[16];
+ int maxcode[17];
+ uint16 firstsymbol[16];
+ uint8 size[288];
+ uint16 value[288];
+} zhuffman;
+
+stbi_inline static int bitreverse16(int n)
+{
+ n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1);
+ n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2);
+ n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4);
+ n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8);
+ return n;
+}
+
+stbi_inline static int bit_reverse(int v, int bits)
+{
+ assert(bits <= 16);
+ // to bit reverse n bits, reverse 16 and shift
+ // e.g. 11 bits, bit reverse and shift away 5
+ return bitreverse16(v) >> (16-bits);
+}
+
+static int zbuild_huffman(zhuffman *z, uint8 *sizelist, int num)
+{
+ int i,k=0;
+ int code, next_code[16], sizes[17];
+
+ // DEFLATE spec for generating codes
+ memset(sizes, 0, sizeof(sizes));
+ memset(z->fast, 255, sizeof(z->fast));
+ for (i=0; i < num; ++i)
+ ++sizes[sizelist[i]];
+ sizes[0] = 0;
+ for (i=1; i < 16; ++i)
+ assert(sizes[i] <= (1 << i));
+ code = 0;
+ for (i=1; i < 16; ++i) {
+ next_code[i] = code;
+ z->firstcode[i] = (uint16) code;
+ z->firstsymbol[i] = (uint16) k;
+ code = (code + sizes[i]);
+ if (sizes[i])
+ if (code-1 >= (1 << i)) return e("bad codelengths","Corrupt JPEG");
+ z->maxcode[i] = code << (16-i); // preshift for inner loop
+ code <<= 1;
+ k += sizes[i];
+ }
+ z->maxcode[16] = 0x10000; // sentinel
+ for (i=0; i < num; ++i) {
+ int s = sizelist[i];
+ if (s) {
+ int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s];
+ z->size[c] = (uint8)s;
+ z->value[c] = (uint16)i;
+ if (s <= ZFAST_BITS) {
+ int k = bit_reverse(next_code[s],s);
+ while (k < (1 << ZFAST_BITS)) {
+ z->fast[k] = (uint16) c;
+ k += (1 << s);
+ }
+ }
+ ++next_code[s];
+ }
+ }
+ return 1;
+}
+
+// zlib-from-memory implementation for PNG reading
+// because PNG allows splitting the zlib stream arbitrarily,
+// and it's annoying structurally to have PNG call ZLIB call PNG,
+// we require PNG read all the IDATs and combine them into a single
+// memory buffer
+
+typedef struct
+{
+ uint8 *zbuffer, *zbuffer_end;
+ int num_bits;
+ uint32 code_buffer;
+
+ char *zout;
+ char *zout_start;
+ char *zout_end;
+ int z_expandable;
+
+ zhuffman z_length, z_distance;
+} zbuf;
+
+stbi_inline static int zget8(zbuf *z)
+{
+ if (z->zbuffer >= z->zbuffer_end) return 0;
+ return *z->zbuffer++;
+}
+
+static void fill_bits(zbuf *z)
+{
+ do {
+ assert(z->code_buffer < (1U << z->num_bits));
+ z->code_buffer |= zget8(z) << z->num_bits;
+ z->num_bits += 8;
+ } while (z->num_bits <= 24);
+}
+
+stbi_inline static unsigned int zreceive(zbuf *z, int n)
+{
+ unsigned int k;
+ if (z->num_bits < n) fill_bits(z);
+ k = z->code_buffer & ((1 << n) - 1);
+ z->code_buffer >>= n;
+ z->num_bits -= n;
+ return k;
+}
+
+stbi_inline static int zhuffman_decode(zbuf *a, zhuffman *z)
+{
+ int b,s,k;
+ if (a->num_bits < 16) fill_bits(a);
+ b = z->fast[a->code_buffer & ZFAST_MASK];
+ if (b < 0xffff) {
+ s = z->size[b];
+ a->code_buffer >>= s;
+ a->num_bits -= s;
+ return z->value[b];
+ }
+
+ // not resolved by fast table, so compute it the slow way
+ // use jpeg approach, which requires MSbits at top
+ k = bit_reverse(a->code_buffer, 16);
+ for (s=ZFAST_BITS+1; ; ++s)
+ if (k < z->maxcode[s])
+ break;
+ if (s == 16) return -1; // invalid code!
+ // code size is s, so:
+ b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s];
+ assert(z->size[b] == s);
+ a->code_buffer >>= s;
+ a->num_bits -= s;
+ return z->value[b];
+}
+
+static int expand(zbuf *z, int n) // need to make room for n bytes
+{
+ char *q;
+ int cur, limit;
+ if (!z->z_expandable) return e("output buffer limit","Corrupt PNG");
+ cur = (int) (z->zout - z->zout_start);
+ limit = (int) (z->zout_end - z->zout_start);
+ while (cur + n > limit)
+ limit *= 2;
+ q = (char *) realloc(z->zout_start, limit);
+ if (q == NULL) return e("outofmem", "Out of memory");
+ z->zout_start = q;
+ z->zout = q + cur;
+ z->zout_end = q + limit;
+ return 1;
+}
+
+static int length_base[31] = {
+ 3,4,5,6,7,8,9,10,11,13,
+ 15,17,19,23,27,31,35,43,51,59,
+ 67,83,99,115,131,163,195,227,258,0,0 };
+
+static int length_extra[31]=
+{ 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 };
+
+static int dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,
+257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0};
+
+static int dist_extra[32] =
+{ 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
+
+static int parse_huffman_block(zbuf *a)
+{
+ for(;;) {
+ int z = zhuffman_decode(a, &a->z_length);
+ if (z < 256) {
+ if (z < 0) return e("bad huffman code","Corrupt PNG"); // error in huffman codes
+ if (a->zout >= a->zout_end) if (!expand(a, 1)) return 0;
+ *a->zout++ = (char) z;
+ } else {
+ uint8 *p;
+ int len,dist;
+ if (z == 256) return 1;
+ z -= 257;
+ len = length_base[z];
+ if (length_extra[z]) len += zreceive(a, length_extra[z]);
+ z = zhuffman_decode(a, &a->z_distance);
+ if (z < 0) return e("bad huffman code","Corrupt PNG");
+ dist = dist_base[z];
+ if (dist_extra[z]) dist += zreceive(a, dist_extra[z]);
+ if (a->zout - a->zout_start < dist) return e("bad dist","Corrupt PNG");
+ if (a->zout + len > a->zout_end) if (!expand(a, len)) return 0;
+ p = (uint8 *) (a->zout - dist);
+ while (len--)
+ *a->zout++ = *p++;
+ }
+ }
+}
+
+static int compute_huffman_codes(zbuf *a)
+{
+ static uint8 length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 };
+ zhuffman z_codelength;
+ uint8 lencodes[286+32+137];//padding for maximum single op
+ uint8 codelength_sizes[19];
+ int i,n;
+
+ int hlit = zreceive(a,5) + 257;
+ int hdist = zreceive(a,5) + 1;
+ int hclen = zreceive(a,4) + 4;
+
+ memset(codelength_sizes, 0, sizeof(codelength_sizes));
+ for (i=0; i < hclen; ++i) {
+ int s = zreceive(a,3);
+ codelength_sizes[length_dezigzag[i]] = (uint8) s;
+ }
+ if (!zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0;
+
+ n = 0;
+ while (n < hlit + hdist) {
+ int c = zhuffman_decode(a, &z_codelength);
+ assert(c >= 0 && c < 19);
+ if (c < 16)
+ lencodes[n++] = (uint8) c;
+ else if (c == 16) {
+ c = zreceive(a,2)+3;
+ memset(lencodes+n, lencodes[n-1], c);
+ n += c;
+ } else if (c == 17) {
+ c = zreceive(a,3)+3;
+ memset(lencodes+n, 0, c);
+ n += c;
+ } else {
+ assert(c == 18);
+ c = zreceive(a,7)+11;
+ memset(lencodes+n, 0, c);
+ n += c;
+ }
+ }
+ if (n != hlit+hdist) return e("bad codelengths","Corrupt PNG");
+ if (!zbuild_huffman(&a->z_length, lencodes, hlit)) return 0;
+ if (!zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0;
+ return 1;
+}
+
+static int parse_uncompressed_block(zbuf *a)
+{
+ uint8 header[4];
+ int len,nlen,k;
+ if (a->num_bits & 7)
+ zreceive(a, a->num_bits & 7); // discard
+ // drain the bit-packed data into header
+ k = 0;
+ while (a->num_bits > 0) {
+ header[k++] = (uint8) (a->code_buffer & 255); // wtf this warns?
+ a->code_buffer >>= 8;
+ a->num_bits -= 8;
+ }
+ assert(a->num_bits == 0);
+ // now fill header the normal way
+ while (k < 4)
+ header[k++] = (uint8) zget8(a);
+ len = header[1] * 256 + header[0];
+ nlen = header[3] * 256 + header[2];
+ if (nlen != (len ^ 0xffff)) return e("zlib corrupt","Corrupt PNG");
+ if (a->zbuffer + len > a->zbuffer_end) return e("read past buffer","Corrupt PNG");
+ if (a->zout + len > a->zout_end)
+ if (!expand(a, len)) return 0;
+ memcpy(a->zout, a->zbuffer, len);
+ a->zbuffer += len;
+ a->zout += len;
+ return 1;
+}
+
+static int parse_zlib_header(zbuf *a)
+{
+ int cmf = zget8(a);
+ int cm = cmf & 15;
+ /* int cinfo = cmf >> 4; */
+ int flg = zget8(a);
+ if ((cmf*256+flg) % 31 != 0) return e("bad zlib header","Corrupt PNG"); // zlib spec
+ if (flg & 32) return e("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png
+ if (cm != 8) return e("bad compression","Corrupt PNG"); // DEFLATE required for png
+ // window = 1 << (8 + cinfo)... but who cares, we fully buffer output
+ return 1;
+}
+
+// @TODO: should statically initialize these for optimal thread safety
+static uint8 default_length[288], default_distance[32];
+static void init_defaults(void)
+{
+ int i; // use <= to match clearly with spec
+ for (i=0; i <= 143; ++i) default_length[i] = 8;
+ for ( ; i <= 255; ++i) default_length[i] = 9;
+ for ( ; i <= 279; ++i) default_length[i] = 7;
+ for ( ; i <= 287; ++i) default_length[i] = 8;
+
+ for (i=0; i <= 31; ++i) default_distance[i] = 5;
+}
+
+int stbi_png_partial; // a quick hack to only allow decoding some of a PNG... I should implement real streaming support instead
+static int parse_zlib(zbuf *a, int parse_header)
+{
+ int final, type;
+ if (parse_header)
+ if (!parse_zlib_header(a)) return 0;
+ a->num_bits = 0;
+ a->code_buffer = 0;
+ do {
+ final = zreceive(a,1);
+ type = zreceive(a,2);
+ if (type == 0) {
+ if (!parse_uncompressed_block(a)) return 0;
+ } else if (type == 3) {
+ return 0;
+ } else {
+ if (type == 1) {
+ // use fixed code lengths
+ if (!default_distance[31]) init_defaults();
+ if (!zbuild_huffman(&a->z_length , default_length , 288)) return 0;
+ if (!zbuild_huffman(&a->z_distance, default_distance, 32)) return 0;
+ } else {
+ if (!compute_huffman_codes(a)) return 0;
+ }
+ if (!parse_huffman_block(a)) return 0;
+ }
+ if (stbi_png_partial && a->zout - a->zout_start > 65536)
+ break;
+ } while (!final);
+ return 1;
+}
+
+static int do_zlib(zbuf *a, char *obuf, int olen, int exp, int parse_header)
+{
+ a->zout_start = obuf;
+ a->zout = obuf;
+ a->zout_end = obuf + olen;
+ a->z_expandable = exp;
+
+ return parse_zlib(a, parse_header);
+}
+
+char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen)
+{
+ zbuf a;
+ char *p = (char *) malloc(initial_size);
+ if (p == NULL) return NULL;
+ a.zbuffer = (uint8 *) buffer;
+ a.zbuffer_end = (uint8 *) buffer + len;
+ if (do_zlib(&a, p, initial_size, 1, 1)) {
+ if (outlen) *outlen = (int) (a.zout - a.zout_start);
+ return a.zout_start;
+ } else {
+ free(a.zout_start);
+ return NULL;
+ }
+}
+
+char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen)
+{
+ return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen);
+}
+
+char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header)
+{
+ zbuf a;
+ char *p = (char *) malloc(initial_size);
+ if (p == NULL) return NULL;
+ a.zbuffer = (uint8 *) buffer;
+ a.zbuffer_end = (uint8 *) buffer + len;
+ if (do_zlib(&a, p, initial_size, 1, parse_header)) {
+ if (outlen) *outlen = (int) (a.zout - a.zout_start);
+ return a.zout_start;
+ } else {
+ free(a.zout_start);
+ return NULL;
+ }
+}
+
+int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen)
+{
+ zbuf a;
+ a.zbuffer = (uint8 *) ibuffer;
+ a.zbuffer_end = (uint8 *) ibuffer + ilen;
+ if (do_zlib(&a, obuffer, olen, 0, 1))
+ return (int) (a.zout - a.zout_start);
+ else
+ return -1;
+}
+
+char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen)
+{
+ zbuf a;
+ char *p = (char *) malloc(16384);
+ if (p == NULL) return NULL;
+ a.zbuffer = (uint8 *) buffer;
+ a.zbuffer_end = (uint8 *) buffer+len;
+ if (do_zlib(&a, p, 16384, 1, 0)) {
+ if (outlen) *outlen = (int) (a.zout - a.zout_start);
+ return a.zout_start;
+ } else {
+ free(a.zout_start);
+ return NULL;
+ }
+}
+
+int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen)
+{
+ zbuf a;
+ a.zbuffer = (uint8 *) ibuffer;
+ a.zbuffer_end = (uint8 *) ibuffer + ilen;
+ if (do_zlib(&a, obuffer, olen, 0, 0))
+ return (int) (a.zout - a.zout_start);
+ else
+ return -1;
+}
+
+// public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18
+// simple implementation
+// - only 8-bit samples
+// - no CRC checking
+// - allocates lots of intermediate memory
+// - avoids problem of streaming data between subsystems
+// - avoids explicit window management
+// performance
+// - uses stb_zlib, a PD zlib implementation with fast huffman decoding
+
+
+typedef struct
+{
+ uint32 length;
+ uint32 type;
+} chunk;
+
+#define PNG_TYPE(a,b,c,d) (((a) << 24) + ((b) << 16) + ((c) << 8) + (d))
+
+static chunk get_chunk_header(stbi *s)
+{
+ chunk c;
+ c.length = get32(s);
+ c.type = get32(s);
+ return c;
+}
+
+static int check_png_header(stbi *s)
+{
+ static uint8 png_sig[8] = { 137,80,78,71,13,10,26,10 };
+ int i;
+ for (i=0; i < 8; ++i)
+ if (get8u(s) != png_sig[i]) return e("bad png sig","Not a PNG");
+ return 1;
+}
+
+typedef struct
+{
+ stbi *s;
+ uint8 *idata, *expanded, *out;
+} png;
+
+
+enum {
+ F_none=0, F_sub=1, F_up=2, F_avg=3, F_paeth=4,
+ F_avg_first, F_paeth_first
+};
+
+static uint8 first_row_filter[5] =
+{
+ F_none, F_sub, F_none, F_avg_first, F_paeth_first
+};
+
+static int paeth(int a, int b, int c)
+{
+ int p = a + b - c;
+ int pa = abs(p-a);
+ int pb = abs(p-b);
+ int pc = abs(p-c);
+ if (pa <= pb && pa <= pc) return a;
+ if (pb <= pc) return b;
+ return c;
+}
+
+// create the png data from post-deflated data
+static int create_png_image_raw(png *a, uint8 *raw, uint32 raw_len, int out_n, uint32 x, uint32 y)
+{
+ stbi *s = a->s;
+ uint32 i,j,stride = x*out_n;
+ int k;
+ int img_n = s->img_n; // copy it into a local for later
+ assert(out_n == s->img_n || out_n == s->img_n+1);
+ if (stbi_png_partial) y = 1;
+ a->out = (uint8 *) malloc(x * y * out_n);
+ if (!a->out) return e("outofmem", "Out of memory");
+ if (!stbi_png_partial) {
+ if (s->img_x == x && s->img_y == y) {
+ if (raw_len != (img_n * x + 1) * y) return e("not enough pixels","Corrupt PNG");
+ } else { // interlaced:
+ if (raw_len < (img_n * x + 1) * y) return e("not enough pixels","Corrupt PNG");
+ }
+ }
+ for (j=0; j < y; ++j) {
+ uint8 *cur = a->out + stride*j;
+ uint8 *prior = cur - stride;
+ int filter = *raw++;
+ if (filter > 4) return e("invalid filter","Corrupt PNG");
+ // if first row, use special filter that doesn't sample previous row
+ if (j == 0) filter = first_row_filter[filter];
+ // handle first pixel explicitly
+ for (k=0; k < img_n; ++k) {
+ switch (filter) {
+ case F_none : cur[k] = raw[k]; break;
+ case F_sub : cur[k] = raw[k]; break;
+ case F_up : cur[k] = raw[k] + prior[k]; break;
+ case F_avg : cur[k] = raw[k] + (prior[k]>>1); break;
+ case F_paeth : cur[k] = (uint8) (raw[k] + paeth(0,prior[k],0)); break;
+ case F_avg_first : cur[k] = raw[k]; break;
+ case F_paeth_first: cur[k] = raw[k]; break;
+ }
+ }
+ if (img_n != out_n) cur[img_n] = 255;
+ raw += img_n;
+ cur += out_n;
+ prior += out_n;
+ // this is a little gross, so that we don't switch per-pixel or per-component
+ if (img_n == out_n) {
+ #define CASE(f) \
+ case f: \
+ for (i=x-1; i >= 1; --i, raw+=img_n,cur+=img_n,prior+=img_n) \
+ for (k=0; k < img_n; ++k)
+ switch (filter) {
+ CASE(F_none) cur[k] = raw[k]; break;
+ CASE(F_sub) cur[k] = raw[k] + cur[k-img_n]; break;
+ CASE(F_up) cur[k] = raw[k] + prior[k]; break;
+ CASE(F_avg) cur[k] = raw[k] + ((prior[k] + cur[k-img_n])>>1); break;
+ CASE(F_paeth) cur[k] = (uint8) (raw[k] + paeth(cur[k-img_n],prior[k],prior[k-img_n])); break;
+ CASE(F_avg_first) cur[k] = raw[k] + (cur[k-img_n] >> 1); break;
+ CASE(F_paeth_first) cur[k] = (uint8) (raw[k] + paeth(cur[k-img_n],0,0)); break;
+ }
+ #undef CASE
+ } else {
+ assert(img_n+1 == out_n);
+ #define CASE(f) \
+ case f: \
+ for (i=x-1; i >= 1; --i, cur[img_n]=255,raw+=img_n,cur+=out_n,prior+=out_n) \
+ for (k=0; k < img_n; ++k)
+ switch (filter) {
+ CASE(F_none) cur[k] = raw[k]; break;
+ CASE(F_sub) cur[k] = raw[k] + cur[k-out_n]; break;
+ CASE(F_up) cur[k] = raw[k] + prior[k]; break;
+ CASE(F_avg) cur[k] = raw[k] + ((prior[k] + cur[k-out_n])>>1); break;
+ CASE(F_paeth) cur[k] = (uint8) (raw[k] + paeth(cur[k-out_n],prior[k],prior[k-out_n])); break;
+ CASE(F_avg_first) cur[k] = raw[k] + (cur[k-out_n] >> 1); break;
+ CASE(F_paeth_first) cur[k] = (uint8) (raw[k] + paeth(cur[k-out_n],0,0)); break;
+ }
+ #undef CASE
+ }
+ }
+ return 1;
+}
+
+static int create_png_image(png *a, uint8 *raw, uint32 raw_len, int out_n, int interlaced)
+{
+ uint8 *final;
+ int p;
+ int save;
+ if (!interlaced)
+ return create_png_image_raw(a, raw, raw_len, out_n, a->s->img_x, a->s->img_y);
+ save = stbi_png_partial;
+ stbi_png_partial = 0;
+
+ // de-interlacing
+ final = (uint8 *) malloc(a->s->img_x * a->s->img_y * out_n);
+ for (p=0; p < 7; ++p) {
+ int xorig[] = { 0,4,0,2,0,1,0 };
+ int yorig[] = { 0,0,4,0,2,0,1 };
+ int xspc[] = { 8,8,4,4,2,2,1 };
+ int yspc[] = { 8,8,8,4,4,2,2 };
+ int i,j,x,y;
+ // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1
+ x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p];
+ y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p];
+ if (x && y) {
+ if (!create_png_image_raw(a, raw, raw_len, out_n, x, y)) {
+ free(final);
+ return 0;
+ }
+ for (j=0; j < y; ++j)
+ for (i=0; i < x; ++i)
+ memcpy(final + (j*yspc[p]+yorig[p])*a->s->img_x*out_n + (i*xspc[p]+xorig[p])*out_n,
+ a->out + (j*x+i)*out_n, out_n);
+ free(a->out);
+ raw += (x*out_n+1)*y;
+ raw_len -= (x*out_n+1)*y;
+ }
+ }
+ a->out = final;
+
+ stbi_png_partial = save;
+ return 1;
+}
+
+static int compute_transparency(png *z, uint8 tc[3], int out_n)
+{
+ stbi *s = z->s;
+ uint32 i, pixel_count = s->img_x * s->img_y;
+ uint8 *p = z->out;
+
+ // compute color-based transparency, assuming we've
+ // already got 255 as the alpha value in the output
+ assert(out_n == 2 || out_n == 4);
+
+ if (out_n == 2) {
+ for (i=0; i < pixel_count; ++i) {
+ p[1] = (p[0] == tc[0] ? 0 : 255);
+ p += 2;
+ }
+ } else {
+ for (i=0; i < pixel_count; ++i) {
+ if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2])
+ p[3] = 0;
+ p += 4;
+ }
+ }
+ return 1;
+}
+
+static int expand_palette(png *a, uint8 *palette, int len, int pal_img_n)
+{
+ uint32 i, pixel_count = a->s->img_x * a->s->img_y;
+ uint8 *p, *temp_out, *orig = a->out;
+
+ p = (uint8 *) malloc(pixel_count * pal_img_n);
+ if (p == NULL) return e("outofmem", "Out of memory");
+
+ // between here and free(out) below, exitting would leak
+ temp_out = p;
+
+ if (pal_img_n == 3) {
+ for (i=0; i < pixel_count; ++i) {
+ int n = orig[i]*4;
+ p[0] = palette[n ];
+ p[1] = palette[n+1];
+ p[2] = palette[n+2];
+ p += 3;
+ }
+ } else {
+ for (i=0; i < pixel_count; ++i) {
+ int n = orig[i]*4;
+ p[0] = palette[n ];
+ p[1] = palette[n+1];
+ p[2] = palette[n+2];
+ p[3] = palette[n+3];
+ p += 4;
+ }
+ }
+ free(a->out);
+ a->out = temp_out;
+
+ STBI_NOTUSED(len);
+
+ return 1;
+}
+
+static int stbi_unpremultiply_on_load = 0;
+static int stbi_de_iphone_flag = 0;
+
+void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply)
+{
+ stbi_unpremultiply_on_load = flag_true_if_should_unpremultiply;
+}
+void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert)
+{
+ stbi_de_iphone_flag = flag_true_if_should_convert;
+}
+
+static void stbi_de_iphone(png *z)
+{
+ stbi *s = z->s;
+ uint32 i, pixel_count = s->img_x * s->img_y;
+ uint8 *p = z->out;
+
+ if (s->img_out_n == 3) { // convert bgr to rgb
+ for (i=0; i < pixel_count; ++i) {
+ uint8 t = p[0];
+ p[0] = p[2];
+ p[2] = t;
+ p += 3;
+ }
+ } else {
+ assert(s->img_out_n == 4);
+ if (stbi_unpremultiply_on_load) {
+ // convert bgr to rgb and unpremultiply
+ for (i=0; i < pixel_count; ++i) {
+ uint8 a = p[3];
+ uint8 t = p[0];
+ if (a) {
+ p[0] = p[2] * 255 / a;
+ p[1] = p[1] * 255 / a;
+ p[2] = t * 255 / a;
+ } else {
+ p[0] = p[2];
+ p[2] = t;
+ }
+ p += 4;
+ }
+ } else {
+ // convert bgr to rgb
+ for (i=0; i < pixel_count; ++i) {
+ uint8 t = p[0];
+ p[0] = p[2];
+ p[2] = t;
+ p += 4;
+ }
+ }
+ }
+}
+
+static int parse_png_file(png *z, int scan, int req_comp)
+{
+ uint8 palette[1024], pal_img_n=0;
+ uint8 has_trans=0, tc[3];
+ uint32 ioff=0, idata_limit=0, i, pal_len=0;
+ int first=1,k,interlace=0, iphone=0;
+ stbi *s = z->s;
+
+ z->expanded = NULL;
+ z->idata = NULL;
+ z->out = NULL;
+
+ if (!check_png_header(s)) return 0;
+
+ if (scan == SCAN_type) return 1;
+
+ for (;;) {
+ chunk c = get_chunk_header(s);
+ switch (c.type) {
+ case PNG_TYPE('C','g','B','I'):
+ iphone = stbi_de_iphone_flag;
+ skip(s, c.length);
+ break;
+ case PNG_TYPE('I','H','D','R'): {
+ int depth,color,comp,filter;
+ if (!first) return e("multiple IHDR","Corrupt PNG");
+ first = 0;
+ if (c.length != 13) return e("bad IHDR len","Corrupt PNG");
+ s->img_x = get32(s); if (s->img_x > (1 << 24)) return e("too large","Very large image (corrupt?)");
+ s->img_y = get32(s); if (s->img_y > (1 << 24)) return e("too large","Very large image (corrupt?)");
+ depth = get8(s); if (depth != 8) return e("8bit only","PNG not supported: 8-bit only");
+ color = get8(s); if (color > 6) return e("bad ctype","Corrupt PNG");
+ if (color == 3) pal_img_n = 3; else if (color & 1) return e("bad ctype","Corrupt PNG");
+ comp = get8(s); if (comp) return e("bad comp method","Corrupt PNG");
+ filter= get8(s); if (filter) return e("bad filter method","Corrupt PNG");
+ interlace = get8(s); if (interlace>1) return e("bad interlace method","Corrupt PNG");
+ if (!s->img_x || !s->img_y) return e("0-pixel image","Corrupt PNG");
+ if (!pal_img_n) {
+ s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0);
+ if ((1 << 30) / s->img_x / s->img_n < s->img_y) return e("too large", "Image too large to decode");
+ if (scan == SCAN_header) return 1;
+ } else {
+ // if paletted, then pal_n is our final components, and
+ // img_n is # components to decompress/filter.
+ s->img_n = 1;
+ if ((1 << 30) / s->img_x / 4 < s->img_y) return e("too large","Corrupt PNG");
+ // if SCAN_header, have to scan to see if we have a tRNS
+ }
+ break;
+ }
+
+ case PNG_TYPE('P','L','T','E'): {
+ if (first) return e("first not IHDR", "Corrupt PNG");
+ if (c.length > 256*3) return e("invalid PLTE","Corrupt PNG");
+ pal_len = c.length / 3;
+ if (pal_len * 3 != c.length) return e("invalid PLTE","Corrupt PNG");
+ for (i=0; i < pal_len; ++i) {
+ palette[i*4+0] = get8u(s);
+ palette[i*4+1] = get8u(s);
+ palette[i*4+2] = get8u(s);
+ palette[i*4+3] = 255;
+ }
+ break;
+ }
+
+ case PNG_TYPE('t','R','N','S'): {
+ if (first) return e("first not IHDR", "Corrupt PNG");
+ if (z->idata) return e("tRNS after IDAT","Corrupt PNG");
+ if (pal_img_n) {
+ if (scan == SCAN_header) { s->img_n = 4; return 1; }
+ if (pal_len == 0) return e("tRNS before PLTE","Corrupt PNG");
+ if (c.length > pal_len) return e("bad tRNS len","Corrupt PNG");
+ pal_img_n = 4;
+ for (i=0; i < c.length; ++i)
+ palette[i*4+3] = get8u(s);
+ } else {
+ if (!(s->img_n & 1)) return e("tRNS with alpha","Corrupt PNG");
+ if (c.length != (uint32) s->img_n*2) return e("bad tRNS len","Corrupt PNG");
+ has_trans = 1;
+ for (k=0; k < s->img_n; ++k)
+ tc[k] = (uint8) get16(s); // non 8-bit images will be larger
+ }
+ break;
+ }
+
+ case PNG_TYPE('I','D','A','T'): {
+ if (first) return e("first not IHDR", "Corrupt PNG");
+ if (pal_img_n && !pal_len) return e("no PLTE","Corrupt PNG");
+ if (scan == SCAN_header) { s->img_n = pal_img_n; return 1; }
+ if (ioff + c.length > idata_limit) {
+ uint8 *p;
+ if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096;
+ while (ioff + c.length > idata_limit)
+ idata_limit *= 2;
+ p = (uint8 *) realloc(z->idata, idata_limit); if (p == NULL) return e("outofmem", "Out of memory");
+ z->idata = p;
+ }
+ if (!getn(s, z->idata+ioff,c.length)) return e("outofdata","Corrupt PNG");
+ ioff += c.length;
+ break;
+ }
+
+ case PNG_TYPE('I','E','N','D'): {
+ uint32 raw_len;
+ if (first) return e("first not IHDR", "Corrupt PNG");
+ if (scan != SCAN_load) return 1;
+ if (z->idata == NULL) return e("no IDAT","Corrupt PNG");
+ z->expanded = (uint8 *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, 16384, (int *) &raw_len, !iphone);
+ if (z->expanded == NULL) return 0; // zlib should set error
+ free(z->idata); z->idata = NULL;
+ if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans)
+ s->img_out_n = s->img_n+1;
+ else
+ s->img_out_n = s->img_n;
+ if (!create_png_image(z, z->expanded, raw_len, s->img_out_n, interlace)) return 0;
+ if (has_trans)
+ if (!compute_transparency(z, tc, s->img_out_n)) return 0;
+ if (iphone && s->img_out_n > 2)
+ stbi_de_iphone(z);
+ if (pal_img_n) {
+ // pal_img_n == 3 or 4
+ s->img_n = pal_img_n; // record the actual colors we had
+ s->img_out_n = pal_img_n;
+ if (req_comp >= 3) s->img_out_n = req_comp;
+ if (!expand_palette(z, palette, pal_len, s->img_out_n))
+ return 0;
+ }
+ free(z->expanded); z->expanded = NULL;
+ return 1;
+ }
+
+ default:
+ // if critical, fail
+ if (first) return e("first not IHDR", "Corrupt PNG");
+ if ((c.type & (1 << 29)) == 0) {
+ #ifndef STBI_NO_FAILURE_STRINGS
+ // not threadsafe
+ static char invalid_chunk[] = "XXXX chunk not known";
+ invalid_chunk[0] = (uint8) (c.type >> 24);
+ invalid_chunk[1] = (uint8) (c.type >> 16);
+ invalid_chunk[2] = (uint8) (c.type >> 8);
+ invalid_chunk[3] = (uint8) (c.type >> 0);
+ #endif
+ return e(invalid_chunk, "PNG not supported: unknown chunk type");
+ }
+ skip(s, c.length);
+ break;
+ }
+ // end of chunk, read and skip CRC
+ get32(s);
+ }
+}
+
+static unsigned char *do_png(png *p, int *x, int *y, int *n, int req_comp)
+{
+ unsigned char *result=NULL;
+ if (req_comp < 0 || req_comp > 4) return epuc("bad req_comp", "Internal error");
+ if (parse_png_file(p, SCAN_load, req_comp)) {
+ result = p->out;
+ p->out = NULL;
+ if (req_comp && req_comp != p->s->img_out_n) {
+ result = convert_format(result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y);
+ p->s->img_out_n = req_comp;
+ if (result == NULL) return result;
+ }
+ *x = p->s->img_x;
+ *y = p->s->img_y;
+ if (n) *n = p->s->img_n;
+ }
+ free(p->out); p->out = NULL;
+ free(p->expanded); p->expanded = NULL;
+ free(p->idata); p->idata = NULL;
+
+ return result;
+}
+
+static unsigned char *stbi_png_load(stbi *s, int *x, int *y, int *comp, int req_comp)
+{
+ png p;
+ p.s = s;
+ return do_png(&p, x,y,comp,req_comp);
+}
+
+static int stbi_png_test(stbi *s)
+{
+ int r;
+ r = check_png_header(s);
+ stbi_rewind(s);
+ return r;
+}
+
+static int stbi_png_info_raw(png *p, int *x, int *y, int *comp)
+{
+ if (!parse_png_file(p, SCAN_header, 0)) {
+ stbi_rewind( p->s );
+ return 0;
+ }
+ if (x) *x = p->s->img_x;
+ if (y) *y = p->s->img_y;
+ if (comp) *comp = p->s->img_n;
+ return 1;
+}
+
+static int stbi_png_info(stbi *s, int *x, int *y, int *comp)
+{
+ png p;
+ p.s = s;
+ return stbi_png_info_raw(&p, x, y, comp);
+}
+
+// Microsoft/Windows BMP image
+
+static int bmp_test(stbi *s)
+{
+ int sz;
+ if (get8(s) != 'B') return 0;
+ if (get8(s) != 'M') return 0;
+ get32le(s); // discard filesize
+ get16le(s); // discard reserved
+ get16le(s); // discard reserved
+ get32le(s); // discard data offset
+ sz = get32le(s);
+ if (sz == 12 || sz == 40 || sz == 56 || sz == 108) return 1;
+ return 0;
+}
+
+static int stbi_bmp_test(stbi *s)
+{
+ int r = bmp_test(s);
+ stbi_rewind(s);
+ return r;
+}
+
+
+// returns 0..31 for the highest set bit
+static int high_bit(unsigned int z)
+{
+ int n=0;
+ if (z == 0) return -1;
+ if (z >= 0x10000) n += 16, z >>= 16;
+ if (z >= 0x00100) n += 8, z >>= 8;
+ if (z >= 0x00010) n += 4, z >>= 4;
+ if (z >= 0x00004) n += 2, z >>= 2;
+ if (z >= 0x00002) n += 1, z >>= 1;
+ return n;
+}
+
+static int bitcount(unsigned int a)
+{
+ a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2
+ a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4
+ a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits
+ a = (a + (a >> 8)); // max 16 per 8 bits
+ a = (a + (a >> 16)); // max 32 per 8 bits
+ return a & 0xff;
+}
+
+static int shiftsigned(int v, int shift, int bits)
+{
+ int result;
+ int z=0;
+
+ if (shift < 0) v <<= -shift;
+ else v >>= shift;
+ result = v;
+
+ z = bits;
+ while (z < 8) {
+ result += v >> z;
+ z += bits;
+ }
+ return result;
+}
+
+static stbi_uc *bmp_load(stbi *s, int *x, int *y, int *comp, int req_comp)
+{
+ uint8 *out;
+ unsigned int mr=0,mg=0,mb=0,ma=0, fake_a=0;
+ stbi_uc pal[256][4];
+ int psize=0,i,j,compress=0,width;
+ int bpp, flip_vertically, pad, target, offset, hsz;
+ if (get8(s) != 'B' || get8(s) != 'M') return epuc("not BMP", "Corrupt BMP");
+ get32le(s); // discard filesize
+ get16le(s); // discard reserved
+ get16le(s); // discard reserved
+ offset = get32le(s);
+ hsz = get32le(s);
+ if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108) return epuc("unknown BMP", "BMP type not supported: unknown");
+ if (hsz == 12) {
+ s->img_x = get16le(s);
+ s->img_y = get16le(s);
+ } else {
+ s->img_x = get32le(s);
+ s->img_y = get32le(s);
+ }
+ if (get16le(s) != 1) return epuc("bad BMP", "bad BMP");
+ bpp = get16le(s);
+ if (bpp == 1) return epuc("monochrome", "BMP type not supported: 1-bit");
+ flip_vertically = ((int) s->img_y) > 0;
+ s->img_y = abs((int) s->img_y);
+ if (hsz == 12) {
+ if (bpp < 24)
+ psize = (offset - 14 - 24) / 3;
+ } else {
+ compress = get32le(s);
+ if (compress == 1 || compress == 2) return epuc("BMP RLE", "BMP type not supported: RLE");
+ get32le(s); // discard sizeof
+ get32le(s); // discard hres
+ get32le(s); // discard vres
+ get32le(s); // discard colorsused
+ get32le(s); // discard max important
+ if (hsz == 40 || hsz == 56) {
+ if (hsz == 56) {
+ get32le(s);
+ get32le(s);
+ get32le(s);
+ get32le(s);
+ }
+ if (bpp == 16 || bpp == 32) {
+ mr = mg = mb = 0;
+ if (compress == 0) {
+ if (bpp == 32) {
+ mr = 0xffu << 16;
+ mg = 0xffu << 8;
+ mb = 0xffu << 0;
+ ma = 0xffu << 24;
+ fake_a = 1; // @TODO: check for cases like alpha value is all 0 and switch it to 255
+ } else {
+ mr = 31u << 10;
+ mg = 31u << 5;
+ mb = 31u << 0;
+ }
+ } else if (compress == 3) {
+ mr = get32le(s);
+ mg = get32le(s);
+ mb = get32le(s);
+ // not documented, but generated by photoshop and handled by mspaint
+ if (mr == mg && mg == mb) {
+ // ?!?!?
+ return epuc("bad BMP", "bad BMP");
+ }
+ } else
+ return epuc("bad BMP", "bad BMP");
+ }
+ } else {
+ assert(hsz == 108);
+ mr = get32le(s);
+ mg = get32le(s);
+ mb = get32le(s);
+ ma = get32le(s);
+ get32le(s); // discard color space
+ for (i=0; i < 12; ++i)
+ get32le(s); // discard color space parameters
+ }
+ if (bpp < 16)
+ psize = (offset - 14 - hsz) >> 2;
+ }
+ s->img_n = ma ? 4 : 3;
+ if (req_comp && req_comp >= 3) // we can directly decode 3 or 4
+ target = req_comp;
+ else
+ target = s->img_n; // if they want monochrome, we'll post-convert
+ out = (stbi_uc *) malloc(target * s->img_x * s->img_y);
+ if (!out) return epuc("outofmem", "Out of memory");
+ if (bpp < 16) {
+ int z=0;
+ if (psize == 0 || psize > 256) { free(out); return epuc("invalid", "Corrupt BMP"); }
+ for (i=0; i < psize; ++i) {
+ pal[i][2] = get8u(s);
+ pal[i][1] = get8u(s);
+ pal[i][0] = get8u(s);
+ if (hsz != 12) get8(s);
+ pal[i][3] = 255;
+ }
+ skip(s, offset - 14 - hsz - psize * (hsz == 12 ? 3 : 4));
+ if (bpp == 4) width = (s->img_x + 1) >> 1;
+ else if (bpp == 8) width = s->img_x;
+ else { free(out); return epuc("bad bpp", "Corrupt BMP"); }
+ pad = (-width)&3;
+ for (j=0; j < (int) s->img_y; ++j) {
+ for (i=0; i < (int) s->img_x; i += 2) {
+ int v=get8(s),v2=0;
+ if (bpp == 4) {
+ v2 = v & 15;
+ v >>= 4;
+ }
+ out[z++] = pal[v][0];
+ out[z++] = pal[v][1];
+ out[z++] = pal[v][2];
+ if (target == 4) out[z++] = 255;
+ if (i+1 == (int) s->img_x) break;
+ v = (bpp == 8) ? get8(s) : v2;
+ out[z++] = pal[v][0];
+ out[z++] = pal[v][1];
+ out[z++] = pal[v][2];
+ if (target == 4) out[z++] = 255;
+ }
+ skip(s, pad);
+ }
+ } else {
+ int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0;
+ int z = 0;
+ int easy=0;
+ skip(s, offset - 14 - hsz);
+ if (bpp == 24) width = 3 * s->img_x;
+ else if (bpp == 16) width = 2*s->img_x;
+ else /* bpp = 32 and pad = 0 */ width=0;
+ pad = (-width) & 3;
+ if (bpp == 24) {
+ easy = 1;
+ } else if (bpp == 32) {
+ if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000)
+ easy = 2;
+ }
+ if (!easy) {
+ if (!mr || !mg || !mb) { free(out); return epuc("bad masks", "Corrupt BMP"); }
+ // right shift amt to put high bit in position #7
+ rshift = high_bit(mr)-7; rcount = bitcount(mr);
+ gshift = high_bit(mg)-7; gcount = bitcount(mr);
+ bshift = high_bit(mb)-7; bcount = bitcount(mr);
+ ashift = high_bit(ma)-7; acount = bitcount(mr);
+ }
+ for (j=0; j < (int) s->img_y; ++j) {
+ if (easy) {
+ for (i=0; i < (int) s->img_x; ++i) {
+ int a;
+ out[z+2] = get8u(s);
+ out[z+1] = get8u(s);
+ out[z+0] = get8u(s);
+ z += 3;
+ a = (easy == 2 ? get8(s) : 255);
+ if (target == 4) out[z++] = (uint8) a;
+ }
+ } else {
+ for (i=0; i < (int) s->img_x; ++i) {
+ uint32 v = (bpp == 16 ? get16le(s) : get32le(s));
+ int a;
+ out[z++] = (uint8) shiftsigned(v & mr, rshift, rcount);
+ out[z++] = (uint8) shiftsigned(v & mg, gshift, gcount);
+ out[z++] = (uint8) shiftsigned(v & mb, bshift, bcount);
+ a = (ma ? shiftsigned(v & ma, ashift, acount) : 255);
+ if (target == 4) out[z++] = (uint8) a;
+ }
+ }
+ skip(s, pad);
+ }
+ }
+ if (flip_vertically) {
+ stbi_uc t;
+ for (j=0; j < (int) s->img_y>>1; ++j) {
+ stbi_uc *p1 = out + j *s->img_x*target;
+ stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target;
+ for (i=0; i < (int) s->img_x*target; ++i) {
+ t = p1[i], p1[i] = p2[i], p2[i] = t;
+ }
+ }
+ }
+
+ if (req_comp && req_comp != target) {
+ out = convert_format(out, target, req_comp, s->img_x, s->img_y);
+ if (out == NULL) return out; // convert_format frees input on failure
+ }
+
+ *x = s->img_x;
+ *y = s->img_y;
+ if (comp) *comp = s->img_n;
+ return out;
+}
+
+static stbi_uc *stbi_bmp_load(stbi *s,int *x, int *y, int *comp, int req_comp)
+{
+ return bmp_load(s, x,y,comp,req_comp);
+}
+
+
+// Targa Truevision - TGA
+// by Jonathan Dummer
+
+static int tga_info(stbi *s, int *x, int *y, int *comp)
+{
+ int tga_w, tga_h, tga_comp;
+ int sz;
+ get8u(s); // discard Offset
+ sz = get8u(s); // color type
+ if( sz > 1 ) {
+ stbi_rewind(s);
+ return 0; // only RGB or indexed allowed
+ }
+ sz = get8u(s); // image type
+ // only RGB or grey allowed, +/- RLE
+ if ((sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11)) return 0;
+ skip(s,9);
+ tga_w = get16le(s);
+ if( tga_w < 1 ) {
+ stbi_rewind(s);
+ return 0; // test width
+ }
+ tga_h = get16le(s);
+ if( tga_h < 1 ) {
+ stbi_rewind(s);
+ return 0; // test height
+ }
+ sz = get8(s); // bits per pixel
+ // only RGB or RGBA or grey allowed
+ if ((sz != 8) && (sz != 16) && (sz != 24) && (sz != 32)) {
+ stbi_rewind(s);
+ return 0;
+ }
+ tga_comp = sz;
+ if (x) *x = tga_w;
+ if (y) *y = tga_h;
+ if (comp) *comp = tga_comp / 8;
+ return 1; // seems to have passed everything
+}
+
+int stbi_tga_info(stbi *s, int *x, int *y, int *comp)
+{
+ return tga_info(s, x, y, comp);
+}
+
+static int tga_test(stbi *s)
+{
+ int sz;
+ get8u(s); // discard Offset
+ sz = get8u(s); // color type
+ if ( sz > 1 ) return 0; // only RGB or indexed allowed
+ sz = get8u(s); // image type
+ if ( (sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11) ) return 0; // only RGB or grey allowed, +/- RLE
+ get16(s); // discard palette start
+ get16(s); // discard palette length
+ get8(s); // discard bits per palette color entry
+ get16(s); // discard x origin
+ get16(s); // discard y origin
+ if ( get16(s) < 1 ) return 0; // test width
+ if ( get16(s) < 1 ) return 0; // test height
+ sz = get8(s); // bits per pixel
+ if ( (sz != 8) && (sz != 16) && (sz != 24) && (sz != 32) ) return 0; // only RGB or RGBA or grey allowed
+ return 1; // seems to have passed everything
+}
+
+static int stbi_tga_test(stbi *s)
+{
+ int res = tga_test(s);
+ stbi_rewind(s);
+ return res;
+}
+
+static stbi_uc *tga_load(stbi *s, int *x, int *y, int *comp, int req_comp)
+{
+ // read in the TGA header stuff
+ int tga_offset = get8u(s);
+ int tga_indexed = get8u(s);
+ int tga_image_type = get8u(s);
+ int tga_is_RLE = 0;
+ int tga_palette_start = get16le(s);
+ int tga_palette_len = get16le(s);
+ int tga_palette_bits = get8u(s);
+ int tga_x_origin = get16le(s);
+ int tga_y_origin = get16le(s);
+ int tga_width = get16le(s);
+ int tga_height = get16le(s);
+ int tga_bits_per_pixel = get8u(s);
+ int tga_inverted = get8u(s);
+ // image data
+ unsigned char *tga_data;
+ unsigned char *tga_palette = NULL;
+ int i, j;
+ unsigned char raw_data[4];
+ unsigned char trans_data[4];
+ int RLE_count = 0;
+ int RLE_repeating = 0;
+ int read_next_pixel = 1;
+
+ // do a tiny bit of precessing
+ if ( tga_image_type >= 8 )
+ {
+ tga_image_type -= 8;
+ tga_is_RLE = 1;
+ }
+ /* int tga_alpha_bits = tga_inverted & 15; */
+ tga_inverted = 1 - ((tga_inverted >> 5) & 1);
+
+ // error check
+ if ( //(tga_indexed) ||
+ (tga_width < 1) || (tga_height < 1) ||
+ (tga_image_type < 1) || (tga_image_type > 3) ||
+ ((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16) &&
+ (tga_bits_per_pixel != 24) && (tga_bits_per_pixel != 32))
+ )
+ {
+ return NULL; // we don't report this as a bad TGA because we don't even know if it's TGA
+ }
+
+ // If I'm paletted, then I'll use the number of bits from the palette
+ if ( tga_indexed )
+ {
+ tga_bits_per_pixel = tga_palette_bits;
+ }
+
+ // tga info
+ *x = tga_width;
+ *y = tga_height;
+ if ( (req_comp < 1) || (req_comp > 4) )
+ {
+ // just use whatever the file was
+ req_comp = tga_bits_per_pixel / 8;
+ *comp = req_comp;
+ } else
+ {
+ // force a new number of components
+ *comp = tga_bits_per_pixel/8;
+ }
+ tga_data = (unsigned char*)malloc( tga_width * tga_height * req_comp );
+ if (!tga_data) return epuc("outofmem", "Out of memory");
+
+ // skip to the data's starting position (offset usually = 0)
+ skip(s, tga_offset );
+ // do I need to load a palette?
+ if ( tga_indexed )
+ {
+ // any data to skip? (offset usually = 0)
+ skip(s, tga_palette_start );
+ // load the palette
+ tga_palette = (unsigned char*)malloc( tga_palette_len * tga_palette_bits / 8 );
+ if (!tga_palette) return epuc("outofmem", "Out of memory");
+ if (!getn(s, tga_palette, tga_palette_len * tga_palette_bits / 8 )) {
+ free(tga_data);
+ free(tga_palette);
+ return epuc("bad palette", "Corrupt TGA");
+ }
+ }
+ // load the data
+ trans_data[0] = trans_data[1] = trans_data[2] = trans_data[3] = 0;
+ for (i=0; i < tga_width * tga_height; ++i)
+ {
+ // if I'm in RLE mode, do I need to get a RLE chunk?
+ if ( tga_is_RLE )
+ {
+ if ( RLE_count == 0 )
+ {
+ // yep, get the next byte as a RLE command
+ int RLE_cmd = get8u(s);
+ RLE_count = 1 + (RLE_cmd & 127);
+ RLE_repeating = RLE_cmd >> 7;
+ read_next_pixel = 1;
+ } else if ( !RLE_repeating )
+ {
+ read_next_pixel = 1;
+ }
+ } else
+ {
+ read_next_pixel = 1;
+ }
+ // OK, if I need to read a pixel, do it now
+ if ( read_next_pixel )
+ {
+ // load however much data we did have
+ if ( tga_indexed )
+ {
+ // read in 1 byte, then perform the lookup
+ int pal_idx = get8u(s);
+ if ( pal_idx >= tga_palette_len )
+ {
+ // invalid index
+ pal_idx = 0;
+ }
+ pal_idx *= tga_bits_per_pixel / 8;
+ for (j = 0; j*8 < tga_bits_per_pixel; ++j)
+ {
+ raw_data[j] = tga_palette[pal_idx+j];
+ }
+ } else
+ {
+ // read in the data raw
+ for (j = 0; j*8 < tga_bits_per_pixel; ++j)
+ {
+ raw_data[j] = get8u(s);
+ }
+ }
+ // convert raw to the intermediate format
+ switch (tga_bits_per_pixel)
+ {
+ case 8:
+ // Luminous => RGBA
+ trans_data[0] = raw_data[0];
+ trans_data[1] = raw_data[0];
+ trans_data[2] = raw_data[0];
+ trans_data[3] = 255;
+ break;
+ case 16:
+ // Luminous,Alpha => RGBA
+ trans_data[0] = raw_data[0];
+ trans_data[1] = raw_data[0];
+ trans_data[2] = raw_data[0];
+ trans_data[3] = raw_data[1];
+ break;
+ case 24:
+ // BGR => RGBA
+ trans_data[0] = raw_data[2];
+ trans_data[1] = raw_data[1];
+ trans_data[2] = raw_data[0];
+ trans_data[3] = 255;
+ break;
+ case 32:
+ // BGRA => RGBA
+ trans_data[0] = raw_data[2];
+ trans_data[1] = raw_data[1];
+ trans_data[2] = raw_data[0];
+ trans_data[3] = raw_data[3];
+ break;
+ }
+ // clear the reading flag for the next pixel
+ read_next_pixel = 0;
+ } // end of reading a pixel
+ // convert to final format
+ switch (req_comp)
+ {
+ case 1:
+ // RGBA => Luminance
+ tga_data[i*req_comp+0] = compute_y(trans_data[0],trans_data[1],trans_data[2]);
+ break;
+ case 2:
+ // RGBA => Luminance,Alpha
+ tga_data[i*req_comp+0] = compute_y(trans_data[0],trans_data[1],trans_data[2]);
+ tga_data[i*req_comp+1] = trans_data[3];
+ break;
+ case 3:
+ // RGBA => RGB
+ tga_data[i*req_comp+0] = trans_data[0];
+ tga_data[i*req_comp+1] = trans_data[1];
+ tga_data[i*req_comp+2] = trans_data[2];
+ break;
+ case 4:
+ // RGBA => RGBA
+ tga_data[i*req_comp+0] = trans_data[0];
+ tga_data[i*req_comp+1] = trans_data[1];
+ tga_data[i*req_comp+2] = trans_data[2];
+ tga_data[i*req_comp+3] = trans_data[3];
+ break;
+ }
+ // in case we're in RLE mode, keep counting down
+ --RLE_count;
+ }
+ // do I need to invert the image?
+ if ( tga_inverted )
+ {
+ for (j = 0; j*2 < tga_height; ++j)
+ {
+ int index1 = j * tga_width * req_comp;
+ int index2 = (tga_height - 1 - j) * tga_width * req_comp;
+ for (i = tga_width * req_comp; i > 0; --i)
+ {
+ unsigned char temp = tga_data[index1];
+ tga_data[index1] = tga_data[index2];
+ tga_data[index2] = temp;
+ ++index1;
+ ++index2;
+ }
+ }
+ }
+ // clear my palette, if I had one
+ if ( tga_palette != NULL )
+ {
+ free( tga_palette );
+ }
+ // the things I do to get rid of an error message, and yet keep
+ // Microsoft's C compilers happy... [8^(
+ tga_palette_start = tga_palette_len = tga_palette_bits =
+ tga_x_origin = tga_y_origin = 0;
+ // OK, done
+ return tga_data;
+}
+
+static stbi_uc *stbi_tga_load(stbi *s, int *x, int *y, int *comp, int req_comp)
+{
+ return tga_load(s,x,y,comp,req_comp);
+}
+
+
+// *************************************************************************************************
+// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB
+
+static int psd_test(stbi *s)
+{
+ if (get32(s) != 0x38425053) return 0; // "8BPS"
+ else return 1;
+}
+
+static int stbi_psd_test(stbi *s)
+{
+ int r = psd_test(s);
+ stbi_rewind(s);
+ return r;
+}
+
+static stbi_uc *psd_load(stbi *s, int *x, int *y, int *comp, int req_comp)
+{
+ int pixelCount;
+ int channelCount, compression;
+ int channel, i, count, len;
+ int w,h;
+ uint8 *out;
+
+ // Check identifier
+ if (get32(s) != 0x38425053) // "8BPS"
+ return epuc("not PSD", "Corrupt PSD image");
+
+ // Check file type version.
+ if (get16(s) != 1)
+ return epuc("wrong version", "Unsupported version of PSD image");
+
+ // Skip 6 reserved bytes.
+ skip(s, 6 );
+
+ // Read the number of channels (R, G, B, A, etc).
+ channelCount = get16(s);
+ if (channelCount < 0 || channelCount > 16)
+ return epuc("wrong channel count", "Unsupported number of channels in PSD image");
+
+ // Read the rows and columns of the image.
+ h = get32(s);
+ w = get32(s);
+
+ // Make sure the depth is 8 bits.
+ if (get16(s) != 8)
+ return epuc("unsupported bit depth", "PSD bit depth is not 8 bit");
+
+ // Make sure the color mode is RGB.
+ // Valid options are:
+ // 0: Bitmap
+ // 1: Grayscale
+ // 2: Indexed color
+ // 3: RGB color
+ // 4: CMYK color
+ // 7: Multichannel
+ // 8: Duotone
+ // 9: Lab color
+ if (get16(s) != 3)
+ return epuc("wrong color format", "PSD is not in RGB color format");
+
+ // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.)
+ skip(s,get32(s) );
+
+ // Skip the image resources. (resolution, pen tool paths, etc)
+ skip(s, get32(s) );
+
+ // Skip the reserved data.
+ skip(s, get32(s) );
+
+ // Find out if the data is compressed.
+ // Known values:
+ // 0: no compression
+ // 1: RLE compressed
+ compression = get16(s);
+ if (compression > 1)
+ return epuc("bad compression", "PSD has an unknown compression format");
+
+ // Create the destination image.
+ out = (stbi_uc *) malloc(4 * w*h);
+ if (!out) return epuc("outofmem", "Out of memory");
+ pixelCount = w*h;
+
+ // Initialize the data to zero.
+ //memset( out, 0, pixelCount * 4 );
+
+ // Finally, the image data.
+ if (compression) {
+ // RLE as used by .PSD and .TIFF
+ // Loop until you get the number of unpacked bytes you are expecting:
+ // Read the next source byte into n.
+ // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally.
+ // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times.
+ // Else if n is 128, noop.
+ // Endloop
+
+ // The RLE-compressed data is preceeded by a 2-byte data count for each row in the data,
+ // which we're going to just skip.
+ skip(s, h * channelCount * 2 );
+
+ // Read the RLE data by channel.
+ for (channel = 0; channel < 4; channel++) {
+ uint8 *p;
+
+ p = out+channel;
+ if (channel >= channelCount) {
+ // Fill this channel with default data.
+ for (i = 0; i < pixelCount; i++) *p = (channel == 3 ? 255 : 0), p += 4;
+ } else {
+ // Read the RLE data.
+ count = 0;
+ while (count < pixelCount) {
+ len = get8(s);
+ if (len == 128) {
+ // No-op.
+ } else if (len < 128) {
+ // Copy next len+1 bytes literally.
+ len++;
+ count += len;
+ while (len) {
+ *p = get8u(s);
+ p += 4;
+ len--;
+ }
+ } else if (len > 128) {
+ uint8 val;
+ // Next -len+1 bytes in the dest are replicated from next source byte.
+ // (Interpret len as a negative 8-bit int.)
+ len ^= 0x0FF;
+ len += 2;
+ val = get8u(s);
+ count += len;
+ while (len) {
+ *p = val;
+ p += 4;
+ len--;
+ }
+ }
+ }
+ }
+ }
+
+ } else {
+ // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...)
+ // where each channel consists of an 8-bit value for each pixel in the image.
+
+ // Read the data by channel.
+ for (channel = 0; channel < 4; channel++) {
+ uint8 *p;
+
+ p = out + channel;
+ if (channel > channelCount) {
+ // Fill this channel with default data.
+ for (i = 0; i < pixelCount; i++) *p = channel == 3 ? 255 : 0, p += 4;
+ } else {
+ // Read the data.
+ for (i = 0; i < pixelCount; i++)
+ *p = get8u(s), p += 4;
+ }
+ }
+ }
+
+ if (req_comp && req_comp != 4) {
+ out = convert_format(out, 4, req_comp, w, h);
+ if (out == NULL) return out; // convert_format frees input on failure
+ }
+
+ if (comp) *comp = channelCount;
+ *y = h;
+ *x = w;
+
+ return out;
+}
+
+static stbi_uc *stbi_psd_load(stbi *s, int *x, int *y, int *comp, int req_comp)
+{
+ return psd_load(s,x,y,comp,req_comp);
+}
+
+// *************************************************************************************************
+// Softimage PIC loader
+// by Tom Seddon
+//
+// See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format
+// See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/
+
+static int pic_is4(stbi *s,const char *str)
+{
+ int i;
+ for (i=0; i<4; ++i)
+ if (get8(s) != (stbi_uc)str[i])
+ return 0;
+
+ return 1;
+}
+
+static int pic_test(stbi *s)
+{
+ int i;
+
+ if (!pic_is4(s,"\x53\x80\xF6\x34"))
+ return 0;
+
+ for(i=0;i<84;++i)
+ get8(s);
+
+ if (!pic_is4(s,"PICT"))
+ return 0;
+
+ return 1;
+}
+
+typedef struct
+{
+ stbi_uc size,type,channel;
+} pic_packet_t;
+
+static stbi_uc *pic_readval(stbi *s, int channel, stbi_uc *dest)
+{
+ int mask=0x80, i;
+
+ for (i=0; i<4; ++i, mask>>=1) {
+ if (channel & mask) {
+ if (at_eof(s)) return epuc("bad file","PIC file too short");
+ dest[i]=get8u(s);
+ }
+ }
+
+ return dest;
+}
+
+static void pic_copyval(int channel,stbi_uc *dest,const stbi_uc *src)
+{
+ int mask=0x80,i;
+
+ for (i=0;i<4; ++i, mask>>=1)
+ if (channel&mask)
+ dest[i]=src[i];
+}
+
+static stbi_uc *pic_load2(stbi *s,int width,int height,int *comp, stbi_uc *result)
+{
+ int act_comp=0,num_packets=0,y,chained;
+ pic_packet_t packets[10];
+
+ // this will (should...) cater for even some bizarre stuff like having data
+ // for the same channel in multiple packets.
+ do {
+ pic_packet_t *packet;
+
+ if (num_packets==sizeof(packets)/sizeof(packets[0]))
+ return epuc("bad format","too many packets");
+
+ packet = &packets[num_packets++];
+
+ chained = get8(s);
+ packet->size = get8u(s);
+ packet->type = get8u(s);
+ packet->channel = get8u(s);
+
+ act_comp |= packet->channel;
+
+ if (at_eof(s)) return epuc("bad file","file too short (reading packets)");
+ if (packet->size != 8) return epuc("bad format","packet isn't 8bpp");
+ } while (chained);
+
+ *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel?
+
+ for(y=0; y<height; ++y) {
+ int packet_idx;
+
+ for(packet_idx=0; packet_idx < num_packets; ++packet_idx) {
+ pic_packet_t *packet = &packets[packet_idx];
+ stbi_uc *dest = result+y*width*4;
+
+ switch (packet->type) {
+ default:
+ return epuc("bad format","packet has bad compression type");
+
+ case 0: {//uncompressed
+ int x;
+
+ for(x=0;x<width;++x, dest+=4)
+ if (!pic_readval(s,packet->channel,dest))
+ return 0;
+ break;
+ }
+
+ case 1://Pure RLE
+ {
+ int left=width, i;
+
+ while (left>0) {
+ stbi_uc count,value[4];
+
+ count=get8u(s);
+ if (at_eof(s)) return epuc("bad file","file too short (pure read count)");
+
+ if (count > left)
+ count = (uint8) left;
+
+ if (!pic_readval(s,packet->channel,value)) return 0;
+
+ for(i=0; i<count; ++i,dest+=4)
+ pic_copyval(packet->channel,dest,value);
+ left -= count;
+ }
+ }
+ break;
+
+ case 2: {//Mixed RLE
+ int left=width;
+ while (left>0) {
+ int count = get8(s), i;
+ if (at_eof(s)) return epuc("bad file","file too short (mixed read count)");
+
+ if (count >= 128) { // Repeated
+ stbi_uc value[4];
+ int i;
+
+ if (count==128)
+ count = get16(s);
+ else
+ count -= 127;
+ if (count > left)
+ return epuc("bad file","scanline overrun");
+
+ if (!pic_readval(s,packet->channel,value))
+ return 0;
+
+ for(i=0;i<count;++i, dest += 4)
+ pic_copyval(packet->channel,dest,value);
+ } else { // Raw
+ ++count;
+ if (count>left) return epuc("bad file","scanline overrun");
+
+ for(i=0;i<count;++i, dest+=4)
+ if (!pic_readval(s,packet->channel,dest))
+ return 0;
+ }
+ left-=count;
+ }
+ break;
+ }
+ }
+ }
+ }
+
+ return result;
+}
+
+static stbi_uc *pic_load(stbi *s,int *px,int *py,int *comp,int req_comp)
+{
+ stbi_uc *result;
+ int i, x,y;
+
+ for (i=0; i<92; ++i)
+ get8(s);
+
+ x = get16(s);
+ y = get16(s);
+ if (at_eof(s)) return epuc("bad file","file too short (pic header)");
+ if ((1 << 28) / x < y) return epuc("too large", "Image too large to decode");
+
+ get32(s); //skip `ratio'
+ get16(s); //skip `fields'
+ get16(s); //skip `pad'
+
+ // intermediate buffer is RGBA
+ result = (stbi_uc *) malloc(x*y*4);
+ memset(result, 0xff, x*y*4);
+
+ if (!pic_load2(s,x,y,comp, result)) {
+ free(result);
+ result=0;
+ }
+ *px = x;
+ *py = y;
+ if (req_comp == 0) req_comp = *comp;
+ result=convert_format(result,4,req_comp,x,y);
+
+ return result;
+}
+
+static int stbi_pic_test(stbi *s)
+{
+ int r = pic_test(s);
+ stbi_rewind(s);
+ return r;
+}
+
+static stbi_uc *stbi_pic_load(stbi *s, int *x, int *y, int *comp, int req_comp)
+{
+ return pic_load(s,x,y,comp,req_comp);
+}
+
+// *************************************************************************************************
+// GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb
+typedef struct stbi_gif_lzw_struct {
+ int16 prefix;
+ uint8 first;
+ uint8 suffix;
+} stbi_gif_lzw;
+
+typedef struct stbi_gif_struct
+{
+ int w,h;
+ stbi_uc *out; // output buffer (always 4 components)
+ int flags, bgindex, ratio, transparent, eflags;
+ uint8 pal[256][4];
+ uint8 lpal[256][4];
+ stbi_gif_lzw codes[4096];
+ uint8 *color_table;
+ int parse, step;
+ int lflags;
+ int start_x, start_y;
+ int max_x, max_y;
+ int cur_x, cur_y;
+ int line_size;
+} stbi_gif;
+
+static int gif_test(stbi *s)
+{
+ int sz;
+ if (get8(s) != 'G' || get8(s) != 'I' || get8(s) != 'F' || get8(s) != '8') return 0;
+ sz = get8(s);
+ if (sz != '9' && sz != '7') return 0;
+ if (get8(s) != 'a') return 0;
+ return 1;
+}
+
+static int stbi_gif_test(stbi *s)
+{
+ int r = gif_test(s);
+ stbi_rewind(s);
+ return r;
+}
+
+static void stbi_gif_parse_colortable(stbi *s, uint8 pal[256][4], int num_entries, int transp)
+{
+ int i;
+ for (i=0; i < num_entries; ++i) {
+ pal[i][2] = get8u(s);
+ pal[i][1] = get8u(s);
+ pal[i][0] = get8u(s);
+ pal[i][3] = transp ? 0 : 255;
+ }
+}
+
+static int stbi_gif_header(stbi *s, stbi_gif *g, int *comp, int is_info)
+{
+ uint8 version;
+ if (get8(s) != 'G' || get8(s) != 'I' || get8(s) != 'F' || get8(s) != '8')
+ return e("not GIF", "Corrupt GIF");
+
+ version = get8u(s);
+ if (version != '7' && version != '9') return e("not GIF", "Corrupt GIF");
+ if (get8(s) != 'a') return e("not GIF", "Corrupt GIF");
+
+ failure_reason = "";
+ g->w = get16le(s);
+ g->h = get16le(s);
+ g->flags = get8(s);
+ g->bgindex = get8(s);
+ g->ratio = get8(s);
+ g->transparent = -1;
+
+ if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments
+
+ if (is_info) return 1;
+
+ if (g->flags & 0x80)
+ stbi_gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1);
+
+ return 1;
+}
+
+static int stbi_gif_info_raw(stbi *s, int *x, int *y, int *comp)
+{
+ stbi_gif g;
+ if (!stbi_gif_header(s, &g, comp, 1)) {
+ stbi_rewind( s );
+ return 0;
+ }
+ if (x) *x = g.w;
+ if (y) *y = g.h;
+ return 1;
+}
+
+static void stbi_out_gif_code(stbi_gif *g, uint16 code)
+{
+ uint8 *p, *c;
+
+ // recurse to decode the prefixes, since the linked-list is backwards,
+ // and working backwards through an interleaved image would be nasty
+ if (g->codes[code].prefix >= 0)
+ stbi_out_gif_code(g, g->codes[code].prefix);
+
+ if (g->cur_y >= g->max_y) return;
+
+ p = &g->out[g->cur_x + g->cur_y];
+ c = &g->color_table[g->codes[code].suffix * 4];
+
+ if (c[3] >= 128) {
+ p[0] = c[2];
+ p[1] = c[1];
+ p[2] = c[0];
+ p[3] = c[3];
+ }
+ g->cur_x += 4;
+
+ if (g->cur_x >= g->max_x) {
+ g->cur_x = g->start_x;
+ g->cur_y += g->step;
+
+ while (g->cur_y >= g->max_y && g->parse > 0) {
+ g->step = (1 << g->parse) * g->line_size;
+ g->cur_y = g->start_y + (g->step >> 1);
+ --g->parse;
+ }
+ }
+}
+
+static uint8 *stbi_process_gif_raster(stbi *s, stbi_gif *g)
+{
+ uint8 lzw_cs;
+ int32 len, code;
+ uint32 first;
+ int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear;
+ stbi_gif_lzw *p;
+
+ lzw_cs = get8u(s);
+ clear = 1 << lzw_cs;
+ first = 1;
+ codesize = lzw_cs + 1;
+ codemask = (1 << codesize) - 1;
+ bits = 0;
+ valid_bits = 0;
+ for (code = 0; code < clear; code++) {
+ g->codes[code].prefix = -1;
+ g->codes[code].first = (uint8) code;
+ g->codes[code].suffix = (uint8) code;
+ }
+
+ // support no starting clear code
+ avail = clear+2;
+ oldcode = -1;
+
+ len = 0;
+ for(;;) {
+ if (valid_bits < codesize) {
+ if (len == 0) {
+ len = get8(s); // start new block
+ if (len == 0)
+ return g->out;
+ }
+ --len;
+ bits |= (int32) get8(s) << valid_bits;
+ valid_bits += 8;
+ } else {
+ int32 code = bits & codemask;
+ bits >>= codesize;
+ valid_bits -= codesize;
+ // @OPTIMIZE: is there some way we can accelerate the non-clear path?
+ if (code == clear) { // clear code
+ codesize = lzw_cs + 1;
+ codemask = (1 << codesize) - 1;
+ avail = clear + 2;
+ oldcode = -1;
+ first = 0;
+ } else if (code == clear + 1) { // end of stream code
+ skip(s, len);
+ while ((len = get8(s)) > 0)
+ skip(s,len);
+ return g->out;
+ } else if (code <= avail) {
+ if (first) return epuc("no clear code", "Corrupt GIF");
+
+ if (oldcode >= 0) {
+ p = &g->codes[avail++];
+ if (avail > 4096) return epuc("too many codes", "Corrupt GIF");
+ p->prefix = (int16) oldcode;
+ p->first = g->codes[oldcode].first;
+ p->suffix = (code == avail) ? p->first : g->codes[code].first;
+ } else if (code == avail)
+ return epuc("illegal code in raster", "Corrupt GIF");
+
+ stbi_out_gif_code(g, (uint16) code);
+
+ if ((avail & codemask) == 0 && avail <= 0x0FFF) {
+ codesize++;
+ codemask = (1 << codesize) - 1;
+ }
+
+ oldcode = code;
+ } else {
+ return epuc("illegal code in raster", "Corrupt GIF");
+ }
+ }
+ }
+}
+
+static void stbi_fill_gif_background(stbi_gif *g)
+{
+ int i;
+ uint8 *c = g->pal[g->bgindex];
+ // @OPTIMIZE: write a dword at a time
+ for (i = 0; i < g->w * g->h * 4; i += 4) {
+ uint8 *p = &g->out[i];
+ p[0] = c[2];
+ p[1] = c[1];
+ p[2] = c[0];
+ p[3] = c[3];
+ }
+}
+
+// this function is designed to support animated gifs, although stb_image doesn't support it
+static uint8 *stbi_gif_load_next(stbi *s, stbi_gif *g, int *comp, int req_comp)
+{
+ int i;
+ uint8 *old_out = 0;
+
+ if (g->out == 0) {
+ if (!stbi_gif_header(s, g, comp,0)) return 0; // failure_reason set by stbi_gif_header
+ g->out = (uint8 *) malloc(4 * g->w * g->h);
+ if (g->out == 0) return epuc("outofmem", "Out of memory");
+ stbi_fill_gif_background(g);
+ } else {
+ // animated-gif-only path
+ if (((g->eflags & 0x1C) >> 2) == 3) {
+ old_out = g->out;
+ g->out = (uint8 *) malloc(4 * g->w * g->h);
+ if (g->out == 0) return epuc("outofmem", "Out of memory");
+ memcpy(g->out, old_out, g->w*g->h*4);
+ }
+ }
+
+ for (;;) {
+ switch (get8(s)) {
+ case 0x2C: /* Image Descriptor */
+ {
+ int32 x, y, w, h;
+ uint8 *o;
+
+ x = get16le(s);
+ y = get16le(s);
+ w = get16le(s);
+ h = get16le(s);
+ if (((x + w) > (g->w)) || ((y + h) > (g->h)))
+ return epuc("bad Image Descriptor", "Corrupt GIF");
+
+ g->line_size = g->w * 4;
+ g->start_x = x * 4;
+ g->start_y = y * g->line_size;
+ g->max_x = g->start_x + w * 4;
+ g->max_y = g->start_y + h * g->line_size;
+ g->cur_x = g->start_x;
+ g->cur_y = g->start_y;
+
+ g->lflags = get8(s);
+
+ if (g->lflags & 0x40) {
+ g->step = 8 * g->line_size; // first interlaced spacing
+ g->parse = 3;
+ } else {
+ g->step = g->line_size;
+ g->parse = 0;
+ }
+
+ if (g->lflags & 0x80) {
+ stbi_gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1);
+ g->color_table = (uint8 *) g->lpal;
+ } else if (g->flags & 0x80) {
+ for (i=0; i < 256; ++i) // @OPTIMIZE: reset only the previous transparent
+ g->pal[i][3] = 255;
+ if (g->transparent >= 0 && (g->eflags & 0x01))
+ g->pal[g->transparent][3] = 0;
+ g->color_table = (uint8 *) g->pal;
+ } else
+ return epuc("missing color table", "Corrupt GIF");
+
+ o = stbi_process_gif_raster(s, g);
+ if (o == NULL) return NULL;
+
+ if (req_comp && req_comp != 4)
+ o = convert_format(o, 4, req_comp, g->w, g->h);
+ return o;
+ }
+
+ case 0x21: // Comment Extension.
+ {
+ int len;
+ if (get8(s) == 0xF9) { // Graphic Control Extension.
+ len = get8(s);
+ if (len == 4) {
+ g->eflags = get8(s);
+ get16le(s); // delay
+ g->transparent = get8(s);
+ } else {
+ skip(s, len);
+ break;
+ }
+ }
+ while ((len = get8(s)) != 0)
+ skip(s, len);
+ break;
+ }
+
+ case 0x3B: // gif stream termination code
+ return (uint8 *) 1;
+
+ default:
+ return epuc("unknown code", "Corrupt GIF");
+ }
+ }
+}
+
+static stbi_uc *stbi_gif_load(stbi *s, int *x, int *y, int *comp, int req_comp)
+{
+ uint8 *u = 0;
+ stbi_gif g={0};
+
+ u = stbi_gif_load_next(s, &g, comp, req_comp);
+ if (u == (void *) 1) u = 0; // end of animated gif marker
+ if (u) {
+ *x = g.w;
+ *y = g.h;
+ }
+
+ return u;
+}
+
+static int stbi_gif_info(stbi *s, int *x, int *y, int *comp)
+{
+ return stbi_gif_info_raw(s,x,y,comp);
+}
+
+
+// *************************************************************************************************
+// Radiance RGBE HDR loader
+// originally by Nicolas Schulz
+#ifndef STBI_NO_HDR
+static int hdr_test(stbi *s)
+{
+ const char *signature = "#?RADIANCE\n";
+ int i;
+ for (i=0; signature[i]; ++i)
+ if (get8(s) != signature[i])
+ return 0;
+ return 1;
+}
+
+static int stbi_hdr_test(stbi* s)
+{
+ int r = hdr_test(s);
+ stbi_rewind(s);
+ return r;
+}
+
+#define HDR_BUFLEN 1024
+static char *hdr_gettoken(stbi *z, char *buffer)
+{
+ int len=0;
+ char c = '\0';
+
+ c = (char) get8(z);
+
+ while (!at_eof(z) && c != '\n') {
+ buffer[len++] = c;
+ if (len == HDR_BUFLEN-1) {
+ // flush to end of line
+ while (!at_eof(z) && get8(z) != '\n')
+ ;
+ break;
+ }
+ c = (char) get8(z);
+ }
+
+ buffer[len] = 0;
+ return buffer;
+}
+
+static void hdr_convert(float *output, stbi_uc *input, int req_comp)
+{
+ if ( input[3] != 0 ) {
+ float f1;
+ // Exponent
+ f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8));
+ if (req_comp <= 2)
+ output[0] = (input[0] + input[1] + input[2]) * f1 / 3;
+ else {
+ output[0] = input[0] * f1;
+ output[1] = input[1] * f1;
+ output[2] = input[2] * f1;
+ }
+ if (req_comp == 2) output[1] = 1;
+ if (req_comp == 4) output[3] = 1;
+ } else {
+ switch (req_comp) {
+ case 4: output[3] = 1; /* fallthrough */
+ case 3: output[0] = output[1] = output[2] = 0;
+ break;
+ case 2: output[1] = 1; /* fallthrough */
+ case 1: output[0] = 0;
+ break;
+ }
+ }
+}
+
+static float *hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp)
+{
+ char buffer[HDR_BUFLEN];
+ char *token;
+ int valid = 0;
+ int width, height;
+ stbi_uc *scanline;
+ float *hdr_data;
+ int len;
+ unsigned char count, value;
+ int i, j, k, c1,c2, z;
+
+
+ // Check identifier
+ if (strcmp(hdr_gettoken(s,buffer), "#?RADIANCE") != 0)
+ return epf("not HDR", "Corrupt HDR image");
+
+ // Parse header
+ for(;;) {
+ token = hdr_gettoken(s,buffer);
+ if (token[0] == 0) break;
+ if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;
+ }
+
+ if (!valid) return epf("unsupported format", "Unsupported HDR format");
+
+ // Parse width and height
+ // can't use sscanf() if we're not using stdio!
+ token = hdr_gettoken(s,buffer);
+ if (strncmp(token, "-Y ", 3)) return epf("unsupported data layout", "Unsupported HDR format");
+ token += 3;
+ height = strtol(token, &token, 10);
+ while (*token == ' ') ++token;
+ if (strncmp(token, "+X ", 3)) return epf("unsupported data layout", "Unsupported HDR format");
+ token += 3;
+ width = strtol(token, NULL, 10);
+
+ *x = width;
+ *y = height;
+
+ *comp = 3;
+ if (req_comp == 0) req_comp = 3;
+
+ // Read data
+ hdr_data = (float *) malloc(height * width * req_comp * sizeof(float));
+
+ // Load image data
+ // image data is stored as some number of sca
+ if ( width < 8 || width >= 32768) {
+ // Read flat data
+ for (j=0; j < height; ++j) {
+ for (i=0; i < width; ++i) {
+ stbi_uc rgbe[4];
+ main_decode_loop:
+ getn(s, rgbe, 4);
+ hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp);
+ }
+ }
+ } else {
+ // Read RLE-encoded data
+ scanline = NULL;
+
+ for (j = 0; j < height; ++j) {
+ c1 = get8(s);
+ c2 = get8(s);
+ len = get8(s);
+ if (c1 != 2 || c2 != 2 || (len & 0x80)) {
+ // not run-length encoded, so we have to actually use THIS data as a decoded
+ // pixel (note this can't be a valid pixel--one of RGB must be >= 128)
+ uint8 rgbe[4];
+ rgbe[0] = (uint8) c1;
+ rgbe[1] = (uint8) c2;
+ rgbe[2] = (uint8) len;
+ rgbe[3] = (uint8) get8u(s);
+ hdr_convert(hdr_data, rgbe, req_comp);
+ i = 1;
+ j = 0;
+ free(scanline);
+ goto main_decode_loop; // yes, this makes no sense
+ }
+ len <<= 8;
+ len |= get8(s);
+ if (len != width) { free(hdr_data); free(scanline); return epf("invalid decoded scanline length", "corrupt HDR"); }
+ if (scanline == NULL) scanline = (stbi_uc *) malloc(width * 4);
+
+ for (k = 0; k < 4; ++k) {
+ i = 0;
+ while (i < width) {
+ count = get8u(s);
+ if (count > 128) {
+ // Run
+ value = get8u(s);
+ count -= 128;
+ for (z = 0; z < count; ++z)
+ scanline[i++ * 4 + k] = value;
+ } else {
+ // Dump
+ for (z = 0; z < count; ++z)
+ scanline[i++ * 4 + k] = get8u(s);
+ }
+ }
+ }
+ for (i=0; i < width; ++i)
+ hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp);
+ }
+ free(scanline);
+ }
+
+ return hdr_data;
+}
+
+static float *stbi_hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp)
+{
+ return hdr_load(s,x,y,comp,req_comp);
+}
+
+static int stbi_hdr_info(stbi *s, int *x, int *y, int *comp)
+{
+ char buffer[HDR_BUFLEN];
+ char *token;
+ int valid = 0;
+
+ if (strcmp(hdr_gettoken(s,buffer), "#?RADIANCE") != 0) {
+ stbi_rewind( s );
+ return 0;
+ }
+
+ for(;;) {
+ token = hdr_gettoken(s,buffer);
+ if (token[0] == 0) break;
+ if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;
+ }
+
+ if (!valid) {
+ stbi_rewind( s );
+ return 0;
+ }
+ token = hdr_gettoken(s,buffer);
+ if (strncmp(token, "-Y ", 3)) {
+ stbi_rewind( s );
+ return 0;
+ }
+ token += 3;
+ *y = strtol(token, &token, 10);
+ while (*token == ' ') ++token;
+ if (strncmp(token, "+X ", 3)) {
+ stbi_rewind( s );
+ return 0;
+ }
+ token += 3;
+ *x = strtol(token, NULL, 10);
+ *comp = 3;
+ return 1;
+}
+#endif // STBI_NO_HDR
+
+static int stbi_bmp_info(stbi *s, int *x, int *y, int *comp)
+{
+ int hsz;
+ if (get8(s) != 'B' || get8(s) != 'M') {
+ stbi_rewind( s );
+ return 0;
+ }
+ skip(s,12);
+ hsz = get32le(s);
+ if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108) {
+ stbi_rewind( s );
+ return 0;
+ }
+ if (hsz == 12) {
+ *x = get16le(s);
+ *y = get16le(s);
+ } else {
+ *x = get32le(s);
+ *y = get32le(s);
+ }
+ if (get16le(s) != 1) {
+ stbi_rewind( s );
+ return 0;
+ }
+ *comp = get16le(s) / 8;
+ return 1;
+}
+
+static int stbi_psd_info(stbi *s, int *x, int *y, int *comp)
+{
+ int channelCount;
+ if (get32(s) != 0x38425053) {
+ stbi_rewind( s );
+ return 0;
+ }
+ if (get16(s) != 1) {
+ stbi_rewind( s );
+ return 0;
+ }
+ skip(s, 6);
+ channelCount = get16(s);
+ if (channelCount < 0 || channelCount > 16) {
+ stbi_rewind( s );
+ return 0;
+ }
+ *y = get32(s);
+ *x = get32(s);
+ if (get16(s) != 8) {
+ stbi_rewind( s );
+ return 0;
+ }
+ if (get16(s) != 3) {
+ stbi_rewind( s );
+ return 0;
+ }
+ *comp = 4;
+ return 1;
+}
+
+static int stbi_pic_info(stbi *s, int *x, int *y, int *comp)
+{
+ int act_comp=0,num_packets=0,chained;
+ pic_packet_t packets[10];
+
+ skip(s, 92);
+
+ *x = get16(s);
+ *y = get16(s);
+ if (at_eof(s)) return 0;
+ if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) {
+ stbi_rewind( s );
+ return 0;
+ }
+
+ skip(s, 8);
+
+ do {
+ pic_packet_t *packet;
+
+ if (num_packets==sizeof(packets)/sizeof(packets[0]))
+ return 0;
+
+ packet = &packets[num_packets++];
+ chained = get8(s);
+ packet->size = get8u(s);
+ packet->type = get8u(s);
+ packet->channel = get8u(s);
+ act_comp |= packet->channel;
+
+ if (at_eof(s)) {
+ stbi_rewind( s );
+ return 0;
+ }
+ if (packet->size != 8) {
+ stbi_rewind( s );
+ return 0;
+ }
+ } while (chained);
+
+ *comp = (act_comp & 0x10 ? 4 : 3);
+
+ return 1;
+}
+
+static int stbi_info_main(stbi *s, int *x, int *y, int *comp)
+{
+ if (stbi_jpeg_info(s, x, y, comp))
+ return 1;
+ if (stbi_png_info(s, x, y, comp))
+ return 1;
+ if (stbi_gif_info(s, x, y, comp))
+ return 1;
+ if (stbi_bmp_info(s, x, y, comp))
+ return 1;
+ if (stbi_psd_info(s, x, y, comp))
+ return 1;
+ if (stbi_pic_info(s, x, y, comp))
+ return 1;
+ #ifndef STBI_NO_HDR
+ if (stbi_hdr_info(s, x, y, comp))
+ return 1;
+ #endif
+ // test tga last because it's a crappy test!
+ if (stbi_tga_info(s, x, y, comp))
+ return 1;
+ return e("unknown image type", "Image not of any known type, or corrupt");
+}
+
+#ifndef STBI_NO_STDIO
+int stbi_info(char const *filename, int *x, int *y, int *comp)
+{
+ FILE *f = fopen(filename, "rb");
+ int result;
+ if (!f) return e("can't fopen", "Unable to open file");
+ result = stbi_info_from_file(f, x, y, comp);
+ fclose(f);
+ return result;
+}
+
+int stbi_info_from_file(FILE *f, int *x, int *y, int *comp)
+{
+ int r;
+ stbi s;
+ long pos = ftell(f);
+ start_file(&s, f);
+ r = stbi_info_main(&s,x,y,comp);
+ fseek(f,pos,SEEK_SET);
+ return r;
+}
+#endif // !STBI_NO_STDIO
+
+int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp)
+{
+ stbi s;
+ start_mem(&s,buffer,len);
+ return stbi_info_main(&s,x,y,comp);
+}
+
+int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp)
+{
+ stbi s;
+ start_callbacks(&s, (stbi_io_callbacks *) c, user);
+ return stbi_info_main(&s,x,y,comp);
+}
+
+#endif // STBI_HEADER_FILE_ONLY
+
+/*
+ revision history:
+ 1.33 (2011-07-14)
+ make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements
+ 1.32 (2011-07-13)
+ support for "info" function for all supported filetypes (SpartanJ)
+ 1.31 (2011-06-20)
+ a few more leak fixes, bug in PNG handling (SpartanJ)
+ 1.30 (2011-06-11)
+ added ability to load files via callbacks to accomidate custom input streams (Ben Wenger)
+ removed deprecated format-specific test/load functions
+ removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway
+ error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha)
+ fix inefficiency in decoding 32-bit BMP (David Woo)
+ 1.29 (2010-08-16)
+ various warning fixes from Aurelien Pocheville
+ 1.28 (2010-08-01)
+ fix bug in GIF palette transparency (SpartanJ)
+ 1.27 (2010-08-01)
+ cast-to-uint8 to fix warnings
+ 1.26 (2010-07-24)
+ fix bug in file buffering for PNG reported by SpartanJ
+ 1.25 (2010-07-17)
+ refix trans_data warning (Won Chun)
+ 1.24 (2010-07-12)
+ perf improvements reading from files on platforms with lock-heavy fgetc()
+ minor perf improvements for jpeg
+ deprecated type-specific functions so we'll get feedback if they're needed
+ attempt to fix trans_data warning (Won Chun)
+ 1.23 fixed bug in iPhone support
+ 1.22 (2010-07-10)
+ removed image *writing* support
+ stbi_info support from Jetro Lauha
+ GIF support from Jean-Marc Lienher
+ iPhone PNG-extensions from James Brown
+ warning-fixes from Nicolas Schulz and Janez Zemva (i.e. Janez (U+017D)emva)
+ 1.21 fix use of 'uint8' in header (reported by jon blow)
+ 1.20 added support for Softimage PIC, by Tom Seddon
+ 1.19 bug in interlaced PNG corruption check (found by ryg)
+ 1.18 2008-08-02
+ fix a threading bug (local mutable static)
+ 1.17 support interlaced PNG
+ 1.16 major bugfix - convert_format converted one too many pixels
+ 1.15 initialize some fields for thread safety
+ 1.14 fix threadsafe conversion bug
+ header-file-only version (#define STBI_HEADER_FILE_ONLY before including)
+ 1.13 threadsafe
+ 1.12 const qualifiers in the API
+ 1.11 Support installable IDCT, colorspace conversion routines
+ 1.10 Fixes for 64-bit (don't use "unsigned long")
+ optimized upsampling by Fabian "ryg" Giesen
+ 1.09 Fix format-conversion for PSD code (bad global variables!)
+ 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz
+ 1.07 attempt to fix C++ warning/errors again
+ 1.06 attempt to fix C++ warning/errors again
+ 1.05 fix TGA loading to return correct *comp and use good luminance calc
+ 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free
+ 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR
+ 1.02 support for (subset of) HDR files, float interface for preferred access to them
+ 1.01 fix bug: possible bug in handling right-side up bmps... not sure
+ fix bug: the stbi_bmp_load() and stbi_tga_load() functions didn't work at all
+ 1.00 interface to zlib that skips zlib header
+ 0.99 correct handling of alpha in palette
+ 0.98 TGA loader by lonesock; dynamically add loaders (untested)
+ 0.97 jpeg errors on too large a file; also catch another malloc failure
+ 0.96 fix detection of invalid v value - particleman@mollyrocket forum
+ 0.95 during header scan, seek to markers in case of padding
+ 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same
+ 0.93 handle jpegtran output; verbose errors
+ 0.92 read 4,8,16,24,32-bit BMP files of several formats
+ 0.91 output 24-bit Windows 3.0 BMP files
+ 0.90 fix a few more warnings; bump version number to approach 1.0
+ 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd
+ 0.60 fix compiling as c++
+ 0.59 fix warnings: merge Dave Moore's -Wall fixes
+ 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian
+ 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available
+ 0.56 fix bug: zlib uncompressed mode len vs. nlen
+ 0.55 fix bug: restart_interval not initialized to 0
+ 0.54 allow NULL for 'int *comp'
+ 0.53 fix bug in png 3->4; speedup png decoding
+ 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments
+ 0.51 obey req_comp requests, 1-component jpegs return as 1-component,
+ on 'test' only check type, not whether we support this variant
+ 0.50 first released version
+*/
diff --git a/src/SFML/Graphics/stb_image/stb_image_write.h b/src/SFML/Graphics/stb_image/stb_image_write.h
new file mode 100644
index 0000000..b9f7aae
--- /dev/null
+++ b/src/SFML/Graphics/stb_image/stb_image_write.h
@@ -0,0 +1,511 @@
+/* stbiw-0.92 - public domain - http://nothings.org/stb/stb_image_write.h
+ writes out PNG/BMP/TGA images to C stdio - Sean Barrett 2010
+ no warranty implied; use at your own risk
+
+
+Before including,
+
+ #define STB_IMAGE_WRITE_IMPLEMENTATION
+
+in the file that you want to have the implementation.
+
+
+ABOUT:
+
+ This header file is a library for writing images to C stdio. It could be
+ adapted to write to memory or a general streaming interface; let me know.
+
+ The PNG output is not optimal; it is 20-50% larger than the file
+ written by a decent optimizing implementation. This library is designed
+ for source code compactness and simplicitly, not optimal image file size
+ or run-time performance.
+
+USAGE:
+
+ There are three functions, one for each image file format:
+
+ int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes);
+ int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data);
+ int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data);
+
+ Each function returns 0 on failure and non-0 on success.
+
+ The functions create an image file defined by the parameters. The image
+ is a rectangle of pixels stored from left-to-right, top-to-bottom.
+ Each pixel contains 'comp' channels of data stored interleaved with 8-bits
+ per channel, in the following order: 1=Y, 2=YA, 3=RGB, 4=RGBA. (Y is
+ monochrome color.) The rectangle is 'w' pixels wide and 'h' pixels tall.
+ The *data pointer points to the first byte of the top-left-most pixel.
+ For PNG, "stride_in_bytes" is the distance in bytes from the first byte of
+ a row of pixels to the first byte of the next row of pixels.
+
+ PNG creates output files with the same number of components as the input.
+ The BMP and TGA formats expand Y to RGB in the file format. BMP does not
+ output alpha.
+
+ PNG supports writing rectangles of data even when the bytes storing rows of
+ data are not consecutive in memory (e.g. sub-rectangles of a larger image),
+ by supplying the stride between the beginning of adjacent rows. The other
+ formats do not. (Thus you cannot write a native-format BMP through the BMP
+ writer, both because it is in BGR order and because it may have padding
+ at the end of the line.)
+*/
+
+#ifndef INCLUDE_STB_IMAGE_WRITE_H
+#define INCLUDE_STB_IMAGE_WRITE_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes);
+extern int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data);
+extern int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif//INCLUDE_STB_IMAGE_WRITE_H
+
+#ifdef STB_IMAGE_WRITE_IMPLEMENTATION
+
+#include <stdarg.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <assert.h>
+
+typedef unsigned int stbiw_uint32;
+typedef int stb_image_write_test[sizeof(stbiw_uint32)==4 ? 1 : -1];
+
+static void writefv(FILE *f, const char *fmt, va_list v)
+{
+ while (*fmt) {
+ switch (*fmt++) {
+ case ' ': break;
+ case '1': { unsigned char x = (unsigned char) va_arg(v, int); fputc(x,f); break; }
+ case '2': { int x = va_arg(v,int); unsigned char b[2];
+ b[0] = (unsigned char) x; b[1] = (unsigned char) (x>>8);
+ fwrite(b,2,1,f); break; }
+ case '4': { stbiw_uint32 x = va_arg(v,int); unsigned char b[4];
+ b[0]=(unsigned char)x; b[1]=(unsigned char)(x>>8);
+ b[2]=(unsigned char)(x>>16); b[3]=(unsigned char)(x>>24);
+ fwrite(b,4,1,f); break; }
+ default:
+ assert(0);
+ return;
+ }
+ }
+}
+
+static void write3(FILE *f, unsigned char a, unsigned char b, unsigned char c)
+{
+ unsigned char arr[3];
+ arr[0] = a, arr[1] = b, arr[2] = c;
+ fwrite(arr, 3, 1, f);
+}
+
+static void write_pixels(FILE *f, int rgb_dir, int vdir, int x, int y, int comp, void *data, int write_alpha, int scanline_pad)
+{
+ unsigned char bg[3] = { 255, 0, 255}, px[3];
+ stbiw_uint32 zero = 0;
+ int i,j,k, j_end;
+
+ if (y <= 0)
+ return;
+
+ if (vdir < 0)
+ j_end = -1, j = y-1;
+ else
+ j_end = y, j = 0;
+
+ for (; j != j_end; j += vdir) {
+ for (i=0; i < x; ++i) {
+ unsigned char *d = (unsigned char *) data + (j*x+i)*comp;
+ if (write_alpha < 0)
+ fwrite(&d[comp-1], 1, 1, f);
+ switch (comp) {
+ case 1:
+ case 2: write3(f, d[0],d[0],d[0]);
+ break;
+ case 4:
+ if (!write_alpha) {
+ // composite against pink background
+ for (k=0; k < 3; ++k)
+ px[k] = bg[k] + ((d[k] - bg[k]) * d[3])/255;
+ write3(f, px[1-rgb_dir],px[1],px[1+rgb_dir]);
+ break;
+ }
+ /* FALLTHROUGH */
+ case 3:
+ write3(f, d[1-rgb_dir],d[1],d[1+rgb_dir]);
+ break;
+ }
+ if (write_alpha > 0)
+ fwrite(&d[comp-1], 1, 1, f);
+ }
+ fwrite(&zero,scanline_pad,1,f);
+ }
+}
+
+static int outfile(char const *filename, int rgb_dir, int vdir, int x, int y, int comp, void *data, int alpha, int pad, const char *fmt, ...)
+{
+ FILE *f;
+ if (y < 0 || x < 0) return 0;
+ f = fopen(filename, "wb");
+ if (f) {
+ va_list v;
+ va_start(v, fmt);
+ writefv(f, fmt, v);
+ va_end(v);
+ write_pixels(f,rgb_dir,vdir,x,y,comp,data,alpha,pad);
+ fclose(f);
+ }
+ return f != NULL;
+}
+
+int stbi_write_bmp(char const *filename, int x, int y, int comp, const void *data)
+{
+ int pad = (-x*3) & 3;
+ return outfile(filename,-1,-1,x,y,comp,(void *) data,0,pad,
+ "11 4 22 4" "4 44 22 444444",
+ 'B', 'M', 14+40+(x*3+pad)*y, 0,0, 14+40, // file header
+ 40, x,y, 1,24, 0,0,0,0,0,0); // bitmap header
+}
+
+int stbi_write_tga(char const *filename, int x, int y, int comp, const void *data)
+{
+ int has_alpha = !(comp & 1);
+ return outfile(filename, -1,-1, x, y, comp, (void *) data, has_alpha, 0,
+ "111 221 2222 11", 0,0,2, 0,0,0, 0,0,x,y, 24+8*has_alpha, 8*has_alpha);
+}
+
+// stretchy buffer; stbi__sbpush() == vector<>::push_back() -- stbi__sbcount() == vector<>::size()
+#define stbi__sbraw(a) ((int *) (a) - 2)
+#define stbi__sbm(a) stbi__sbraw(a)[0]
+#define stbi__sbn(a) stbi__sbraw(a)[1]
+
+#define stbi__sbneedgrow(a,n) ((a)==0 || stbi__sbn(a)+n >= stbi__sbm(a))
+#define stbi__sbmaybegrow(a,n) (stbi__sbneedgrow(a,(n)) ? stbi__sbgrow(a,n) : 0)
+#define stbi__sbgrow(a,n) stbi__sbgrowf((void **) &(a), (n), sizeof(*(a)))
+
+#define stbi__sbpush(a, v) (stbi__sbmaybegrow(a,1), (a)[stbi__sbn(a)++] = (v))
+#define stbi__sbcount(a) ((a) ? stbi__sbn(a) : 0)
+#define stbi__sbfree(a) ((a) ? free(stbi__sbraw(a)),0 : 0)
+
+static void *stbi__sbgrowf(void **arr, int increment, int itemsize)
+{
+ int m = *arr ? 2*stbi__sbm(*arr)+increment : increment+1;
+ void *p = realloc(*arr ? stbi__sbraw(*arr) : 0, itemsize * m + sizeof(int)*2);
+ assert(p);
+ if (p) {
+ if (!*arr) ((int *) p)[1] = 0;
+ *arr = (void *) ((int *) p + 2);
+ stbi__sbm(*arr) = m;
+ }
+ return *arr;
+}
+
+static unsigned char *stbi__zlib_flushf(unsigned char *data, unsigned int *bitbuffer, int *bitcount)
+{
+ while (*bitcount >= 8) {
+ stbi__sbpush(data, (unsigned char) *bitbuffer);
+ *bitbuffer >>= 8;
+ *bitcount -= 8;
+ }
+ return data;
+}
+
+static int stbi__zlib_bitrev(int code, int codebits)
+{
+ int res=0;
+ while (codebits--) {
+ res = (res << 1) | (code & 1);
+ code >>= 1;
+ }
+ return res;
+}
+
+static unsigned int stbi__zlib_countm(unsigned char *a, unsigned char *b, int limit)
+{
+ int i;
+ for (i=0; i < limit && i < 258; ++i)
+ if (a[i] != b[i]) break;
+ return i;
+}
+
+static unsigned int stbi__zhash(unsigned char *data)
+{
+ stbiw_uint32 hash = data[0] + (data[1] << 8) + (data[2] << 16);
+ hash ^= hash << 3;
+ hash += hash >> 5;
+ hash ^= hash << 4;
+ hash += hash >> 17;
+ hash ^= hash << 25;
+ hash += hash >> 6;
+ return hash;
+}
+
+#define stbi__zlib_flush() (out = stbi__zlib_flushf(out, &bitbuf, &bitcount))
+#define stbi__zlib_add(code,codebits) \
+ (bitbuf |= (code) << bitcount, bitcount += (codebits), stbi__zlib_flush())
+#define stbi__zlib_huffa(b,c) stbi__zlib_add(stbi__zlib_bitrev(b,c),c)
+// default huffman tables
+#define stbi__zlib_huff1(n) stbi__zlib_huffa(0x30 + (n), 8)
+#define stbi__zlib_huff2(n) stbi__zlib_huffa(0x190 + (n)-144, 9)
+#define stbi__zlib_huff3(n) stbi__zlib_huffa(0 + (n)-256,7)
+#define stbi__zlib_huff4(n) stbi__zlib_huffa(0xc0 + (n)-280,8)
+#define stbi__zlib_huff(n) ((n) <= 143 ? stbi__zlib_huff1(n) : (n) <= 255 ? stbi__zlib_huff2(n) : (n) <= 279 ? stbi__zlib_huff3(n) : stbi__zlib_huff4(n))
+#define stbi__zlib_huffb(n) ((n) <= 143 ? stbi__zlib_huff1(n) : stbi__zlib_huff2(n))
+
+#define stbi__ZHASH 16384
+
+unsigned char * stbi_zlib_compress(unsigned char *data, int data_len, int *out_len, int quality)
+{
+ static unsigned short lengthc[] = { 3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258, 259 };
+ static unsigned char lengtheb[]= { 0,0,0,0,0,0,0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 };
+ static unsigned short distc[] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577, 32768 };
+ static unsigned char disteb[] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13 };
+ unsigned int bitbuf=0;
+ int i,j, bitcount=0;
+ unsigned char *out = NULL;
+ unsigned char **hash_table[stbi__ZHASH]; // 64KB on the stack!
+ if (quality < 5) quality = 5;
+
+ stbi__sbpush(out, 0x78); // DEFLATE 32K window
+ stbi__sbpush(out, 0x5e); // FLEVEL = 1
+ stbi__zlib_add(1,1); // BFINAL = 1
+ stbi__zlib_add(1,2); // BTYPE = 1 -- fixed huffman
+
+ for (i=0; i < stbi__ZHASH; ++i)
+ hash_table[i] = NULL;
+
+ i=0;
+ while (i < data_len-3) {
+ // hash next 3 bytes of data to be compressed
+ int h = stbi__zhash(data+i)&(stbi__ZHASH-1), best=3;
+ unsigned char *bestloc = 0;
+ unsigned char **hlist = hash_table[h];
+ int n = stbi__sbcount(hlist);
+ for (j=0; j < n; ++j) {
+ if (hlist[j]-data > i-32768) { // if entry lies within window
+ int d = stbi__zlib_countm(hlist[j], data+i, data_len-i);
+ if (d >= best) best=d,bestloc=hlist[j];
+ }
+ }
+ // when hash table entry is too long, delete half the entries
+ if (hash_table[h] && stbi__sbn(hash_table[h]) == 2*quality) {
+ memcpy(hash_table[h], hash_table[h]+quality, sizeof(hash_table[h][0])*quality);
+ stbi__sbn(hash_table[h]) = quality;
+ }
+ stbi__sbpush(hash_table[h],data+i);
+
+ if (bestloc) {
+ // "lazy matching" - check match at *next* byte, and if it's better, do cur byte as literal
+ h = stbi__zhash(data+i+1)&(stbi__ZHASH-1);
+ hlist = hash_table[h];
+ n = stbi__sbcount(hlist);
+ for (j=0; j < n; ++j) {
+ if (hlist[j]-data > i-32767) {
+ int e = stbi__zlib_countm(hlist[j], data+i+1, data_len-i-1);
+ if (e > best) { // if next match is better, bail on current match
+ bestloc = NULL;
+ break;
+ }
+ }
+ }
+ }
+
+ if (bestloc) {
+ int d = data+i - bestloc; // distance back
+ assert(d <= 32767 && best <= 258);
+ for (j=0; best > lengthc[j+1]-1; ++j);
+ stbi__zlib_huff(j+257);
+ if (lengtheb[j]) stbi__zlib_add(best - lengthc[j], lengtheb[j]);
+ for (j=0; d > distc[j+1]-1; ++j);
+ stbi__zlib_add(stbi__zlib_bitrev(j,5),5);
+ if (disteb[j]) stbi__zlib_add(d - distc[j], disteb[j]);
+ i += best;
+ } else {
+ stbi__zlib_huffb(data[i]);
+ ++i;
+ }
+ }
+ // write out final bytes
+ for (;i < data_len; ++i)
+ stbi__zlib_huffb(data[i]);
+ stbi__zlib_huff(256); // end of block
+ // pad with 0 bits to byte boundary
+ while (bitcount)
+ stbi__zlib_add(0,1);
+
+ for (i=0; i < stbi__ZHASH; ++i)
+ (void) stbi__sbfree(hash_table[i]);
+
+ {
+ // compute adler32 on input
+ unsigned int i=0, s1=1, s2=0, blocklen = data_len % 5552;
+ int j=0;
+ while (j < data_len) {
+ for (i=0; i < blocklen; ++i) s1 += data[j+i], s2 += s1;
+ s1 %= 65521, s2 %= 65521;
+ j += blocklen;
+ blocklen = 5552;
+ }
+ stbi__sbpush(out, (unsigned char) (s2 >> 8));
+ stbi__sbpush(out, (unsigned char) s2);
+ stbi__sbpush(out, (unsigned char) (s1 >> 8));
+ stbi__sbpush(out, (unsigned char) s1);
+ }
+ *out_len = stbi__sbn(out);
+ // make returned pointer freeable
+ memmove(stbi__sbraw(out), out, *out_len);
+ return (unsigned char *) stbi__sbraw(out);
+}
+
+unsigned int stbi__crc32(unsigned char *buffer, int len)
+{
+ static unsigned int crc_table[256];
+ unsigned int crc = ~0u;
+ int i,j;
+ if (crc_table[1] == 0)
+ for(i=0; i < 256; i++)
+ for (crc_table[i]=i, j=0; j < 8; ++j)
+ crc_table[i] = (crc_table[i] >> 1) ^ (crc_table[i] & 1 ? 0xedb88320 : 0);
+ for (i=0; i < len; ++i)
+ crc = (crc >> 8) ^ crc_table[buffer[i] ^ (crc & 0xff)];
+ return ~crc;
+}
+
+#define stbi__wpng4(o,a,b,c,d) ((o)[0]=(unsigned char)(a),(o)[1]=(unsigned char)(b),(o)[2]=(unsigned char)(c),(o)[3]=(unsigned char)(d),(o)+=4)
+#define stbi__wp32(data,v) stbi__wpng4(data, (v)>>24,(v)>>16,(v)>>8,(v));
+#define stbi__wptag(data,s) stbi__wpng4(data, s[0],s[1],s[2],s[3])
+
+static void stbi__wpcrc(unsigned char **data, int len)
+{
+ unsigned int crc = stbi__crc32(*data - len - 4, len+4);
+ stbi__wp32(*data, crc);
+}
+
+static unsigned char stbi__paeth(int a, int b, int c)
+{
+ int p = a + b - c, pa = abs(p-a), pb = abs(p-b), pc = abs(p-c);
+ if (pa <= pb && pa <= pc) return (unsigned char) a;
+ if (pb <= pc) return (unsigned char) b;
+ return (unsigned char) c;
+}
+
+unsigned char *stbi_write_png_to_mem(unsigned char *pixels, int stride_bytes, int x, int y, int n, int *out_len)
+{
+ int ctype[5] = { -1, 0, 4, 2, 6 };
+ unsigned char sig[8] = { 137,80,78,71,13,10,26,10 };
+ unsigned char *out,*o, *filt, *zlib;
+ signed char *line_buffer;
+ int i,j,k,p,zlen;
+
+ if (stride_bytes == 0)
+ stride_bytes = x * n;
+
+ filt = (unsigned char *) malloc((x*n+1) * y); if (!filt) return 0;
+ line_buffer = (signed char *) malloc(x * n); if (!line_buffer) { free(filt); return 0; }
+ for (j=0; j < y; ++j) {
+ static int mapping[] = { 0,1,2,3,4 };
+ static int firstmap[] = { 0,1,0,5,6 };
+ int *mymap = j ? mapping : firstmap;
+ int best = 0, bestval = 0x7fffffff;
+ for (p=0; p < 2; ++p) {
+ for (k= p?best:0; k < 5; ++k) {
+ int type = mymap[k],est=0;
+ unsigned char *z = pixels + stride_bytes*j;
+ for (i=0; i < n; ++i)
+ switch (type) {
+ case 0: line_buffer[i] = z[i]; break;
+ case 1: line_buffer[i] = z[i]; break;
+ case 2: line_buffer[i] = z[i] - z[i-stride_bytes]; break;
+ case 3: line_buffer[i] = z[i] - (z[i-stride_bytes]>>1); break;
+ case 4: line_buffer[i] = (signed char) (z[i] - stbi__paeth(0,z[i-stride_bytes],0)); break;
+ case 5: line_buffer[i] = z[i]; break;
+ case 6: line_buffer[i] = z[i]; break;
+ }
+ for (i=n; i < x*n; ++i) {
+ switch (type) {
+ case 0: line_buffer[i] = z[i]; break;
+ case 1: line_buffer[i] = z[i] - z[i-n]; break;
+ case 2: line_buffer[i] = z[i] - z[i-stride_bytes]; break;
+ case 3: line_buffer[i] = z[i] - ((z[i-n] + z[i-stride_bytes])>>1); break;
+ case 4: line_buffer[i] = z[i] - stbi__paeth(z[i-n], z[i-stride_bytes], z[i-stride_bytes-n]); break;
+ case 5: line_buffer[i] = z[i] - (z[i-n]>>1); break;
+ case 6: line_buffer[i] = z[i] - stbi__paeth(z[i-n], 0,0); break;
+ }
+ }
+ if (p) break;
+ for (i=0; i < x*n; ++i)
+ est += abs((signed char) line_buffer[i]);
+ if (est < bestval) { bestval = est; best = k; }
+ }
+ }
+ // when we get here, best contains the filter type, and line_buffer contains the data
+ filt[j*(x*n+1)] = (unsigned char) best;
+ memcpy(filt+j*(x*n+1)+1, line_buffer, x*n);
+ }
+ free(line_buffer);
+ zlib = stbi_zlib_compress(filt, y*( x*n+1), &zlen, 8); // increase 8 to get smaller but use more memory
+ free(filt);
+ if (!zlib) return 0;
+
+ // each tag requires 12 bytes of overhead
+ out = (unsigned char *) malloc(8 + 12+13 + 12+zlen + 12);
+ if (!out) return 0;
+ *out_len = 8 + 12+13 + 12+zlen + 12;
+
+ o=out;
+ memcpy(o,sig,8); o+= 8;
+ stbi__wp32(o, 13); // header length
+ stbi__wptag(o, "IHDR");
+ stbi__wp32(o, x);
+ stbi__wp32(o, y);
+ *o++ = 8;
+ *o++ = (unsigned char) ctype[n];
+ *o++ = 0;
+ *o++ = 0;
+ *o++ = 0;
+ stbi__wpcrc(&o,13);
+
+ stbi__wp32(o, zlen);
+ stbi__wptag(o, "IDAT");
+ memcpy(o, zlib, zlen); o += zlen; free(zlib);
+ stbi__wpcrc(&o, zlen);
+
+ stbi__wp32(o,0);
+ stbi__wptag(o, "IEND");
+ stbi__wpcrc(&o,0);
+
+ assert(o == out + *out_len);
+
+ return out;
+}
+
+int stbi_write_png(char const *filename, int x, int y, int comp, const void *data, int stride_bytes)
+{
+ FILE *f;
+ int len;
+ unsigned char *png = stbi_write_png_to_mem((unsigned char *) data, stride_bytes, x, y, comp, &len);
+ if (!png) return 0;
+ f = fopen(filename, "wb");
+ if (!f) { free(png); return 0; }
+ fwrite(png, 1, len, f);
+ fclose(f);
+ free(png);
+ return 1;
+}
+#endif // STB_IMAGE_WRITE_IMPLEMENTATION
+
+/* Revision history
+
+ 0.92 (2010-08-01)
+ casts to unsigned char to fix warnings
+ 0.91 (2010-07-17)
+ first public release
+ 0.90 first internal release
+*/
diff --git a/src/SFML/Main/CMakeLists.txt b/src/SFML/Main/CMakeLists.txt
new file mode 100644
index 0000000..2a3575e
--- /dev/null
+++ b/src/SFML/Main/CMakeLists.txt
@@ -0,0 +1,21 @@
+
+# sources
+set(SRC
+ ${PROJECT_SOURCE_DIR}/src/SFML/Main/SFML_Main.cpp
+)
+source_group("" FILES ${SRC})
+
+# define the sfml-main target
+add_library(sfml-main STATIC ${SRC})
+
+# set the debug suffix
+set_target_properties(sfml-main PROPERTIES DEBUG_POSTFIX -d)
+
+# insert the major version number in the output filename
+set_target_properties(sfml-main PROPERTIES OUTPUT_NAME "sfml-main")
+
+# set the target's folder (for IDEs that support it, e.g. Visual Studio)
+set_target_properties(sfml-main PROPERTIES FOLDER "SFML")
+
+# setup the install rule
+install(TARGETS sfml-main ARCHIVE DESTINATION lib${LIB_SUFFIX} COMPONENT devel)
diff --git a/src/SFML/Main/SFML_Main.cpp b/src/SFML/Main/SFML_Main.cpp
index a39d0c1..b4d04a3 100755..100644
--- a/src/SFML/Main/SFML_Main.cpp
+++ b/src/SFML/Main/SFML_Main.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
diff --git a/src/SFML/Makefile b/src/SFML/Makefile
deleted file mode 100755
index d8f633e..0000000
--- a/src/SFML/Makefile
+++ /dev/null
@@ -1,67 +0,0 @@
-export DEBUGBUILD = no
-export STATIC = no
-
-ifeq ($(DEBUGBUILD), yes)
- DEBUGFLAGS = -g -DDEBUG
-else
- DEBUGFLAGS = -O2 -DNDEBUG
-endif
-
-ifeq ($(STATIC), no)
- BUILDFLAGS = -fPIC
- LINKFLAGS = -shared
-else
- BUILDFLAGS =
- LINKFLAGS =
-endif
-
-export CC = gcc
-export CPP = g++
-export CFLAGS = -W -Wall -pedantic -I../../../include -I../../ $(DEBUGFLAGS) $(BUILDFLAGS)
-export CFLAGSEXT = -I../../../include -I../.. $(DEBUGFLAGS) $(BUILDFLAGS)
-export LDFLAGS = $(LINKFLAGS)
-export LIBPATH = ../../../lib
-export VERSION = 1.6
-export CP = cp
-export LN = ln
-export LNFLAGS = -s -f
-export AR = ar
-export ARFLAGS = rcs
-export DESTDIR = /usr/local
-export DESTLIBDIR = $(DESTDIR)/lib
-export DESTINCDIR = $(DESTDIR)/include
-
-all: sfml-system sfml-window sfml-network sfml-graphics sfml-audio
-
-sfml-system:
- @(mkdir -p ../../lib)
- @(cd ./System && $(MAKE))
-
-sfml-window:
- @(mkdir -p ../../lib)
- @(cd ./Window && $(MAKE))
-
-sfml-network:
- @(mkdir -p ../../lib)
- @(cd ./Network && $(MAKE))
-
-sfml-graphics:
- @(mkdir -p ../../lib)
- @(cd ./Graphics && $(MAKE))
-
-sfml-audio:
- @(mkdir -p ../../lib)
- @(cd ./Audio && $(MAKE))
-
-.PHONY: clean mrproper
-
-clean:
- @(cd ./System && $(MAKE) $@ && cd ../Window && $(MAKE) $@ && cd ../Network && $(MAKE) $@ && cd ../Graphics && $(MAKE) $@ && cd ../Audio && $(MAKE) $@)
-
-mrproper: clean
- @(cd ./System && $(MAKE) $@ && cd ../Window && $(MAKE) $@ && cd ../Network && $(MAKE) $@ && cd ../Graphics && $(MAKE) $@ && cd ../Audio && $(MAKE) $@)
-
-install:
- @(mkdir -p $(DESTLIBDIR))
- @(mkdir -p $(DESTINCDIR))
- @(cd ./System && $(MAKE) $@ && cd ../Window && $(MAKE) $@ && cd ../Network && $(MAKE) $@ && cd ../Graphics && $(MAKE) $@ && cd ../Audio && $(MAKE) $@ && $(CP) -r ../../../include/SFML/ $(DESTINCDIR)/)
diff --git a/src/SFML/Network/CMakeLists.txt b/src/SFML/Network/CMakeLists.txt
new file mode 100644
index 0000000..fdf3966
--- /dev/null
+++ b/src/SFML/Network/CMakeLists.txt
@@ -0,0 +1,57 @@
+
+set(INCROOT ${PROJECT_SOURCE_DIR}/include/SFML/Network)
+set(SRCROOT ${PROJECT_SOURCE_DIR}/src/SFML/Network)
+
+# all source files
+set(SRC
+ ${INCROOT}/Export.hpp
+ ${SRCROOT}/Ftp.cpp
+ ${INCROOT}/Ftp.hpp
+ ${SRCROOT}/Http.cpp
+ ${INCROOT}/Http.hpp
+ ${SRCROOT}/IpAddress.cpp
+ ${INCROOT}/IpAddress.hpp
+ ${SRCROOT}/Packet.cpp
+ ${INCROOT}/Packet.hpp
+ ${SRCROOT}/Socket.cpp
+ ${INCROOT}/Socket.hpp
+ ${SRCROOT}/SocketImpl.hpp
+ ${INCROOT}/SocketHandle.hpp
+ ${SRCROOT}/SocketSelector.cpp
+ ${INCROOT}/SocketSelector.hpp
+ ${SRCROOT}/TcpListener.cpp
+ ${INCROOT}/TcpListener.hpp
+ ${SRCROOT}/TcpSocket.cpp
+ ${INCROOT}/TcpSocket.hpp
+ ${SRCROOT}/UdpSocket.cpp
+ ${INCROOT}/UdpSocket.hpp
+)
+
+# add platform specific sources
+if(WINDOWS)
+ set(SRC
+ ${SRC}
+ ${SRCROOT}/Win32/SocketImpl.cpp
+ ${SRCROOT}/Win32/SocketImpl.hpp
+ )
+else()
+ set(SRC
+ ${SRC}
+ ${SRCROOT}/Unix/SocketImpl.cpp
+ ${SRCROOT}/Unix/SocketImpl.hpp
+ )
+endif()
+
+source_group("" FILES ${SRC})
+
+# build the list of external libraries to link
+set(NETWORK_EXT_LIBS)
+if(WINDOWS)
+ set(NETWORK_EXT_LIBS ${NETWORK_EXT_LIBS} ws2_32)
+endif()
+
+# define the sfml-network target
+sfml_add_library(sfml-network
+ SOURCES ${SRC}
+ DEPENDS sfml-system
+ EXTERNAL_LIBS ${NETWORK_EXT_LIBS})
diff --git a/src/SFML/Network/Ftp.cpp b/src/SFML/Network/Ftp.cpp
index c53322c..b2fe846 100755..100644
--- a/src/SFML/Network/Ftp.cpp
+++ b/src/SFML/Network/Ftp.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -26,7 +26,7 @@
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Network/Ftp.hpp>
-#include <SFML/Network/IPAddress.hpp>
+#include <SFML/Network/IpAddress.hpp>
#include <algorithm>
#include <fstream>
#include <iterator>
@@ -36,509 +36,431 @@
namespace sf
{
////////////////////////////////////////////////////////////
-// Utility class for exchanging stuff with the server
-// on the data channel
-////////////////////////////////////////////////////////////
class Ftp::DataChannel : NonCopyable
{
public :
////////////////////////////////////////////////////////////
- // Constructor
- ////////////////////////////////////////////////////////////
- DataChannel(Ftp& Owner);
+ DataChannel(Ftp& owner);
////////////////////////////////////////////////////////////
- // Destructor
- ////////////////////////////////////////////////////////////
- ~DataChannel();
+ Ftp::Response open(Ftp::TransferMode mode);
////////////////////////////////////////////////////////////
- // Open the data channel using the specified mode and port
- ////////////////////////////////////////////////////////////
- Ftp::Response Open(Ftp::TransferMode Mode);
-
- ////////////////////////////////////////////////////////////
- // Send data on the data channel
- ////////////////////////////////////////////////////////////
- void Send(const std::vector<char>& Data);
+ void send(const std::vector<char>& data);
////////////////////////////////////////////////////////////
- // Receive data on the data channel until it is closed
- ////////////////////////////////////////////////////////////
- void Receive(std::vector<char>& Data);
+ void receive(std::vector<char>& data);
private :
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
- Ftp& myFtp; ///< Reference to the owner Ftp instance
- SocketTCP myDataSocket; ///< Socket used for data transfers
+ Ftp& m_ftp; ///< Reference to the owner Ftp instance
+ TcpSocket m_dataSocket; ///< Socket used for data transfers
};
////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
-Ftp::Response::Response(Status Code, const std::string& Message) :
-myStatus (Code),
-myMessage(Message)
+Ftp::Response::Response(Status code, const std::string& message) :
+m_status (code),
+m_message(message)
{
}
////////////////////////////////////////////////////////////
-/// Convenience function to check if the response status code
-/// means a success
-////////////////////////////////////////////////////////////
-bool Ftp::Response::IsOk() const
+bool Ftp::Response::isOk() const
{
- return myStatus < 400;
+ return m_status < 400;
}
////////////////////////////////////////////////////////////
-/// Get the response status code
-////////////////////////////////////////////////////////////
-Ftp::Response::Status Ftp::Response::GetStatus() const
+Ftp::Response::Status Ftp::Response::getStatus() const
{
- return myStatus;
+ return m_status;
}
////////////////////////////////////////////////////////////
-/// Get the full message contained in the response
-////////////////////////////////////////////////////////////
-const std::string& Ftp::Response::GetMessage() const
+const std::string& Ftp::Response::getMessage() const
{
- return myMessage;
+ return m_message;
}
////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
-Ftp::DirectoryResponse::DirectoryResponse(Ftp::Response Resp) :
-Ftp::Response(Resp)
+Ftp::DirectoryResponse::DirectoryResponse(const Ftp::Response& response) :
+Ftp::Response(response)
{
- if (IsOk())
+ if (isOk())
{
// Extract the directory from the server response
- std::string::size_type Begin = Resp.GetMessage().find('"', 0);
- std::string::size_type End = Resp.GetMessage().find('"', Begin + 1);
- myDirectory = Resp.GetMessage().substr(Begin + 1, End - Begin - 1);
+ std::string::size_type begin = getMessage().find('"', 0);
+ std::string::size_type end = getMessage().find('"', begin + 1);
+ m_directory = getMessage().substr(begin + 1, end - begin - 1);
}
}
////////////////////////////////////////////////////////////
-/// Get the directory returned in the response
-////////////////////////////////////////////////////////////
-const std::string& Ftp::DirectoryResponse::GetDirectory() const
+const std::string& Ftp::DirectoryResponse::getDirectory() const
{
- return myDirectory;
+ return m_directory;
}
////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
-Ftp::ListingResponse::ListingResponse(Ftp::Response Resp, const std::vector<char>& Data) :
-Ftp::Response(Resp)
+Ftp::ListingResponse::ListingResponse(const Ftp::Response& response, const std::vector<char>& data) :
+Ftp::Response(response)
{
- if (IsOk())
+ if (isOk())
{
// Fill the array of strings
- std::string Paths(Data.begin(), Data.end());
- std::string::size_type LastPos = 0;
- for (std::string::size_type Pos = Paths.find("\r\n"); Pos != std::string::npos; Pos = Paths.find("\r\n", LastPos))
+ std::string paths(data.begin(), data.end());
+ std::string::size_type lastPos = 0;
+ for (std::string::size_type pos = paths.find("\r\n"); pos != std::string::npos; pos = paths.find("\r\n", lastPos))
{
- myFilenames.push_back(Paths.substr(LastPos, Pos - LastPos));
- LastPos = Pos + 2;
+ m_listing.push_back(paths.substr(lastPos, pos - lastPos));
+ lastPos = pos + 2;
}
}
}
////////////////////////////////////////////////////////////
-/// Get the number of filenames in the listing
-////////////////////////////////////////////////////////////
-std::size_t Ftp::ListingResponse::GetCount() const
+const std::vector<std::string>& Ftp::ListingResponse::getListing() const
{
- return myFilenames.size();
+ return m_listing;
}
////////////////////////////////////////////////////////////
-/// Get the Index-th filename in the directory
-////////////////////////////////////////////////////////////
-const std::string& Ftp::ListingResponse::GetFilename(std::size_t Index) const
-{
- return myFilenames[Index];
-}
-
-
-////////////////////////////////////////////////////////////
-/// Destructor -- close the connection with the server
-////////////////////////////////////////////////////////////
Ftp::~Ftp()
{
- Disconnect();
+ disconnect();
}
////////////////////////////////////////////////////////////
-/// Connect to the specified FTP server
-////////////////////////////////////////////////////////////
-Ftp::Response Ftp::Connect(const IPAddress& Server, unsigned short Port, float Timeout)
+Ftp::Response Ftp::connect(const IpAddress& server, unsigned short port, Time timeout)
{
// Connect to the server
- if (myCommandSocket.Connect(Port, Server, Timeout) != Socket::Done)
+ if (m_commandSocket.connect(server, port, timeout) != Socket::Done)
return Response(Response::ConnectionFailed);
// Get the response to the connection
- return GetResponse();
+ return getResponse();
}
////////////////////////////////////////////////////////////
-/// Log in using anonymous account
-////////////////////////////////////////////////////////////
-Ftp::Response Ftp::Login()
+Ftp::Response Ftp::login()
{
- return Login("anonymous", "user@sfml-dev.org");
+ return login("anonymous", "user@sfml-dev.org");
}
////////////////////////////////////////////////////////////
-/// Log in using a username and a password
-////////////////////////////////////////////////////////////
-Ftp::Response Ftp::Login(const std::string& UserName, const std::string& Password)
+Ftp::Response Ftp::login(const std::string& name, const std::string& password)
{
- Response Resp = SendCommand("USER", UserName);
- if (Resp.IsOk())
- Resp = SendCommand("PASS", Password);
+ Response response = sendCommand("USER", name);
+ if (response.isOk())
+ response = sendCommand("PASS", password);
- return Resp;
+ return response;
}
////////////////////////////////////////////////////////////
-/// Close the connection with FTP server
-////////////////////////////////////////////////////////////
-Ftp::Response Ftp::Disconnect()
+Ftp::Response Ftp::disconnect()
{
// Send the exit command
- Response Resp = SendCommand("QUIT");
- if (Resp.IsOk())
- myCommandSocket.Close();
+ Response response = sendCommand("QUIT");
+ if (response.isOk())
+ m_commandSocket.disconnect();
- return Resp;
+ return response;
}
////////////////////////////////////////////////////////////
-/// Send a null command just to prevent from being disconnected
-////////////////////////////////////////////////////////////
-Ftp::Response Ftp::KeepAlive()
+Ftp::Response Ftp::keepAlive()
{
- return SendCommand("NOOP");
+ return sendCommand("NOOP");
}
////////////////////////////////////////////////////////////
-/// Get the current working directory
-////////////////////////////////////////////////////////////
-Ftp::DirectoryResponse Ftp::GetWorkingDirectory()
+Ftp::DirectoryResponse Ftp::getWorkingDirectory()
{
- return DirectoryResponse(SendCommand("PWD"));
+ return DirectoryResponse(sendCommand("PWD"));
}
////////////////////////////////////////////////////////////
-/// Get the contents of the given directory
-/// (subdirectories and files)
-////////////////////////////////////////////////////////////
-Ftp::ListingResponse Ftp::GetDirectoryListing(const std::string& Directory)
+Ftp::ListingResponse Ftp::getDirectoryListing(const std::string& directory)
{
// Open a data channel on default port (20) using ASCII transfer mode
- std::vector<char> DirData;
- DataChannel Data(*this);
- Response Resp = Data.Open(Ascii);
- if (Resp.IsOk())
+ std::vector<char> directoryData;
+ DataChannel data(*this);
+ Response response = data.open(Ascii);
+ if (response.isOk())
{
// Tell the server to send us the listing
- Resp = SendCommand("NLST", Directory);
- if (Resp.IsOk())
+ response = sendCommand("NLST", directory);
+ if (response.isOk())
{
// Receive the listing
- Data.Receive(DirData);
+ data.receive(directoryData);
// Get the response from the server
- Resp = GetResponse();
+ response = getResponse();
}
}
- return ListingResponse(Resp, DirData);
+ return ListingResponse(response, directoryData);
}
////////////////////////////////////////////////////////////
-/// Change the current working directory
-////////////////////////////////////////////////////////////
-Ftp::Response Ftp::ChangeDirectory(const std::string& Directory)
+Ftp::Response Ftp::changeDirectory(const std::string& directory)
{
- return SendCommand("CWD", Directory);
+ return sendCommand("CWD", directory);
}
////////////////////////////////////////////////////////////
-/// Go to the parent directory of the current one
-////////////////////////////////////////////////////////////
-Ftp::Response Ftp::ParentDirectory()
+Ftp::Response Ftp::parentDirectory()
{
- return SendCommand("CDUP");
+ return sendCommand("CDUP");
}
////////////////////////////////////////////////////////////
-/// Create a new directory
-////////////////////////////////////////////////////////////
-Ftp::Response Ftp::MakeDirectory(const std::string& Name)
+Ftp::Response Ftp::createDirectory(const std::string& name)
{
- return SendCommand("MKD", Name);
+ return sendCommand("MKD", name);
}
////////////////////////////////////////////////////////////
-/// Remove an existing directory
-////////////////////////////////////////////////////////////
-Ftp::Response Ftp::DeleteDirectory(const std::string& Name)
+Ftp::Response Ftp::deleteDirectory(const std::string& name)
{
- return SendCommand("RMD", Name);
+ return sendCommand("RMD", name);
}
////////////////////////////////////////////////////////////
-/// Rename a file
-////////////////////////////////////////////////////////////
-Ftp::Response Ftp::RenameFile(const std::string& File, const std::string& NewName)
+Ftp::Response Ftp::renameFile(const std::string& file, const std::string& newName)
{
- Response Resp = SendCommand("RNFR", File);
- if (Resp.IsOk())
- Resp = SendCommand("RNTO", NewName);
+ Response response = sendCommand("RNFR", file);
+ if (response.isOk())
+ response = sendCommand("RNTO", newName);
- return Resp;
+ return response;
}
////////////////////////////////////////////////////////////
-/// Remove an existing file
-////////////////////////////////////////////////////////////
-Ftp::Response Ftp::DeleteFile(const std::string& Name)
+Ftp::Response Ftp::deleteFile(const std::string& name)
{
- return SendCommand("DELE", Name);
+ return sendCommand("DELE", name);
}
////////////////////////////////////////////////////////////
-/// Download a file from the server
-////////////////////////////////////////////////////////////
-Ftp::Response Ftp::Download(const std::string& DistantFile, const std::string& DestPath, TransferMode Mode)
+Ftp::Response Ftp::download(const std::string& remoteFile, const std::string& localPath, TransferMode mode)
{
// Open a data channel using the given transfer mode
- DataChannel Data(*this);
- Response Resp = Data.Open(Mode);
- if (Resp.IsOk())
+ DataChannel data(*this);
+ Response response = data.open(mode);
+ if (response.isOk())
{
// Tell the server to start the transfer
- Resp = SendCommand("RETR", DistantFile);
- if (Resp.IsOk())
+ response = sendCommand("RETR", remoteFile);
+ if (response.isOk())
{
// Receive the file data
- std::vector<char> FileData;
- Data.Receive(FileData);
+ std::vector<char> fileData;
+ data.receive(fileData);
// Get the response from the server
- Resp = GetResponse();
- if (Resp.IsOk())
+ response = getResponse();
+ if (response.isOk())
{
// Extract the filename from the file path
- std::string Filename = DistantFile;
- std::string::size_type Pos = Filename.find_last_of("/\\");
- if (Pos != std::string::npos)
- Filename = Filename.substr(Pos + 1);
+ std::string filename = remoteFile;
+ std::string::size_type pos = filename.find_last_of("/\\");
+ if (pos != std::string::npos)
+ filename = filename.substr(pos + 1);
// Make sure the destination path ends with a slash
- std::string Path = DestPath;
- if (!Path.empty() && (Path[Path.size() - 1] != '\\') && (Path[Path.size() - 1] != '/'))
- Path += "/";
+ std::string path = localPath;
+ if (!path.empty() && (path[path.size() - 1] != '\\') && (path[path.size() - 1] != '/'))
+ path += "/";
// Create the file and copy the received data into it
- std::ofstream File((Path + Filename).c_str(), std::ios_base::binary);
- if (!File)
+ std::ofstream file((path + filename).c_str(), std::ios_base::binary);
+ if (!file)
return Response(Response::InvalidFile);
- if (!FileData.empty())
- File.write(&FileData[0], static_cast<std::streamsize>(FileData.size()));
+
+ if (!fileData.empty())
+ file.write(&fileData[0], static_cast<std::streamsize>(fileData.size()));
}
}
}
- return Resp;
+ return response;
}
////////////////////////////////////////////////////////////
-/// Upload a file to the server
-////////////////////////////////////////////////////////////
-Ftp::Response Ftp::Upload(const std::string& LocalFile, const std::string& DestPath, TransferMode Mode)
+Ftp::Response Ftp::upload(const std::string& localFile, const std::string& remotePath, TransferMode mode)
{
// Get the contents of the file to send
- std::ifstream File(LocalFile.c_str(), std::ios_base::binary);
- if (!File)
+ std::ifstream file(localFile.c_str(), std::ios_base::binary);
+ if (!file)
return Response(Response::InvalidFile);
- File.seekg(0, std::ios::end);
- std::size_t Length = File.tellg();
- File.seekg(0, std::ios::beg);
- std::vector<char> FileData(Length);
- if (Length > 0)
- File.read(&FileData[0], static_cast<std::streamsize>(Length));
+
+ file.seekg(0, std::ios::end);
+ std::size_t length = static_cast<std::size_t>(file.tellg());
+ file.seekg(0, std::ios::beg);
+ std::vector<char> fileData(length);
+ if (length > 0)
+ file.read(&fileData[0], static_cast<std::streamsize>(length));
// Extract the filename from the file path
- std::string Filename = LocalFile;
- std::string::size_type Pos = Filename.find_last_of("/\\");
- if (Pos != std::string::npos)
- Filename = Filename.substr(Pos + 1);
+ std::string filename = localFile;
+ std::string::size_type pos = filename.find_last_of("/\\");
+ if (pos != std::string::npos)
+ filename = filename.substr(pos + 1);
// Make sure the destination path ends with a slash
- std::string Path = DestPath;
- if (!Path.empty() && (Path[Path.size() - 1] != '\\') && (Path[Path.size() - 1] != '/'))
- Path += "/";
+ std::string path = remotePath;
+ if (!path.empty() && (path[path.size() - 1] != '\\') && (path[path.size() - 1] != '/'))
+ path += "/";
// Open a data channel using the given transfer mode
- DataChannel Data(*this);
- Response Resp = Data.Open(Mode);
- if (Resp.IsOk())
+ DataChannel data(*this);
+ Response response = data.open(mode);
+ if (response.isOk())
{
// Tell the server to start the transfer
- Resp = SendCommand("STOR", Path + Filename);
- if (Resp.IsOk())
+ response = sendCommand("STOR", path + filename);
+ if (response.isOk())
{
// Send the file data
- Data.Send(FileData);
+ data.send(fileData);
// Get the response from the server
- Resp = GetResponse();
+ response = getResponse();
}
}
- return Resp;
+ return response;
}
////////////////////////////////////////////////////////////
-/// Send a command to the FTP server
-////////////////////////////////////////////////////////////
-Ftp::Response Ftp::SendCommand(const std::string& Command, const std::string& Parameter)
+Ftp::Response Ftp::sendCommand(const std::string& command, const std::string& parameter)
{
// Build the command string
- std::string CommandStr;
- if (Parameter != "")
- CommandStr = Command + " " + Parameter + "\r\n";
+ std::string commandStr;
+ if (parameter != "")
+ commandStr = command + " " + parameter + "\r\n";
else
- CommandStr = Command + "\r\n";
+ commandStr = command + "\r\n";
// Send it to the server
- if (myCommandSocket.Send(CommandStr.c_str(), CommandStr.length()) != sf::Socket::Done)
+ if (m_commandSocket.send(commandStr.c_str(), commandStr.length()) != Socket::Done)
return Response(Response::ConnectionClosed);
// Get the response
- return GetResponse();
+ return getResponse();
}
////////////////////////////////////////////////////////////
-/// Receive a response from the server
-/// (usually after a command has been sent)
-////////////////////////////////////////////////////////////
-Ftp::Response Ftp::GetResponse()
+Ftp::Response Ftp::getResponse()
{
// We'll use a variable to keep track of the last valid code.
// It is useful in case of multi-lines responses, because the end of such a response
// will start by the same code
- unsigned int LastCode = 0;
- bool IsInsideMultiline = false;
- std::string Message;
+ unsigned int lastCode = 0;
+ bool isInsideMultiline = false;
+ std::string message;
for (;;)
{
// Receive the response from the server
- char Buffer[1024];
- std::size_t Length;
- if (myCommandSocket.Receive(Buffer, sizeof(Buffer), Length) != sf::Socket::Done)
+ char buffer[1024];
+ std::size_t length;
+ if (m_commandSocket.receive(buffer, sizeof(buffer), length) != Socket::Done)
return Response(Response::ConnectionClosed);
// There can be several lines inside the received buffer, extract them all
- std::istringstream In(std::string(Buffer, Length), std::ios_base::binary);
- while (In)
+ std::istringstream in(std::string(buffer, length), std::ios_base::binary);
+ while (in)
{
// Try to extract the code
- unsigned int Code;
- if (In >> Code)
+ unsigned int code;
+ if (in >> code)
{
// Extract the separator
- char Sep;
- In.get(Sep);
+ char separator;
+ in.get(separator);
// The '-' character means a multiline response
- if ((Sep == '-') && !IsInsideMultiline)
+ if ((separator == '-') && !isInsideMultiline)
{
// Set the multiline flag
- IsInsideMultiline = true;
+ isInsideMultiline = true;
// Keep track of the code
- if (LastCode == 0)
- LastCode = Code;
+ if (lastCode == 0)
+ lastCode = code;
// Extract the line
- std::getline(In, Message);
+ std::getline(in, message);
// Remove the ending '\r' (all lines are terminated by "\r\n")
- Message.erase(Message.length() - 1);
- Message = Sep + Message + "\n";
+ message.erase(message.length() - 1);
+ message = separator + message + "\n";
}
else
{
// We must make sure that the code is the same, otherwise it means
// we haven't reached the end of the multiline response
- if ((Sep != '-') && ((Code == LastCode) || (LastCode == 0)))
+ if ((separator != '-') && ((code == lastCode) || (lastCode == 0)))
{
// Clear the multiline flag
- IsInsideMultiline = false;
+ isInsideMultiline = false;
// Extract the line
- std::string Line;
- std::getline(In, Line);
+ std::string line;
+ std::getline(in, line);
// Remove the ending '\r' (all lines are terminated by "\r\n")
- Line.erase(Line.length() - 1);
+ line.erase(line.length() - 1);
// Append it to the message
- if (Code == LastCode)
+ if (code == lastCode)
{
- std::ostringstream Out;
- Out << Code << Sep << Line;
- Message += Out.str();
+ std::ostringstream out;
+ out << code << separator << line;
+ message += out.str();
}
else
{
- Message = Sep + Line;
+ message = separator + line;
}
// Return the response code and message
- return Response(static_cast<Response::Status>(Code), Message);
+ return Response(static_cast<Response::Status>(code), message);
}
else
{
@@ -546,40 +468,40 @@ Ftp::Response Ftp::GetResponse()
// only a new part of the current multiline response
// Extract the line
- std::string Line;
- std::getline(In, Line);
+ std::string line;
+ std::getline(in, line);
- if (!Line.empty())
+ if (!line.empty())
{
// Remove the ending '\r' (all lines are terminated by "\r\n")
- Line.erase(Line.length() - 1);
+ line.erase(line.length() - 1);
// Append it to the current message
- std::ostringstream Out;
- Out << Code << Sep << Line << "\n";
- Message += Out.str();
+ std::ostringstream out;
+ out << code << separator << line << "\n";
+ message += out.str();
}
}
}
}
- else if (LastCode != 0)
+ else if (lastCode != 0)
{
// It seems we are in the middle of a multiline response
// Clear the error bits of the stream
- In.clear();
+ in.clear();
// Extract the line
- std::string Line;
- std::getline(In, Line);
+ std::string line;
+ std::getline(in, line);
- if (!Line.empty())
+ if (!line.empty())
{
// Remove the ending '\r' (all lines are terminated by "\r\n")
- Line.erase(Line.length() - 1);
+ line.erase(line.length() - 1);
// Append it to the current message
- Message += Line + "\n";
+ message += line + "\n";
}
}
else
@@ -595,118 +517,100 @@ Ftp::Response Ftp::GetResponse()
////////////////////////////////////////////////////////////
-/// Constructor
-////////////////////////////////////////////////////////////
-Ftp::DataChannel::DataChannel(Ftp& Owner) :
-myFtp(Owner)
+Ftp::DataChannel::DataChannel(Ftp& owner) :
+m_ftp(owner)
{
}
////////////////////////////////////////////////////////////
-/// Destructor
-////////////////////////////////////////////////////////////
-Ftp::DataChannel::~DataChannel()
-{
- // Close the data socket
- myDataSocket.Close();
-}
-
-
-////////////////////////////////////////////////////////////
-/// Open the data channel using the specified mode and port
-////////////////////////////////////////////////////////////
-Ftp::Response Ftp::DataChannel::Open(Ftp::TransferMode Mode)
+Ftp::Response Ftp::DataChannel::open(Ftp::TransferMode mode)
{
// Open a data connection in active mode (we connect to the server)
- Ftp::Response Resp = myFtp.SendCommand("PASV");
- if (Resp.IsOk())
+ Ftp::Response response = m_ftp.sendCommand("PASV");
+ if (response.isOk())
{
// Extract the connection address and port from the response
- std::string::size_type begin = Resp.GetMessage().find_first_of("0123456789");
+ std::string::size_type begin = response.getMessage().find_first_of("0123456789");
if (begin != std::string::npos)
{
- sf::Uint8 Data[6] = {0, 0, 0, 0, 0, 0};
- std::string Str = Resp.GetMessage().substr(begin);
- std::size_t Index = 0;
+ Uint8 data[6] = {0, 0, 0, 0, 0, 0};
+ std::string str = response.getMessage().substr(begin);
+ std::size_t index = 0;
for (int i = 0; i < 6; ++i)
{
// Extract the current number
- while (isdigit(Str[Index]))
+ while (isdigit(str[index]))
{
- Data[i] = Data[i] * 10 + (Str[Index] - '0');
- Index++;
+ data[i] = data[i] * 10 + (str[index] - '0');
+ index++;
}
// Skip separator
- Index++;
+ index++;
}
// Reconstruct connection port and address
- unsigned short Port = Data[4] * 256 + Data[5];
- sf::IPAddress Address(static_cast<sf::Uint8>(Data[0]),
- static_cast<sf::Uint8>(Data[1]),
- static_cast<sf::Uint8>(Data[2]),
- static_cast<sf::Uint8>(Data[3]));
+ unsigned short port = data[4] * 256 + data[5];
+ IpAddress address(static_cast<Uint8>(data[0]),
+ static_cast<Uint8>(data[1]),
+ static_cast<Uint8>(data[2]),
+ static_cast<Uint8>(data[3]));
// Connect the data channel to the server
- if (myDataSocket.Connect(Port, Address) == Socket::Done)
+ if (m_dataSocket.connect(address, port) == Socket::Done)
{
// Translate the transfer mode to the corresponding FTP parameter
- std::string ModeStr;
- switch (Mode)
+ std::string modeStr;
+ switch (mode)
{
- case Ftp::Binary : ModeStr = "I"; break;
- case Ftp::Ascii : ModeStr = "A"; break;
- case Ftp::Ebcdic : ModeStr = "E"; break;
+ case Ftp::Binary : modeStr = "I"; break;
+ case Ftp::Ascii : modeStr = "A"; break;
+ case Ftp::Ebcdic : modeStr = "E"; break;
}
// Set the transfer mode
- Resp = myFtp.SendCommand("TYPE", ModeStr);
+ response = m_ftp.sendCommand("TYPE", modeStr);
}
else
{
// Failed to connect to the server
- Resp = Ftp::Response(Ftp::Response::ConnectionFailed);
+ response = Ftp::Response(Ftp::Response::ConnectionFailed);
}
}
}
- return Resp;
+ return response;
}
////////////////////////////////////////////////////////////
-/// Receive data on the data channel until it is closed
-////////////////////////////////////////////////////////////
-void Ftp::DataChannel::Receive(std::vector<char>& Data)
+void Ftp::DataChannel::receive(std::vector<char>& data)
{
// Receive data
- Data.clear();
- char Buffer[1024];
- std::size_t Received;
- while (myDataSocket.Receive(Buffer, sizeof(Buffer), Received) == sf::Socket::Done)
+ data.clear();
+ char buffer[1024];
+ std::size_t received;
+ while (m_dataSocket.receive(buffer, sizeof(buffer), received) == Socket::Done)
{
- std::copy(Buffer, Buffer + Received, std::back_inserter(Data));
+ std::copy(buffer, buffer + received, std::back_inserter(data));
}
// Close the data socket
- myDataSocket.Close();
+ m_dataSocket.disconnect();
}
////////////////////////////////////////////////////////////
-/// Send data on the data channel
-////////////////////////////////////////////////////////////
-void Ftp::DataChannel::Send(const std::vector<char>& Data)
+void Ftp::DataChannel::send(const std::vector<char>& data)
{
// Send data
- if (!Data.empty())
- myDataSocket.Send(&Data[0], Data.size());
+ if (!data.empty())
+ m_dataSocket.send(&data[0], data.size());
// Close the data socket
- myDataSocket.Close();
+ m_dataSocket.disconnect();
}
} // namespace sf
diff --git a/src/SFML/Network/Http.cpp b/src/SFML/Network/Http.cpp
index 4a9502f..5b7f62c 100755..100644
--- a/src/SFML/Network/Http.cpp
+++ b/src/SFML/Network/Http.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -26,7 +26,7 @@
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Network/Http.hpp>
-#include <ctype.h>
+#include <cctype>
#include <algorithm>
#include <iterator>
#include <sstream>
@@ -34,16 +34,12 @@
namespace
{
- ////////////////////////////////////////////////////////////
- // Convenience function to convert a string to lower case
- ////////////////////////////////////////////////////////////
- std::string ToLower(const std::string& Str)
+ // Convert a string to lower case
+ std::string toLower(std::string str)
{
- std::string Ret = Str;
- for (std::string::iterator i = Ret.begin(); i != Ret.end(); ++i)
- *i = static_cast<char>(tolower(*i));
-
- return Ret;
+ for (std::string::iterator i = str.begin(); i != str.end(); ++i)
+ *i = static_cast<char>(std::tolower(*i));
+ return str;
}
}
@@ -51,382 +47,330 @@ namespace
namespace sf
{
////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
-Http::Request::Request(Method RequestMethod, const std::string& URI, const std::string& Body)
+Http::Request::Request(const std::string& uri, Method method, const std::string& body)
{
- SetMethod(RequestMethod);
- SetURI(URI);
- SetHttpVersion(1, 0);
- SetBody(Body);
+ setMethod(method);
+ setUri(uri);
+ setHttpVersion(1, 0);
+ setBody(body);
}
////////////////////////////////////////////////////////////
-/// Set the value of a field; the field is added if it doesn't exist
-////////////////////////////////////////////////////////////
-void Http::Request::SetField(const std::string& Field, const std::string& Value)
+void Http::Request::setField(const std::string& field, const std::string& value)
{
- myFields[ToLower(Field)] = Value;
+ m_fields[toLower(field)] = value;
}
////////////////////////////////////////////////////////////
-/// Set the request method.
-/// This parameter is Get by default
-////////////////////////////////////////////////////////////
-void Http::Request::SetMethod(Http::Request::Method RequestMethod)
+void Http::Request::setMethod(Http::Request::Method method)
{
- myMethod = RequestMethod;
+ m_method = method;
}
////////////////////////////////////////////////////////////
-/// Set the target URI of the request.
-/// This parameter is "/" by default
-////////////////////////////////////////////////////////////
-void Http::Request::SetURI(const std::string& URI)
+void Http::Request::setUri(const std::string& uri)
{
- myURI = URI;
+ m_uri = uri;
// Make sure it starts with a '/'
- if (myURI.empty() || (myURI[0] != '/'))
- myURI.insert(0, "/");
+ if (m_uri.empty() || (m_uri[0] != '/'))
+ m_uri.insert(0, "/");
}
////////////////////////////////////////////////////////////
-/// Set the HTTP version of the request.
-/// This parameter is 1.0 by default
-////////////////////////////////////////////////////////////
-void Http::Request::SetHttpVersion(unsigned int Major, unsigned int Minor)
+void Http::Request::setHttpVersion(unsigned int major, unsigned int minor)
{
- myMajorVersion = Major;
- myMinorVersion = Minor;
+ m_majorVersion = major;
+ m_minorVersion = minor;
}
////////////////////////////////////////////////////////////
-/// Set the body of the request. This parameter is optional and
-/// makes sense only for POST requests.
-/// This parameter is empty by default
-////////////////////////////////////////////////////////////
-void Http::Request::SetBody(const std::string& Body)
+void Http::Request::setBody(const std::string& body)
{
- myBody = Body;
+ m_body = body;
}
////////////////////////////////////////////////////////////
-/// Get the string representation of a request header
-////////////////////////////////////////////////////////////
-std::string Http::Request::ToString() const
+std::string Http::Request::prepare() const
{
- std::ostringstream Out;
+ std::ostringstream out;
// Convert the method to its string representation
- std::string RequestMethod;
- switch (myMethod)
+ std::string method;
+ switch (m_method)
{
default :
- case Get : RequestMethod = "GET"; break;
- case Post : RequestMethod = "POST"; break;
- case Head : RequestMethod = "HEAD"; break;
+ case Get : method = "GET"; break;
+ case Post : method = "POST"; break;
+ case Head : method = "HEAD"; break;
}
// Write the first line containing the request type
- Out << RequestMethod << " " << myURI << " ";
- Out << "HTTP/" << myMajorVersion << "." << myMinorVersion << "\r\n";
+ out << method << " " << m_uri << " ";
+ out << "HTTP/" << m_majorVersion << "." << m_minorVersion << "\r\n";
// Write fields
- for (FieldTable::const_iterator i = myFields.begin(); i != myFields.end(); ++i)
+ for (FieldTable::const_iterator i = m_fields.begin(); i != m_fields.end(); ++i)
{
- Out << i->first << ": " << i->second << "\r\n";
+ out << i->first << ": " << i->second << "\r\n";
}
// Use an extra \r\n to separate the header from the body
- Out << "\r\n";
+ out << "\r\n";
// Add the body
- Out << myBody;
+ out << m_body;
- return Out.str();
+ return out.str();
}
////////////////////////////////////////////////////////////
-/// Check if the given field has been defined
-////////////////////////////////////////////////////////////
-bool Http::Request::HasField(const std::string& Field) const
+bool Http::Request::hasField(const std::string& field) const
{
- return myFields.find(Field) != myFields.end();
+ return m_fields.find(toLower(field)) != m_fields.end();
}
////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
Http::Response::Response() :
-myStatus (ConnectionFailed),
-myMajorVersion(0),
-myMinorVersion(0)
+m_status (ConnectionFailed),
+m_majorVersion(0),
+m_minorVersion(0)
{
}
////////////////////////////////////////////////////////////
-/// Get the value of a field
-////////////////////////////////////////////////////////////
-const std::string& Http::Response::GetField(const std::string& Field) const
+const std::string& Http::Response::getField(const std::string& field) const
{
- FieldTable::const_iterator It = myFields.find(ToLower(Field));
- if (It != myFields.end())
+ FieldTable::const_iterator it = m_fields.find(toLower(field));
+ if (it != m_fields.end())
{
- return It->second;
+ return it->second;
}
else
{
- static const std::string Empty = "";
- return Empty;
+ static const std::string empty = "";
+ return empty;
}
}
////////////////////////////////////////////////////////////
-/// Get the header's status code
-////////////////////////////////////////////////////////////
-Http::Response::Status Http::Response::GetStatus() const
+Http::Response::Status Http::Response::getStatus() const
{
- return myStatus;
+ return m_status;
}
////////////////////////////////////////////////////////////
-/// Get the major HTTP version number of the response
-////////////////////////////////////////////////////////////
-unsigned int Http::Response::GetMajorHttpVersion() const
+unsigned int Http::Response::getMajorHttpVersion() const
{
- return myMajorVersion;
+ return m_majorVersion;
}
////////////////////////////////////////////////////////////
-/// Get the major HTTP version number of the response
-////////////////////////////////////////////////////////////
-unsigned int Http::Response::GetMinorHttpVersion() const
+unsigned int Http::Response::getMinorHttpVersion() const
{
- return myMinorVersion;
+ return m_minorVersion;
}
////////////////////////////////////////////////////////////
-/// Get the body of the response. The body can contain :
-/// - the requested page (for GET requests)
-/// - a response from the server (for POST requests)
-/// - nothing (for HEAD requests)
-/// - an error message (in case of an error)
-////////////////////////////////////////////////////////////
-const std::string& Http::Response::GetBody() const
+const std::string& Http::Response::getBody() const
{
- return myBody;
+ return m_body;
}
////////////////////////////////////////////////////////////
-/// Construct the header from a response string
-////////////////////////////////////////////////////////////
-void Http::Response::FromString(const std::string& Data)
+void Http::Response::parse(const std::string& data)
{
- std::istringstream In(Data);
+ std::istringstream in(data);
// Extract the HTTP version from the first line
- std::string Version;
- if (In >> Version)
+ std::string version;
+ if (in >> version)
{
- if ((Version.size() >= 8) && (Version[6] == '.') &&
- (ToLower(Version.substr(0, 5)) == "http/") &&
- isdigit(Version[5]) && isdigit(Version[7]))
+ if ((version.size() >= 8) && (version[6] == '.') &&
+ (toLower(version.substr(0, 5)) == "http/") &&
+ isdigit(version[5]) && isdigit(version[7]))
{
- myMajorVersion = Version[5] - '0';
- myMinorVersion = Version[7] - '0';
+ m_majorVersion = version[5] - '0';
+ m_minorVersion = version[7] - '0';
}
else
{
// Invalid HTTP version
- myStatus = InvalidResponse;
+ m_status = InvalidResponse;
return;
}
}
// Extract the status code from the first line
- int StatusCode;
- if (In >> StatusCode)
+ int status;
+ if (in >> status)
{
- myStatus = static_cast<Status>(StatusCode);
+ m_status = static_cast<Status>(status);
}
else
{
// Invalid status code
- myStatus = InvalidResponse;
+ m_status = InvalidResponse;
return;
}
// Ignore the end of the first line
- In.ignore(10000, '\n');
+ in.ignore(10000, '\n');
// Parse the other lines, which contain fields, one by one
- std::string Line;
- while (std::getline(In, Line) && (Line.size() > 2))
+ std::string line;
+ while (std::getline(in, line) && (line.size() > 2))
{
- std::string::size_type Pos = Line.find(": ");
- if (Pos != std::string::npos)
+ std::string::size_type pos = line.find(": ");
+ if (pos != std::string::npos)
{
// Extract the field name and its value
- std::string Field = Line.substr(0, Pos);
- std::string Value = Line.substr(Pos + 2);
+ std::string field = line.substr(0, pos);
+ std::string value = line.substr(pos + 2);
// Remove any trailing \r
- if (!Value.empty() && (*Value.rbegin() == '\r'))
- Value.erase(Value.size() - 1);
+ if (!value.empty() && (*value.rbegin() == '\r'))
+ value.erase(value.size() - 1);
// Add the field
- myFields[ToLower(Field)] = Value;
+ m_fields[toLower(field)] = value;
}
}
// Finally extract the body
- myBody.clear();
- std::copy(std::istreambuf_iterator<char>(In), std::istreambuf_iterator<char>(), std::back_inserter(myBody));
+ m_body.clear();
+ std::copy(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>(), std::back_inserter(m_body));
}
////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
Http::Http() :
-myHost(),
-myPort(0)
+m_host(),
+m_port(0)
{
}
////////////////////////////////////////////////////////////
-/// Construct the Http instance with the target host
-////////////////////////////////////////////////////////////
-Http::Http(const std::string& Host, unsigned short Port)
+Http::Http(const std::string& host, unsigned short port)
{
- SetHost(Host, Port);
+ setHost(host, port);
}
////////////////////////////////////////////////////////////
-/// Set the target host
-////////////////////////////////////////////////////////////
-void Http::SetHost(const std::string& Host, unsigned short Port)
+void Http::setHost(const std::string& host, unsigned short port)
{
// Detect the protocol used
- std::string Protocol = ToLower(Host.substr(0, 8));
- if (Protocol.substr(0, 7) == "http://")
+ std::string protocol = toLower(host.substr(0, 8));
+ if (protocol.substr(0, 7) == "http://")
{
// HTTP protocol
- myHostName = Host.substr(7);
- myPort = (Port != 0 ? Port : 80);
+ m_hostName = host.substr(7);
+ m_port = (port != 0 ? port : 80);
}
- else if (Protocol == "https://")
+ else if (protocol == "https://")
{
// HTTPS protocol
- myHostName = Host.substr(8);
- myPort = (Port != 0 ? Port : 443);
+ m_hostName = host.substr(8);
+ m_port = (port != 0 ? port : 443);
}
else
{
// Undefined protocol - use HTTP
- myHostName = Host;
- myPort = (Port != 0 ? Port : 80);
+ m_hostName = host;
+ m_port = (port != 0 ? port : 80);
}
// Remove any trailing '/' from the host name
- if (!myHostName.empty() && (*myHostName.rbegin() == '/'))
- myHostName.erase(myHostName.size() - 1);
+ if (!m_hostName.empty() && (*m_hostName.rbegin() == '/'))
+ m_hostName.erase(m_hostName.size() - 1);
- myHost = sf::IPAddress(myHostName);
+ m_host = IpAddress(m_hostName);
}
////////////////////////////////////////////////////////////
-/// Send a HTTP request and return the server's response.
-/// You must be connected to a host before sending requests.
-/// Any missing mandatory header field will be added with an appropriate value.
-/// Warning : this function waits for the server's response and may
-/// not return instantly; use a thread if you don't want to block your
-/// application.
-////////////////////////////////////////////////////////////
-Http::Response Http::SendRequest(const Http::Request& Req, float Timeout)
+Http::Response Http::sendRequest(const Http::Request& request, Time timeout)
{
- // First make sure the request is valid -- add missing mandatory fields
- Request ToSend(Req);
- if (!ToSend.HasField("From"))
+ // First make sure that the request is valid -- add missing mandatory fields
+ Request toSend(request);
+ if (!toSend.hasField("From"))
{
- ToSend.SetField("From", "user@sfml-dev.org");
+ toSend.setField("From", "user@sfml-dev.org");
}
- if (!ToSend.HasField("User-Agent"))
+ if (!toSend.hasField("User-Agent"))
{
- ToSend.SetField("User-Agent", "libsfml-network/1.x");
+ toSend.setField("User-Agent", "libsfml-network/2.x");
}
- if (!ToSend.HasField("Host"))
+ if (!toSend.hasField("Host"))
{
- ToSend.SetField("Host", myHostName);
+ toSend.setField("Host", m_hostName);
}
- if (!ToSend.HasField("Content-Length"))
+ if (!toSend.hasField("Content-Length"))
{
- std::ostringstream Out;
- Out << ToSend.myBody.size();
- ToSend.SetField("Content-Length", Out.str());
+ std::ostringstream out;
+ out << toSend.m_body.size();
+ toSend.setField("Content-Length", out.str());
}
- if ((ToSend.myMethod == Request::Post) && !ToSend.HasField("Content-Type"))
+ if ((toSend.m_method == Request::Post) && !toSend.hasField("Content-Type"))
{
- ToSend.SetField("Content-Type", "application/x-www-form-urlencoded");
+ toSend.setField("Content-Type", "application/x-www-form-urlencoded");
}
- if ((ToSend.myMajorVersion * 10 + ToSend.myMinorVersion >= 11) && !ToSend.HasField("Connection"))
+ if ((toSend.m_majorVersion * 10 + toSend.m_minorVersion >= 11) && !toSend.hasField("Connection"))
{
- ToSend.SetField("Connection", "close");
+ toSend.setField("Connection", "close");
}
// Prepare the response
- Response Received;
+ Response received;
// Connect the socket to the host
- if (myConnection.Connect(myPort, myHost, Timeout) == Socket::Done)
+ if (m_connection.connect(m_host, m_port, timeout) == Socket::Done)
{
// Convert the request to string and send it through the connected socket
- std::string RequestStr = ToSend.ToString();
+ std::string requestStr = toSend.prepare();
- if (!RequestStr.empty())
+ if (!requestStr.empty())
{
// Send it through the socket
- if (myConnection.Send(RequestStr.c_str(), RequestStr.size()) == sf::Socket::Done)
+ if (m_connection.send(requestStr.c_str(), requestStr.size()) == Socket::Done)
{
// Wait for the server's response
- std::string ReceivedStr;
- std::size_t Size = 0;
- char Buffer[1024];
- while (myConnection.Receive(Buffer, sizeof(Buffer), Size) == sf::Socket::Done)
+ std::string receivedStr;
+ std::size_t size = 0;
+ char buffer[1024];
+ while (m_connection.receive(buffer, sizeof(buffer), size) == Socket::Done)
{
- ReceivedStr.append(Buffer, Buffer + Size);
+ receivedStr.append(buffer, buffer + size);
}
// Build the Response object from the received data
- Received.FromString(ReceivedStr);
+ received.parse(receivedStr);
}
}
// Close the connection
- myConnection.Close();
+ m_connection.disconnect();
}
- return Received;
+ return received;
}
} // namespace sf
diff --git a/src/SFML/Network/IPAddress.cpp b/src/SFML/Network/IPAddress.cpp
deleted file mode 100755
index 9d51f24..0000000
--- a/src/SFML/Network/IPAddress.cpp
+++ /dev/null
@@ -1,298 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Network/IPAddress.hpp>
-#include <SFML/Network/Http.hpp>
-#include <SFML/Network/SocketHelper.hpp>
-#include <string.h>
-
-
-namespace sf
-{
-////////////////////////////////////////////////////////////
-/// Static member data
-////////////////////////////////////////////////////////////
-const IPAddress IPAddress::LocalHost("127.0.0.1");
-
-
-////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
-IPAddress::IPAddress() :
-myAddress(INADDR_NONE)
-{
-
-}
-
-
-////////////////////////////////////////////////////////////
-/// Construct the address from a string
-////////////////////////////////////////////////////////////
-IPAddress::IPAddress(const std::string& Address)
-{
- // First try to convert it as a byte representation ("xxx.xxx.xxx.xxx")
- myAddress = inet_addr(Address.c_str());
-
- // If not successful, try to convert it as a host name
- if (!IsValid())
- {
- hostent* Host = gethostbyname(Address.c_str());
- if (Host)
- {
- // Host found, extract its IP address
- myAddress = reinterpret_cast<in_addr*>(Host->h_addr)->s_addr;
- }
- else
- {
- // Host name not found on the network
- myAddress = INADDR_NONE;
- }
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Construct the address from a C-style string ;
-/// Needed for implicit conversions from literal strings to IPAddress to work
-////////////////////////////////////////////////////////////
-IPAddress::IPAddress(const char* Address)
-{
- // First try to convert it as a byte representation ("xxx.xxx.xxx.xxx")
- myAddress = inet_addr(Address);
-
- // If not successful, try to convert it as a host name
- if (!IsValid())
- {
- hostent* Host = gethostbyname(Address);
- if (Host)
- {
- // Host found, extract its IP address
- myAddress = reinterpret_cast<in_addr*>(Host->h_addr)->s_addr;
- }
- else
- {
- // Host name not found on the network
- myAddress = INADDR_NONE;
- }
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Construct the address from 4 bytes
-////////////////////////////////////////////////////////////
-IPAddress::IPAddress(Uint8 Byte0, Uint8 Byte1, Uint8 Byte2, Uint8 Byte3)
-{
- myAddress = htonl((Byte0 << 24) | (Byte1 << 16) | (Byte2 << 8) | Byte3);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Construct the address from a 32-bits integer
-////////////////////////////////////////////////////////////
-IPAddress::IPAddress(Uint32 Address)
-{
- myAddress = htonl(Address);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Tell if the address is a valid one
-////////////////////////////////////////////////////////////
-bool IPAddress::IsValid() const
-{
- return myAddress != INADDR_NONE;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get a string representation of the address
-////////////////////////////////////////////////////////////
-std::string IPAddress::ToString() const
-{
- in_addr InAddr;
- InAddr.s_addr = myAddress;
-
- return inet_ntoa(InAddr);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get an integer representation of the address
-////////////////////////////////////////////////////////////
-Uint32 IPAddress::ToInteger() const
-{
- return ntohl(myAddress);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the computer's local IP address (from the LAN point of view)
-////////////////////////////////////////////////////////////
-IPAddress IPAddress::GetLocalAddress()
-{
- // The method here is to connect a UDP socket to anyone (here to localhost),
- // and get the local socket address with the getsockname function.
- // UDP connection will not send anything to the network, so this function won't cause any overhead.
-
- IPAddress LocalAddress;
-
- // Create the socket
- SocketHelper::SocketType Socket = socket(PF_INET, SOCK_DGRAM, 0);
- if (Socket == SocketHelper::InvalidSocket())
- return LocalAddress;
-
- // Build the host address (use a random port)
- sockaddr_in SockAddr;
- memset(SockAddr.sin_zero, 0, sizeof(SockAddr.sin_zero));
- SockAddr.sin_addr.s_addr = INADDR_LOOPBACK;
- SockAddr.sin_family = AF_INET;
- SockAddr.sin_port = htons(4567);
-
- // Connect the socket
- if (connect(Socket, reinterpret_cast<sockaddr*>(&SockAddr), sizeof(SockAddr)) == -1)
- {
- SocketHelper::Close(Socket);
- return LocalAddress;
- }
-
- // Get the local address of the socket connection
- SocketHelper::LengthType Size = sizeof(SockAddr);
- if (getsockname(Socket, reinterpret_cast<sockaddr*>(&SockAddr), &Size) == -1)
- {
- SocketHelper::Close(Socket);
- return LocalAddress;
- }
-
- // Close the socket
- SocketHelper::Close(Socket);
-
- // Finally build the IP address
- LocalAddress.myAddress = SockAddr.sin_addr.s_addr;
-
- return LocalAddress;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the computer's public IP address (from the web point of view)
-////////////////////////////////////////////////////////////
-IPAddress IPAddress::GetPublicAddress(float Timeout)
-{
- // The trick here is more complicated, because the only way
- // to get our public IP address is to get it from a distant computer.
- // Here we get the web page from http://www.sfml-dev.org/ip-provider.php
- // and parse the result to extract our IP address
- // (not very hard : the web page contains only our IP address).
-
- Http Server("www.sfml-dev.org");
- Http::Request Request(Http::Request::Get, "/ip-provider.php");
- Http::Response Page = Server.SendRequest(Request, Timeout);
- if (Page.GetStatus() == Http::Response::Ok)
- return IPAddress(Page.GetBody());
-
- // Something failed: return an invalid address
- return IPAddress();
-}
-
-
-////////////////////////////////////////////////////////////
-/// Comparison operator ==
-////////////////////////////////////////////////////////////
-bool IPAddress::operator ==(const IPAddress& Other) const
-{
- return myAddress == Other.myAddress;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Comparison operator !=
-////////////////////////////////////////////////////////////
-bool IPAddress::operator !=(const IPAddress& Other) const
-{
- return myAddress != Other.myAddress;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Comparison operator <
-////////////////////////////////////////////////////////////
-bool IPAddress::operator <(const IPAddress& Other) const
-{
- return myAddress < Other.myAddress;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Comparison operator >
-////////////////////////////////////////////////////////////
-bool IPAddress::operator >(const IPAddress& Other) const
-{
- return myAddress > Other.myAddress;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Comparison operator <=
-////////////////////////////////////////////////////////////
-bool IPAddress::operator <=(const IPAddress& Other) const
-{
- return myAddress <= Other.myAddress;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Comparison operator >=
-////////////////////////////////////////////////////////////
-bool IPAddress::operator >=(const IPAddress& Other) const
-{
- return myAddress >= Other.myAddress;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Operator >> overload to extract an address from an input stream
-////////////////////////////////////////////////////////////
-std::istream& operator >>(std::istream& Stream, IPAddress& Address)
-{
- std::string Str;
- Stream >> Str;
- Address = IPAddress(Str);
-
- return Stream;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Operator << overload to print an address to an output stream
-////////////////////////////////////////////////////////////
-std::ostream& operator <<(std::ostream& Stream, const IPAddress& Address)
-{
- return Stream << Address.ToString();
-}
-
-} // namespace sf
diff --git a/src/SFML/Network/IpAddress.cpp b/src/SFML/Network/IpAddress.cpp
new file mode 100644
index 0000000..c4efaba
--- /dev/null
+++ b/src/SFML/Network/IpAddress.cpp
@@ -0,0 +1,255 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Network/IpAddress.hpp>
+#include <SFML/Network/Http.hpp>
+#include <SFML/Network/SocketImpl.hpp>
+#include <cstring>
+
+
+namespace
+{
+ sf::Uint32 resolve(const std::string& address)
+ {
+ if (address == "255.255.255.255")
+ {
+ // The broadcast address needs to be handled explicitely,
+ // because it is also the value returned by inet_addr on error
+ return INADDR_BROADCAST;
+ }
+ else
+ {
+ // Try to convert the address as a byte representation ("xxx.xxx.xxx.xxx")
+ sf::Uint32 ip = inet_addr(address.c_str());
+ if (ip != INADDR_NONE)
+ return ip;
+
+ // Not a valid address, try to convert it as a host name
+ addrinfo hints;
+ std::memset(&hints, 0, sizeof(hints));
+ hints.ai_family = AF_INET;
+ addrinfo* result = NULL;
+ if (getaddrinfo(address.c_str(), NULL, &hints, &result) == 0)
+ {
+ if (result)
+ {
+ ip = reinterpret_cast<sockaddr_in*>(result->ai_addr)->sin_addr.s_addr;
+ freeaddrinfo(result);
+ return ip;
+ }
+ }
+
+ // Not a valid address nor a host name
+ return 0;
+ }
+ }
+}
+
+
+namespace sf
+{
+////////////////////////////////////////////////////////////
+const IpAddress IpAddress::None;
+const IpAddress IpAddress::LocalHost(127, 0, 0, 1);
+const IpAddress IpAddress::Broadcast(255, 255, 255, 255);
+
+
+////////////////////////////////////////////////////////////
+IpAddress::IpAddress() :
+m_address(0)
+{
+ // We're using 0 (INADDR_ANY) instead of INADDR_NONE to represent the invalid address,
+ // because the latter is also the broadcast address (255.255.255.255); it's ok because
+ // SFML doesn't publicly use INADDR_ANY (it is always used implicitely)
+}
+
+
+////////////////////////////////////////////////////////////
+IpAddress::IpAddress(const std::string& address) :
+m_address(resolve(address))
+{
+}
+
+
+////////////////////////////////////////////////////////////
+IpAddress::IpAddress(const char* address) :
+m_address(resolve(address))
+{
+}
+
+
+////////////////////////////////////////////////////////////
+IpAddress::IpAddress(Uint8 byte0, Uint8 byte1, Uint8 byte2, Uint8 byte3) :
+m_address(htonl((byte0 << 24) | (byte1 << 16) | (byte2 << 8) | byte3))
+{
+}
+
+
+////////////////////////////////////////////////////////////
+IpAddress::IpAddress(Uint32 address) :
+m_address(htonl(address))
+{
+}
+
+
+////////////////////////////////////////////////////////////
+std::string IpAddress::toString() const
+{
+ in_addr address;
+ address.s_addr = m_address;
+
+ return inet_ntoa(address);
+}
+
+
+////////////////////////////////////////////////////////////
+Uint32 IpAddress::toInteger() const
+{
+ return ntohl(m_address);
+}
+
+
+////////////////////////////////////////////////////////////
+IpAddress IpAddress::getLocalAddress()
+{
+ // The method here is to connect a UDP socket to anyone (here to localhost),
+ // and get the local socket address with the getsockname function.
+ // UDP connection will not send anything to the network, so this function won't cause any overhead.
+
+ IpAddress localAddress;
+
+ // Create the socket
+ SocketHandle sock = socket(PF_INET, SOCK_DGRAM, 0);
+ if (sock == priv::SocketImpl::invalidSocket())
+ return localAddress;
+
+ // Connect the socket to localhost on any port
+ sockaddr_in address = priv::SocketImpl::createAddress(ntohl(INADDR_LOOPBACK), 0);
+ if (connect(sock, reinterpret_cast<sockaddr*>(&address), sizeof(address)) == -1)
+ {
+ priv::SocketImpl::close(sock);
+ return localAddress;
+ }
+
+ // Get the local address of the socket connection
+ priv::SocketImpl::AddrLength size = sizeof(address);
+ if (getsockname(sock, reinterpret_cast<sockaddr*>(&address), &size) == -1)
+ {
+ priv::SocketImpl::close(sock);
+ return localAddress;
+ }
+
+ // Close the socket
+ priv::SocketImpl::close(sock);
+
+ // Finally build the IP address
+ localAddress = IpAddress(ntohl(address.sin_addr.s_addr));
+
+ return localAddress;
+}
+
+
+////////////////////////////////////////////////////////////
+IpAddress IpAddress::getPublicAddress(Time timeout)
+{
+ // The trick here is more complicated, because the only way
+ // to get our public IP address is to get it from a distant computer.
+ // Here we get the web page from http://www.sfml-dev.org/ip-provider.php
+ // and parse the result to extract our IP address
+ // (not very hard: the web page contains only our IP address).
+
+ Http server("www.sfml-dev.org");
+ Http::Request request("/ip-provider.php", Http::Request::Get);
+ Http::Response page = server.sendRequest(request, timeout);
+ if (page.getStatus() == Http::Response::Ok)
+ return IpAddress(page.getBody());
+
+ // Something failed: return an invalid address
+ return IpAddress();
+}
+
+
+////////////////////////////////////////////////////////////
+bool operator ==(const IpAddress& left, const IpAddress& right)
+{
+ return left.toInteger() == right.toInteger();
+}
+
+
+////////////////////////////////////////////////////////////
+bool operator !=(const IpAddress& left, const IpAddress& right)
+{
+ return !(left == right);
+}
+
+
+////////////////////////////////////////////////////////////
+bool operator <(const IpAddress& left, const IpAddress& right)
+{
+ return left.toInteger() < right.toInteger();
+}
+
+
+////////////////////////////////////////////////////////////
+bool operator >(const IpAddress& left, const IpAddress& right)
+{
+ return right < left;
+}
+
+
+////////////////////////////////////////////////////////////
+bool operator <=(const IpAddress& left, const IpAddress& right)
+{
+ return !(right < left);
+}
+
+
+////////////////////////////////////////////////////////////
+bool operator >=(const IpAddress& left, const IpAddress& right)
+{
+ return !(left < right);
+}
+
+
+////////////////////////////////////////////////////////////
+std::istream& operator >>(std::istream& stream, IpAddress& address)
+{
+ std::string str;
+ stream >> str;
+ address = IpAddress(str);
+
+ return stream;
+}
+
+
+////////////////////////////////////////////////////////////
+std::ostream& operator <<(std::ostream& stream, const IpAddress& address)
+{
+ return stream << address.toString();
+}
+
+} // namespace sf
diff --git a/src/SFML/Network/Makefile b/src/SFML/Network/Makefile
deleted file mode 100755
index 62fb673..0000000
--- a/src/SFML/Network/Makefile
+++ /dev/null
@@ -1,34 +0,0 @@
-SRC = $(wildcard *.cpp ./Unix/*.cpp)
-OBJ = $(SRC:.cpp=.o)
-
-ifeq ($(STATIC), yes)
- LIB = libsfml-network-s.a
- LIBNAME = $(LIBPATH)/$(LIB)
- INSTALL =
-else
- LIB = libsfml-network.so
- LIBNAME = $(LIBPATH)/$(LIB).$(VERSION)
- INSTALL = && $(LN) $(LNFLAGS) $(LIB).$(VERSION) $(DESTLIBDIR)/$(LIB)
-endif
-
-all: $(LIB)
-
-libsfml-network-s.a: $(OBJ)
- $(AR) $(ARFLAGS) $(LIBNAME) $(OBJ)
-
-libsfml-network.so: $(OBJ)
- $(CPP) $(LDFLAGS) -Wl,-soname,$(LIB).$(VERSION) -o $(LIBNAME) $(OBJ)
-
-$(OBJ): %.o: %.cpp
- $(CPP) -o $@ -c $< $(CFLAGS)
-
-.PHONY: clean mrproper
-
-clean:
- @rm -rf $(OBJ)
-
-mrproper: clean
- @rm -rf $(LIBNAME)
-
-install:
- @($(CP) $(LIBNAME) $(DESTLIBDIR) $(INSTALL))
diff --git a/src/SFML/Network/Packet.cpp b/src/SFML/Network/Packet.cpp
index 7eaea50..053fa4e 100755..100644
--- a/src/SFML/Network/Packet.cpp
+++ b/src/SFML/Network/Packet.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -26,26 +26,24 @@
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Network/Packet.hpp>
-#include <SFML/Network/SocketHelper.hpp>
-#include <string.h>
+#include <SFML/Network/SocketImpl.hpp>
+#include <SFML/System/String.hpp>
+#include <cstring>
+#include <cwchar>
namespace sf
{
////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
Packet::Packet() :
-myReadPos(0),
-myIsValid(true)
+m_readPos(0),
+m_isValid(true)
{
}
////////////////////////////////////////////////////////////
-/// Virtual destructor
-////////////////////////////////////////////////////////////
Packet::~Packet()
{
@@ -53,230 +51,250 @@ Packet::~Packet()
////////////////////////////////////////////////////////////
-/// Append data to the end of the packet
-////////////////////////////////////////////////////////////
-void Packet::Append(const void* Data, std::size_t SizeInBytes)
+void Packet::append(const void* data, std::size_t sizeInBytes)
{
- if (Data && (SizeInBytes > 0))
+ if (data && (sizeInBytes > 0))
{
- std::size_t Start = myData.size();
- myData.resize(Start + SizeInBytes);
- memcpy(&myData[Start], Data, SizeInBytes);
+ std::size_t start = m_data.size();
+ m_data.resize(start + sizeInBytes);
+ std::memcpy(&m_data[start], data, sizeInBytes);
}
}
////////////////////////////////////////////////////////////
-/// Clear the packet data
-////////////////////////////////////////////////////////////
-void Packet::Clear()
+void Packet::clear()
{
- myData.clear();
- myReadPos = 0;
- myIsValid = true;
+ m_data.clear();
+ m_readPos = 0;
+ m_isValid = true;
}
////////////////////////////////////////////////////////////
-/// Get a pointer to the data contained in the packet
-/// Warning : the returned pointer may be invalid after you
-/// append data to the packet
-////////////////////////////////////////////////////////////
-const char* Packet::GetData() const
+const void* Packet::getData() const
{
- return !myData.empty() ? &myData[0] : NULL;
+ return !m_data.empty() ? &m_data[0] : NULL;
}
////////////////////////////////////////////////////////////
-/// Get the size of the data contained in the packet
-////////////////////////////////////////////////////////////
-std::size_t Packet::GetDataSize() const
+std::size_t Packet::getDataSize() const
{
- return myData.size();
+ return m_data.size();
}
////////////////////////////////////////////////////////////
-/// Tell if the reading position has reached the end of the packet
-////////////////////////////////////////////////////////////
-bool Packet::EndOfPacket() const
+bool Packet::endOfPacket() const
{
- return myReadPos >= myData.size();
+ return m_readPos >= m_data.size();
}
////////////////////////////////////////////////////////////
-/// Tell if the packet is valid for reading
-////////////////////////////////////////////////////////////
-Packet::operator bool() const
+Packet::operator BoolType() const
{
- return myIsValid;
+ return m_isValid ? &Packet::checkSize : NULL;
}
////////////////////////////////////////////////////////////
-/// Operator >> overloads to extract data from the packet
-////////////////////////////////////////////////////////////
-Packet& Packet::operator >>(bool& Data)
+Packet& Packet::operator >>(bool& data)
{
- Uint8 Value;
- if (*this >> Value)
- Data = (Value != 0);
+ Uint8 value;
+ if (*this >> value)
+ data = (value != 0);
return *this;
}
-Packet& Packet::operator >>(Int8& Data)
+
+
+////////////////////////////////////////////////////////////
+Packet& Packet::operator >>(Int8& data)
{
- if (CheckSize(sizeof(Data)))
+ if (checkSize(sizeof(data)))
{
- Data = *reinterpret_cast<const Int8*>(GetData() + myReadPos);
- myReadPos += sizeof(Data);
+ data = *reinterpret_cast<const Int8*>(&m_data[m_readPos]);
+ m_readPos += sizeof(data);
}
return *this;
}
-Packet& Packet::operator >>(Uint8& Data)
+
+
+////////////////////////////////////////////////////////////
+Packet& Packet::operator >>(Uint8& data)
{
- if (CheckSize(sizeof(Data)))
+ if (checkSize(sizeof(data)))
{
- Data = *reinterpret_cast<const Uint8*>(GetData() + myReadPos);
- myReadPos += sizeof(Data);
+ data = *reinterpret_cast<const Uint8*>(&m_data[m_readPos]);
+ m_readPos += sizeof(data);
}
return *this;
}
-Packet& Packet::operator >>(Int16& Data)
+
+
+////////////////////////////////////////////////////////////
+Packet& Packet::operator >>(Int16& data)
{
- if (CheckSize(sizeof(Data)))
+ if (checkSize(sizeof(data)))
{
- Data = ntohs(*reinterpret_cast<const Int16*>(GetData() + myReadPos));
- myReadPos += sizeof(Data);
+ data = ntohs(*reinterpret_cast<const Int16*>(&m_data[m_readPos]));
+ m_readPos += sizeof(data);
}
return *this;
}
-Packet& Packet::operator >>(Uint16& Data)
+
+
+////////////////////////////////////////////////////////////
+Packet& Packet::operator >>(Uint16& data)
{
- if (CheckSize(sizeof(Data)))
+ if (checkSize(sizeof(data)))
{
- Data = ntohs(*reinterpret_cast<const Uint16*>(GetData() + myReadPos));
- myReadPos += sizeof(Data);
+ data = ntohs(*reinterpret_cast<const Uint16*>(&m_data[m_readPos]));
+ m_readPos += sizeof(data);
}
return *this;
}
-Packet& Packet::operator >>(Int32& Data)
+
+
+////////////////////////////////////////////////////////////
+Packet& Packet::operator >>(Int32& data)
{
- if (CheckSize(sizeof(Data)))
+ if (checkSize(sizeof(data)))
{
- Data = ntohl(*reinterpret_cast<const Int32*>(GetData() + myReadPos));
- myReadPos += sizeof(Data);
+ data = ntohl(*reinterpret_cast<const Int32*>(&m_data[m_readPos]));
+ m_readPos += sizeof(data);
}
return *this;
}
-Packet& Packet::operator >>(Uint32& Data)
+
+
+////////////////////////////////////////////////////////////
+Packet& Packet::operator >>(Uint32& data)
{
- if (CheckSize(sizeof(Data)))
+ if (checkSize(sizeof(data)))
{
- Data = ntohl(*reinterpret_cast<const Uint32*>(GetData() + myReadPos));
- myReadPos += sizeof(Data);
+ data = ntohl(*reinterpret_cast<const Uint32*>(&m_data[m_readPos]));
+ m_readPos += sizeof(data);
}
return *this;
}
-Packet& Packet::operator >>(float& Data)
+
+
+////////////////////////////////////////////////////////////
+Packet& Packet::operator >>(float& data)
{
- if (CheckSize(sizeof(Data)))
+ if (checkSize(sizeof(data)))
{
- Data = *reinterpret_cast<const float*>(GetData() + myReadPos);
- myReadPos += sizeof(Data);
+ data = *reinterpret_cast<const float*>(&m_data[m_readPos]);
+ m_readPos += sizeof(data);
}
return *this;
}
-Packet& Packet::operator >>(double& Data)
+
+
+////////////////////////////////////////////////////////////
+Packet& Packet::operator >>(double& data)
{
- if (CheckSize(sizeof(Data)))
+ if (checkSize(sizeof(data)))
{
- Data = *reinterpret_cast<const double*>(GetData() + myReadPos);
- myReadPos += sizeof(Data);
+ data = *reinterpret_cast<const double*>(&m_data[m_readPos]);
+ m_readPos += sizeof(data);
}
return *this;
}
-Packet& Packet::operator >>(char* Data)
+
+
+////////////////////////////////////////////////////////////
+Packet& Packet::operator >>(char* data)
{
// First extract string length
- Uint32 Length;
- *this >> Length;
+ Uint32 length = 0;
+ *this >> length;
- if ((Length > 0) && CheckSize(Length))
+ if ((length > 0) && checkSize(length))
{
// Then extract characters
- memcpy(Data, GetData() + myReadPos, Length);
- Data[Length] = '\0';
+ std::memcpy(data, &m_data[m_readPos], length);
+ data[length] = '\0';
// Update reading position
- myReadPos += Length;
+ m_readPos += length;
}
return *this;
}
-Packet& Packet::operator >>(std::string& Data)
+
+
+////////////////////////////////////////////////////////////
+Packet& Packet::operator >>(std::string& data)
{
// First extract string length
- Uint32 Length;
- *this >> Length;
+ Uint32 length = 0;
+ *this >> length;
- Data.clear();
- if ((Length > 0) && CheckSize(Length))
+ data.clear();
+ if ((length > 0) && checkSize(length))
{
// Then extract characters
- Data.assign(GetData() + myReadPos, Length);
+ data.assign(&m_data[m_readPos], length);
// Update reading position
- myReadPos += Length;
+ m_readPos += length;
}
return *this;
}
-Packet& Packet::operator >>(wchar_t* Data)
+
+
+////////////////////////////////////////////////////////////
+Packet& Packet::operator >>(wchar_t* data)
{
// First extract string length
- Uint32 Length;
- *this >> Length;
+ Uint32 length = 0;
+ *this >> length;
- if ((Length > 0) && CheckSize(Length * sizeof(Int32)))
+ if ((length > 0) && checkSize(length * sizeof(Uint32)))
{
// Then extract characters
- for (Uint32 i = 0; i < Length; ++i)
+ for (Uint32 i = 0; i < length; ++i)
{
- Uint32 c;
- *this >> c;
- Data[i] = static_cast<wchar_t>(c);
+ Uint32 character = 0;
+ *this >> character;
+ data[i] = static_cast<wchar_t>(character);
}
- Data[Length] = L'\0';
+ data[length] = L'\0';
}
return *this;
}
-Packet& Packet::operator >>(std::wstring& Data)
+
+
+////////////////////////////////////////////////////////////
+Packet& Packet::operator >>(std::wstring& data)
{
// First extract string length
- Uint32 Length;
- *this >> Length;
+ Uint32 length = 0;
+ *this >> length;
- Data.clear();
- if ((Length > 0) && CheckSize(Length * sizeof(Int32)))
+ data.clear();
+ if ((length > 0) && checkSize(length * sizeof(Uint32)))
{
// Then extract characters
- for (Uint32 i = 0; i < Length; ++i)
+ for (Uint32 i = 0; i < length; ++i)
{
- Uint32 c;
- *this >> c;
- Data += static_cast<wchar_t>(c);
+ Uint32 character = 0;
+ *this >> character;
+ data += static_cast<wchar_t>(character);
}
}
@@ -285,109 +303,160 @@ Packet& Packet::operator >>(std::wstring& Data)
////////////////////////////////////////////////////////////
-/// Operator << overloads to put data into the packet
+Packet& Packet::operator >>(String& data)
+{
+ // First extract the string length
+ Uint32 length = 0;
+ *this >> length;
+
+ data.clear();
+ if ((length > 0) && checkSize(length * sizeof(Uint32)))
+ {
+ // Then extract characters
+ for (Uint32 i = 0; i < length; ++i)
+ {
+ Uint32 character = 0;
+ *this >> character;
+ data += character;
+ }
+ }
+
+ return *this;
+}
+
+
////////////////////////////////////////////////////////////
-Packet& Packet::operator <<(bool Data)
+Packet& Packet::operator <<(bool data)
{
- *this << static_cast<Uint8>(Data);
+ *this << static_cast<Uint8>(data);
return *this;
}
-Packet& Packet::operator <<(Int8 Data)
+
+
+////////////////////////////////////////////////////////////
+Packet& Packet::operator <<(Int8 data)
{
- Append(&Data, sizeof(Data));
+ append(&data, sizeof(data));
return *this;
}
-Packet& Packet::operator <<(Uint8 Data)
+
+
+////////////////////////////////////////////////////////////
+Packet& Packet::operator <<(Uint8 data)
{
- Append(&Data, sizeof(Data));
+ append(&data, sizeof(data));
return *this;
}
-Packet& Packet::operator <<(Int16 Data)
+
+
+////////////////////////////////////////////////////////////
+Packet& Packet::operator <<(Int16 data)
{
- Int16 ToWrite = htons(Data);
- Append(&ToWrite, sizeof(ToWrite));
+ Int16 toWrite = htons(data);
+ append(&toWrite, sizeof(toWrite));
return *this;
}
-Packet& Packet::operator <<(Uint16 Data)
+
+
+////////////////////////////////////////////////////////////
+Packet& Packet::operator <<(Uint16 data)
{
- Uint16 ToWrite = htons(Data);
- Append(&ToWrite, sizeof(ToWrite));
+ Uint16 toWrite = htons(data);
+ append(&toWrite, sizeof(toWrite));
return *this;
}
-Packet& Packet::operator <<(Int32 Data)
+
+
+////////////////////////////////////////////////////////////
+Packet& Packet::operator <<(Int32 data)
{
- Int32 ToWrite = htonl(Data);
- Append(&ToWrite, sizeof(ToWrite));
+ Int32 toWrite = htonl(data);
+ append(&toWrite, sizeof(toWrite));
return *this;
}
-Packet& Packet::operator <<(Uint32 Data)
+
+
+////////////////////////////////////////////////////////////
+Packet& Packet::operator <<(Uint32 data)
{
- Uint32 ToWrite = htonl(Data);
- Append(&ToWrite, sizeof(ToWrite));
+ Uint32 toWrite = htonl(data);
+ append(&toWrite, sizeof(toWrite));
return *this;
}
-Packet& Packet::operator <<(float Data)
+
+
+////////////////////////////////////////////////////////////
+Packet& Packet::operator <<(float data)
{
- Append(&Data, sizeof(Data));
+ append(&data, sizeof(data));
return *this;
}
-Packet& Packet::operator <<(double Data)
+
+
+////////////////////////////////////////////////////////////
+Packet& Packet::operator <<(double data)
{
- Append(&Data, sizeof(Data));
+ append(&data, sizeof(data));
return *this;
}
-Packet& Packet::operator <<(const char* Data)
+
+
+////////////////////////////////////////////////////////////
+Packet& Packet::operator <<(const char* data)
{
// First insert string length
- Uint32 Length = 0;
- for (const char* c = Data; *c != '\0'; ++c)
- ++Length;
- *this << Length;
+ Uint32 length = std::strlen(data);
+ *this << length;
// Then insert characters
- Append(Data, Length * sizeof(char));
+ append(data, length * sizeof(char));
return *this;
}
-Packet& Packet::operator <<(const std::string& Data)
+
+
+////////////////////////////////////////////////////////////
+Packet& Packet::operator <<(const std::string& data)
{
// First insert string length
- Uint32 Length = static_cast<Uint32>(Data.size());
- *this << Length;
+ Uint32 length = static_cast<Uint32>(data.size());
+ *this << length;
// Then insert characters
- if (Length > 0)
- {
- Append(Data.c_str(), Length * sizeof(std::string::value_type));
- }
+ if (length > 0)
+ append(data.c_str(), length * sizeof(std::string::value_type));
return *this;
}
-Packet& Packet::operator <<(const wchar_t* Data)
+
+
+////////////////////////////////////////////////////////////
+Packet& Packet::operator <<(const wchar_t* data)
{
// First insert string length
- Uint32 Length = 0;
- for (const wchar_t* c = Data; *c != L'\0'; ++c)
- ++Length;
- *this << Length;
+ Uint32 length = std::wcslen(data);
+ *this << length;
// Then insert characters
- for (const wchar_t* c = Data; *c != L'\0'; ++c)
- *this << static_cast<Int32>(*c);
+ for (const wchar_t* c = data; *c != L'\0'; ++c)
+ *this << static_cast<Uint32>(*c);
return *this;
}
-Packet& Packet::operator <<(const std::wstring& Data)
+
+
+////////////////////////////////////////////////////////////
+Packet& Packet::operator <<(const std::wstring& data)
{
// First insert string length
- Uint32 Length = static_cast<Uint32>(Data.size());
- *this << Length;
+ Uint32 length = static_cast<Uint32>(data.size());
+ *this << length;
// Then insert characters
- if (Length > 0)
+ if (length > 0)
{
- for (std::wstring::const_iterator c = Data.begin(); c != Data.end(); ++c)
- *this << static_cast<Int32>(*c);
+ for (std::wstring::const_iterator c = data.begin(); c != data.end(); ++c)
+ *this << static_cast<Uint32>(*c);
}
return *this;
@@ -395,32 +464,44 @@ Packet& Packet::operator <<(const std::wstring& Data)
////////////////////////////////////////////////////////////
-/// Check if the packet can extract a given size of bytes
-////////////////////////////////////////////////////////////
-bool Packet::CheckSize(std::size_t Size)
+Packet& Packet::operator <<(const String& data)
{
- myIsValid = myIsValid && (myReadPos + Size <= myData.size());
+ // First insert the string length
+ Uint32 length = static_cast<Uint32>(data.getSize());
+ *this << length;
- return myIsValid;
+ // Then insert characters
+ if (length > 0)
+ {
+ for (String::ConstIterator c = data.begin(); c != data.end(); ++c)
+ *this << *c;
+ }
+
+ return *this;
}
////////////////////////////////////////////////////////////
-/// Called before the packet is sent to the network
-////////////////////////////////////////////////////////////
-const char* Packet::OnSend(std::size_t& DataSize)
+bool Packet::checkSize(std::size_t size)
{
- DataSize = GetDataSize();
- return GetData();
+ m_isValid = m_isValid && (m_readPos + size <= m_data.size());
+
+ return m_isValid;
}
////////////////////////////////////////////////////////////
-/// Called after the packet has been received from the network
+const void* Packet::onSend(std::size_t& size)
+{
+ size = getDataSize();
+ return getData();
+}
+
+
////////////////////////////////////////////////////////////
-void Packet::OnReceive(const char* Data, std::size_t DataSize)
+void Packet::onReceive(const void* data, std::size_t size)
{
- Append(Data, DataSize);
+ append(data, size);
}
} // namespace sf
diff --git a/src/SFML/Network/SelectorBase.cpp b/src/SFML/Network/SelectorBase.cpp
deleted file mode 100755
index eeca707..0000000
--- a/src/SFML/Network/SelectorBase.cpp
+++ /dev/null
@@ -1,132 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-#ifdef _MSC_VER
- #pragma warning(disable : 4127) // "conditional expression is constant" generated by the FD_SET macro
-#endif
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Network/SelectorBase.hpp>
-
-
-namespace sf
-{
-////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
-SelectorBase::SelectorBase() :
-myMaxSocket(0)
-{
- Clear();
-}
-
-
-////////////////////////////////////////////////////////////
-/// Add a socket to watch
-////////////////////////////////////////////////////////////
-void SelectorBase::Add(SocketHelper::SocketType Socket)
-{
- FD_SET(Socket, &mySet);
-
- int Size = static_cast<int>(Socket);
- if (Size > myMaxSocket)
- myMaxSocket = Size;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Remove a socket
-////////////////////////////////////////////////////////////
-void SelectorBase::Remove(SocketHelper::SocketType Socket)
-{
- FD_CLR(Socket, &mySet);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Remove all sockets
-////////////////////////////////////////////////////////////
-void SelectorBase::Clear()
-{
- FD_ZERO(&mySet);
- FD_ZERO(&mySetReady);
-
- myMaxSocket = 0;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Wait and collect sockets which are ready for reading.
-/// This functions will return either when at least one socket
-/// is ready, or when the given time is out
-////////////////////////////////////////////////////////////
-unsigned int SelectorBase::Wait(float Timeout)
-{
- // Setup the timeout structure
- timeval Time;
- Time.tv_sec = static_cast<long>(Timeout);
- Time.tv_usec = (static_cast<long>(Timeout * 1000) % 1000) * 1000;
-
- // Prepare the set of sockets to return
- mySetReady = mySet;
-
- // Wait until one of the sockets is ready for reading, or timeout is reached
- int NbSockets = select(myMaxSocket + 1, &mySetReady, NULL, NULL, Timeout > 0 ? &Time : NULL);
-
- return NbSockets >= 0 ? static_cast<unsigned int>(NbSockets) : 0;
-}
-
-
-////////////////////////////////////////////////////////////
-/// After a call to Wait(), get the Index-th socket which is
-/// ready for reading. The total number of sockets ready
-/// is the integer returned by the previous call to Wait()
-////////////////////////////////////////////////////////////
-SocketHelper::SocketType SelectorBase::GetSocketReady(unsigned int Index)
-{
- // The standard FD_xxx interface doesn't define a direct access,
- // so we must go through the whole set to find the socket we're looking for
- for (int i = 0; i < myMaxSocket + 1; ++i)
- {
- if (FD_ISSET(i, &mySetReady))
- {
- // Current socket is ready, but is it the Index-th one ?
- if (Index > 0)
- {
- Index--;
- }
- else
- {
- return static_cast<SocketHelper::SocketType>(i);
- }
- }
- }
-
- // Invalid index : return an invalid socket
- return SocketHelper::InvalidSocket();
-}
-
-} // namespace sf
diff --git a/src/SFML/Network/Socket.cpp b/src/SFML/Network/Socket.cpp
new file mode 100644
index 0000000..3e8489f
--- /dev/null
+++ b/src/SFML/Network/Socket.cpp
@@ -0,0 +1,144 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Network/Socket.hpp>
+#include <SFML/Network/SocketImpl.hpp>
+#include <SFML/System/Err.hpp>
+
+
+namespace sf
+{
+////////////////////////////////////////////////////////////
+Socket::Socket(Type type) :
+m_type (type),
+m_socket (priv::SocketImpl::invalidSocket()),
+m_isBlocking(true)
+{
+
+}
+
+
+////////////////////////////////////////////////////////////
+Socket::~Socket()
+{
+ // Close the socket before it gets destructed
+ close();
+}
+
+
+////////////////////////////////////////////////////////////
+void Socket::setBlocking(bool blocking)
+{
+ // Apply if the socket is already created
+ if (m_socket != priv::SocketImpl::invalidSocket())
+ priv::SocketImpl::setBlocking(m_socket, blocking);
+
+ m_isBlocking = blocking;
+}
+
+
+////////////////////////////////////////////////////////////
+bool Socket::isBlocking() const
+{
+ return m_isBlocking;
+}
+
+
+////////////////////////////////////////////////////////////
+SocketHandle Socket::getHandle() const
+{
+ return m_socket;
+}
+
+
+////////////////////////////////////////////////////////////
+void Socket::create()
+{
+ // Don't create the socket if it already exists
+ if (m_socket == priv::SocketImpl::invalidSocket())
+ {
+ SocketHandle handle = socket(PF_INET, m_type == Tcp ? SOCK_STREAM : SOCK_DGRAM, 0);
+ create(handle);
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void Socket::create(SocketHandle handle)
+{
+ // Don't create the socket if it already exists
+ if (m_socket == priv::SocketImpl::invalidSocket())
+ {
+ // Assign the new handle
+ m_socket = handle;
+
+ // Set the current blocking state
+ setBlocking(m_isBlocking);
+
+ if (m_type == Tcp)
+ {
+ // Disable the Nagle algorithm (ie. removes buffering of TCP packets)
+ int yes = 1;
+ if (setsockopt(m_socket, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char*>(&yes), sizeof(yes)) == -1)
+ {
+ err() << "Failed to set socket option \"TCP_NODELAY\" ; "
+ << "all your TCP packets will be buffered" << std::endl;
+ }
+
+ // On Mac OS X, disable the SIGPIPE signal on disconnection
+ #ifdef SFML_SYSTEM_MACOS
+ if (setsockopt(m_socket, SOL_SOCKET, SO_NOSIGPIPE, reinterpret_cast<char*>(&yes), sizeof(yes)) == -1)
+ {
+ err() << "Failed to set socket option \"SO_NOSIGPIPE\"" << std::endl;
+ }
+ #endif
+ }
+ else
+ {
+ // Enable broadcast by default for UDP sockets
+ int yes = 1;
+ if (setsockopt(m_socket, SOL_SOCKET, SO_BROADCAST, reinterpret_cast<char*>(&yes), sizeof(yes)) == -1)
+ {
+ err() << "Failed to enable broadcast on UDP socket" << std::endl;
+ }
+ }
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void Socket::close()
+{
+ // Close the socket
+ if (m_socket != priv::SocketImpl::invalidSocket())
+ {
+ priv::SocketImpl::close(m_socket);
+ m_socket = priv::SocketImpl::invalidSocket();
+ }
+}
+
+} // namespace sf
diff --git a/src/SFML/System/Platform.hpp b/src/SFML/Network/SocketImpl.hpp
index f9b7e12..163489d 100755..100644
--- a/src/SFML/System/Platform.hpp
+++ b/src/SFML/Network/SocketImpl.hpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -22,9 +22,6 @@
//
////////////////////////////////////////////////////////////
-#ifndef SFML_PLATFORM_HPP
-#define SFML_PLATFORM_HPP
-
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
@@ -33,13 +30,10 @@
#if defined(SFML_SYSTEM_WINDOWS)
- #include <SFML/System/Win32/Platform.hpp>
+ #include <SFML/Network/Win32/SocketImpl.hpp>
-#elif defined(SFML_SYSTEM_LINUX) || defined(SFML_SYSTEM_MACOS) || defined(SFML_SYSTEM_FREEBSD)
+#else
- #include <SFML/System/Unix/Platform.hpp>
+ #include <SFML/Network/Unix/SocketImpl.hpp>
#endif
-
-
-#endif // SFML_PLATFORM_HPP
diff --git a/src/SFML/Network/SocketSelector.cpp b/src/SFML/Network/SocketSelector.cpp
new file mode 100644
index 0000000..b6df372
--- /dev/null
+++ b/src/SFML/Network/SocketSelector.cpp
@@ -0,0 +1,141 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Network/SocketSelector.hpp>
+#include <SFML/Network/Socket.hpp>
+#include <SFML/Network/SocketImpl.hpp>
+#include <SFML/System/Err.hpp>
+#include <utility>
+
+#ifdef _MSC_VER
+ #pragma warning(disable : 4127) // "conditional expression is constant" generated by the FD_SET macro
+#endif
+
+
+namespace sf
+{
+////////////////////////////////////////////////////////////
+struct SocketSelector::SocketSelectorImpl
+{
+ fd_set AllSockets; ///< Set containing all the sockets handles
+ fd_set SocketsReady; ///< Set containing handles of the sockets that are ready
+ int MaxSocket; ///< Maximum socket handle
+};
+
+
+////////////////////////////////////////////////////////////
+SocketSelector::SocketSelector() :
+m_impl(new SocketSelectorImpl)
+{
+ clear();
+}
+
+
+////////////////////////////////////////////////////////////
+SocketSelector::SocketSelector(const SocketSelector& copy) :
+m_impl(new SocketSelectorImpl(*copy.m_impl))
+{
+
+}
+
+
+////////////////////////////////////////////////////////////
+SocketSelector::~SocketSelector()
+{
+ delete m_impl;
+}
+
+
+////////////////////////////////////////////////////////////
+void SocketSelector::add(Socket& socket)
+{
+ SocketHandle handle = socket.getHandle();
+ if (handle != priv::SocketImpl::invalidSocket())
+ {
+ FD_SET(handle, &m_impl->AllSockets);
+
+ int size = static_cast<int>(handle);
+ if (size > m_impl->MaxSocket)
+ m_impl->MaxSocket = size;
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void SocketSelector::remove(Socket& socket)
+{
+ FD_CLR(socket.getHandle(), &m_impl->AllSockets);
+ FD_CLR(socket.getHandle(), &m_impl->SocketsReady);
+}
+
+
+////////////////////////////////////////////////////////////
+void SocketSelector::clear()
+{
+ FD_ZERO(&m_impl->AllSockets);
+ FD_ZERO(&m_impl->SocketsReady);
+
+ m_impl->MaxSocket = 0;
+}
+
+
+////////////////////////////////////////////////////////////
+bool SocketSelector::wait(Time timeout)
+{
+ // Setup the timeout
+ timeval time;
+ time.tv_sec = static_cast<long>(timeout.asMicroseconds() / 1000000);
+ time.tv_usec = static_cast<long>(timeout.asMicroseconds() % 1000000);
+
+ // Initialize the set that will contain the sockets that are ready
+ m_impl->SocketsReady = m_impl->AllSockets;
+
+ // Wait until one of the sockets is ready for reading, or timeout is reached
+ int count = select(m_impl->MaxSocket + 1, &m_impl->SocketsReady, NULL, NULL, timeout != Time::Zero ? &time : NULL);
+
+ return count > 0;
+}
+
+
+////////////////////////////////////////////////////////////
+bool SocketSelector::isReady(Socket& socket) const
+{
+ return FD_ISSET(socket.getHandle(), &m_impl->SocketsReady) != 0;
+}
+
+
+////////////////////////////////////////////////////////////
+SocketSelector& SocketSelector::operator =(const SocketSelector& right)
+{
+ SocketSelector temp(right);
+
+ std::swap(m_impl, temp.m_impl);
+
+ return *this;
+}
+
+} // namespace sf
diff --git a/src/SFML/Network/SocketTCP.cpp b/src/SFML/Network/SocketTCP.cpp
deleted file mode 100755
index 6a200fc..0000000
--- a/src/SFML/Network/SocketTCP.cpp
+++ /dev/null
@@ -1,511 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Network/SocketTCP.hpp>
-#include <SFML/Network/IPAddress.hpp>
-#include <SFML/Network/Packet.hpp>
-#include <SFML/Network/SocketHelper.hpp>
-#include <algorithm>
-#include <iostream>
-#include <string.h>
-
-
-#ifdef _MSC_VER
- #pragma warning(disable : 4127) // "conditional expression is constant" generated by the FD_SET macro
-#endif
-
-
-namespace sf
-{
-////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
-SocketTCP::SocketTCP()
-{
- Create(SocketHelper::InvalidSocket());
-}
-
-
-////////////////////////////////////////////////////////////
-/// Change the blocking state of the socket
-////////////////////////////////////////////////////////////
-void SocketTCP::SetBlocking(bool Blocking)
-{
- // Make sure our socket is valid
- if (!IsValid())
- Create();
-
- SocketHelper::SetBlocking(mySocket, Blocking);
- myIsBlocking = Blocking;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Connect to another computer on a specified port
-////////////////////////////////////////////////////////////
-Socket::Status SocketTCP::Connect(unsigned short Port, const IPAddress& HostAddress, float Timeout)
-{
- // Make sure our socket is valid
- if (!IsValid())
- Create();
-
- // Build the host address
- sockaddr_in SockAddr;
- memset(SockAddr.sin_zero, 0, sizeof(SockAddr.sin_zero));
- SockAddr.sin_addr.s_addr = inet_addr(HostAddress.ToString().c_str());
- SockAddr.sin_family = AF_INET;
- SockAddr.sin_port = htons(Port);
-
- if (Timeout <= 0)
- {
- // ----- We're not using a timeout : just try to connect -----
-
- if (connect(mySocket, reinterpret_cast<sockaddr*>(&SockAddr), sizeof(SockAddr)) == -1)
- {
- // Failed to connect
- return SocketHelper::GetErrorStatus();
- }
-
- // Connection succeeded
- return Socket::Done;
- }
- else
- {
- // ----- We're using a timeout : we'll need a few tricks to make it work -----
-
- // Save the previous blocking state
- bool IsBlocking = myIsBlocking;
-
- // Switch to non-blocking to enable our connection timeout
- if (IsBlocking)
- SetBlocking(false);
-
- // Try to connect to host
- if (connect(mySocket, reinterpret_cast<sockaddr*>(&SockAddr), sizeof(SockAddr)) >= 0)
- {
- // We got instantly connected! (it may no happen a lot...)
- return Socket::Done;
- }
-
- // Get the error status
- Socket::Status Status = SocketHelper::GetErrorStatus();
-
- // If we were in non-blocking mode, return immediatly
- if (!IsBlocking)
- return Status;
-
- // Otherwise, wait until something happens to our socket (success, timeout or error)
- if (Status == Socket::NotReady)
- {
- // Setup the selector
- fd_set Selector;
- FD_ZERO(&Selector);
- FD_SET(mySocket, &Selector);
-
- // Setup the timeout
- timeval Time;
- Time.tv_sec = static_cast<long>(Timeout);
- Time.tv_usec = (static_cast<long>(Timeout * 1000) % 1000) * 1000;
-
- // Wait for something to write on our socket (which means that the connection request has returned)
- if (select(static_cast<int>(mySocket + 1), NULL, &Selector, NULL, &Time) > 0)
- {
- // At this point the connection may have been either accepted or refused.
- // To know whether it's a success or a failure, we try to retrieve the name of the connected peer
- SocketHelper::LengthType Size = sizeof(SockAddr);
- if (getpeername(mySocket, reinterpret_cast<sockaddr*>(&SockAddr), &Size) != -1)
- {
- // Connection accepted
- Status = Socket::Done;
- }
- else
- {
- // Connection failed
- Status = SocketHelper::GetErrorStatus();
- }
- }
- else
- {
- // Failed to connect before timeout is over
- Status = SocketHelper::GetErrorStatus();
- }
- }
-
- // Switch back to blocking mode
- SetBlocking(true);
-
- return Status;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Listen to a specified port for incoming data or connections
-////////////////////////////////////////////////////////////
-bool SocketTCP::Listen(unsigned short Port)
-{
- // Make sure our socket is valid
- if (!IsValid())
- Create();
-
- // Build the address
- sockaddr_in SockAddr;
- memset(SockAddr.sin_zero, 0, sizeof(SockAddr.sin_zero));
- SockAddr.sin_addr.s_addr = htonl(INADDR_ANY);
- SockAddr.sin_family = AF_INET;
- SockAddr.sin_port = htons(Port);
-
- // Bind the socket to the specified port
- if (bind(mySocket, reinterpret_cast<sockaddr*>(&SockAddr), sizeof(SockAddr)) == -1)
- {
- // Not likely to happen, but...
- std::cerr << "Failed to bind socket to port " << Port << std::endl;
- return false;
- }
-
- // Listen to the bound port
- if (listen(mySocket, 0) == -1)
- {
- // Oops, socket is deaf
- std::cerr << "Failed to listen to port " << Port << std::endl;
- return false;
- }
-
- return true;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Wait for a connection (must be listening to a port).
-/// This function will block if the socket is blocking
-////////////////////////////////////////////////////////////
-Socket::Status SocketTCP::Accept(SocketTCP& Connected, IPAddress* Address)
-{
- // Address that will be filled with client informations
- sockaddr_in ClientAddress;
- SocketHelper::LengthType Length = sizeof(ClientAddress);
-
- // Accept a new connection
- Connected = accept(mySocket, reinterpret_cast<sockaddr*>(&ClientAddress), &Length);
-
- // Check errors
- if (!Connected.IsValid())
- {
- if (Address)
- *Address = IPAddress();
-
- return SocketHelper::GetErrorStatus();
- }
-
- // Fill address if requested
- if (Address)
- *Address = IPAddress(inet_ntoa(ClientAddress.sin_addr));
-
- return Socket::Done;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Send an array of bytes to the host (must be connected first)
-////////////////////////////////////////////////////////////
-Socket::Status SocketTCP::Send(const char* Data, std::size_t Size)
-{
- // First check that socket is valid
- if (!IsValid())
- return Socket::Error;
-
- // Check parameters
- if (Data && Size)
- {
- // Loop until every byte has been sent
- int Sent = 0;
- int SizeToSend = static_cast<int>(Size);
- for (int Length = 0; Length < SizeToSend; Length += Sent)
- {
- // Send a chunk of data
- Sent = send(mySocket, Data + Length, SizeToSend - Length, 0);
-
- // Check if an error occured
- if (Sent <= 0)
- return SocketHelper::GetErrorStatus();
- }
-
- return Socket::Done;
- }
- else
- {
- // Error...
- std::cerr << "Cannot send data over the network (invalid parameters)" << std::endl;
- return Socket::Error;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Receive an array of bytes from the host (must be connected first).
-/// This function will block if the socket is blocking
-////////////////////////////////////////////////////////////
-Socket::Status SocketTCP::Receive(char* Data, std::size_t MaxSize, std::size_t& SizeReceived)
-{
- // First clear the size received
- SizeReceived = 0;
-
- // Check that socket is valid
- if (!IsValid())
- return Socket::Error;
-
- // Check parameters
- if (Data && MaxSize)
- {
- // Receive a chunk of bytes
- int Received = recv(mySocket, Data, static_cast<int>(MaxSize), 0);
-
- // Check the number of bytes received
- if (Received > 0)
- {
- SizeReceived = static_cast<std::size_t>(Received);
- return Socket::Done;
- }
- else if (Received == 0)
- {
- return Socket::Disconnected;
- }
- else
- {
- return SocketHelper::GetErrorStatus();
- }
- }
- else
- {
- // Error...
- std::cerr << "Cannot receive data from the network (invalid parameters)" << std::endl;
- return Socket::Error;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Send a packet of data to the host (must be connected first)
-////////////////////////////////////////////////////////////
-Socket::Status SocketTCP::Send(Packet& PacketToSend)
-{
- // Get the data to send from the packet
- std::size_t DataSize = 0;
- const char* Data = PacketToSend.OnSend(DataSize);
-
- // Send the packet size
- Uint32 PacketSize = htonl(static_cast<unsigned long>(DataSize));
- Send(reinterpret_cast<const char*>(&PacketSize), sizeof(PacketSize));
-
- // Send the packet data
- if (PacketSize > 0)
- {
- return Send(Data, DataSize);
- }
- else
- {
- return Socket::Done;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Receive a packet from the host (must be connected first).
-/// This function will block if the socket is blocking
-////////////////////////////////////////////////////////////
-Socket::Status SocketTCP::Receive(Packet& PacketToReceive)
-{
- // We start by getting the size of the incoming packet
- Uint32 PacketSize = 0;
- std::size_t Received = 0;
- if (myPendingPacketSize < 0)
- {
- // Loop until we've received the entire size of the packet
- // (even a 4 bytes variable may be received in more than one call)
- while (myPendingHeaderSize < sizeof(myPendingHeader))
- {
- char* Data = reinterpret_cast<char*>(&myPendingHeader) + myPendingHeaderSize;
- Socket::Status Status = Receive(Data, sizeof(myPendingHeader) - myPendingHeaderSize, Received);
- myPendingHeaderSize += Received;
-
- if (Status != Socket::Done)
- return Status;
- }
-
- PacketSize = ntohl(myPendingHeader);
- myPendingHeaderSize = 0;
- }
- else
- {
- // There is a pending packet : we already know its size
- PacketSize = myPendingPacketSize;
- }
-
- // Then loop until we receive all the packet data
- char Buffer[1024];
- while (myPendingPacket.size() < PacketSize)
- {
- // Receive a chunk of data
- std::size_t SizeToGet = std::min(static_cast<std::size_t>(PacketSize - myPendingPacket.size()), sizeof(Buffer));
- Socket::Status Status = Receive(Buffer, SizeToGet, Received);
- if (Status != Socket::Done)
- {
- // We must save the size of the pending packet until we can receive its content
- if (Status == Socket::NotReady)
- myPendingPacketSize = PacketSize;
- return Status;
- }
-
- // Append it into the packet
- if (Received > 0)
- {
- myPendingPacket.resize(myPendingPacket.size() + Received);
- char* Begin = &myPendingPacket[0] + myPendingPacket.size() - Received;
- memcpy(Begin, Buffer, Received);
- }
- }
-
- // We have received all the datas : we can copy it to the user packet, and clear our internal packet
- PacketToReceive.Clear();
- if (!myPendingPacket.empty())
- PacketToReceive.OnReceive(&myPendingPacket[0], myPendingPacket.size());
- myPendingPacket.clear();
- myPendingPacketSize = -1;
-
- return Socket::Done;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Close the socket
-////////////////////////////////////////////////////////////
-bool SocketTCP::Close()
-{
- if (IsValid())
- {
- if (!SocketHelper::Close(mySocket))
- {
- std::cerr << "Failed to close socket" << std::endl;
- return false;
- }
-
- mySocket = SocketHelper::InvalidSocket();
- }
-
- myIsBlocking = true;
-
- return true;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Check if the socket is in a valid state ; this function
-/// can be called any time to check if the socket is OK
-////////////////////////////////////////////////////////////
-bool SocketTCP::IsValid() const
-{
- return mySocket != SocketHelper::InvalidSocket();
-}
-
-
-////////////////////////////////////////////////////////////
-/// Comparison operator ==
-////////////////////////////////////////////////////////////
-bool SocketTCP::operator ==(const SocketTCP& Other) const
-{
- return mySocket == Other.mySocket;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Comparison operator !=
-////////////////////////////////////////////////////////////
-bool SocketTCP::operator !=(const SocketTCP& Other) const
-{
- return mySocket != Other.mySocket;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Comparison operator <.
-/// Provided for compatibility with standard containers, as
-/// comparing two sockets doesn't make much sense...
-////////////////////////////////////////////////////////////
-bool SocketTCP::operator <(const SocketTCP& Other) const
-{
- return mySocket < Other.mySocket;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Construct the socket from a socket descriptor
-/// (for internal use only)
-////////////////////////////////////////////////////////////
-SocketTCP::SocketTCP(SocketHelper::SocketType Descriptor)
-{
- Create(Descriptor);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Create the socket
-////////////////////////////////////////////////////////////
-void SocketTCP::Create(SocketHelper::SocketType Descriptor)
-{
- // Use the given socket descriptor, or get a new one
- mySocket = Descriptor ? Descriptor : socket(PF_INET, SOCK_STREAM, 0);
- myIsBlocking = true;
-
- // Reset the pending packet
- myPendingHeaderSize = 0;
- myPendingPacket.clear();
- myPendingPacketSize = -1;
-
- // Setup default options
- if (IsValid())
- {
- // To avoid the "Address already in use" error message when trying to bind to the same port
- int Yes = 1;
- if (setsockopt(mySocket, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char*>(&Yes), sizeof(Yes)) == -1)
- {
- std::cerr << "Failed to set socket option \"SO_REUSEADDR\" ; "
- << "binding to a same port may fail if too fast" << std::endl;
- }
-
- // Disable the Nagle algorithm (ie. removes buffering of TCP packets)
- if (setsockopt(mySocket, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char*>(&Yes), sizeof(Yes)) == -1)
- {
- std::cerr << "Failed to set socket option \"TCP_NODELAY\" ; "
- << "all your TCP packets will be buffered" << std::endl;
- }
-
- // Set blocking by default (should always be the case anyway)
- SetBlocking(true);
- }
-}
-
-} // namespace sf
diff --git a/src/SFML/Network/SocketUDP.cpp b/src/SFML/Network/SocketUDP.cpp
deleted file mode 100755
index c1fbc7b..0000000
--- a/src/SFML/Network/SocketUDP.cpp
+++ /dev/null
@@ -1,433 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Network/SocketUDP.hpp>
-#include <SFML/Network/IPAddress.hpp>
-#include <SFML/Network/Packet.hpp>
-#include <algorithm>
-#include <iostream>
-#include <string.h>
-
-
-namespace sf
-{
-////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
-SocketUDP::SocketUDP()
-{
- Create();
-}
-
-
-////////////////////////////////////////////////////////////
-/// Change the blocking state of the socket
-////////////////////////////////////////////////////////////
-void SocketUDP::SetBlocking(bool Blocking)
-{
- // Make sure our socket is valid
- if (!IsValid())
- Create();
-
- SocketHelper::SetBlocking(mySocket, Blocking);
- myIsBlocking = Blocking;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Bind the socket to a specific port
-////////////////////////////////////////////////////////////
-bool SocketUDP::Bind(unsigned short Port)
-{
- // Check if the socket is already bound to the specified port
- if (myPort != Port)
- {
- // If the socket was previously bound to another port, we need to unbind it first
- Unbind();
-
- if (Port != 0)
- {
- // Build an address with the specified port
- sockaddr_in Addr;
- Addr.sin_family = AF_INET;
- Addr.sin_port = htons(Port);
- Addr.sin_addr.s_addr = INADDR_ANY;
- memset(Addr.sin_zero, 0, sizeof(Addr.sin_zero));
-
- // Bind the socket to the port
- if (bind(mySocket, reinterpret_cast<sockaddr*>(&Addr), sizeof(Addr)) == -1)
- {
- std::cerr << "Failed to bind the socket to port " << Port << std::endl;
- myPort = 0;
- return false;
- }
- }
-
- // Save the new port
- myPort = Port;
- }
-
- return true;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Unbind the socket to its previous port
-////////////////////////////////////////////////////////////
-bool SocketUDP::Unbind()
-{
- // To unbind the socket, we just recreate it
- if (myPort != 0)
- {
- Close();
- Create();
- myPort = 0;
- }
-
- return true;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Send an array of bytes
-////////////////////////////////////////////////////////////
-Socket::Status SocketUDP::Send(const char* Data, std::size_t Size, const IPAddress& Address, unsigned short Port)
-{
- // Make sure the socket is valid
- if (!IsValid())
- Create();
-
- // Check parameters
- if (Data && Size)
- {
- // Build the target address
- sockaddr_in Target;
- Target.sin_family = AF_INET;
- Target.sin_port = htons(Port);
- Target.sin_addr.s_addr = inet_addr(Address.ToString().c_str());
- memset(Target.sin_zero, 0, sizeof(Target.sin_zero));
-
- // Loop until every byte has been sent
- int Sent = 0;
- int SizeToSend = static_cast<int>(Size);
- for (int Length = 0; Length < SizeToSend; Length += Sent)
- {
- // Send a chunk of data
- Sent = sendto(mySocket, Data + Length, SizeToSend - Length, 0, reinterpret_cast<sockaddr*>(&Target), sizeof(Target));
-
- // Check errors
- if (Sent <= 0)
- return SocketHelper::GetErrorStatus();
- }
-
- return Socket::Done;
- }
- else
- {
- // Error...
- std::cerr << "Cannot send data over the network (invalid parameters)" << std::endl;
- return Socket::Error;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Receive an array of bytes.
-/// This function will block if the socket is blocking
-////////////////////////////////////////////////////////////
-Socket::Status SocketUDP::Receive(char* Data, std::size_t MaxSize, std::size_t& SizeReceived, IPAddress& Address, unsigned short& Port)
-{
- // First clear the size received
- SizeReceived = 0;
-
- // Make sure the socket is bound to a port
- if (myPort == 0)
- {
- std::cerr << "Failed to receive data ; the UDP socket first needs to be bound to a port" << std::endl;
- return Socket::Error;
- }
-
- // Make sure the socket is valid
- if (!IsValid())
- Create();
-
- // Check parameters
- if (Data && MaxSize)
- {
- // Data that will be filled with the other computer's address
- sockaddr_in Sender;
- Sender.sin_family = AF_INET;
- Sender.sin_port = 0;
- Sender.sin_addr.s_addr = INADDR_ANY;
- memset(Sender.sin_zero, 0, sizeof(Sender.sin_zero));
- SocketHelper::LengthType SenderSize = sizeof(Sender);
-
- // Receive a chunk of bytes
- int Received = recvfrom(mySocket, Data, static_cast<int>(MaxSize), 0, reinterpret_cast<sockaddr*>(&Sender), &SenderSize);
-
- // Check the number of bytes received
- if (Received > 0)
- {
- Address = IPAddress(inet_ntoa(Sender.sin_addr));
- Port = ntohs(Sender.sin_port);
- SizeReceived = static_cast<std::size_t>(Received);
- return Socket::Done;
- }
- else
- {
- Address = IPAddress();
- Port = 0;
- return Received == 0 ? Socket::Disconnected : SocketHelper::GetErrorStatus();
- }
- }
- else
- {
- // Error...
- std::cerr << "Cannot receive data from the network (invalid parameters)" << std::endl;
- return Socket::Error;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Send a packet of data
-////////////////////////////////////////////////////////////
-Socket::Status SocketUDP::Send(Packet& PacketToSend, const IPAddress& Address, unsigned short Port)
-{
- // Get the data to send from the packet
- std::size_t DataSize = 0;
- const char* Data = PacketToSend.OnSend(DataSize);
-
- // Send the packet size
- Uint32 PacketSize = htonl(static_cast<unsigned long>(DataSize));
- Send(reinterpret_cast<const char*>(&PacketSize), sizeof(PacketSize), Address, Port);
-
- // Send the packet data
- if (PacketSize > 0)
- {
- return Send(Data, DataSize, Address, Port);
- }
- else
- {
- return Socket::Done;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Receive a packet.
-/// This function will block if the socket is blocking
-////////////////////////////////////////////////////////////
-Socket::Status SocketUDP::Receive(Packet& PacketToReceive, IPAddress& Address, unsigned short& Port)
-{
- // We start by getting the size of the incoming packet
- Uint32 PacketSize = 0;
- std::size_t Received = 0;
- if (myPendingPacketSize < 0)
- {
- // Loop until we've received the entire size of the packet
- // (even a 4 bytes variable may be received in more than one call)
- while (myPendingHeaderSize < sizeof(myPendingHeader))
- {
- char* Data = reinterpret_cast<char*>(&myPendingHeader) + myPendingHeaderSize;
- Socket::Status Status = Receive(Data, sizeof(myPendingHeader) - myPendingHeaderSize, Received, Address, Port);
- myPendingHeaderSize += Received;
-
- if (Status != Socket::Done)
- return Status;
- }
-
- PacketSize = ntohl(myPendingHeader);
- myPendingHeaderSize = 0;
- }
- else
- {
- // There is a pending packet : we already know its size
- PacketSize = myPendingPacketSize;
- }
-
- // Use another address instance for receiving the packet data ;
- // chunks of data coming from a different sender will be discarded (and lost...)
- IPAddress Sender;
- unsigned short SenderPort;
-
- // Then loop until we receive all the packet data
- char Buffer[1024];
- while (myPendingPacket.size() < PacketSize)
- {
- // Receive a chunk of data
- std::size_t SizeToGet = std::min(static_cast<std::size_t>(PacketSize - myPendingPacket.size()), sizeof(Buffer));
- Socket::Status Status = Receive(Buffer, SizeToGet, Received, Sender, SenderPort);
- if (Status != Socket::Done)
- {
- // We must save the size of the pending packet until we can receive its content
- if (Status == Socket::NotReady)
- myPendingPacketSize = PacketSize;
- return Status;
- }
-
- // Append it into the packet
- if ((Sender == Address) && (SenderPort == Port) && (Received > 0))
- {
- myPendingPacket.resize(myPendingPacket.size() + Received);
- char* Begin = &myPendingPacket[0] + myPendingPacket.size() - Received;
- memcpy(Begin, Buffer, Received);
- }
- }
-
- // We have received all the datas : we can copy it to the user packet, and clear our internal packet
- PacketToReceive.Clear();
- if (!myPendingPacket.empty())
- PacketToReceive.OnReceive(&myPendingPacket[0], myPendingPacket.size());
- myPendingPacket.clear();
- myPendingPacketSize = -1;
-
- return Socket::Done;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Close the socket
-////////////////////////////////////////////////////////////
-bool SocketUDP::Close()
-{
- if (IsValid())
- {
- if (!SocketHelper::Close(mySocket))
- {
- std::cerr << "Failed to close socket" << std::endl;
- return false;
- }
-
- mySocket = SocketHelper::InvalidSocket();
- }
-
- myPort = 0;
- myIsBlocking = true;
-
- return true;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Check if the socket is in a valid state ; this function
-/// can be called any time to check if the socket is OK
-////////////////////////////////////////////////////////////
-bool SocketUDP::IsValid() const
-{
- return mySocket != SocketHelper::InvalidSocket();
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the port the socket is currently bound to
-////////////////////////////////////////////////////////////
-unsigned short SocketUDP::GetPort() const
-{
- return myPort;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Comparison operator ==
-////////////////////////////////////////////////////////////
-bool SocketUDP::operator ==(const SocketUDP& Other) const
-{
- return mySocket == Other.mySocket;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Comparison operator !=
-////////////////////////////////////////////////////////////
-bool SocketUDP::operator !=(const SocketUDP& Other) const
-{
- return mySocket != Other.mySocket;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Comparison operator <.
-/// Provided for compatibility with standard containers, as
-/// comparing two sockets doesn't make much sense...
-////////////////////////////////////////////////////////////
-bool SocketUDP::operator <(const SocketUDP& Other) const
-{
- return mySocket < Other.mySocket;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Construct the socket from a socket descriptor
-/// (for internal use only)
-////////////////////////////////////////////////////////////
-SocketUDP::SocketUDP(SocketHelper::SocketType Descriptor)
-{
- Create(Descriptor);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Create the socket
-////////////////////////////////////////////////////////////
-void SocketUDP::Create(SocketHelper::SocketType Descriptor)
-{
- // Use the given socket descriptor, or get a new one
- mySocket = Descriptor ? Descriptor : socket(PF_INET, SOCK_DGRAM, 0);
- myIsBlocking = true;
-
- // Clear the last port used
- myPort = 0;
-
- // Reset the pending packet
- myPendingHeaderSize = 0;
- myPendingPacket.clear();
- myPendingPacketSize = -1;
-
- // Setup default options
- if (IsValid())
- {
- // To avoid the "Address already in use" error message when trying to bind to the same port
- int Yes = 1;
- if (setsockopt(mySocket, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char*>(&Yes), sizeof(Yes)) == -1)
- {
- std::cerr << "Failed to set socket option \"reuse address\" ; "
- << "binding to a same port may fail if too fast" << std::endl;
- }
-
- // Enable broadcast by default
- if (setsockopt(mySocket, SOL_SOCKET, SO_BROADCAST, reinterpret_cast<char*>(&Yes), sizeof(Yes)) == -1)
- {
- std::cerr << "Failed to enable broadcast on UDP socket" << std::endl;
- }
-
- // Set blocking by default (should always be the case anyway)
- SetBlocking(true);
- }
-}
-
-} // namespace sf
diff --git a/src/SFML/Network/TcpListener.cpp b/src/SFML/Network/TcpListener.cpp
new file mode 100644
index 0000000..6c101dc
--- /dev/null
+++ b/src/SFML/Network/TcpListener.cpp
@@ -0,0 +1,124 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Network/TcpListener.hpp>
+#include <SFML/Network/TcpSocket.hpp>
+#include <SFML/Network/SocketImpl.hpp>
+#include <SFML/System/Err.hpp>
+
+
+namespace sf
+{
+////////////////////////////////////////////////////////////
+TcpListener::TcpListener() :
+Socket(Tcp)
+{
+
+}
+
+
+////////////////////////////////////////////////////////////
+unsigned short TcpListener::getLocalPort() const
+{
+ if (getHandle() != priv::SocketImpl::invalidSocket())
+ {
+ // Retrieve informations about the local end of the socket
+ sockaddr_in address;
+ priv::SocketImpl::AddrLength size = sizeof(address);
+ if (getsockname(getHandle(), reinterpret_cast<sockaddr*>(&address), &size) != -1)
+ {
+ return ntohs(address.sin_port);
+ }
+ }
+
+ // We failed to retrieve the port
+ return 0;
+}
+
+
+////////////////////////////////////////////////////////////
+Socket::Status TcpListener::listen(unsigned short port)
+{
+ // Create the internal socket if it doesn't exist
+ create();
+
+ // Bind the socket to the specified port
+ sockaddr_in address = priv::SocketImpl::createAddress(INADDR_ANY, port);
+ if (bind(getHandle(), reinterpret_cast<sockaddr*>(&address), sizeof(address)) == -1)
+ {
+ // Not likely to happen, but...
+ err() << "Failed to bind listener socket to port " << port << std::endl;
+ return Error;
+ }
+
+ // Listen to the bound port
+ if (::listen(getHandle(), 0) == -1)
+ {
+ // Oops, socket is deaf
+ err() << "Failed to listen to port " << port << std::endl;
+ return Error;
+ }
+
+ return Done;
+}
+
+
+////////////////////////////////////////////////////////////
+void TcpListener::close()
+{
+ // Simply close the socket
+ Socket::close();
+}
+
+
+////////////////////////////////////////////////////////////
+Socket::Status TcpListener::accept(TcpSocket& socket)
+{
+ // Make sure that we're listening
+ if (getHandle() == priv::SocketImpl::invalidSocket())
+ {
+ err() << "Failed to accept a new connection, the socket is not listening" << std::endl;
+ return Error;
+ }
+
+ // Accept a new connection
+ sockaddr_in address;
+ priv::SocketImpl::AddrLength length = sizeof(address);
+ SocketHandle remote = ::accept(getHandle(), reinterpret_cast<sockaddr*>(&address), &length);
+
+ // Check for errors
+ if (remote == priv::SocketImpl::invalidSocket())
+ return priv::SocketImpl::getErrorStatus();
+
+ // Initialize the new connected socket
+ socket.close();
+ socket.create(remote);
+
+ return Done;
+}
+
+} // namespace sf
diff --git a/src/SFML/Network/TcpSocket.cpp b/src/SFML/Network/TcpSocket.cpp
new file mode 100644
index 0000000..c7eb6ec
--- /dev/null
+++ b/src/SFML/Network/TcpSocket.cpp
@@ -0,0 +1,381 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Network/TcpSocket.hpp>
+#include <SFML/Network/IpAddress.hpp>
+#include <SFML/Network/Packet.hpp>
+#include <SFML/Network/SocketImpl.hpp>
+#include <SFML/System/Err.hpp>
+#include <algorithm>
+#include <cstring>
+
+#ifdef _MSC_VER
+ #pragma warning(disable : 4127) // "conditional expression is constant" generated by the FD_SET macro
+#endif
+
+
+namespace
+{
+ // Define the low-level send/receive flags, which depend on the OS
+ #ifdef SFML_SYSTEM_LINUX
+ const int flags = MSG_NOSIGNAL;
+ #else
+ const int flags = 0;
+ #endif
+}
+
+namespace sf
+{
+////////////////////////////////////////////////////////////
+TcpSocket::TcpSocket() :
+Socket(Tcp)
+{
+
+}
+
+
+////////////////////////////////////////////////////////////
+unsigned short TcpSocket::getLocalPort() const
+{
+ if (getHandle() != priv::SocketImpl::invalidSocket())
+ {
+ // Retrieve informations about the local end of the socket
+ sockaddr_in address;
+ priv::SocketImpl::AddrLength size = sizeof(address);
+ if (getsockname(getHandle(), reinterpret_cast<sockaddr*>(&address), &size) != -1)
+ {
+ return ntohs(address.sin_port);
+ }
+ }
+
+ // We failed to retrieve the port
+ return 0;
+}
+
+
+////////////////////////////////////////////////////////////
+IpAddress TcpSocket::getRemoteAddress() const
+{
+ if (getHandle() != priv::SocketImpl::invalidSocket())
+ {
+ // Retrieve informations about the remote end of the socket
+ sockaddr_in address;
+ priv::SocketImpl::AddrLength size = sizeof(address);
+ if (getpeername(getHandle(), reinterpret_cast<sockaddr*>(&address), &size) != -1)
+ {
+ return IpAddress(ntohl(address.sin_addr.s_addr));
+ }
+ }
+
+ // We failed to retrieve the address
+ return IpAddress::None;
+}
+
+
+////////////////////////////////////////////////////////////
+unsigned short TcpSocket::getRemotePort() const
+{
+ if (getHandle() != priv::SocketImpl::invalidSocket())
+ {
+ // Retrieve informations about the remote end of the socket
+ sockaddr_in address;
+ priv::SocketImpl::AddrLength size = sizeof(address);
+ if (getpeername(getHandle(), reinterpret_cast<sockaddr*>(&address), &size) != -1)
+ {
+ return ntohs(address.sin_port);
+ }
+ }
+
+ // We failed to retrieve the port
+ return 0;
+}
+
+
+////////////////////////////////////////////////////////////
+Socket::Status TcpSocket::connect(const IpAddress& remoteAddress, unsigned short remotePort, Time timeout)
+{
+ // Create the internal socket if it doesn't exist
+ create();
+
+ // Create the remote address
+ sockaddr_in address = priv::SocketImpl::createAddress(remoteAddress.toInteger(), remotePort);
+
+ if (timeout <= Time::Zero)
+ {
+ // ----- We're not using a timeout: just try to connect -----
+
+ // Connect the socket
+ if (::connect(getHandle(), reinterpret_cast<sockaddr*>(&address), sizeof(address)) == -1)
+ return priv::SocketImpl::getErrorStatus();
+
+ // Connection succeeded
+ return Done;
+ }
+ else
+ {
+ // ----- We're using a timeout: we'll need a few tricks to make it work -----
+
+ // Save the previous blocking state
+ bool blocking = isBlocking();
+
+ // Switch to non-blocking to enable our connection timeout
+ if (blocking)
+ setBlocking(false);
+
+ // Try to connect to the remote address
+ if (::connect(getHandle(), reinterpret_cast<sockaddr*>(&address), sizeof(address)) >= 0)
+ {
+ // We got instantly connected! (it may no happen a lot...)
+ return Done;
+ }
+
+ // Get the error status
+ Status status = priv::SocketImpl::getErrorStatus();
+
+ // If we were in non-blocking mode, return immediatly
+ if (!blocking)
+ return status;
+
+ // Otherwise, wait until something happens to our socket (success, timeout or error)
+ if (status == Socket::NotReady)
+ {
+ // Setup the selector
+ fd_set selector;
+ FD_ZERO(&selector);
+ FD_SET(getHandle(), &selector);
+
+ // Setup the timeout
+ timeval time;
+ time.tv_sec = static_cast<long>(timeout.asMicroseconds() / 1000000);
+ time.tv_usec = static_cast<long>(timeout.asMicroseconds() % 1000000);
+
+ // Wait for something to write on our socket (which means that the connection request has returned)
+ if (select(static_cast<int>(getHandle() + 1), NULL, &selector, NULL, &time) > 0)
+ {
+ // At this point the connection may have been either accepted or refused.
+ // To know whether it's a success or a failure, we must check the address of the connected peer
+ if (getRemoteAddress() != sf::IpAddress::None)
+ {
+ // Connection accepted
+ status = Done;
+ }
+ else
+ {
+ // Connection refused
+ status = priv::SocketImpl::getErrorStatus();
+ }
+ }
+ else
+ {
+ // Failed to connect before timeout is over
+ status = priv::SocketImpl::getErrorStatus();
+ }
+ }
+
+ // Switch back to blocking mode
+ setBlocking(true);
+
+ return status;
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void TcpSocket::disconnect()
+{
+ // Close the socket
+ close();
+
+ // Reset the pending packet data
+ m_pendingPacket = PendingPacket();
+}
+
+
+////////////////////////////////////////////////////////////
+Socket::Status TcpSocket::send(const void* data, std::size_t size)
+{
+ // Check the parameters
+ if (!data || (size == 0))
+ {
+ err() << "Cannot send data over the network (no data to send)" << std::endl;
+ return Error;
+ }
+
+ // Loop until every byte has been sent
+ int sent = 0;
+ int sizeToSend = static_cast<int>(size);
+ for (int length = 0; length < sizeToSend; length += sent)
+ {
+ // Send a chunk of data
+ sent = ::send(getHandle(), static_cast<const char*>(data) + length, sizeToSend - length, flags);
+
+ // Check for errors
+ if (sent < 0)
+ return priv::SocketImpl::getErrorStatus();
+ }
+
+ return Done;
+}
+
+
+////////////////////////////////////////////////////////////
+Socket::Status TcpSocket::receive(void* data, std::size_t size, std::size_t& received)
+{
+ // First clear the variables to fill
+ received = 0;
+
+ // Check the destination buffer
+ if (!data)
+ {
+ err() << "Cannot receive data from the network (the destination buffer is invalid)" << std::endl;
+ return Error;
+ }
+
+ // Receive a chunk of bytes
+ int sizeReceived = recv(getHandle(), static_cast<char*>(data), static_cast<int>(size), flags);
+
+ // Check the number of bytes received
+ if (sizeReceived > 0)
+ {
+ received = static_cast<std::size_t>(sizeReceived);
+ return Done;
+ }
+ else if (sizeReceived == 0)
+ {
+ return Socket::Disconnected;
+ }
+ else
+ {
+ return priv::SocketImpl::getErrorStatus();
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+Socket::Status TcpSocket::send(Packet& packet)
+{
+ // TCP is a stream protocol, it doesn't preserve messages boundaries.
+ // This means that we have to send the packet size first, so that the
+ // receiver knows the actual end of the packet in the data stream.
+
+ // We allocate an extra memory block so that the size can be sent
+ // together with the data in a single call. This may seem inefficient,
+ // but it is actually required to avoid partial send, which could cause
+ // data corruption on the receiving end.
+
+ // Get the data to send from the packet
+ std::size_t size = 0;
+ const void* data = packet.onSend(size);
+
+ // First convert the packet size to network byte order
+ Uint32 packetSize = htonl(static_cast<Uint32>(size));
+
+ // Allocate memory for the data block to send
+ std::vector<char> blockToSend(sizeof(packetSize) + size);
+
+ // Copy the packet size and data into the block to send
+ std::memcpy(&blockToSend[0], &packetSize, sizeof(packetSize));
+ if (size > 0)
+ std::memcpy(&blockToSend[0] + sizeof(packetSize), data, size);
+
+ // Send the data block
+ return send(&blockToSend[0], blockToSend.size());
+}
+
+
+////////////////////////////////////////////////////////////
+Socket::Status TcpSocket::receive(Packet& packet)
+{
+ // First clear the variables to fill
+ packet.clear();
+
+ // We start by getting the size of the incoming packet
+ Uint32 packetSize = 0;
+ std::size_t received = 0;
+ if (m_pendingPacket.SizeReceived < sizeof(m_pendingPacket.Size))
+ {
+ // Loop until we've received the entire size of the packet
+ // (even a 4 byte variable may be received in more than one call)
+ while (m_pendingPacket.SizeReceived < sizeof(m_pendingPacket.Size))
+ {
+ char* data = reinterpret_cast<char*>(&m_pendingPacket.Size) + m_pendingPacket.SizeReceived;
+ Status status = receive(data, sizeof(m_pendingPacket.Size) - m_pendingPacket.SizeReceived, received);
+ m_pendingPacket.SizeReceived += received;
+
+ if (status != Done)
+ return status;
+ }
+
+ // The packet size has been fully received
+ packetSize = ntohl(m_pendingPacket.Size);
+ }
+ else
+ {
+ // The packet size has already been received in a previous call
+ packetSize = ntohl(m_pendingPacket.Size);
+ }
+
+ // Loop until we receive all the packet data
+ char buffer[1024];
+ while (m_pendingPacket.Data.size() < packetSize)
+ {
+ // Receive a chunk of data
+ std::size_t sizeToGet = std::min(static_cast<std::size_t>(packetSize - m_pendingPacket.Data.size()), sizeof(buffer));
+ Status status = receive(buffer, sizeToGet, received);
+ if (status != Done)
+ return status;
+
+ // Append it into the packet
+ if (received > 0)
+ {
+ m_pendingPacket.Data.resize(m_pendingPacket.Data.size() + received);
+ char* begin = &m_pendingPacket.Data[0] + m_pendingPacket.Data.size() - received;
+ std::memcpy(begin, buffer, received);
+ }
+ }
+
+ // We have received all the packet data: we can copy it to the user packet
+ if (!m_pendingPacket.Data.empty())
+ packet.onReceive(&m_pendingPacket.Data[0], m_pendingPacket.Data.size());
+
+ // Clear the pending packet data
+ m_pendingPacket = PendingPacket();
+
+ return Done;
+}
+
+
+////////////////////////////////////////////////////////////
+TcpSocket::PendingPacket::PendingPacket() :
+Size (0),
+SizeReceived(0),
+Data ()
+{
+
+}
+
+} // namespace sf
diff --git a/src/SFML/Network/UdpSocket.cpp b/src/SFML/Network/UdpSocket.cpp
new file mode 100644
index 0000000..78e4b99
--- /dev/null
+++ b/src/SFML/Network/UdpSocket.cpp
@@ -0,0 +1,193 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Network/UdpSocket.hpp>
+#include <SFML/Network/IpAddress.hpp>
+#include <SFML/Network/Packet.hpp>
+#include <SFML/Network/SocketImpl.hpp>
+#include <SFML/System/Err.hpp>
+#include <algorithm>
+
+
+namespace sf
+{
+////////////////////////////////////////////////////////////
+UdpSocket::UdpSocket() :
+Socket (Udp),
+m_buffer(MaxDatagramSize)
+{
+
+}
+
+
+////////////////////////////////////////////////////////////
+unsigned short UdpSocket::getLocalPort() const
+{
+ if (getHandle() != priv::SocketImpl::invalidSocket())
+ {
+ // Retrieve informations about the local end of the socket
+ sockaddr_in address;
+ priv::SocketImpl::AddrLength size = sizeof(address);
+ if (getsockname(getHandle(), reinterpret_cast<sockaddr*>(&address), &size) != -1)
+ {
+ return ntohs(address.sin_port);
+ }
+ }
+
+ // We failed to retrieve the port
+ return 0;
+}
+
+
+////////////////////////////////////////////////////////////
+Socket::Status UdpSocket::bind(unsigned short port)
+{
+ // Create the internal socket if it doesn't exist
+ create();
+
+ // Bind the socket
+ sockaddr_in address = priv::SocketImpl::createAddress(INADDR_ANY, port);
+ if (::bind(getHandle(), reinterpret_cast<sockaddr*>(&address), sizeof(address)) == -1)
+ {
+ err() << "Failed to bind socket to port " << port << std::endl;
+ return Error;
+ }
+
+ return Done;
+}
+
+
+////////////////////////////////////////////////////////////
+void UdpSocket::unbind()
+{
+ // Simply close the socket
+ close();
+}
+
+
+////////////////////////////////////////////////////////////
+Socket::Status UdpSocket::send(const void* data, std::size_t size, const IpAddress& remoteAddress, unsigned short remotePort)
+{
+ // Create the internal socket if it doesn't exist
+ create();
+
+ // Make sure that all the data will fit in one datagram
+ if (size > MaxDatagramSize)
+ {
+ err() << "Cannot send data over the network "
+ << "(the number of bytes to send is greater than sf::UdpSocket::MaxDatagramSize)" << std::endl;
+ return Error;
+ }
+
+ // Build the target address
+ sockaddr_in address = priv::SocketImpl::createAddress(remoteAddress.toInteger(), remotePort);
+
+ // Send the data (unlike TCP, all the data is always sent in one call)
+ int sent = sendto(getHandle(), static_cast<const char*>(data), static_cast<int>(size), 0, reinterpret_cast<sockaddr*>(&address), sizeof(address));
+
+ // Check for errors
+ if (sent < 0)
+ return priv::SocketImpl::getErrorStatus();
+
+ return Done;
+}
+
+
+////////////////////////////////////////////////////////////
+Socket::Status UdpSocket::receive(void* data, std::size_t size, std::size_t& received, IpAddress& remoteAddress, unsigned short& remotePort)
+{
+ // First clear the variables to fill
+ received = 0;
+ remoteAddress = IpAddress();
+ remotePort = 0;
+
+ // Check the destination buffer
+ if (!data)
+ {
+ err() << "Cannot receive data from the network (the destination buffer is invalid)" << std::endl;
+ return Error;
+ }
+
+ // Data that will be filled with the other computer's address
+ sockaddr_in address = priv::SocketImpl::createAddress(INADDR_ANY, 0);
+
+ // Receive a chunk of bytes
+ priv::SocketImpl::AddrLength addressSize = sizeof(address);
+ int sizeReceived = recvfrom(getHandle(), static_cast<char*>(data), static_cast<int>(size), 0, reinterpret_cast<sockaddr*>(&address), &addressSize);
+
+ // Check for errors
+ if (sizeReceived < 0)
+ return priv::SocketImpl::getErrorStatus();
+
+ // Fill the sender informations
+ received = static_cast<std::size_t>(sizeReceived);
+ remoteAddress = IpAddress(ntohl(address.sin_addr.s_addr));
+ remotePort = ntohs(address.sin_port);
+
+ return Done;
+}
+
+
+////////////////////////////////////////////////////////////
+Socket::Status UdpSocket::send(Packet& packet, const IpAddress& remoteAddress, unsigned short remotePort)
+{
+ // UDP is a datagram-oriented protocol (as opposed to TCP which is a stream protocol).
+ // Sending one datagram is almost safe: it may be lost but if it's received, then its data
+ // is guaranteed to be ok. However, splitting a packet into multiple datagrams would be highly
+ // unreliable, since datagrams may be reordered, dropped or mixed between different sources.
+ // That's why SFML imposes a limit on packet size so that they can be sent in a single datagram.
+ // This also removes the overhead associated to packets -- there's no size to send in addition
+ // to the packet's data.
+
+ // Get the data to send from the packet
+ std::size_t size = 0;
+ const void* data = packet.onSend(size);
+
+ // Send it
+ return send(data, size, remoteAddress, remotePort);
+}
+
+
+////////////////////////////////////////////////////////////
+Socket::Status UdpSocket::receive(Packet& packet, IpAddress& remoteAddress, unsigned short& remotePort)
+{
+ // See the detailed comment in send(Packet) above.
+
+ // Receive the datagram
+ std::size_t received = 0;
+ Status status = receive(&m_buffer[0], m_buffer.size(), received, remoteAddress, remotePort);
+
+ // If we received valid data, we can copy it to the user packet
+ packet.clear();
+ if ((status == Done) && (received > 0))
+ packet.onReceive(&m_buffer[0], received);
+
+ return status;
+}
+
+
+} // namespace sf
diff --git a/src/SFML/Network/Unix/SocketHelper.cpp b/src/SFML/Network/Unix/SocketImpl.cpp
index 1fc4e68..4a6b508 100755..100644
--- a/src/SFML/Network/Unix/SocketHelper.cpp
+++ b/src/SFML/Network/Unix/SocketImpl.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -25,48 +25,56 @@
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
-#include <SFML/Network/SocketHelper.hpp>
+#include <SFML/Network/Unix/SocketImpl.hpp>
#include <errno.h>
#include <fcntl.h>
+#include <cstring>
namespace sf
{
+namespace priv
+{
////////////////////////////////////////////////////////////
-/// Return the value of the invalid socket
+sockaddr_in SocketImpl::createAddress(Uint32 address, unsigned short port)
+{
+ sockaddr_in addr;
+ std::memset(addr.sin_zero, 0, sizeof(addr.sin_zero));
+ addr.sin_addr.s_addr = htonl(address);
+ addr.sin_family = AF_INET;
+ addr.sin_port = htons(port);
+
+ return addr;
+}
+
+
////////////////////////////////////////////////////////////
-SocketHelper::SocketType SocketHelper::InvalidSocket()
+SocketHandle SocketImpl::invalidSocket()
{
return -1;
}
////////////////////////////////////////////////////////////
-/// Close / destroy a socket
-////////////////////////////////////////////////////////////
-bool SocketHelper::Close(SocketHelper::SocketType Socket)
+void SocketImpl::close(SocketHandle sock)
{
- return close(Socket) != -1;
+ ::close(sock);
}
////////////////////////////////////////////////////////////
-/// Set a socket as blocking or non-blocking
-////////////////////////////////////////////////////////////
-void SocketHelper::SetBlocking(SocketHelper::SocketType Socket, bool Block)
+void SocketImpl::setBlocking(SocketHandle sock, bool block)
{
- int Status = fcntl(Socket, F_GETFL);
- if (Block)
- fcntl(Socket, F_SETFL, Status & ~O_NONBLOCK);
+ int status = fcntl(sock, F_GETFL);
+ if (block)
+ fcntl(sock, F_SETFL, status & ~O_NONBLOCK);
else
- fcntl(Socket, F_SETFL, Status | O_NONBLOCK);
+ fcntl(sock, F_SETFL, status | O_NONBLOCK);
}
////////////////////////////////////////////////////////////
-/// Get the last socket error status
-////////////////////////////////////////////////////////////
-Socket::Status SocketHelper::GetErrorStatus()
+Socket::Status SocketImpl::getErrorStatus()
{
// The followings are sometimes equal to EWOULDBLOCK,
// so we have to make a special case for them in order
@@ -82,8 +90,11 @@ Socket::Status SocketHelper::GetErrorStatus()
case ETIMEDOUT : return Socket::Disconnected;
case ENETRESET : return Socket::Disconnected;
case ENOTCONN : return Socket::Disconnected;
+ case EPIPE : return Socket::Disconnected;
default : return Socket::Error;
}
}
+} // namespace priv
+
} // namespace sf
diff --git a/src/SFML/Network/Unix/SocketImpl.hpp b/src/SFML/Network/Unix/SocketImpl.hpp
new file mode 100644
index 0000000..fde4bea
--- /dev/null
+++ b/src/SFML/Network/Unix/SocketImpl.hpp
@@ -0,0 +1,109 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_SOCKETIMPL_HPP
+#define SFML_SOCKETIMPL_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Network/Socket.hpp>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <netinet/tcp.h>
+#include <arpa/inet.h>
+#include <netdb.h>
+#include <unistd.h>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief Helper class implementing all the non-portable
+/// socket stuff; this is the Unix version
+///
+////////////////////////////////////////////////////////////
+class SocketImpl
+{
+public :
+
+ ////////////////////////////////////////////////////////////
+ // Types
+ ////////////////////////////////////////////////////////////
+ typedef socklen_t AddrLength;
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Create an internal sockaddr_in address
+ ///
+ /// \param address Target address
+ /// \param port Target port
+ ///
+ /// \return sockaddr_in ready to be used by socket functions
+ ///
+ ////////////////////////////////////////////////////////////
+ static sockaddr_in createAddress(Uint32 address, unsigned short port);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Return the value of the invalid socket
+ ///
+ /// \return Special value of the invalid socket
+ ///
+ ////////////////////////////////////////////////////////////
+ static SocketHandle invalidSocket();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Close and destroy a socket
+ ///
+ /// \param sock Handle of the socket to close
+ ///
+ ////////////////////////////////////////////////////////////
+ static void close(SocketHandle sock);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Set a socket as blocking or non-blocking
+ ///
+ /// \param sock Handle of the socket
+ /// \param block New blocking state of the socket
+ ///
+ ////////////////////////////////////////////////////////////
+ static void setBlocking(SocketHandle sock, bool block);
+
+ ////////////////////////////////////////////////////////////
+ /// Get the last socket error status
+ ///
+ /// \return Status corresponding to the last socket error
+ ///
+ ////////////////////////////////////////////////////////////
+ static Socket::Status getErrorStatus();
+};
+
+} // namespace priv
+
+} // namespace sf
+
+
+#endif // SFML_SOCKETIMPL_HPP
diff --git a/src/SFML/Network/Win32/SocketHelper.cpp b/src/SFML/Network/Win32/SocketImpl.cpp
index 2d904a7..a3c26b7 100755..100644
--- a/src/SFML/Network/Win32/SocketHelper.cpp
+++ b/src/SFML/Network/Win32/SocketImpl.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -25,52 +25,62 @@
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
-#include <SFML/Network/SocketHelper.hpp>
+#include <SFML/Network/Win32/SocketImpl.hpp>
+#include <cstring>
namespace sf
{
+namespace priv
+{
////////////////////////////////////////////////////////////
-/// Return the value of the invalid socket
+sockaddr_in SocketImpl::createAddress(Uint32 address, unsigned short port)
+{
+ sockaddr_in addr;
+ std::memset(addr.sin_zero, 0, sizeof(addr.sin_zero));
+ addr.sin_addr.s_addr = htonl(address);
+ addr.sin_family = AF_INET;
+ addr.sin_port = htons(port);
+
+ return addr;
+}
+
+
////////////////////////////////////////////////////////////
-SocketHelper::SocketType SocketHelper::InvalidSocket()
+SocketHandle SocketImpl::invalidSocket()
{
return INVALID_SOCKET;
}
////////////////////////////////////////////////////////////
-/// Close / destroy a socket
-////////////////////////////////////////////////////////////
-bool SocketHelper::Close(SocketHelper::SocketType Socket)
+void SocketImpl::close(SocketHandle sock)
{
- return closesocket(Socket) != -1;
+ closesocket(sock);
}
////////////////////////////////////////////////////////////
-/// Set a socket as blocking or non-blocking
-////////////////////////////////////////////////////////////
-void SocketHelper::SetBlocking(SocketHelper::SocketType Socket, bool Block)
+void SocketImpl::setBlocking(SocketHandle sock, bool block)
{
- unsigned long Blocking = Block ? 0 : 1;
- ioctlsocket(Socket, FIONBIO, &Blocking);
+ u_long blocking = block ? 0 : 1;
+ ioctlsocket(sock, FIONBIO, &blocking);
}
////////////////////////////////////////////////////////////
-/// Get the last socket error status
-////////////////////////////////////////////////////////////
-Socket::Status SocketHelper::GetErrorStatus()
+Socket::Status SocketImpl::getErrorStatus()
{
switch (WSAGetLastError())
{
case WSAEWOULDBLOCK : return Socket::NotReady;
+ case WSAEALREADY : return Socket::NotReady;
case WSAECONNABORTED : return Socket::Disconnected;
case WSAECONNRESET : return Socket::Disconnected;
case WSAETIMEDOUT : return Socket::Disconnected;
case WSAENETRESET : return Socket::Disconnected;
case WSAENOTCONN : return Socket::Disconnected;
+ case WSAEISCONN : return Socket::Done; // when connecting a non-blocking socket
default : return Socket::Error;
}
}
@@ -85,8 +95,8 @@ struct SocketInitializer
{
SocketInitializer()
{
- WSADATA InitData;
- WSAStartup(MAKEWORD(2,2), &InitData);
+ WSADATA init;
+ WSAStartup(MAKEWORD(2, 2), &init);
}
~SocketInitializer()
@@ -95,6 +105,8 @@ struct SocketInitializer
}
};
-SocketInitializer GlobalInitializer;
+SocketInitializer globalInitializer;
+
+} // namespace priv
} // namespace sf
diff --git a/src/SFML/Network/Win32/SocketImpl.hpp b/src/SFML/Network/Win32/SocketImpl.hpp
new file mode 100644
index 0000000..b575869
--- /dev/null
+++ b/src/SFML/Network/Win32/SocketImpl.hpp
@@ -0,0 +1,112 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_SOCKETIMPL_HPP
+#define SFML_SOCKETIMPL_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#ifdef _WIN32_WINDOWS
+ #undef _WIN32_WINDOWS
+#endif
+#ifdef _WIN32_WINNT
+ #undef _WIN32_WINNT
+#endif
+#define _WIN32_WINDOWS 0x0501
+#define _WIN32_WINNT 0x0501
+#include <SFML/Network/Socket.hpp>
+#include <winsock2.h>
+#include <ws2tcpip.h>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief Helper class implementing all the non-portable
+/// socket stuff; this is the Windows version
+///
+////////////////////////////////////////////////////////////
+class SocketImpl
+{
+public :
+
+ ////////////////////////////////////////////////////////////
+ // Types
+ ////////////////////////////////////////////////////////////
+ typedef int AddrLength;
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Create an internal sockaddr_in address
+ ///
+ /// \param address Target address
+ /// \param port Target port
+ ///
+ /// \return sockaddr_in ready to be used by socket functions
+ ///
+ ////////////////////////////////////////////////////////////
+ static sockaddr_in createAddress(Uint32 address, unsigned short port);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Return the value of the invalid socket
+ ///
+ /// \return Special value of the invalid socket
+ ///
+ ////////////////////////////////////////////////////////////
+ static SocketHandle invalidSocket();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Close and destroy a socket
+ ///
+ /// \param sock Handle of the socket to close
+ ///
+ ////////////////////////////////////////////////////////////
+ static void close(SocketHandle sock);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Set a socket as blocking or non-blocking
+ ///
+ /// \param sock Handle of the socket
+ /// \param block New blocking state of the socket
+ ///
+ ////////////////////////////////////////////////////////////
+ static void setBlocking(SocketHandle sock, bool block);
+
+ ////////////////////////////////////////////////////////////
+ /// Get the last socket error status
+ ///
+ /// \return Status corresponding to the last socket error
+ ///
+ ////////////////////////////////////////////////////////////
+ static Socket::Status getErrorStatus();
+};
+
+} // namespace priv
+
+} // namespace sf
+
+
+#endif // SFML_SOCKETIMPL_HPP
diff --git a/src/SFML/System/CMakeLists.txt b/src/SFML/System/CMakeLists.txt
new file mode 100644
index 0000000..5ef9139
--- /dev/null
+++ b/src/SFML/System/CMakeLists.txt
@@ -0,0 +1,83 @@
+
+set(INCROOT ${PROJECT_SOURCE_DIR}/include/SFML/System)
+set(SRCROOT ${PROJECT_SOURCE_DIR}/src/SFML/System)
+
+# all source files
+set(SRC
+ ${SRCROOT}/Clock.cpp
+ ${INCROOT}/Clock.hpp
+ ${SRCROOT}/Err.cpp
+ ${INCROOT}/Err.hpp
+ ${INCROOT}/Export.hpp
+ ${INCROOT}/InputStream.hpp
+ ${SRCROOT}/Lock.cpp
+ ${INCROOT}/Lock.hpp
+ ${SRCROOT}/Mutex.cpp
+ ${INCROOT}/Mutex.hpp
+ ${INCROOT}/NonCopyable.hpp
+ ${SRCROOT}/Sleep.cpp
+ ${INCROOT}/Sleep.hpp
+ ${SRCROOT}/String.cpp
+ ${INCROOT}/String.hpp
+ ${SRCROOT}/Thread.cpp
+ ${INCROOT}/Thread.hpp
+ ${INCROOT}/Thread.inl
+ ${SRCROOT}/ThreadLocal.cpp
+ ${INCROOT}/ThreadLocal.hpp
+ ${INCROOT}/ThreadLocalPtr.hpp
+ ${INCROOT}/ThreadLocalPtr.inl
+ ${SRCROOT}/Time.cpp
+ ${INCROOT}/Time.hpp
+ ${INCROOT}/Utf.hpp
+ ${INCROOT}/Utf.inl
+ ${INCROOT}/Vector2.hpp
+ ${INCROOT}/Vector2.inl
+ ${INCROOT}/Vector3.hpp
+ ${INCROOT}/Vector3.inl
+)
+source_group("" FILES ${SRC})
+
+# add platform specific sources
+if(WINDOWS)
+ set(PLATFORM_SRC
+ ${SRCROOT}/Win32/ClockImpl.cpp
+ ${SRCROOT}/Win32/ClockImpl.hpp
+ ${SRCROOT}/Win32/MutexImpl.cpp
+ ${SRCROOT}/Win32/MutexImpl.hpp
+ ${SRCROOT}/Win32/SleepImpl.cpp
+ ${SRCROOT}/Win32/SleepImpl.hpp
+ ${SRCROOT}/Win32/ThreadImpl.cpp
+ ${SRCROOT}/Win32/ThreadImpl.hpp
+ ${SRCROOT}/Win32/ThreadLocalImpl.cpp
+ ${SRCROOT}/Win32/ThreadLocalImpl.hpp
+ )
+ source_group("windows" FILES ${PLATFORM_SRC})
+else()
+ set(PLATFORM_SRC
+ ${SRCROOT}/Unix/ClockImpl.cpp
+ ${SRCROOT}/Unix/ClockImpl.hpp
+ ${SRCROOT}/Unix/MutexImpl.cpp
+ ${SRCROOT}/Unix/MutexImpl.hpp
+ ${SRCROOT}/Unix/SleepImpl.cpp
+ ${SRCROOT}/Unix/SleepImpl.hpp
+ ${SRCROOT}/Unix/ThreadImpl.cpp
+ ${SRCROOT}/Unix/ThreadImpl.hpp
+ ${SRCROOT}/Unix/ThreadLocalImpl.cpp
+ ${SRCROOT}/Unix/ThreadLocalImpl.hpp
+ )
+ source_group("unix" FILES ${PLATFORM_SRC})
+endif()
+
+# build the list of external libraries to link
+set(SYSTEM_EXT_LIBS)
+if(UNIX)
+ set(SYSTEM_EXT_LIBS ${SYSTEM_EXT_LIBS} pthread)
+endif()
+if(LINUX)
+ set(SYSTEM_EXT_LIBS ${SYSTEM_EXT_LIBS} rt)
+endif()
+
+# define the sfml-system target
+sfml_add_library(sfml-system
+ SOURCES ${SRC} ${PLATFORM_SRC}
+ EXTERNAL_LIBS ${SYSTEM_EXT_LIBS})
diff --git a/src/SFML/System/Clock.cpp b/src/SFML/System/Clock.cpp
index 65e0e4d..de3c642 100755..100644
--- a/src/SFML/System/Clock.cpp
+++ b/src/SFML/System/Clock.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -26,35 +26,38 @@
// Headers
////////////////////////////////////////////////////////////
#include <SFML/System/Clock.hpp>
-#include <SFML/System/Platform.hpp>
+
+#if defined(SFML_SYSTEM_WINDOWS)
+ #include <SFML/System/Win32/ClockImpl.hpp>
+#else
+ #include <SFML/System/Unix/ClockImpl.hpp>
+#endif
namespace sf
{
////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
-Clock::Clock()
+Clock::Clock() :
+m_startTime(priv::ClockImpl::getCurrentTime())
{
- Reset();
}
////////////////////////////////////////////////////////////
-/// Get the time elapsed since last reset
-////////////////////////////////////////////////////////////
-float Clock::GetElapsedTime() const
+Time Clock::getElapsedTime() const
{
- return static_cast<float>(sf::priv::Platform::GetSystemTime() - myStartTime);
+ return priv::ClockImpl::getCurrentTime() - m_startTime;
}
////////////////////////////////////////////////////////////
-/// Restart the timer
-////////////////////////////////////////////////////////////
-void Clock::Reset()
+Time Clock::restart()
{
- myStartTime = sf::priv::Platform::GetSystemTime();
+ Time now = priv::ClockImpl::getCurrentTime();
+ Time elapsed = now - m_startTime;
+ m_startTime = now;
+
+ return elapsed;
}
} // namespace sf
diff --git a/src/SFML/System/Err.cpp b/src/SFML/System/Err.cpp
new file mode 100644
index 0000000..a1224dd
--- /dev/null
+++ b/src/SFML/System/Err.cpp
@@ -0,0 +1,110 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/System/Err.hpp>
+#include <streambuf>
+#include <cstdio>
+
+
+namespace
+{
+// This class will be used as the default streambuf of sf::Err,
+// it outputs to stderr by default (to keep the default behaviour)
+class DefaultErrStreamBuf : public std::streambuf
+{
+public :
+
+ DefaultErrStreamBuf()
+ {
+ // Allocate the write buffer
+ static const int size = 64;
+ char* buffer = new char[size];
+ setp(buffer, buffer + size);
+ }
+
+ ~DefaultErrStreamBuf()
+ {
+ // Synchronize
+ sync();
+
+ // Delete the write buffer
+ delete[] pbase();
+ }
+
+private :
+
+ virtual int overflow(int character)
+ {
+ if ((character != EOF) && (pptr() != epptr()))
+ {
+ // Valid character
+ return sputc(static_cast<char>(character));
+ }
+ else if (character != EOF)
+ {
+ // Not enough space in the buffer: synchronize output and try again
+ sync();
+ return overflow(character);
+ }
+ else
+ {
+ // Invalid character: synchronize output
+ return sync();
+ }
+ }
+
+ virtual int sync()
+ {
+ // Check if there is something into the write buffer
+ if (pbase() != pptr())
+ {
+ // Print the contents of the write buffer into the standard error output
+ std::size_t size = static_cast<int>(pptr() - pbase());
+ fwrite(pbase(), 1, size, stderr);
+
+ // Reset the pointer position to the beginning of the write buffer
+ setp(pbase(), epptr());
+ }
+
+ return 0;
+ }
+};
+}
+
+namespace sf
+{
+////////////////////////////////////////////////////////////
+std::ostream& err()
+{
+ static DefaultErrStreamBuf buffer;
+ static std::ostream stream(&buffer);
+
+ return stream;
+}
+
+
+} // namespace sf
diff --git a/src/SFML/System/Lock.cpp b/src/SFML/System/Lock.cpp
index eb0967d..17b1aa2 100755..100644
--- a/src/SFML/System/Lock.cpp
+++ b/src/SFML/System/Lock.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -32,21 +32,17 @@
namespace sf
{
////////////////////////////////////////////////////////////
-/// Construct the lock with a target mutex (lock it)
-////////////////////////////////////////////////////////////
-Lock::Lock(Mutex& Mutex) :
-myMutex(Mutex)
+Lock::Lock(Mutex& mutex) :
+m_mutex(mutex)
{
- myMutex.Lock();
+ m_mutex.lock();
}
////////////////////////////////////////////////////////////
-/// Destructor (unlocks the mutex)
-////////////////////////////////////////////////////////////
Lock::~Lock()
{
- myMutex.Unlock();
+ m_mutex.unlock();
}
} // namespace sf
diff --git a/src/SFML/System/Makefile b/src/SFML/System/Makefile
deleted file mode 100755
index 1cf6211..0000000
--- a/src/SFML/System/Makefile
+++ /dev/null
@@ -1,34 +0,0 @@
-SRC = $(wildcard *.cpp ./Unix/*.cpp)
-OBJ = $(SRC:.cpp=.o)
-
-ifeq ($(STATIC), yes)
- LIB = libsfml-system-s.a
- LIBNAME = $(LIBPATH)/$(LIB)
- INSTALL =
-else
- LIB = libsfml-system.so
- LIBNAME = $(LIBPATH)/$(LIB).$(VERSION)
- INSTALL = && $(LN) $(LNFLAGS) $(LIB).$(VERSION) $(DESTLIBDIR)/$(LIB)
-endif
-
-all: $(LIB)
-
-libsfml-system-s.a: $(OBJ)
- $(AR) $(ARFLAGS) $(LIBNAME) $(OBJ)
-
-libsfml-system.so: $(OBJ)
- $(CPP) $(LDFLAGS) -Wl,-soname,$(LIB).$(VERSION) -o $(LIBNAME) $(OBJ) -lpthread
-
-$(OBJ): %.o: %.cpp
- $(CPP) -o $@ -c $< $(CFLAGS)
-
-.PHONY: clean mrproper
-
-clean:
- @rm -rf $(OBJ)
-
-mrproper: clean
- @rm -rf $(LIBNAME)
-
-install:
- @($(CP) $(LIBNAME) $(DESTLIBDIR) $(INSTALL))
diff --git a/src/SFML/System/Mutex.cpp b/src/SFML/System/Mutex.cpp
new file mode 100644
index 0000000..e08e25b
--- /dev/null
+++ b/src/SFML/System/Mutex.cpp
@@ -0,0 +1,66 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/System/Mutex.hpp>
+
+#if defined(SFML_SYSTEM_WINDOWS)
+ #include <SFML/System/Win32/MutexImpl.hpp>
+#else
+ #include <SFML/System/Unix/MutexImpl.hpp>
+#endif
+
+
+namespace sf
+{
+////////////////////////////////////////////////////////////
+Mutex::Mutex()
+{
+ m_mutexImpl = new priv::MutexImpl;
+}
+
+
+////////////////////////////////////////////////////////////
+Mutex::~Mutex()
+{
+ delete m_mutexImpl;
+}
+
+
+////////////////////////////////////////////////////////////
+void Mutex::lock()
+{
+ m_mutexImpl->lock();
+}
+
+
+////////////////////////////////////////////////////////////
+void Mutex::unlock()
+{
+ m_mutexImpl->unlock();
+}
+
+} // namespace sf
diff --git a/src/SFML/System/Randomizer.cpp b/src/SFML/System/Randomizer.cpp
deleted file mode 100755
index 18bbe9c..0000000
--- a/src/SFML/System/Randomizer.cpp
+++ /dev/null
@@ -1,96 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/System/Randomizer.hpp>
-#include <stdlib.h>
-#include <time.h>
-
-
-namespace
-{
- // Set the random numbers sequence seed with the current system time, so that it is always different
- unsigned int SetRandomSeed()
- {
- unsigned int Seed = static_cast<unsigned int>(time(NULL));
- srand(Seed);
- return Seed;
- }
-}
-
-
-namespace sf
-{
-////////////////////////////////////////////////////////////
-// Static member variables
-////////////////////////////////////////////////////////////
-unsigned int Randomizer::ourSeed = SetRandomSeed();
-
-
-////////////////////////////////////////////////////////////
-/// Set the seed for the generator. Using a known seed
-/// allows you to reproduce the same sequence of random number
-////////////////////////////////////////////////////////////
-void Randomizer::SetSeed(unsigned int Seed)
-{
- srand(Seed);
- ourSeed = Seed;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the seed used to generate random numbers the generator.
-////////////////////////////////////////////////////////////
-unsigned int Randomizer::GetSeed()
-{
- return ourSeed;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get a random float number in a given range
-////////////////////////////////////////////////////////////
-float Randomizer::Random(float Begin, float End)
-{
- // This is not the best algorithm, but it is fast and will be enough in most cases
- // (see Google for best approaches)
-
- return static_cast<float>(rand()) / RAND_MAX * (End - Begin) + Begin;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get a random integer number in a given range
-////////////////////////////////////////////////////////////
-int Randomizer::Random(int Begin, int End)
-{
- // This is not the best algorithm, but it is fast and will be enough in most cases
- // (see Google for best approaches)
-
- return rand() % (End - Begin + 1) + Begin;
-}
-
-} // namespace sf
diff --git a/src/SFML/System/Sleep.cpp b/src/SFML/System/Sleep.cpp
index 81ff885..9415ade 100755..100644
--- a/src/SFML/System/Sleep.cpp
+++ b/src/SFML/System/Sleep.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -26,18 +26,21 @@
// Headers
////////////////////////////////////////////////////////////
#include <SFML/System/Sleep.hpp>
-#include <SFML/System/Platform.hpp>
+
+#if defined(SFML_SYSTEM_WINDOWS)
+ #include <SFML/System/Win32/SleepImpl.hpp>
+#else
+ #include <SFML/System/Unix/SleepImpl.hpp>
+#endif
namespace sf
{
////////////////////////////////////////////////////////////
-/// Make the current thread sleep for a given time
-////////////////////////////////////////////////////////////
-void Sleep(float Duration)
+void sleep(Time duration)
{
- if (Duration >= 0)
- priv::Platform::Sleep(Duration);
+ if (duration >= Time::Zero)
+ priv::sleepImpl(duration);
}
} // namespace sf
diff --git a/src/SFML/System/String.cpp b/src/SFML/System/String.cpp
new file mode 100644
index 0000000..b4ee135
--- /dev/null
+++ b/src/SFML/System/String.cpp
@@ -0,0 +1,335 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/System/String.hpp>
+#include <SFML/System/Utf.hpp>
+#include <iterator>
+#include <cstring>
+
+
+namespace sf
+{
+////////////////////////////////////////////////////////////
+const std::size_t String::InvalidPos = std::basic_string<Uint32>::npos;
+
+
+////////////////////////////////////////////////////////////
+String::String()
+{
+}
+
+
+////////////////////////////////////////////////////////////
+String::String(char ansiChar, const std::locale& locale)
+{
+ m_string += Utf32::decodeAnsi(ansiChar, locale);
+}
+
+
+////////////////////////////////////////////////////////////
+String::String(wchar_t wideChar)
+{
+ m_string += Utf32::decodeWide(wideChar);
+}
+
+
+////////////////////////////////////////////////////////////
+String::String(Uint32 utf32Char)
+{
+ m_string += utf32Char;
+}
+
+
+////////////////////////////////////////////////////////////
+String::String(const char* ansiString, const std::locale& locale)
+{
+ if (ansiString)
+ {
+ std::size_t length = strlen(ansiString);
+ if (length > 0)
+ {
+ m_string.reserve(length + 1);
+ Utf32::fromAnsi(ansiString, ansiString + length, std::back_inserter(m_string), locale);
+ }
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+String::String(const std::string& ansiString, const std::locale& locale)
+{
+ m_string.reserve(ansiString.length() + 1);
+ Utf32::fromAnsi(ansiString.begin(), ansiString.end(), std::back_inserter(m_string), locale);
+}
+
+
+////////////////////////////////////////////////////////////
+String::String(const wchar_t* wideString)
+{
+ if (wideString)
+ {
+ std::size_t length = std::wcslen(wideString);
+ if (length > 0)
+ {
+ m_string.reserve(length + 1);
+ Utf32::fromWide(wideString, wideString + length, std::back_inserter(m_string));
+ }
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+String::String(const std::wstring& wideString)
+{
+ m_string.reserve(wideString.length() + 1);
+ Utf32::fromWide(wideString.begin(), wideString.end(), std::back_inserter(m_string));
+}
+
+
+////////////////////////////////////////////////////////////
+String::String(const Uint32* utf32String)
+{
+ if (utf32String)
+ m_string = utf32String;
+}
+
+
+////////////////////////////////////////////////////////////
+String::String(const std::basic_string<Uint32>& utf32String) :
+m_string(utf32String)
+{
+}
+
+
+////////////////////////////////////////////////////////////
+String::String(const String& copy) :
+m_string(copy.m_string)
+{
+}
+
+
+////////////////////////////////////////////////////////////
+String::operator std::string() const
+{
+ return toAnsiString();
+}
+
+
+////////////////////////////////////////////////////////////
+String::operator std::wstring() const
+{
+ return toWideString();
+}
+
+
+////////////////////////////////////////////////////////////
+std::string String::toAnsiString(const std::locale& locale) const
+{
+ // Prepare the output string
+ std::string output;
+ output.reserve(m_string.length() + 1);
+
+ // Convert
+ Utf32::toAnsi(m_string.begin(), m_string.end(), std::back_inserter(output), 0, locale);
+
+ return output;
+}
+
+
+////////////////////////////////////////////////////////////
+std::wstring String::toWideString() const
+{
+ // Prepare the output string
+ std::wstring output;
+ output.reserve(m_string.length() + 1);
+
+ // Convert
+ Utf32::toWide(m_string.begin(), m_string.end(), std::back_inserter(output), 0);
+
+ return output;
+}
+
+
+////////////////////////////////////////////////////////////
+String& String::operator =(const String& right)
+{
+ m_string = right.m_string;
+ return *this;
+}
+
+
+////////////////////////////////////////////////////////////
+String& String::operator +=(const String& right)
+{
+ m_string += right.m_string;
+ return *this;
+}
+
+
+////////////////////////////////////////////////////////////
+Uint32 String::operator [](std::size_t index) const
+{
+ return m_string[index];
+}
+
+
+////////////////////////////////////////////////////////////
+Uint32& String::operator [](std::size_t index)
+{
+ return m_string[index];
+}
+
+
+////////////////////////////////////////////////////////////
+void String::clear()
+{
+ m_string.clear();
+}
+
+
+////////////////////////////////////////////////////////////
+std::size_t String::getSize() const
+{
+ return m_string.size();
+}
+
+
+////////////////////////////////////////////////////////////
+bool String::isEmpty() const
+{
+ return m_string.empty();
+}
+
+
+////////////////////////////////////////////////////////////
+void String::erase(std::size_t position, std::size_t count)
+{
+ m_string.erase(position, count);
+}
+
+
+////////////////////////////////////////////////////////////
+void String::insert(std::size_t position, const String& str)
+{
+ m_string.insert(position, str.m_string);
+}
+
+
+////////////////////////////////////////////////////////////
+std::size_t String::find(const String& str, std::size_t start) const
+{
+ return m_string.find(str.m_string, start);
+}
+
+
+////////////////////////////////////////////////////////////
+const Uint32* String::getData() const
+{
+ return m_string.c_str();
+}
+
+
+////////////////////////////////////////////////////////////
+String::Iterator String::begin()
+{
+ return m_string.begin();
+}
+
+
+////////////////////////////////////////////////////////////
+String::ConstIterator String::begin() const
+{
+ return m_string.begin();
+}
+
+
+////////////////////////////////////////////////////////////
+String::Iterator String::end()
+{
+ return m_string.end();
+}
+
+
+////////////////////////////////////////////////////////////
+String::ConstIterator String::end() const
+{
+ return m_string.end();
+}
+
+
+////////////////////////////////////////////////////////////
+bool operator ==(const String& left, const String& right)
+{
+ return left.m_string == right.m_string;
+}
+
+
+////////////////////////////////////////////////////////////
+bool operator !=(const String& left, const String& right)
+{
+ return !(left == right);
+}
+
+
+////////////////////////////////////////////////////////////
+bool operator <(const String& left, const String& right)
+{
+ return left.m_string < right.m_string;
+}
+
+
+////////////////////////////////////////////////////////////
+bool operator >(const String& left, const String& right)
+{
+ return right < left;
+}
+
+
+////////////////////////////////////////////////////////////
+bool operator <=(const String& left, const String& right)
+{
+ return !(right < left);
+}
+
+
+////////////////////////////////////////////////////////////
+bool operator >=(const String& left, const String& right)
+{
+ return !(left < right);
+}
+
+
+////////////////////////////////////////////////////////////
+String operator +(const String& left, const String& right)
+{
+ String string = left;
+ string += right;
+
+ return string;
+}
+
+} // namespace sf
diff --git a/src/SFML/System/Thread.cpp b/src/SFML/System/Thread.cpp
new file mode 100644
index 0000000..69bf077
--- /dev/null
+++ b/src/SFML/System/Thread.cpp
@@ -0,0 +1,86 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/System/Thread.hpp>
+
+
+#if defined(SFML_SYSTEM_WINDOWS)
+ #include <SFML/System/Win32/ThreadImpl.hpp>
+#else
+ #include <SFML/System/Unix/ThreadImpl.hpp>
+#endif
+
+
+namespace sf
+{
+////////////////////////////////////////////////////////////
+Thread::~Thread()
+{
+ wait();
+ delete m_entryPoint;
+}
+
+
+////////////////////////////////////////////////////////////
+void Thread::launch()
+{
+ wait();
+ m_impl = new priv::ThreadImpl(this);
+}
+
+
+////////////////////////////////////////////////////////////
+void Thread::wait()
+{
+ if (m_impl)
+ {
+ m_impl->wait();
+ delete m_impl;
+ m_impl = NULL;
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void Thread::terminate()
+{
+ if (m_impl)
+ {
+ m_impl->terminate();
+ delete m_impl;
+ m_impl = NULL;
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void Thread::run()
+{
+ m_entryPoint->run();
+}
+
+} // namespace sf
diff --git a/src/SFML/System/ThreadLocal.cpp b/src/SFML/System/ThreadLocal.cpp
new file mode 100644
index 0000000..0d134db
--- /dev/null
+++ b/src/SFML/System/ThreadLocal.cpp
@@ -0,0 +1,67 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/System/ThreadLocal.hpp>
+
+#if defined(SFML_SYSTEM_WINDOWS)
+ #include <SFML/System/Win32/ThreadLocalImpl.hpp>
+#else
+ #include <SFML/System/Unix/ThreadLocalImpl.hpp>
+#endif
+
+
+namespace sf
+{
+////////////////////////////////////////////////////////////
+ThreadLocal::ThreadLocal(void* value)
+{
+ m_impl = new priv::ThreadLocalImpl;
+ setValue(value);
+}
+
+
+////////////////////////////////////////////////////////////
+ThreadLocal::~ThreadLocal()
+{
+ delete m_impl;
+}
+
+
+////////////////////////////////////////////////////////////
+void ThreadLocal::setValue(void* value)
+{
+ m_impl->setValue(value);
+}
+
+
+////////////////////////////////////////////////////////////
+void* ThreadLocal::getValue() const
+{
+ return m_impl->getValue();
+}
+
+} // namespace sf
diff --git a/src/SFML/System/Time.cpp b/src/SFML/System/Time.cpp
new file mode 100644
index 0000000..69fd78e
--- /dev/null
+++ b/src/SFML/System/Time.cpp
@@ -0,0 +1,239 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/System/Time.hpp>
+
+
+namespace sf
+{
+////////////////////////////////////////////////////////////
+const Time Time::Zero;
+
+
+////////////////////////////////////////////////////////////
+Time::Time() :
+m_microseconds(0)
+{
+}
+
+
+////////////////////////////////////////////////////////////
+float Time::asSeconds() const
+{
+ return m_microseconds / 1000000.f;
+}
+
+
+////////////////////////////////////////////////////////////
+Int32 Time::asMilliseconds() const
+{
+ return static_cast<Int32>(m_microseconds / 1000);
+}
+
+
+////////////////////////////////////////////////////////////
+Int64 Time::asMicroseconds() const
+{
+ return m_microseconds;
+}
+
+
+////////////////////////////////////////////////////////////
+Time::Time(Int64 microseconds) :
+m_microseconds(microseconds)
+{
+}
+
+
+////////////////////////////////////////////////////////////
+Time seconds(float amount)
+{
+ return Time(static_cast<Int64>(amount * 1000000));
+}
+
+
+////////////////////////////////////////////////////////////
+Time milliseconds(Int32 amount)
+{
+ return Time(static_cast<Int64>(amount) * 1000);
+}
+
+
+////////////////////////////////////////////////////////////
+Time microseconds(Int64 amount)
+{
+ return Time(amount);
+}
+
+
+////////////////////////////////////////////////////////////
+bool operator ==(Time left, Time right)
+{
+ return left.asMicroseconds() == right.asMicroseconds();
+}
+
+
+////////////////////////////////////////////////////////////
+bool operator !=(Time left, Time right)
+{
+ return left.asMicroseconds() != right.asMicroseconds();
+}
+
+
+////////////////////////////////////////////////////////////
+bool operator <(Time left, Time right)
+{
+ return left.asMicroseconds() < right.asMicroseconds();
+}
+
+
+////////////////////////////////////////////////////////////
+bool operator >(Time left, Time right)
+{
+ return left.asMicroseconds() > right.asMicroseconds();
+}
+
+
+////////////////////////////////////////////////////////////
+bool operator <=(Time left, Time right)
+{
+ return left.asMicroseconds() <= right.asMicroseconds();
+}
+
+
+////////////////////////////////////////////////////////////
+bool operator >=(Time left, Time right)
+{
+ return left.asMicroseconds() >= right.asMicroseconds();
+}
+
+
+////////////////////////////////////////////////////////////
+Time operator -(Time right)
+{
+ return microseconds(-right.asMicroseconds());
+}
+
+
+////////////////////////////////////////////////////////////
+Time operator +(Time left, Time right)
+{
+ return microseconds(left.asMicroseconds() + right.asMicroseconds());
+}
+
+
+////////////////////////////////////////////////////////////
+Time& operator +=(Time& left, Time right)
+{
+ return left = left + right;
+}
+
+
+////////////////////////////////////////////////////////////
+Time operator -(Time left, Time right)
+{
+ return microseconds(left.asMicroseconds() - right.asMicroseconds());
+}
+
+
+////////////////////////////////////////////////////////////
+Time& operator -=(Time& left, Time right)
+{
+ return left = left - right;
+}
+
+
+////////////////////////////////////////////////////////////
+Time operator *(Time left, float right)
+{
+ return seconds(left.asSeconds() * right);
+}
+
+
+////////////////////////////////////////////////////////////
+Time operator *(Time left, Int64 right)
+{
+ return microseconds(left.asMicroseconds() * right);
+}
+
+
+////////////////////////////////////////////////////////////
+Time operator *(float left, Time right)
+{
+ return right * left;
+}
+
+
+////////////////////////////////////////////////////////////
+Time operator *(Int64 left, Time right)
+{
+ return right * left;
+}
+
+
+////////////////////////////////////////////////////////////
+Time& operator *=(Time& left, float right)
+{
+ return left = left * right;
+}
+
+
+////////////////////////////////////////////////////////////
+Time& operator *=(Time& left, Int64 right)
+{
+ return left = left * right;
+}
+
+
+////////////////////////////////////////////////////////////
+Time operator /(Time left, float right)
+{
+ return seconds(left.asSeconds() / right);
+}
+
+
+////////////////////////////////////////////////////////////
+Time operator /(Time left, Int64 right)
+{
+ return microseconds(left.asMicroseconds() / right);
+}
+
+
+////////////////////////////////////////////////////////////
+Time& operator /=(Time& left, float right)
+{
+ return left = left / right;
+}
+
+
+////////////////////////////////////////////////////////////
+Time& operator /=(Time& left, Int64 right)
+{
+ return left = left / right;
+}
+
+} // namespace sf
diff --git a/src/SFML/System/Unicode.cpp b/src/SFML/System/Unicode.cpp
deleted file mode 100755
index 1e46ec0..0000000
--- a/src/SFML/System/Unicode.cpp
+++ /dev/null
@@ -1,300 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/System/Unicode.hpp>
-#include <stdexcept>
-#include <string.h>
-
-
-////////////////////////////////////////////////////////////
-// References :
-//
-// http://www.unicode.org/
-// http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
-// http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.h
-// http://people.w3.org/rishida/scripts/uniview/conversion
-//
-////////////////////////////////////////////////////////////
-
-namespace
-{
- ////////////////////////////////////////////////////////////
- // Generic utility function to compute the number
- // of characters in a null-terminated string of any type
- ////////////////////////////////////////////////////////////
- template <typename T>
- std::size_t StrLen(const T* Str)
- {
- std::size_t Length = 0;
- while (*Str++) Length++;
- return Length;
- }
-
- ////////////////////////////////////////////////////////////
- // Get the current system locale
- ////////////////////////////////////////////////////////////
- std::locale GetCurrentLocale()
- {
- try
- {
- return std::locale("");
- }
- catch (std::runtime_error&)
- {
- // It seems some implementations don't know the "" locale
- // (Mac OS, MinGW)
-
- return std::locale();
- }
- }
-}
-
-namespace sf
-{
-////////////////////////////////////////////////////////////
-// Static member data
-////////////////////////////////////////////////////////////
-const int Unicode::UTF8TrailingBytes[256] =
-{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5
-};
-const Uint32 Unicode::UTF8Offsets[6] =
-{
- 0x00000000, 0x00003080, 0x000E2080, 0x03C82080, 0xFA082080, 0x82082080
-};
-const Uint8 Unicode::UTF8FirstBytes[7] =
-{
- 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC
-};
-
-
-////////////////////////////////////////////////////////////
-/// Default constructor (empty text)
-////////////////////////////////////////////////////////////
-Unicode::Text::Text()
-{
- // Nothing to do
-}
-
-
-////////////////////////////////////////////////////////////
-/// Construct the unicode text from any type of string
-////////////////////////////////////////////////////////////
-Unicode::Text::Text(const char* Str)
-{
- if (Str)
- {
- std::size_t Length = StrLen(Str);
- if (Length > 0)
- {
- myUTF32String.reserve(Length + 1);
- Unicode::ANSIToUTF32(Str, Str + Length, std::back_inserter(myUTF32String));
- }
- }
-}
-Unicode::Text::Text(const wchar_t* Str)
-{
- if (Str)
- {
- std::size_t Length = StrLen(Str);
- if (Length > 0)
- {
- // See comments below, in Unicode::Text::Text(const std::wstring&)
- myUTF32String.reserve(Length + 1);
- switch (sizeof(wchar_t))
- {
- case 2 : Unicode::UTF16ToUTF32(Str, Str + Length, std::back_inserter(myUTF32String), 0); break;
- case 4 : std::copy(Str, Str + Length, std::back_inserter(myUTF32String)); break;
- default : break;
- }
- }
- }
-}
-Unicode::Text::Text(const Uint8* Str)
-{
- if (Str)
- {
- std::size_t Length = StrLen(Str);
- if (Length > 0)
- {
- myUTF32String.reserve(Length + 1);
- Unicode::UTF8ToUTF32(Str, Str + Length, std::back_inserter(myUTF32String), 0);
- }
- }
-}
-Unicode::Text::Text(const Uint16* Str)
-{
- if (Str)
- {
- std::size_t Length = StrLen(Str);
- if (Length > 0)
- {
- myUTF32String.reserve(Length+ 1);
- Unicode::UTF16ToUTF32(Str, Str + Length, std::back_inserter(myUTF32String), 0);
- }
- }
-}
-Unicode::Text::Text(const Uint32* Str)
-{
- if (Str)
- myUTF32String = Str;
-}
-Unicode::Text::Text(const std::string& Str)
-{
- myUTF32String.reserve(Str.length() + 1);
- Unicode::ANSIToUTF32(Str.begin(), Str.end(), std::back_inserter(myUTF32String));
-}
-Unicode::Text::Text(const std::wstring& Str)
-{
- // This function assumes that 2-byte large wchar_t are encoded in UTF-16 (Windows), and
- // 4-byte large wchar_t are encoded using UTF-32 (Unix)
- // Is that always true ? (some platforms may use JIS Japanese encoding)
- // The macro __STDC_ISO_10646__ should help identifying UTF-32 compliant implementations
-
- myUTF32String.reserve(Str.length() + 1);
-
- // Select the proper function according to the (supposed) wchar_t system encoding
- switch (sizeof(wchar_t))
- {
- // wchar_t uses UTF-16 -- need a conversion
- case 2 :
- {
- Unicode::UTF16ToUTF32(Str.begin(), Str.end(), std::back_inserter(myUTF32String), 0);
- break;
- }
-
- // wchar_t uses UTF-32 -- direct copy
- case 4 :
- {
- std::copy(Str.begin(), Str.end(), std::back_inserter(myUTF32String));
- break;
- }
-
- // This should never happen
- default : break;
- }
-}
-Unicode::Text::Text(const Unicode::UTF8String& Str)
-{
- myUTF32String.reserve(Str.length() + 1);
- Unicode::UTF8ToUTF32(Str.begin(), Str.end(), std::back_inserter(myUTF32String), 0);
-}
-Unicode::Text::Text(const Unicode::UTF16String& Str)
-{
- myUTF32String.reserve(Str.length() + 1);
- Unicode::UTF16ToUTF32(Str.begin(), Str.end(), std::back_inserter(myUTF32String), 0);
-}
-Unicode::Text::Text(const Unicode::UTF32String& Str)
-{
- myUTF32String = Str;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Operator to cast the text to any type of string
-////////////////////////////////////////////////////////////
-Unicode::Text::operator std::string() const
-{
- std::string Output;
- Output.reserve(myUTF32String.length() + 1);
- Unicode::UTF32ToANSI(myUTF32String.begin(), myUTF32String.end(), std::back_inserter(Output), 0, Unicode::GetDefaultLocale());
- return Output;
-}
-Unicode::Text::operator std::wstring() const
-{
- // This function assumes that 2-byte large wchar_t are encoded in UTF-16 (Windows), and
- // 4-byte large wchar_t are encoded using UTF-32 (Unix)
- // Is that always true ? (some platforms may use JIS Japanese encoding)
- // The macro __STDC_ISO_10646__ should help identifying UTF-32 compliant implementations
-
- std::wstring Output;
- Output.reserve(myUTF32String.length() + 1);
-
- // Select the proper function according to the (supposed) wchar_t system encoding
- switch (sizeof(wchar_t))
- {
- // wchar_t uses UTF-16 -- need a conversion
- case 2 :
- {
- UTF32ToUTF16(myUTF32String.begin(), myUTF32String.end(), std::back_inserter(Output), 0);
- break;
- }
-
- // wchar_t uses UTF-32 -- direct copy
- case 4 :
- {
- std::copy(myUTF32String.begin(), myUTF32String.end(), std::back_inserter(Output));
- break;
- }
-
- // This should never happen
- default : break;
- }
- return Output;
-}
-Unicode::Text::operator sf::Unicode::UTF8String() const
-{
- Unicode::UTF8String Output;
- Output.reserve(myUTF32String.length() * 4 + 1);
- Unicode::UTF32ToUTF8(myUTF32String.begin(), myUTF32String.end(), std::back_inserter(Output), 0);
- return Output;
-}
-Unicode::Text::operator sf::Unicode::UTF16String() const
-{
- Unicode::UTF16String Output;
- Output.reserve(myUTF32String.length() * 2 + 1);
- Unicode::UTF32ToUTF16(myUTF32String.begin(), myUTF32String.end(), std::back_inserter(Output), 0);
- return Output;
-}
-Unicode::Text::operator const sf::Unicode::UTF32String&() const
-{
- return myUTF32String;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the default system locale
-////////////////////////////////////////////////////////////
-const std::locale& Unicode::GetDefaultLocale()
-{
- // It seems getting the default locale is a very expensive operation,
- // so we only do it once and then store the locale for reuse.
- // Warning : this code won't be aware of any change of the default locale during runtime
-
- static std::locale DefaultLocale = GetCurrentLocale();
-
- return DefaultLocale;
-}
-
-} // namespace sf
diff --git a/src/SFML/System/Unix/ClockImpl.cpp b/src/SFML/System/Unix/ClockImpl.cpp
new file mode 100644
index 0000000..813eec4
--- /dev/null
+++ b/src/SFML/System/Unix/ClockImpl.cpp
@@ -0,0 +1,64 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/System/Unix/ClockImpl.hpp>
+#ifdef SFML_SYSTEM_MACOS
+ #include <mach/mach_time.h>
+#else
+ #include <time.h>
+#endif
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+Time ClockImpl::getCurrentTime()
+{
+#ifdef SFML_SYSTEM_MACOS
+
+ // Mac OS X specific implementation (it doesn't support clock_gettime)
+ static mach_timebase_info_data_t frequency = {0, 0};
+ if (frequency.denom == 0)
+ mach_timebase_info(&frequency);
+ Uint64 nanoseconds = mach_absolute_time() * frequency.numer / frequency.denom;
+ return sf::microseconds(nanoseconds / 1000);
+
+#else
+
+ // POSIX implementation
+ timespec time;
+ clock_gettime(CLOCK_MONOTONIC, &time);
+ return sf::microseconds(static_cast<Uint64>(time.tv_sec) * 1000000 + time.tv_nsec / 1000);
+
+#endif
+}
+
+} // namespace priv
+
+} // namespace sf
diff --git a/src/SFML/System/Unix/Platform.hpp b/src/SFML/System/Unix/ClockImpl.hpp
index 0cd0990..e55f5e9 100755..100644
--- a/src/SFML/System/Unix/Platform.hpp
+++ b/src/SFML/System/Unix/ClockImpl.hpp
@@ -1,69 +1,61 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-#ifndef SFML_PLATFORMUNIX_HPP
-#define SFML_PLATFORMUNIX_HPP
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Config.hpp>
-#include <vector>
-
-
-namespace sf
-{
-namespace priv
-{
-////////////////////////////////////////////////////////////
-/// Unix implementation fo Platform
-/// Give access to various global system functions
-////////////////////////////////////////////////////////////
-class Platform
-{
-public :
-
- ////////////////////////////////////////////////////////////
- /// Get the current system time
- ///
- /// \return System time, in seconds
- ///
- ////////////////////////////////////////////////////////////
- static double GetSystemTime();
-
- ////////////////////////////////////////////////////////////
- /// Suspend the execution of the current thread for a specified time
- ///
- /// \param Time : Time to sleep, in seconds
- ///
- ////////////////////////////////////////////////////////////
- static void Sleep(float Time);
-};
-
-} // namespace priv
-
-} // namespace sf
-
-
-#endif // SFML_PLATFORMUNIX_HPP
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_CLOCKIMPLUNIX_HPP
+#define SFML_CLOCKIMPLUNIX_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Config.hpp>
+#include <SFML/System/Time.hpp>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief Unix implementaton of sf::Clock
+///
+////////////////////////////////////////////////////////////
+class ClockImpl
+{
+public :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Get the current time
+ ///
+ /// \return Current time
+ ///
+ ////////////////////////////////////////////////////////////
+ static Time getCurrentTime();
+};
+
+} // namespace priv
+
+} // namespace sf
+
+
+#endif // SFML_CLOCKIMPLUNIX_HPP
diff --git a/src/SFML/System/Unix/Initializer.cpp b/src/SFML/System/Unix/Initializer.cpp
deleted file mode 100755
index 0d3dbee..0000000
--- a/src/SFML/System/Unix/Initializer.cpp
+++ /dev/null
@@ -1,86 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Lucas Soltic (ceylow@gmail.com) and Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Config.hpp>
-
-
-#ifdef SFML_SYSTEM_MACOS
-
-#include <CoreFoundation/CoreFoundation.h>
-#include <iostream>
-#include <cstdio>
-
-namespace sf
-{
-namespace priv
-{
-////////////////////////////////////////////////////////////
-/// Under Mac OS X, when launching an application from the Finder,
-/// the default working directory is the user home directory ;
-/// when launching from Xcode, the default one is the directory
-/// containing the application. In order to produce a uniform behaviour
-/// and simplify the use of resources, SFML sets the working directory to
-/// the Resources folder of the application bundle.
-/// The "constructor" attribute forces the function to be called
-/// at library loading time.
-////////////////////////////////////////////////////////////
-void InitializeWorkingDirectory(void) __attribute__ ((constructor));
-void InitializeWorkingDirectory(void)
-{
- char PathBuffer[4096];
- bool Encoded = false;
-
- // Get the application bundle
- CFBundleRef MainBundle = CFBundleGetMainBundle();
- assert(MainBundle != NULL);
-
- // Get the resource directory URL
- CFURLRef ResourceDirectory = CFBundleCopyResourcesDirectoryURL(MainBundle);
- assert(ResourceDirectory != NULL);
-
- // Convert it as absolute URL
- CFURLRef AbsoluteURL = CFURLCopyAbsoluteURL(ResourceDirectory);
- assert(AbsoluteURL != NULL);
-
- // Get the path as C string
- Encoded = CFURLGetFileSystemRepresentation(AbsoluteURL, true, (UInt8 *)PathBuffer, 4096);
- assert(Encoded);
-
- // Set the working directory
- chdir(PathBuffer);
-
- CFRelease(AbsoluteURL);
- CFRelease(ResourceDirectory);
-}
-
-} // namespace priv
-
-} // namespace sf
-
-
-#endif // SFML_SYSTEM_MACOS
-
diff --git a/src/SFML/Window/Template for new ports/VideoModeSupport.cpp b/src/SFML/System/Unix/MutexImpl.cpp
index 0057992..8382dca 100755..100644
--- a/src/SFML/Window/Template for new ports/VideoModeSupport.cpp
+++ b/src/SFML/System/Unix/MutexImpl.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -25,7 +25,7 @@
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
-#include <SFML/Window/XXX/VideoModeSupport.hpp>
+#include <SFML/System/Unix/MutexImpl.hpp>
namespace sf
@@ -33,26 +33,35 @@ namespace sf
namespace priv
{
////////////////////////////////////////////////////////////
-/// Get supported video modes
-////////////////////////////////////////////////////////////
-void VideoModeSupport::GetSupportedVideoModes(std::vector<VideoMode>& Modes)
+MutexImpl::MutexImpl()
{
- // Get all the supported fullscreen modes and put them in Modes array
+ // Make it recursive to follow the expected behaviour
+ pthread_mutexattr_t attributes;
+ pthread_mutexattr_init(&attributes);
+ pthread_mutexattr_settype(&attributes, PTHREAD_MUTEX_RECURSIVE);
- // Just care about width, height and bpp (ignore frequency and other attributes)
+ pthread_mutex_init(&m_mutex, &attributes);
+}
- // You must remove duplicates
- // Order doesn't matter (the array will be sorted later)
+////////////////////////////////////////////////////////////
+MutexImpl::~MutexImpl()
+{
+ pthread_mutex_destroy(&m_mutex);
}
////////////////////////////////////////////////////////////
-/// Get current desktop video mode
+void MutexImpl::lock()
+{
+ pthread_mutex_lock(&m_mutex);
+}
+
+
////////////////////////////////////////////////////////////
-VideoMode VideoModeSupport::GetDesktopVideoMode()
+void MutexImpl::unlock()
{
- // Return the current desktop video mode
+ pthread_mutex_unlock(&m_mutex);
}
} // namespace priv
diff --git a/src/SFML/Window/Template for new ports/Joystick.hpp b/src/SFML/System/Unix/MutexImpl.hpp
index bb5243a..b6f728e 100755..100644
--- a/src/SFML/Window/Template for new ports/Joystick.hpp
+++ b/src/SFML/System/Unix/MutexImpl.hpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -22,12 +22,14 @@
//
////////////////////////////////////////////////////////////
-#ifndef SFML_JOYSTICKXXX_HPP
-#define SFML_JOYSTICKXXX_HPP
+#ifndef SFML_MUTEXIMPL_HPP
+#define SFML_MUTEXIMPL_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
+#include <SFML/System/NonCopyable.hpp>
+#include <pthread.h>
namespace sf
@@ -35,43 +37,42 @@ namespace sf
namespace priv
{
////////////////////////////////////////////////////////////
-/// Linux implementation of Joystick
+/// \brief Unix implementation of mutexes
////////////////////////////////////////////////////////////
-class Joystick
+class MutexImpl : NonCopyable
{
public :
////////////////////////////////////////////////////////////
- /// Initialize the instance and bind it to a physical joystick
- ///
- /// \param Index : Index of the physical joystick to bind to
+ /// \brief Default constructor
///
////////////////////////////////////////////////////////////
- void Initialize(unsigned int Index);
+ MutexImpl();
////////////////////////////////////////////////////////////
- /// Update the current joystick and return its new state
- ///
- /// \return Current state of the joystick
+ /// \brief Destructor
///
////////////////////////////////////////////////////////////
- JoystickState UpdateState();
+ ~MutexImpl();
////////////////////////////////////////////////////////////
- /// Get the number of axes supported by the joystick
- ///
- /// \return Number of axis
+ /// \brief Lock the mutex
///
////////////////////////////////////////////////////////////
- unsigned int GetAxesCount() const;
+ void lock();
////////////////////////////////////////////////////////////
- /// Get the number of buttons supported by the joystick
- ///
- /// \return Number of buttons
+ /// \brief Unlock the mutex
///
////////////////////////////////////////////////////////////
- unsigned int GetButtonsCount() const;
+ void unlock();
+
+private :
+
+ ////////////////////////////////////////////////////////////
+ // Member data
+ ////////////////////////////////////////////////////////////
+ pthread_mutex_t m_mutex; ///< pthread handle of the mutex
};
} // namespace priv
@@ -79,4 +80,4 @@ public :
} // namespace sf
-#endif // SFML_JOYSTICKXXX_HPP
+#endif // SFML_MUTEXIMPL_HPP
diff --git a/src/SFML/System/Unix/SleepImpl.cpp b/src/SFML/System/Unix/SleepImpl.cpp
new file mode 100644
index 0000000..d817d58
--- /dev/null
+++ b/src/SFML/System/Unix/SleepImpl.cpp
@@ -0,0 +1,77 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/System/Unix/SleepImpl.hpp>
+#include <pthread.h>
+#include <unistd.h>
+#include <sys/time.h>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+void sleepImpl(Time time)
+{
+ // usleep is not reliable enough (it might block the
+ // whole process instead of just the current thread)
+ // so we must use pthread_cond_timedwait instead
+
+ // this implementation is inspired from Qt
+
+ Uint64 usecs = time.asMicroseconds();
+
+ // get the current time
+ timeval tv;
+ gettimeofday(&tv, NULL);
+
+ // construct the time limit (current time + time to wait)
+ timespec ti;
+ ti.tv_nsec = (tv.tv_usec + (usecs % 1000000)) * 1000;
+ ti.tv_sec = tv.tv_sec + (usecs / 1000000) + (ti.tv_nsec / 1000000000);
+ ti.tv_nsec %= 1000000000;
+
+ // create a mutex and thread condition
+ pthread_mutex_t mutex;
+ pthread_mutex_init(&mutex, 0);
+ pthread_cond_t condition;
+ pthread_cond_init(&condition, 0);
+
+ // wait...
+ pthread_mutex_lock(&mutex);
+ pthread_cond_timedwait(&condition, &mutex, &ti);
+ pthread_mutex_unlock(&mutex);
+
+ // destroy the mutex and condition
+ pthread_cond_destroy(&condition);
+ pthread_mutex_destroy(&mutex);
+}
+
+} // namespace priv
+
+} // namespace sf
diff --git a/src/SFML/System/Unix/SleepImpl.hpp b/src/SFML/System/Unix/SleepImpl.hpp
new file mode 100644
index 0000000..02142e4
--- /dev/null
+++ b/src/SFML/System/Unix/SleepImpl.hpp
@@ -0,0 +1,52 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_SLEEPIMPLUNIX_HPP
+#define SFML_SLEEPIMPLUNIX_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Config.hpp>
+#include <SFML/System/Time.hpp>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief Unix implementation of sf::Sleep
+///
+/// \param time Time to sleep
+///
+////////////////////////////////////////////////////////////
+void sleepImpl(Time time);
+
+} // namespace priv
+
+} // namespace sf
+
+
+#endif // SFML_SLEEPIMPLUNIX_HPP
diff --git a/src/SFML/System/Unix/Thread.cpp b/src/SFML/System/Unix/Thread.cpp
deleted file mode 100755
index da02399..0000000
--- a/src/SFML/System/Unix/Thread.cpp
+++ /dev/null
@@ -1,148 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/System/Unix/Thread.hpp>
-#include <iostream>
-
-
-namespace sf
-{
-////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
-Thread::Thread() :
-myIsActive(false),
-myFunction(NULL),
-myUserData(NULL)
-{
-
-}
-
-
-////////////////////////////////////////////////////////////
-/// Construct the thread from a function pointer
-////////////////////////////////////////////////////////////
-Thread::Thread(Thread::FuncType Function, void* UserData) :
-myIsActive(false),
-myFunction(Function),
-myUserData(UserData)
-{
-
-}
-
-
-////////////////////////////////////////////////////////////
-/// Virtual destructor
-////////////////////////////////////////////////////////////
-Thread::~Thread()
-{
- // Wait for the thread to finish before destroying the instance
- Wait();
-}
-
-
-////////////////////////////////////////////////////////////
-/// Create and run the thread
-////////////////////////////////////////////////////////////
-void Thread::Launch()
-{
- // Wait for the thread to finish, in case it was already running
- Wait();
-
- // Create the thread
- myIsActive = true;
- int Error = pthread_create(&myThread, NULL, &Thread::ThreadFunc, this);
-
- // Error ?
- if (Error != 0)
- {
- std::cerr << "Failed to create thread" << std::endl;
- myIsActive = false;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Wait until the thread finishes
-////////////////////////////////////////////////////////////
-void Thread::Wait()
-{
- if (myIsActive)
- {
- // Wait for the thread to finish, no timeout
- pthread_join(myThread, NULL);
-
- // Reset the thread state
- myIsActive = false;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Terminate the thread
-/// Terminating a thread with this function is not safe,
-/// you should rather try to make the thread function
-/// terminate by itself
-////////////////////////////////////////////////////////////
-void Thread::Terminate()
-{
- if (myIsActive)
- {
- pthread_cancel(myThread);
- myIsActive = false;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Function called as the thread entry point
-////////////////////////////////////////////////////////////
-void Thread::Run()
-{
- if (myFunction)
- myFunction(myUserData);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Actual thread entry point, dispatches to instances
-////////////////////////////////////////////////////////////
-void* Thread::ThreadFunc(void* UserData)
-{
- // The sfThread instance is stored in the user data
- Thread* ThreadToRun = reinterpret_cast<Thread*>(UserData);
-
- // Tell the thread to handle cancel requests immediatly
- pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
-
- // Forward to the instance
- ThreadToRun->Run();
-
- return NULL;
-}
-
-} // namespace sf
diff --git a/src/SFML/System/Win32/Platform.cpp b/src/SFML/System/Unix/ThreadImpl.cpp
index 948d154..663fb71 100755..100644
--- a/src/SFML/System/Win32/Platform.cpp
+++ b/src/SFML/System/Unix/ThreadImpl.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -25,8 +25,10 @@
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
-#include <SFML/System/Win32/Platform.hpp>
-#include <windows.h>
+#include <SFML/System/Unix/ThreadImpl.hpp>
+#include <SFML/System/Thread.hpp>
+#include <iostream>
+#include <cassert>
namespace sf
@@ -34,35 +36,48 @@ namespace sf
namespace priv
{
////////////////////////////////////////////////////////////
-/// Get the current system time
-////////////////////////////////////////////////////////////
-double Platform::GetSystemTime()
+ThreadImpl::ThreadImpl(Thread* owner) :
+m_isActive(true)
{
- static LARGE_INTEGER Frequency;
- static BOOL UseHighPerformanceTimer = QueryPerformanceFrequency(&Frequency);
+ m_isActive = pthread_create(&m_thread, NULL, &ThreadImpl::entryPoint, owner) == 0;
- if (UseHighPerformanceTimer)
- {
- // High performance counter available : use it
- LARGE_INTEGER CurrentTime;
- QueryPerformanceCounter(&CurrentTime);
+ if (!m_isActive)
+ std::cerr << "Failed to create thread" << std::endl;
+}
- return static_cast<double>(CurrentTime.QuadPart) / Frequency.QuadPart;
- }
- else
+
+////////////////////////////////////////////////////////////
+void ThreadImpl::wait()
+{
+ if (m_isActive)
{
- // High performance counter not available : use GetTickCount (less accurate)
- return GetTickCount() * 0.001;
+ assert(pthread_equal(pthread_self(), m_thread) == 0); // A thread cannot wait for itself!
+ pthread_join(m_thread, NULL);
}
}
////////////////////////////////////////////////////////////
-/// Suspend the execution of the current thread for a specified time
+void ThreadImpl::terminate()
+{
+ if (m_isActive)
+ pthread_cancel(m_thread);
+}
+
+
////////////////////////////////////////////////////////////
-void Platform::Sleep(float Time)
+void* ThreadImpl::entryPoint(void* userData)
{
- ::Sleep(static_cast<DWORD>(Time * 1000));
+ // The Thread instance is stored in the user data
+ Thread* owner = static_cast<Thread*>(userData);
+
+ // Tell the thread to handle cancel requests immediatly
+ pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
+
+ // Forward to the owner
+ owner->run();
+
+ return NULL;
}
} // namespace priv
diff --git a/src/SFML/Window/Linux/Joystick.hpp b/src/SFML/System/Unix/ThreadImpl.hpp
index 3122264..5bf32d0 100755..100644
--- a/src/SFML/Window/Linux/Joystick.hpp
+++ b/src/SFML/System/Unix/ThreadImpl.hpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -22,78 +22,66 @@
//
////////////////////////////////////////////////////////////
-#ifndef SFML_JOYSTICKLINUX_HPP
-#define SFML_JOYSTICKLINUX_HPP
+#ifndef SFML_THREADIMPL_HPP
+#define SFML_THREADIMPL_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
-#if defined(SFML_SYSTEM_LINUX)
- #include <linux/joystick.h>
- #include <fcntl.h>
-#elif defined(SFML_SYSTEM_FREEBSD)
- // #include <sys/joystick.h> ?
- #define ABS_MAX 1
-#endif
+#include <SFML/System/NonCopyable.hpp>
+#include <pthread.h>
namespace sf
{
+class Thread;
+
namespace priv
{
////////////////////////////////////////////////////////////
-/// Linux implementation of Joystick
+/// \brief Unix implementation of threads
////////////////////////////////////////////////////////////
-class Joystick
+class ThreadImpl : NonCopyable
{
public :
////////////////////////////////////////////////////////////
- /// Initialize the instance and bind it to a physical joystick
+ /// \brief Default constructor, launch the thread
///
- /// \param Index : Index of the physical joystick to bind to
+ /// \param owner The Thread instance to run
///
////////////////////////////////////////////////////////////
- void Initialize(unsigned int Index);
+ ThreadImpl(Thread* owner);
////////////////////////////////////////////////////////////
- /// Update the current joystick and return its new state
- ///
- /// \return Current state of the joystick
+ /// \brief Wait until the thread finishes
///
////////////////////////////////////////////////////////////
- JoystickState UpdateState();
+ void wait();
////////////////////////////////////////////////////////////
- /// Check if the joystick supports the given axis
- ///
- /// \param Axis : Axis to check
- ///
- /// \return True of the axis is supported, false otherwise
+ /// \brief Terminate the thread
///
////////////////////////////////////////////////////////////
- bool HasAxis(Joy::Axis Axis) const;
+ void terminate();
+
+private :
////////////////////////////////////////////////////////////
- /// Get the number of buttons supported by the joystick
+ /// \brief Global entry point for all threads
+ ///
+ /// \param userData User-defined data (contains the Thread instance)
///
- /// \return Number of buttons
+ /// \return Os specific error code
///
////////////////////////////////////////////////////////////
- unsigned int GetButtonsCount() const;
-
-private :
+ static void* entryPoint(void* userData);
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
- int myDescriptor; ///< Linux descriptor of the joystick
- unsigned int myNbButtons; ///< Number of buttons supported by the joystick
- bool myAxes[Joy::AxisCount]; ///< Supported axes
- JoystickState myState; ///< Current state of the joystick
- int myPovX; ///< Last X position of the POV
- int myPovY; ///< Last Y position of the POV
- char myAxesMapping[ABS_MAX + 1]; ///< Axes mapping (index --> axis id)
+ pthread_t m_thread; ///< pthread thread instance
+ bool m_isActive; ///< Thread state (active or inactive)
};
} // namespace priv
@@ -101,4 +89,4 @@ private :
} // namespace sf
-#endif // SFML_JOYSTICKLINUX_HPP
+#endif // SFML_THREADIMPL_HPP
diff --git a/src/SFML/System/Unix/Platform.cpp b/src/SFML/System/Unix/ThreadLocalImpl.cpp
index 0149c36..7b2ae6d 100755..100644
--- a/src/SFML/System/Unix/Platform.cpp
+++ b/src/SFML/System/Unix/ThreadLocalImpl.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -25,32 +25,38 @@
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
-#include <SFML/System/Unix/Platform.hpp>
-#include <unistd.h>
-#include <sys/time.h>
+#include <SFML/System/Unix/ThreadLocalImpl.hpp>
+
namespace sf
{
namespace priv
{
////////////////////////////////////////////////////////////
-/// Get the current system time
-////////////////////////////////////////////////////////////
-double Platform::GetSystemTime()
+ThreadLocalImpl::ThreadLocalImpl()
{
- timeval Time = {0, 0};
- gettimeofday(&Time, NULL);
+ pthread_key_create(&m_key, NULL);
+}
- return Time.tv_sec + Time.tv_usec / 1000000.;
+
+////////////////////////////////////////////////////////////
+ThreadLocalImpl::~ThreadLocalImpl()
+{
+ pthread_key_delete(m_key);
}
////////////////////////////////////////////////////////////
-/// Suspend the execution of the current thread for a specified time
+void ThreadLocalImpl::setValue(void* value)
+{
+ pthread_setspecific(m_key, value);
+}
+
+
////////////////////////////////////////////////////////////
-void Platform::Sleep(float Time)
+void* ThreadLocalImpl::getValue() const
{
- usleep(static_cast<unsigned long>(Time * 1000000));
+ return pthread_getspecific(m_key);
}
} // namespace priv
diff --git a/src/SFML/System/Unix/ThreadLocalImpl.hpp b/src/SFML/System/Unix/ThreadLocalImpl.hpp
new file mode 100644
index 0000000..4d547fb
--- /dev/null
+++ b/src/SFML/System/Unix/ThreadLocalImpl.hpp
@@ -0,0 +1,87 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_THREADLOCALIMPL_HPP
+#define SFML_THREADLOCALIMPL_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/System/NonCopyable.hpp>
+#include <pthread.h>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief Unix implementation of thread-local storage
+////////////////////////////////////////////////////////////
+class ThreadLocalImpl : NonCopyable
+{
+public :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Default constructor -- allocate the storage
+ ///
+ ////////////////////////////////////////////////////////////
+ ThreadLocalImpl();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Destructor -- free the storage
+ ///
+ ////////////////////////////////////////////////////////////
+ ~ThreadLocalImpl();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Set the thread-specific value of the variable
+ ///
+ /// \param value Value of the variable for this thread
+ ///
+ ////////////////////////////////////////////////////////////
+ void setValue(void* value);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Retrieve the thread-specific value of the variable
+ ///
+ /// \return Value of the variable for this thread
+ ///
+ ////////////////////////////////////////////////////////////
+ void* getValue() const;
+
+private :
+
+ ////////////////////////////////////////////////////////////
+ // Member data
+ ////////////////////////////////////////////////////////////
+ pthread_key_t m_key; ///< Index of our thread-local storage slot
+};
+
+} // namespace priv
+
+} // namespace sf
+
+
+#endif // SFML_THREADLOCALIMPL_HPP
diff --git a/src/SFML/System/Win32/ClockImpl.cpp b/src/SFML/System/Win32/ClockImpl.cpp
new file mode 100644
index 0000000..c3cb711
--- /dev/null
+++ b/src/SFML/System/Win32/ClockImpl.cpp
@@ -0,0 +1,71 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/System/Win32/ClockImpl.hpp>
+#include <windows.h>
+
+
+namespace
+{
+ LARGE_INTEGER getFrequency()
+ {
+ LARGE_INTEGER frequency;
+ QueryPerformanceFrequency(&frequency);
+ return frequency;
+ }
+}
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+Time ClockImpl::getCurrentTime()
+{
+ // Force the following code to run on first core
+ // (see http://msdn.microsoft.com/en-us/library/windows/desktop/ms644904(v=vs.85).aspx)
+ HANDLE currentThread = GetCurrentThread();
+ DWORD_PTR previousMask = SetThreadAffinityMask(currentThread, 1);
+
+ // Get the frequency of the performance counter
+ // (it is constant across the program lifetime)
+ static LARGE_INTEGER frequency = getFrequency();
+
+ // Get the current time
+ LARGE_INTEGER time;
+ QueryPerformanceCounter(&time);
+
+ // Restore the thread affinity
+ SetThreadAffinityMask(currentThread, previousMask);
+
+ // Return the current time as microseconds
+ return sf::microseconds(1000000 * time.QuadPart / frequency.QuadPart);
+}
+
+} // namespace priv
+
+} // namespace sf
diff --git a/src/SFML/System/Win32/ClockImpl.hpp b/src/SFML/System/Win32/ClockImpl.hpp
new file mode 100644
index 0000000..d7e3863
--- /dev/null
+++ b/src/SFML/System/Win32/ClockImpl.hpp
@@ -0,0 +1,61 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_CLOCKIMPLWIN32_HPP
+#define SFML_CLOCKIMPLWIN32_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Config.hpp>
+#include <SFML/System/Time.hpp>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief Windows implementaton of sf::Clock
+///
+////////////////////////////////////////////////////////////
+class ClockImpl
+{
+public :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Get the current time
+ ///
+ /// \return Current time
+ ///
+ ////////////////////////////////////////////////////////////
+ static Time getCurrentTime();
+};
+
+} // namespace priv
+
+} // namespace sf
+
+
+#endif // SFML_CLOCKIMPLWIN32_HPP
diff --git a/src/SFML/System/Win32/MutexImpl.cpp b/src/SFML/System/Win32/MutexImpl.cpp
new file mode 100644
index 0000000..7e7f0c3
--- /dev/null
+++ b/src/SFML/System/Win32/MutexImpl.cpp
@@ -0,0 +1,64 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/System/Win32/MutexImpl.hpp>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+MutexImpl::MutexImpl()
+{
+ InitializeCriticalSection(&m_mutex);
+}
+
+
+////////////////////////////////////////////////////////////
+MutexImpl::~MutexImpl()
+{
+ DeleteCriticalSection(&m_mutex);
+}
+
+
+////////////////////////////////////////////////////////////
+void MutexImpl::lock()
+{
+ EnterCriticalSection(&m_mutex);
+}
+
+
+////////////////////////////////////////////////////////////
+void MutexImpl::unlock()
+{
+ LeaveCriticalSection(&m_mutex);
+}
+
+} // namespace priv
+
+} // namespace sf
diff --git a/src/SFML/Window/Cocoa/Joystick.hpp b/src/SFML/System/Win32/MutexImpl.hpp
index 60c5db2..db78fb1 100755..100644
--- a/src/SFML/Window/Cocoa/Joystick.hpp
+++ b/src/SFML/System/Win32/MutexImpl.hpp
@@ -1,84 +1,83 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-#ifndef SFML_JOYSTICKCARBON_HPP
-#define SFML_JOYSTICKCARBON_HPP
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-
-
-namespace sf
-{
-namespace priv
-{
-////////////////////////////////////////////////////////////
-/// ****** implementation of Joystick (unknown implementation kind for now)
-////////////////////////////////////////////////////////////
-class Joystick
-{
-public :
-
- ////////////////////////////////////////////////////////////
- /// Initialize the instance and bind it to a physical joystick
- ///
- /// \param Index : Index of the physical joystick to bind to
- ///
- ////////////////////////////////////////////////////////////
- void Initialize(unsigned int Index);
-
- ////////////////////////////////////////////////////////////
- /// Update the current joystick and return its new state
- ///
- /// \return Current state of the joystick
- ///
- ////////////////////////////////////////////////////////////
- JoystickState UpdateState();
-
- ////////////////////////////////////////////////////////////
- /// Check if the joystick supports the given axis
- ///
- /// \param Axis : Axis to check
- ///
- /// \return True of the axis is supported, false otherwise
- ///
- ////////////////////////////////////////////////////////////
- bool HasAxis(Joy::Axis Axis) const;
-
- ////////////////////////////////////////////////////////////
- /// Get the number of buttons supported by the joystick
- ///
- /// \return Number of buttons
- ///
- ////////////////////////////////////////////////////////////
- unsigned int GetButtonsCount() const;
-};
-
-} // namespace priv
-
-} // namespace sf
-
-
-#endif // SFML_JOYSTICKCARBON_HPP
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_MUTEXIMPL_HPP
+#define SFML_MUTEXIMPL_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/System/NonCopyable.hpp>
+#include <windows.h>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief Windows implementation of mutexes
+////////////////////////////////////////////////////////////
+class MutexImpl : NonCopyable
+{
+public :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Default constructor
+ ///
+ ////////////////////////////////////////////////////////////
+ MutexImpl();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Destructor
+ ///
+ ////////////////////////////////////////////////////////////
+ ~MutexImpl();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Lock the mutex
+ ///
+ ////////////////////////////////////////////////////////////
+ void lock();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Unlock the mutex
+ ///
+ ////////////////////////////////////////////////////////////
+ void unlock();
+
+private :
+
+ ////////////////////////////////////////////////////////////
+ // Member data
+ ////////////////////////////////////////////////////////////
+ CRITICAL_SECTION m_mutex; ///< Win32 handle of the mutex
+};
+
+} // namespace priv
+
+} // namespace sf
+
+
+#endif // SFML_MUTEXIMPL_HPP
diff --git a/src/SFML/System/Win32/SleepImpl.cpp b/src/SFML/System/Win32/SleepImpl.cpp
new file mode 100644
index 0000000..c3acda6
--- /dev/null
+++ b/src/SFML/System/Win32/SleepImpl.cpp
@@ -0,0 +1,44 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/System/Win32/SleepImpl.hpp>
+#include <windows.h>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+void sleepImpl(Time time)
+{
+ ::Sleep(time.asMilliseconds());
+}
+
+} // namespace priv
+
+} // namespace sf
diff --git a/src/SFML/System/Win32/SleepImpl.hpp b/src/SFML/System/Win32/SleepImpl.hpp
new file mode 100644
index 0000000..e6f4c99
--- /dev/null
+++ b/src/SFML/System/Win32/SleepImpl.hpp
@@ -0,0 +1,52 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_SLEEPIMPLWIN32_HPP
+#define SFML_SLEEPIMPLWIN32_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Config.hpp>
+#include <SFML/System/Time.hpp>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief Windows implementation of sf::Sleep
+///
+/// \param time Time to sleep
+///
+////////////////////////////////////////////////////////////
+void sleepImpl(Time time);
+
+} // namespace priv
+
+} // namespace sf
+
+
+#endif // SFML_SLEEPIMPLWIN32_HPP
diff --git a/src/SFML/System/Win32/Thread.cpp b/src/SFML/System/Win32/Thread.cpp
deleted file mode 100755
index 3252100..0000000
--- a/src/SFML/System/Win32/Thread.cpp
+++ /dev/null
@@ -1,146 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/System/Win32/Thread.hpp>
-#include <process.h>
-#include <iostream>
-
-
-namespace sf
-{
-////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
-Thread::Thread() :
-myHandle (NULL),
-myFunction(NULL),
-myUserData(NULL)
-{
-
-}
-
-
-////////////////////////////////////////////////////////////
-/// Construct the thread from a function pointer
-////////////////////////////////////////////////////////////
-Thread::Thread(Thread::FuncType Function, void* UserData) :
-myHandle (NULL),
-myFunction(Function),
-myUserData(UserData)
-{
-
-}
-
-
-////////////////////////////////////////////////////////////
-/// Virtual destructor
-////////////////////////////////////////////////////////////
-Thread::~Thread()
-{
- // Wait for the thread to finish before destroying the instance
- Wait();
-}
-
-
-////////////////////////////////////////////////////////////
-/// Create and run the thread
-////////////////////////////////////////////////////////////
-void Thread::Launch()
-{
- // Wait for the thread to finish, in case it was already running
- Wait();
-
- // Create the thread
- myHandle = reinterpret_cast<HANDLE>(_beginthreadex(NULL, 0, &Thread::ThreadFunc, this, 0, NULL));
-
- // Error ?
- if (myHandle == NULL)
- std::cerr << "Failed to create thread" << std::endl;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Wait until the thread finishes
-////////////////////////////////////////////////////////////
-void Thread::Wait()
-{
- if (myHandle)
- {
- // Wait for the thread to finish, no timeout
- WaitForSingleObject(myHandle, INFINITE);
-
- // Don't forget to close the thread handle (__endthreadex doesn't do it)
- CloseHandle(myHandle);
- myHandle = NULL;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Terminate the thread
-/// Terminating a thread with this function is not safe,
-/// you should rather try to make the thread function
-/// terminate by itself
-////////////////////////////////////////////////////////////
-void Thread::Terminate()
-{
- if (myHandle)
- {
- TerminateThread(myHandle, 0);
- myHandle = NULL;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Function called as the thread entry point
-////////////////////////////////////////////////////////////
-void Thread::Run()
-{
- if (myFunction)
- myFunction(myUserData);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Actual thread entry point, dispatches to instances
-////////////////////////////////////////////////////////////
-unsigned int __stdcall Thread::ThreadFunc(void* UserData)
-{
- // The Thread instance is stored in the user data
- Thread* ThreadInstance = reinterpret_cast<Thread*>(UserData);
-
- // Forward to the instance
- ThreadInstance->Run();
-
- // Optional, but it is cleaner
- _endthreadex(0);
-
- return 0;
-}
-
-} // namespace sf
diff --git a/src/SFML/System/Win32/ThreadImpl.cpp b/src/SFML/System/Win32/ThreadImpl.cpp
new file mode 100644
index 0000000..be80ed4
--- /dev/null
+++ b/src/SFML/System/Win32/ThreadImpl.cpp
@@ -0,0 +1,93 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/System/Win32/ThreadImpl.hpp>
+#include <SFML/System/Thread.hpp>
+#include <SFML/System/Err.hpp>
+#include <cassert>
+#include <process.h>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+ThreadImpl::ThreadImpl(Thread* owner)
+{
+ m_thread = reinterpret_cast<HANDLE>(_beginthreadex(NULL, 0, &ThreadImpl::entryPoint, owner, 0, &m_threadId));
+
+ if (!m_thread)
+ err() << "Failed to create thread" << std::endl;
+}
+
+
+////////////////////////////////////////////////////////////
+ThreadImpl::~ThreadImpl()
+{
+ if (m_thread)
+ CloseHandle(m_thread);
+}
+
+
+////////////////////////////////////////////////////////////
+void ThreadImpl::wait()
+{
+ if (m_thread)
+ {
+ assert(m_threadId != GetCurrentThreadId()); // A thread cannot wait for itself!
+ WaitForSingleObject(m_thread, INFINITE);
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void ThreadImpl::terminate()
+{
+ if (m_thread)
+ TerminateThread(m_thread, 0);
+}
+
+
+////////////////////////////////////////////////////////////
+unsigned int __stdcall ThreadImpl::entryPoint(void* userData)
+{
+ // The Thread instance is stored in the user data
+ Thread* owner = static_cast<Thread*>(userData);
+
+ // Forward to the owner
+ owner->run();
+
+ // Optional, but it is cleaner
+ _endthreadex(0);
+
+ return 0;
+}
+
+} // namespace priv
+
+} // namespace sf
diff --git a/src/SFML/Window/Win32/Joystick.hpp b/src/SFML/System/Win32/ThreadImpl.hpp
index 1538069..196494f 100755..100644
--- a/src/SFML/Window/Win32/Joystick.hpp
+++ b/src/SFML/System/Win32/ThreadImpl.hpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -22,69 +22,72 @@
//
////////////////////////////////////////////////////////////
-#ifndef SFML_JOYSTICKWIN32_HPP
-#define SFML_JOYSTICKWIN32_HPP
+#ifndef SFML_THREADIMPL_HPP
+#define SFML_THREADIMPL_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
+#include <SFML/System/NonCopyable.hpp>
+#include <windows.h>
namespace sf
{
+class Thread;
+
namespace priv
{
////////////////////////////////////////////////////////////
-/// Win32 implementation of Joystick
+/// \brief Windows implementation of threads
////////////////////////////////////////////////////////////
-class Joystick
+class ThreadImpl : NonCopyable
{
public :
////////////////////////////////////////////////////////////
- /// Initialize the instance and bind it to a physical joystick
+ /// \brief Default constructor, launch the thread
///
- /// \param Index : Index of the physical joystick to bind to
+ /// \param owner The Thread instance to run
///
////////////////////////////////////////////////////////////
- void Initialize(unsigned int Index);
+ ThreadImpl(Thread* owner);
////////////////////////////////////////////////////////////
- /// Update the current joystick and return its new state
- ///
- /// \return Current state of the joystick
+ /// \brief Destructor
///
////////////////////////////////////////////////////////////
- JoystickState UpdateState();
+ ~ThreadImpl();
////////////////////////////////////////////////////////////
- /// Check if the joystick supports the given axis
- ///
- /// \param Axis : Axis to check
- ///
- /// \return True of the axis is supported, false otherwise
+ /// \brief Wait until the thread finishes
///
////////////////////////////////////////////////////////////
- bool HasAxis(Joy::Axis Axis) const;
+ void wait();
////////////////////////////////////////////////////////////
- /// Get the number of buttons supported by the joystick
- ///
- /// \return Number of buttons
+ /// \brief Terminate the thread
///
////////////////////////////////////////////////////////////
- unsigned int GetButtonsCount() const;
+ void terminate();
private :
////////////////////////////////////////////////////////////
+ /// \brief Global entry point for all threads
+ ///
+ /// \param userData User-defined data (contains the Thread instance)
+ ///
+ /// \return OS specific error code
+ ///
+ ////////////////////////////////////////////////////////////
+ static unsigned int __stdcall entryPoint(void* userData);
+
+ ////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
- bool myIsConnected; ///< Is there a joystick connected?
- unsigned int myIndex; ///< Windows ID of the joystick
- unsigned int myNbButtons; ///< Number of buttons supported by the joystick
- bool myAxes[Joy::AxisCount]; ///< Supported axes
- bool myHasContinuousPOV; ///< True if the driver supports continuous values for the POV
+ HANDLE m_thread; ///< Win32 thread handle
+ unsigned int m_threadId; ///< Win32 thread identifier
};
} // namespace priv
@@ -92,4 +95,4 @@ private :
} // namespace sf
-#endif // SFML_JOYSTICKWIN32_HPP
+#endif // SFML_THREADIMPL_HPP
diff --git a/src/SFML/System/Win32/ThreadLocalImpl.cpp b/src/SFML/System/Win32/ThreadLocalImpl.cpp
new file mode 100644
index 0000000..a4d850e
--- /dev/null
+++ b/src/SFML/System/Win32/ThreadLocalImpl.cpp
@@ -0,0 +1,64 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/System/Win32/ThreadLocalImpl.hpp>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+ThreadLocalImpl::ThreadLocalImpl()
+{
+ m_index = TlsAlloc();
+}
+
+
+////////////////////////////////////////////////////////////
+ThreadLocalImpl::~ThreadLocalImpl()
+{
+ TlsFree(m_index);
+}
+
+
+////////////////////////////////////////////////////////////
+void ThreadLocalImpl::setValue(void* value)
+{
+ TlsSetValue(m_index, value);
+}
+
+
+////////////////////////////////////////////////////////////
+void* ThreadLocalImpl::getValue() const
+{
+ return TlsGetValue(m_index);
+}
+
+} // namespace priv
+
+} // namespace sf
diff --git a/src/SFML/System/Win32/ThreadLocalImpl.hpp b/src/SFML/System/Win32/ThreadLocalImpl.hpp
new file mode 100644
index 0000000..d6606f6
--- /dev/null
+++ b/src/SFML/System/Win32/ThreadLocalImpl.hpp
@@ -0,0 +1,87 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_THREADLOCALIMPL_HPP
+#define SFML_THREADLOCALIMPL_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/System/NonCopyable.hpp>
+#include <windows.h>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief Windows implementation of thread-local storage
+////////////////////////////////////////////////////////////
+class ThreadLocalImpl : NonCopyable
+{
+public :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Default constructor -- allocate the storage
+ ///
+ ////////////////////////////////////////////////////////////
+ ThreadLocalImpl();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Destructor -- free the storage
+ ///
+ ////////////////////////////////////////////////////////////
+ ~ThreadLocalImpl();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Set the thread-specific value of the variable
+ ///
+ /// \param value Value of the variable for this thread
+ ///
+ ////////////////////////////////////////////////////////////
+ void setValue(void* value);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Retrieve the thread-specific value of the variable
+ ///
+ /// \return Value of the variable for this thread
+ ///
+ ////////////////////////////////////////////////////////////
+ void* getValue() const;
+
+private :
+
+ ////////////////////////////////////////////////////////////
+ // Member data
+ ////////////////////////////////////////////////////////////
+ DWORD m_index; ///< Index of our thread-local storage slot
+};
+
+} // namespace priv
+
+} // namespace sf
+
+
+#endif // SFML_THREADLOCALIMPL_HPP
diff --git a/src/SFML/Window/CMakeLists.txt b/src/SFML/Window/CMakeLists.txt
new file mode 100644
index 0000000..b1d9aca
--- /dev/null
+++ b/src/SFML/Window/CMakeLists.txt
@@ -0,0 +1,132 @@
+
+set(INCROOT ${PROJECT_SOURCE_DIR}/include/SFML/Window)
+set(SRCROOT ${PROJECT_SOURCE_DIR}/src/SFML/Window)
+
+# all source files
+set(SRC
+ ${SRCROOT}/Context.cpp
+ ${INCROOT}/Context.hpp
+ ${INCROOT}/Export.hpp
+ ${SRCROOT}/GlContext.cpp
+ ${SRCROOT}/GlContext.hpp
+ ${SRCROOT}/GlResource.cpp
+ ${INCROOT}/GlResource.hpp
+ ${INCROOT}/ContextSettings.hpp
+ ${INCROOT}/Event.hpp
+ ${SRCROOT}/InputImpl.hpp
+ ${INCROOT}/Joystick.hpp
+ ${SRCROOT}/Joystick.cpp
+ ${SRCROOT}/JoystickImpl.hpp
+ ${SRCROOT}/JoystickManager.cpp
+ ${SRCROOT}/JoystickManager.hpp
+ ${INCROOT}/Keyboard.hpp
+ ${SRCROOT}/Keyboard.cpp
+ ${INCROOT}/Mouse.hpp
+ ${SRCROOT}/Mouse.cpp
+ ${SRCROOT}/VideoMode.cpp
+ ${INCROOT}/VideoMode.hpp
+ ${SRCROOT}/VideoModeImpl.hpp
+ ${SRCROOT}/Window.cpp
+ ${INCROOT}/Window.hpp
+ ${INCROOT}/WindowHandle.hpp
+ ${SRCROOT}/WindowImpl.cpp
+ ${SRCROOT}/WindowImpl.hpp
+ ${INCROOT}/WindowStyle.hpp
+)
+source_group("" FILES ${SRC})
+
+# add platform specific sources
+if(WINDOWS)
+ set(PLATFORM_SRC
+ ${SRCROOT}/Win32/WglContext.cpp
+ ${SRCROOT}/Win32/WglContext.hpp
+ ${SRCROOT}/Win32/InputImpl.cpp
+ ${SRCROOT}/Win32/InputImpl.hpp
+ ${SRCROOT}/Win32/JoystickImpl.cpp
+ ${SRCROOT}/Win32/JoystickImpl.hpp
+ ${SRCROOT}/Win32/VideoModeImpl.cpp
+ ${SRCROOT}/Win32/WindowImplWin32.cpp
+ ${SRCROOT}/Win32/WindowImplWin32.hpp
+ )
+ source_group("windows" FILES ${PLATFORM_SRC})
+elseif(LINUX)
+ set(PLATFORM_SRC
+ ${SRCROOT}/Linux/Display.cpp
+ ${SRCROOT}/Linux/Display.hpp
+ ${SRCROOT}/Linux/GlxContext.cpp
+ ${SRCROOT}/Linux/GlxContext.hpp
+ ${SRCROOT}/Linux/InputImpl.cpp
+ ${SRCROOT}/Linux/InputImpl.hpp
+ ${SRCROOT}/Linux/JoystickImpl.cpp
+ ${SRCROOT}/Linux/JoystickImpl.hpp
+ ${SRCROOT}/Linux/VideoModeImpl.cpp
+ ${SRCROOT}/Linux/WindowImplX11.cpp
+ ${SRCROOT}/Linux/WindowImplX11.hpp
+ )
+ source_group("linux" FILES ${PLATFORM_SRC})
+else() # MACOSX
+ set(PLATFORM_SRC
+ ${SRCROOT}/OSX/cpp_objc_conversion.h
+ ${SRCROOT}/OSX/cpp_objc_conversion.mm
+ ${SRCROOT}/OSX/cg_sf_conversion.hpp
+ ${SRCROOT}/OSX/cg_sf_conversion.cpp
+ ${SRCROOT}/OSX/InputImpl.mm
+ ${SRCROOT}/OSX/InputImpl.hpp
+ ${SRCROOT}/OSX/HIDInputManager.hpp
+ ${SRCROOT}/OSX/HIDInputManager.mm
+ ${SRCROOT}/OSX/HIDJoystickManager.hpp
+ ${SRCROOT}/OSX/HIDJoystickManager.cpp
+ ${SRCROOT}/OSX/JoystickImpl.cpp
+ ${SRCROOT}/OSX/JoystickImpl.hpp
+ ${SRCROOT}/OSX/SFApplication.h
+ ${SRCROOT}/OSX/SFApplication.m
+ ${SRCROOT}/OSX/SFContext.hpp
+ ${SRCROOT}/OSX/SFContext.mm
+ ${SRCROOT}/OSX/SFKeyboardModifiersHelper.h
+ ${SRCROOT}/OSX/SFKeyboardModifiersHelper.mm
+ ${SRCROOT}/OSX/SFOpenGLView.h
+ ${SRCROOT}/OSX/SFOpenGLView.mm
+ ${SRCROOT}/OSX/SFSilentResponder.h
+ ${SRCROOT}/OSX/SFSilentResponder.m
+ ${SRCROOT}/OSX/SFWindow.h
+ ${SRCROOT}/OSX/SFWindow.m
+ ${SRCROOT}/OSX/SFWindowController.h
+ ${SRCROOT}/OSX/SFWindowController.mm
+ ${SRCROOT}/OSX/SFViewController.h
+ ${SRCROOT}/OSX/SFViewController.mm
+ ${SRCROOT}/OSX/VideoModeImpl.cpp
+ ${SRCROOT}/OSX/WindowImplCocoa.hpp
+ ${SRCROOT}/OSX/WindowImplCocoa.mm
+ ${SRCROOT}/OSX/WindowImplDelegateProtocol.h
+ ${SRCROOT}/OSX/AutoreleasePoolWrapper.h
+ ${SRCROOT}/OSX/AutoreleasePoolWrapper.mm
+ )
+ source_group("mac" FILES ${PLATFORM_SRC})
+endif()
+
+# find external libraries
+find_package(OpenGL REQUIRED)
+include_directories(${OPENGL_INCLUDE_DIR})
+if(LINUX)
+ find_package(X11 REQUIRED)
+ if(NOT X11_Xrandr_FOUND)
+ message(FATAL_ERROR "Xrandr library not found")
+ endif()
+ include_directories(${X11_INCLUDE_DIR})
+endif()
+
+# build the list of external libraries to link
+set(WINDOW_EXT_LIBS ${OPENGL_gl_LIBRARY})
+if(WINDOWS)
+ set(WINDOW_EXT_LIBS ${WINDOW_EXT_LIBS} winmm gdi32)
+elseif(LINUX)
+ set(WINDOW_EXT_LIBS ${WINDOW_EXT_LIBS} ${X11_X11_LIB} ${X11_Xrandr_LIB})
+elseif(MACOSX)
+ set(WINDOW_EXT_LIBS ${WINDOW_EXT_LIBS} "-framework Foundation -framework AppKit -framework IOKit -framework Carbon")
+endif()
+
+# define the sfml-window target
+sfml_add_library(sfml-window
+ SOURCES ${SRC} ${PLATFORM_SRC}
+ DEPENDS sfml-system
+ EXTERNAL_LIBS ${WINDOW_EXT_LIBS})
diff --git a/src/SFML/Window/Cocoa/AppController.h b/src/SFML/Window/Cocoa/AppController.h
deleted file mode 100755
index de2d055..0000000
--- a/src/SFML/Window/Cocoa/AppController.h
+++ /dev/null
@@ -1,95 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Lucas Soltic (ceylow@gmail.com) and Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#import <SFML/Window/VideoMode.hpp>
-#import <Cocoa/Cocoa.h>
-
-
-// Fade operations
-enum {
- FillScreen,
- CleanScreen
-};
-
-@class sfPrivWindow;
-@interface sfPrivAppController : NSObject {
- BOOL myOwningEventLoop;
- sfPrivWindow *myFullscreenWrapper;
- NSAutoreleasePool *myMainPool;
- sf::VideoMode myDesktopMode;
- sf::VideoMode myPrevMode;
-}
-
-////////////////////////////////////////////////////////////
-/// Return the shared AppController instance. Make one if needed.
-////////////////////////////////////////////////////////////
-+ (sfPrivAppController *)sharedController;
-
-////////////////////////////////////////////////////////////
-/// Returns the primay computer's screen
-////////////////////////////////////////////////////////////
-+ (CGDirectDisplayID)primaryScreen;
-
-////////////////////////////////////////////////////////////
-/// Reset notifictions about application focus
-////////////////////////////////////////////////////////////
-- (void)setNotifications;
-
-////////////////////////////////////////////////////////////
-/// Make the menu bar
-////////////////////////////////////////////////////////////
-- (void)makeMenuBar;
-
-////////////////////////////////////////////////////////////
-/// Process all the events and send them to the application
-/// No event is processed if the AppController instance is
-/// not the owner of the event loop (ie: user made his own loop)
-////////////////////////////////////////////////////////////
-- (void)processEvents;
-
-////////////////////////////////////////////////////////////
-/// Set @window as the current fullscreen window
-/// Change the screen resolution if needed according to @window and @fullscreenMode
-////////////////////////////////////////////////////////////
-- (void)setFullscreenWindow:(sfPrivWindow *)window mode:(sf::VideoMode *)fullscreenMode;
-
-////////////////////////////////////////////////////////////
-/// Perform fade operation where 'operation' is one of { FillScreen, CleanScreen}
-/// and 'time' is the time during which you wish the operation to be performed.
-/// Set 'sync' to true if you do not want the method to end before the end
-/// of the fade operation.
-////////////////////////////////////////////////////////////
-- (void)doFadeOperation:(int)operation time:(float)time sync:(bool)sync;
-
-////////////////////////////////////////////////////////////
-/// Return the desktop video mode (made at the instance initialization)
-////////////////////////////////////////////////////////////
-- (const sf::VideoMode&)desktopMode;
-
-@end
-
diff --git a/src/SFML/Window/Cocoa/AppController.mm b/src/SFML/Window/Cocoa/AppController.mm
deleted file mode 100755
index 9356090..0000000
--- a/src/SFML/Window/Cocoa/AppController.mm
+++ /dev/null
@@ -1,578 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Lucas Soltic (ceylow@gmail.com) and Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#import <SFML/Window/Cocoa/AppController.h>
-#import <SFML/Window/Cocoa/GLKit.h>
-#import <SFML/System.hpp>
-#import <ApplicationServices/ApplicationServices.h>
-#import <iostream>
-
-
-
-/* setAppleMenu disappeared from the headers in 10.4 */
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
-@interface NSApplication (SFML)
-- (void)setAppleMenu:(NSMenu *)menu;
-@end
-#endif
-
-#define ENABLE_FADE_OPERATIONS 1
-
-@implementation NSApplication (SFML)
-
-- (void)setRunning:(BOOL)flag
-{
- // Note: _running is a short, not a BOOL
- if (flag)
- _running = 1;
- else
- _running = 0;
-}
-
-@end
-
-
-@implementation sfPrivAppController
-
-
-////////////////////////////////////////////////////////////
-/// Return an initialized AppController instance
-/// Save the desktop mode
-/// Make the main autorelease pool
-/// Set the application observer
-////////////////////////////////////////////////////////////
-- (id)init
-{
- self = [super init];
-
- if (self != nil) {
- myOwningEventLoop = NO;
-
- // Save the desktop mode
- myDesktopMode = sf::VideoMode::GetDesktopMode();
- myPrevMode = myDesktopMode;
-
- // Make the app autorelease pool
- myMainPool = [[NSAutoreleasePool alloc] init];
-
- if (!myMainPool) {
- [self release];
- throw std::bad_alloc();
- }
-
- // Don't go on if the user handles the app
- if (![NSApp isRunning])
- {
- // Force our application to appear in the Dock and make it able
- // to get focus (even when it's a raw executable)
- ProcessSerialNumber psn;
-
- if (!GetCurrentProcess(&psn)) {
- TransformProcessType(&psn, kProcessTransformToForegroundApplication);
- SetFrontProcess(&psn);
- }
-
- // Make the app
- if (![NSApplication sharedApplication]) {
- [self release];
- throw std::bad_alloc();
- }
-
- [self setNotifications];
-
- if ([NSApp mainMenu] == nil) {
- [self makeMenuBar];
- }
- }
- }
-
- return self;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Clean the controller
-////////////////////////////////////////////////////////////
-- (void)dealloc
-{
- [[NSNotificationCenter defaultCenter] removeObserver:self];
- [myMainPool release];
- [super dealloc];
-}
-
-
-////////////////////////////////////////////////////////////
-/// Return the shared AppController instance. Make one if needed.
-////////////////////////////////////////////////////////////
-+ (sfPrivAppController *)sharedController
-{
- // AppController singleton object
- static sfPrivAppController *shared = [[sfPrivAppController alloc] init];
- return shared;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Returns the primay computer's screen
-////////////////////////////////////////////////////////////
-+ (CGDirectDisplayID)primaryScreen
-{
- static BOOL firstTime = YES;
- static CGDirectDisplayID screen = kCGNullDirectDisplay;
-
- if (firstTime) {
- CGDisplayCount numScr;
- CGDisplayErr err = CGGetDisplaysWithPoint(CGPointMake(0, 0), 1, &screen, &numScr);
-
- if (err != kCGErrorSuccess || numScr < 1) {
- std::cerr << "Unable to get primary screen (error code " << err
- << " ). Using the main screen.";
- screen = CGMainDisplayID();
- }
- firstTime = NO;
- }
-
- return screen;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Reset notifictions about application focus
-////////////////////////////////////////////////////////////
-- (void)setNotifications
-{
- NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
- [nc addObserver:self
- selector:@selector(applicationWillDeactivate:)
- name:NSApplicationWillResignActiveNotification
- object:NSApp];
- [nc addObserver:self
- selector:@selector(applicationWillActivate:)
- name:NSApplicationWillBecomeActiveNotification
- object:NSApp];
-
- [nc addObserver:self
- selector:@selector(applicationWillTerminate:)
- name:NSApplicationWillTerminateNotification
- object:NSApp];
-}
-
-
-////////////////////////////////////////////////////////////
-/// Hide all the fullscreen windows and switch back to the desktop display mode
-////////////////////////////////////////////////////////////
-- (void)applicationWillDeactivate:(NSNotification *)aNotification
-{
- // Note: not using fading because it produces reactivation issues
- if (myFullscreenWrapper) {
- myPrevMode = sf::VideoMode::GetDesktopMode();
-
- CFDictionaryRef displayMode = CGDisplayBestModeForParameters ([sfPrivAppController primaryScreen],
- myDesktopMode.BitsPerPixel,
- myDesktopMode.Width,
- myDesktopMode.Height,
- NULL);
-
- // Make the full screen window unvisible
- [[myFullscreenWrapper window] setAlphaValue:0.0f];
-
- // Switch to the wished display mode
- CGDisplaySwitchToMode([sfPrivAppController primaryScreen], displayMode);
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Unhide all the fullscreen windows and switch to full screen display mode
-////////////////////////////////////////////////////////////
-- (void)applicationWillActivate:(NSNotification *)aNotification
-{
- if (myFullscreenWrapper) {
- CFDictionaryRef displayMode = CGDisplayBestModeForParameters ([sfPrivAppController primaryScreen],
- myPrevMode.BitsPerPixel,
- myPrevMode.Width,
- myPrevMode.Height,
- NULL);
- [NSMenu setMenuBarVisible:NO];
-
- // Switch to the wished display mode
- CGDisplaySwitchToMode([sfPrivAppController primaryScreen], displayMode);
-
- // Show the fullscreen window if existing
- if (myFullscreenWrapper)
- {
- [[myFullscreenWrapper window] setAlphaValue:1.0f];
- [[myFullscreenWrapper window] center];
- [[myFullscreenWrapper window] makeKeyAndOrderFront:self];
- }
- }
-}
-
-
-- (void)applicationWillTerminate:(NSNotification *)aNotification
-{
- if (myFullscreenWrapper)
- [self setFullscreenWindow:nil mode:NULL];
-}
-
-////////////////////////////////////////////////////////////
-/// Make menu bar
-////////////////////////////////////////////////////////////
-- (void)makeMenuBar
-{
- // Source taken from SDL 1.3
- NSString *appName = nil;
- NSString *title = nil;
- NSMenu *appleMenu = nil;
- NSMenu *fileMenu = nil;
- NSMenu *windowMenu = nil;
- NSMenuItem *menuItem = nil;
- NSMenuItem *quitMenuItem = nil;
-
- // Determine the application name
- appName = [[[NSBundle mainBundle] infoDictionary] objectForKey: @"CFBundleName"];
-
- if (![appName length])
- appName = [[NSProcessInfo processInfo] processName];
-
-
- // Create the main menu bar
- [NSApp setMainMenu:[[NSMenu alloc] init]];
-
- // Create the application menu
- appleMenu = [[NSMenu alloc] initWithTitle:@""];
-
- // Put menu items
- // + 'About' menu item
- title = [@"About " stringByAppendingString:appName];
- [appleMenu addItemWithTitle:title
- action:@selector(orderFrontStandardAboutPanel:)
- keyEquivalent:@""];
-
- [appleMenu addItem:[NSMenuItem separatorItem]];
-
- // + 'Hide' menu item
- title = [@"Hide " stringByAppendingString:appName];
- [appleMenu addItemWithTitle:title
- action:@selector(hide:)
- keyEquivalent:@"h"];
-
- // + 'Hide other' menu item
- menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others"
- action:@selector(hideOtherApplications:)
- keyEquivalent:@"h"];
- [menuItem setKeyEquivalentModifierMask:NSAlternateKeyMask | NSCommandKeyMask];
-
- // + 'Show all' menu item
- [appleMenu addItemWithTitle:@"Show All"
- action:@selector(unhideAllApplications:)
- keyEquivalent:@""];
-
- [appleMenu addItem:[NSMenuItem separatorItem]];
-
- // + 'Quit' menu item
- title = [@"Quit " stringByAppendingString:appName];
- quitMenuItem = [[[NSMenuItem alloc]
- initWithTitle:title
- action:@selector(terminate:)
- keyEquivalent:@"q"] autorelease];
- //[quitMenuItem setTarget:self];
- [appleMenu addItem:quitMenuItem];
-
- // Put the menu into the menubar
- menuItem = [[NSMenuItem alloc]
- initWithTitle:@""
- action:nil
- keyEquivalent:@""];
- [menuItem setSubmenu:appleMenu];
- [[NSApp mainMenu] addItem:menuItem];
- [menuItem release];
-
- // Tell the application object that this is now the application menu
- [NSApp setAppleMenu:appleMenu];
- [appleMenu release];
-
- // 'File' menu
- fileMenu = [[NSMenu alloc]
- initWithTitle:@"File"];
-
- // + 'Close' menu item
- menuItem = [[NSMenuItem alloc]
- initWithTitle:@"Close"
- action:@selector(performClose:)
- keyEquivalent:@"w"];
- [fileMenu addItem:menuItem];
- [menuItem release];
-
- // + 'File' menu item (head)
- menuItem = [[NSMenuItem alloc]
- initWithTitle:@"File"
- action:nil
- keyEquivalent:@""];
- [menuItem setSubmenu:fileMenu];
- [[NSApp mainMenu] addItem:menuItem];
- [menuItem release];
-
- // 'Window' menu
- windowMenu = [[NSMenu alloc]
- initWithTitle:@"Window"];
-
- // + 'Minimize' menu item
- menuItem = [[NSMenuItem alloc]
- initWithTitle:@"Minimize"
- action:@selector(performMiniaturize:)
- keyEquivalent:@"m"];
- [windowMenu addItem:menuItem];
- [menuItem release];
-
- // + 'Window' menu item (head)
- menuItem = [[NSMenuItem alloc]
- initWithTitle:@"Window"
- action:nil keyEquivalent:@""];
- [menuItem setSubmenu:windowMenu];
- [[NSApp mainMenu] addItem:menuItem];
- [menuItem release];
-
- // Tell the application object that this is now the window menu
- [NSApp setWindowsMenu:windowMenu];
- [windowMenu release];
-}
-
-
-////////////////////////////////////////////////////////////
-/// Process all the events and send them to the application
-/// No event is processed if the AppController instance is
-/// not the owner of the event loop (ie: user made his own loop)
-////////////////////////////////////////////////////////////
-- (void)processEvents
-{
- // Check there is a run loop
- if (![NSApp isRunning])
- {
- // Get the ownershipt of event handling if not and run
- [NSApp finishLaunching];
- [NSApp setRunning:YES];
- myOwningEventLoop = YES;
- }
-
- NSEvent *event = nil;
-
- if (myOwningEventLoop)
- {
- // Clean the autorelease pool
- [myMainPool release];
- myMainPool = [[NSAutoreleasePool alloc] init];
-
- // Minimal event loop
- while (nil != (event = [NSApp nextEventMatchingMask:NSAnyEventMask
- untilDate:nil
- inMode:NSDefaultRunLoopMode
- dequeue:YES]))
- {
- [NSApp sendEvent:event];
- }
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Set @window as the current fullscreen window
-/// Change the screen resolution if needed according to @window and @fullscreenMode
-////////////////////////////////////////////////////////////
-- (void)setFullscreenWindow:(sfPrivWindow *)aWindow mode:(sf::VideoMode *)fullscreenMode
-{
- // If we have a fullscreen window and want to remove it
- if (aWindow == nil && myFullscreenWrapper)
- {
- // Get the CoreGraphics display mode according to the desktop mode
- CFDictionaryRef displayMode = CGDisplayBestModeForParameters ([sfPrivAppController primaryScreen],
- myDesktopMode.BitsPerPixel,
- myDesktopMode.Width,
- myDesktopMode.Height,
- NULL);
-
-#if ENABLE_FADE_OPERATIONS
- // Fade to black screen
- [self doFadeOperation:FillScreen time:0.2f sync:true];
-#endif
-
- // Switch to the desktop display mode
- CGDisplaySwitchToMode([sfPrivAppController primaryScreen], displayMode);
-
- // Close the window
- [[myFullscreenWrapper window] close];
-
- // Show the menu bar
- [NSMenu setMenuBarVisible:YES];
-
-#if ENABLE_FADE_OPERATIONS
- // Fade to normal screen
- [self doFadeOperation:CleanScreen time:0.5f sync:true];
-#endif
-
- // Release the saved window wrapper
- myFullscreenWrapper = nil;
- }
- else if (aWindow)
- {
- // else if we want to SET fullscreen
- assert(fullscreenMode != NULL);
-
- // Get the CoreGraphics display mode according to the given sf mode
- CFDictionaryRef displayMode = CGDisplayBestModeForParameters ([sfPrivAppController primaryScreen],
- fullscreenMode->BitsPerPixel,
- fullscreenMode->Width,
- fullscreenMode->Height,
- NULL);
-
-#if ENABLE_FADE_OPERATIONS
- // Fade to a black screen
- [self doFadeOperation:FillScreen time:0.5f sync:true];
-#endif
-
- if (!myFullscreenWrapper)
- {
- // Hide the main menu bar
- [NSMenu setMenuBarVisible:NO];
- }
-
- if (myPrevMode != *fullscreenMode)
- {
- // Switch to the wished display mode
- myPrevMode = *fullscreenMode;
- CGDisplaySwitchToMode([sfPrivAppController primaryScreen], displayMode);
- }
-
- if (myFullscreenWrapper)
- {
- [[myFullscreenWrapper window] close];
- }
-
- // Open and center the window
- [[aWindow window] makeKeyAndOrderFront:nil];
- [[aWindow window] center];
-
-#if ENABLE_FADE_OPERATIONS
- // Fade to normal screen
- [self doFadeOperation:CleanScreen time:0.2f sync:false];
-#endif
-
- // Save the fullscreen wrapper
- myFullscreenWrapper = aWindow;
- }
- else
- {
- std::cerr << "Inconcistency error for arguments given to -[sfPrivAppController setFullscreenWindow:mode:]" << std::endl;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Perform fade operation where 'operation' is one of {FillScreen, CleanScreen}
-/// and 'time' is the time during which you wish the operation to be performed.
-/// Set 'sync' to true if you do not want the method to end before the end
-/// of the fade operation. Pass the last used token or a new one if you are
-/// using this method for the first time. This lets the method release some
-/// resources when doing CleanScreen operation.
-////////////////////////////////////////////////////////////
-- (void) doFadeOperation:(int)operation time:(float)time sync:(bool)sync
-{
- static CGDisplayFadeReservationToken prevToken = kCGDisplayFadeReservationInvalidToken;
- CGDisplayFadeReservationToken token = prevToken;
-
- CGError result = 0, capture = 0;
-
- if (operation == FillScreen) {
- // Get access for the fade operation
- result = CGAcquireDisplayFadeReservation((int)(3 + time), &token);
-
- if (!result) {
- // Capture display but do not fill the screen with black
- // so that we can see the fade operation
- capture = CGDisplayCaptureWithOptions([sfPrivAppController primaryScreen], kCGCaptureNoFill);
-
- if (!capture) {
- // Do the increasing fade operation
- CGDisplayFade(token, time,
- kCGDisplayBlendNormal,
- kCGDisplayBlendSolidColor,
- 0.0f, 0.0f, 0.0f, sync);
-
- // Now, release the non black-filling capture
- CGDisplayRelease([sfPrivAppController primaryScreen]);
-
- // And capture with filling
- // so that we don't see the switching in the meantime
- CGDisplayCaptureWithOptions([sfPrivAppController primaryScreen], kCGCaptureNoOptions);
- }
-
- prevToken = token;
- }
- } else if (operation == CleanScreen) {
- // Get access for the fade operation
- if (token == kCGDisplayFadeReservationInvalidToken)
- result = CGAcquireDisplayFadeReservation((int)(3 + time), &token);
-
- if (!result) {
- if (!capture) {
- // Release the black-filling capture
- CGDisplayRelease([sfPrivAppController primaryScreen]);
-
- // Capture the display but do not fill with black (still for the fade operation)
- CGDisplayCaptureWithOptions([sfPrivAppController primaryScreen], kCGCaptureNoFill);
-
- // Do the decreasing fading
- CGDisplayFade(token, time,
- kCGDisplayBlendSolidColor,
- kCGDisplayBlendNormal,
- 0.0f, 0.0f, 0.0f, sync);
-
- // Release the fade operation token
- CGReleaseDisplayFadeReservation(token);
-
- // Invalidate the given token
- prevToken = kCGDisplayFadeReservationInvalidToken;
- }
-
- // Release the captured display
- CGDisplayRelease([sfPrivAppController primaryScreen]);
- }
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Return the desktop video mode (made at the instance initialization)
-////////////////////////////////////////////////////////////
-- (const sf::VideoMode&)desktopMode
-{
- return myDesktopMode;
-}
-
-@end
-
diff --git a/src/SFML/Window/Cocoa/GLKit.h b/src/SFML/Window/Cocoa/GLKit.h
deleted file mode 100755
index f4cff4a..0000000
--- a/src/SFML/Window/Cocoa/GLKit.h
+++ /dev/null
@@ -1,233 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Lucas Soltic (ceylow@gmail.com) and Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#import <Cocoa/Cocoa.h>
-#import <SFML/Window/Cocoa/WindowImplCocoa.hpp>
-
-
-////////////////////////////////////////////////////////////
-/// Window independant OpenGL context class
-////////////////////////////////////////////////////////////
-@interface sfPrivGLContext : NSOpenGLContext
-
-////////////////////////////////////////////////////////////
-/// Return the shared OpenGL context instance (making one if needed)
-////////////////////////////////////////////////////////////
-+ (id)sharedContext;
-
-////////////////////////////////////////////////////////////
-/// Make a new OpenGL context according to the @attribs settings
-/// and the shared context @context
-////////////////////////////////////////////////////////////
-- (id)initWithAttributes:(sf::WindowSettings&)attribs
- mode:(const sf::VideoMode&)mode
- sharedContext:(sfPrivGLContext *)context;
-
-@end
-
-
-////////////////////////////////////////////////////////////
-/// Customized Cocoa OpenGL view
-////////////////////////////////////////////////////////////
-@interface sfPrivGLView : NSOpenGLView
-{
- sf::priv::WindowImplCocoa *myDelegate;
- sfPrivGLContext *myGLContext;
-}
-
-////////////////////////////////////////////////////////////
-/// Make a new view according the the rect @frame,
-/// the video mode @mode, the window settings @settings
-/// @delegate must not be null
-////////////////////////////////////////////////////////////
-- (id)initWithFrame:(NSRect)frame
- mode:(const sf::VideoMode&)mode
- settings:(sf::WindowSettings&)settings;
-
-
-////////////////////////////////////////////////////////////
-/// Sets @aDelegate as the view delegate
-////////////////////////////////////////////////////////////
-- (void)setDelegate:(sf::priv::WindowImplCocoa *)aDelegate;
-
-////////////////////////////////////////////////////////////
-/// Returns the view delegate
-////////////////////////////////////////////////////////////
-- (sf::priv::WindowImplCocoa *)delegate;
-
-////////////////////////////////////////////////////////////
-/// Finish view setting (after having added it to the window)
-////////////////////////////////////////////////////////////
-- (void)finishInitialization;
-
-////////////////////////////////////////////////////////////
-/// Forward call to en/disable vertical synchronization
-////////////////////////////////////////////////////////////
-- (void)enableVerticalSync:(bool)flag;
-
-////////////////////////////////////////////////////////////
-/// Forward call to set the OpenGL context as active according to @flag
-////////////////////////////////////////////////////////////
-- (void)setActive:(bool)flag;
-
-////////////////////////////////////////////////////////////
-/// Forward call to flush the OpenGL context
-////////////////////////////////////////////////////////////
-- (void)flushBuffer;
-
-@end
-
-////////////////////////////////////////////////////////////
-/// Parent class for handling general SFML window stuff
-////////////////////////////////////////////////////////////
-@interface sfPrivWindow : NSObject
-{
-@private
- NSWindow *myWindow;
- sfPrivGLView *myView;
-}
-
-////////////////////////////////////////////////////////////
-/// Return a reference to the internal Cocoa window
-////////////////////////////////////////////////////////////
-- (NSWindow *)window;
-
-////////////////////////////////////////////////////////////
-/// Return a reference to the internal Cocoa OpenGL view
-////////////////////////////////////////////////////////////
-- (sfPrivGLView *)view;
-
-////////////////////////////////////////////////////////////
-/// Sets @aDelegate as the window delegate
-////////////////////////////////////////////////////////////
-- (void)setDelegate:(sf::priv::WindowImplCocoa *)aDelegate;
-
-////////////////////////////////////////////////////////////
-/// Returns the window delegate
-////////////////////////////////////////////////////////////
-- (sf::priv::WindowImplCocoa *)delegate;
-
-////////////////////////////////////////////////////////////
-/// Forward call to set the window position on screen
-////////////////////////////////////////////////////////////
-- (void)setPosition:(NSPoint)pos;
-
-////////////////////////////////////////////////////////////
-/// Forward call to set the window size
-////////////////////////////////////////////////////////////
-- (void)setSize:(NSSize)size;
-
-////////////////////////////////////////////////////////////
-/// Return the mouse location relative to the internal window
-////////////////////////////////////////////////////////////
-- (NSPoint)mouseLocation;
-
-////////////////////////////////////////////////////////////
-/// Return whether the mouse is on our window
-////////////////////////////////////////////////////////////
-- (BOOL)mouseInside;
-
-////////////////////////////////////////////////////////////
-/// Close or open the window
-////////////////////////////////////////////////////////////
-- (void)show:(bool)flag;
-
-////////////////////////////////////////////////////////////
-/// Forward call to en/disable the OpenGL view vertical synchronization
-////////////////////////////////////////////////////////////
-- (void)enableVerticalSync:(bool)flag;
-
-////////////////////////////////////////////////////////////
-/// Forward 'setActive' call the the OpenGL view
-////////////////////////////////////////////////////////////
-- (void)setActive:(bool)flag;
-
-////////////////////////////////////////////////////////////
-/// Forward call to flush the OpenGL view
-////////////////////////////////////////////////////////////
-- (void)flushBuffer;
-
-@end
-
-////////////////////////////////////////////////////////////
-/// Class for creating new SFML windows from informations
-////////////////////////////////////////////////////////////
-@interface sfPrivOwnedWindow : sfPrivWindow
-{
-@private
- sf::VideoMode myFullscreenMode;
- bool myIsFullscreen;
-}
-
-////////////////////////////////////////////////////////////
-/// Creates and returns a new SFML window handler with
-/// the given parameters
-////////////////////////////////////////////////////////////
-- (id)initWithVideoMode:(sf::VideoMode&)aMode
- settings:(sf::WindowSettings&)someSettings
- style:(unsigned long)aStyle
- title:(NSString *)aTitle;
-
-////////////////////////////////////////////////////////////
-/// Returns the window's fullscreen state
-////////////////////////////////////////////////////////////
-- (BOOL)isFullscreen;
-
-@end
-
-
-////////////////////////////////////////////////////////////
-/// Class for creating SFML windows from Cocoa windows
-////////////////////////////////////////////////////////////
-@interface sfPrivImportedWindow : sfPrivWindow
-
-////////////////////////////////////////////////////////////
-/// Returns a new SFML window handler with the given window
-/// and parameters
-////////////////////////////////////////////////////////////
-- (id)initWithWindow:(NSWindow *)aWindow
- settings:(sf::WindowSettings&)someSettings;
-
-@end
-
-
-////////////////////////////////////////////////////////////
-/// Class for creating SFML windows from Cocoa views
-////////////////////////////////////////////////////////////
-@interface sfPrivImportedView : sfPrivWindow
-{
- NSView *parentView;
-}
-
-////////////////////////////////////////////////////////////
-/// Returns a new SFML window handler with the given view
-/// and parameters
-////////////////////////////////////////////////////////////
-- (id)initWithView:(NSView *)aView
- settings:(sf::WindowSettings&)someSettings;
-
-@end
diff --git a/src/SFML/Window/Cocoa/GLKit.mm b/src/SFML/Window/Cocoa/GLKit.mm
deleted file mode 100755
index f19fa77..0000000
--- a/src/SFML/Window/Cocoa/GLKit.mm
+++ /dev/null
@@ -1,1124 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Lucas Soltic (ceylow@gmail.com) and Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#import <SFML/Window/Cocoa/GLKit.h>
-#import <SFML/Window/Cocoa/AppController.h>
-#import <SFML/Window/VideoMode.hpp>
-#import <SFML/Window/WindowStyle.hpp>
-#import <OpenGL/gl.h>
-#import <iostream>
-
-
-@interface sfPrivWindow (Protected)
-
-////////////////////////////////////////////////////////////
-/// Registers a reference to the internal Cocoa window
-////////////////////////////////////////////////////////////
-- (void)setWindow:(NSWindow *)aWindow;
-
-////////////////////////////////////////////////////////////
-/// Registers the the OpenGL view and adds it to its parent container
-////////////////////////////////////////////////////////////
-- (void)putOpenGLView:(sfPrivGLView *)aView;
-
-////////////////////////////////////////////////////////////
-/// Registers a reference to the internal Cocoa OpenGL view
-////////////////////////////////////////////////////////////
-- (void)setView:(sfPrivGLView *)aView;
-
-@end
-
-@interface sfPrivOwnedWindow (Private)
-
-////////////////////////////////////////////////////////////
-/// Sets the window's fullscreen state
-////////////////////////////////////////////////////////////
-- (void)setFullscreen:(BOOL)aFlag;
-
-@end
-
-
-////////////////////////////////////////////////////////////
-/// Window independant OpenGL context class
-////////////////////////////////////////////////////////////
-@implementation sfPrivGLContext
-
-
-////////////////////////////////////////////////////////////
-/// Return the shared OpenGL context instance (making one if needed)
-////////////////////////////////////////////////////////////
-+ (id)sharedContext
-{
- // Make a new context with the default parameters
- sf::WindowSettings params;
- sf::VideoMode m;
- static sfPrivGLContext *sharedCtx = [[sfPrivGLContext alloc] initWithAttributes:params
- mode:m
- sharedContext:nil];
- return sharedCtx;
-}
-
-- (void)dealloc
-{
- [[sfPrivGLContext sharedContext] release];
- [super dealloc];
-}
-
-////////////////////////////////////////////////////////////
-/// Make a new OpenGL context according to the @attribs settings
-/// and the shared context @context
-////////////////////////////////////////////////////////////
-- (id)initWithAttributes:(sf::WindowSettings&)attribs mode:(const sf::VideoMode&)mode sharedContext:(sfPrivGLContext *)sharedContext
-{
- // Note about antialiasing and other context attributes :
- // OpenGL context sharing does not allow the shared contexts to use different attributes.
- // The point is that the default shared global OpenGL context uses default parameters.
- // That means that all the other context *should* use the same paramaters.
- // Fortunately some values parameters for some parameters are compatible, but some are not
- // among which : the antialising level.
- //
- // I've no way to fix this for now.
-
- if (attribs.AntialiasingLevel) {
- NSLog(@"Warning: antialiasing settings are inhibited on Mac OS X for technical reasons");
- }
-
- if (attribs.StencilBits != 8) {
- NSLog(@"Warning: stencil bits settings are inhibited on Mac OS X for technical reasons");
- }
-
- NSOpenGLPixelFormat *myPixelFormat = nil;
- unsigned idx = 0;
-
- // Attributes list
- NSOpenGLPixelFormatAttribute ctxtAttribs[15] = {(NSOpenGLPixelFormatAttribute) 0};
-
- // Accelerated, double buffered
- ctxtAttribs[idx++] = NSOpenGLPFAClosestPolicy;
- ctxtAttribs[idx++] = NSOpenGLPFADoubleBuffer;
- ctxtAttribs[idx++] = NSOpenGLPFAAccelerated;
-
- // Force use of first screen
- //ctxtAttribs[idx++] = NSOpenGLPFAScreenMask;
- //ctxtAttribs[idx++] = CGDisplayIDToOpenGLDisplayMask([sfPrivAppController primaryScreen]);
-
- // windowed context (even fullscreen mode uses a window)
- ctxtAttribs[idx++] = NSOpenGLPFAWindow;
-
- // Color buffer bits ; usually 32 bits per pixel
- ctxtAttribs[idx++] = NSOpenGLPFAColorSize;
-
- // well.. whatever I put here, the color size is always 24 bits on my computer..
- ctxtAttribs[idx++] = (NSOpenGLPixelFormatAttribute) mode.BitsPerPixel;
-
- // Alpha buffer size
- // FIXME: I don't really remember whether I can safely use the user video mode settings
- // to set this attribute (because of the shared context attributes conflicts)
- if (mode.BitsPerPixel > 24) {
- ctxtAttribs[idx++] = NSOpenGLPFAAlphaSize;
- ctxtAttribs[idx++] = (NSOpenGLPixelFormatAttribute) 8;
- }
-
- // Depth buffer size
- ctxtAttribs[idx++] = NSOpenGLPFADepthSize;
- ctxtAttribs[idx++] = (NSOpenGLPixelFormatAttribute) attribs.DepthBits;
-
- // Stencil buffer bits
- // Note: even with "NSOpenGLPFAClosestPolicy" set, the NSOpenGLPFAStencilSize value must be an valid and exact one
- // I've been looking for possible diffferent default stencil bits values among different Apple computers
- // but I can't again get the website I found oneaday
- // (describing all the graphic cards used by Apple, the supported extensions, etc).
- ctxtAttribs[idx++] = NSOpenGLPFAStencilSize;
- ctxtAttribs[idx++] = (NSOpenGLPixelFormatAttribute) /* attribs.StencilBits */ 8;
-
- myPixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:ctxtAttribs];
-
- if (myPixelFormat) {
- self = [super initWithFormat:myPixelFormat
- shareContext:[sharedContext retain]];
-
- // Get the effective properties from our OpenGL context
- GLint tmpDepthSize = 0, tmpStencilBits = 0, tmpAntialiasingLevel = 0;
-
- if (self) {
- [myPixelFormat getValues:&tmpDepthSize
- forAttribute:NSOpenGLPFADepthSize
- forVirtualScreen:[self currentVirtualScreen]];
-
- [myPixelFormat getValues:&tmpStencilBits
- forAttribute:NSOpenGLPFAStencilSize
- forVirtualScreen:[self currentVirtualScreen]];
-
- [myPixelFormat getValues:&tmpAntialiasingLevel
- forAttribute:NSOpenGLPFASamples
- forVirtualScreen:[self currentVirtualScreen]];
- }
-
-
- attribs.DepthBits = (unsigned) tmpDepthSize;
- attribs.StencilBits = (unsigned) tmpStencilBits;
- attribs.AntialiasingLevel = (unsigned) tmpAntialiasingLevel;
-
- [myPixelFormat release];
- } else {
- NSLog(@"NSOpenGLPixelFormat creation failed! (invalid video settings ?)");
- }
-
- return self;
-}
-
-@end
-
-
-////////////////////////////////////////////////////////////
-/// Customized Cocoa OpenGL view
-////////////////////////////////////////////////////////////
-@implementation sfPrivGLView
-
-////////////////////////////////////////////////////////////
-/// Make a new view according the the rect @frame,
-/// the video mode @mode, the window settings @settings
-/// and the sf window delegate @delegate
-/// @delegate must not be null
-////////////////////////////////////////////////////////////
-- (id)initWithFrame:(NSRect)frame
- mode:(const sf::VideoMode&)mode
- settings:(sf::WindowSettings&)settings
-{
- // make the view
- self = [super initWithFrame:frame pixelFormat:nil];
-
- if (self)
- {
- // enabled auto-resizing
- [self setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
-
- // make the OpenGL context
- myGLContext = [[sfPrivGLContext alloc] initWithAttributes:settings
- mode:mode
- sharedContext:[sfPrivGLContext sharedContext]];
-
- if (!myGLContext) {
- [self release];
- return nil;
- }
-
- // We need to update the OpenGL view when it's resized
- NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
- [nc addObserver:self
- selector:@selector(viewFrameDidChange:)
- name:NSViewFrameDidChangeNotification
- object:self];
- }
-
- return self;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Clean the instance
-////////////////////////////////////////////////////////////
-- (void)dealloc
-{
- // Remove the observer and release the OpenGL context
- [[NSNotificationCenter defaultCenter] removeObserver:self];
- [myGLContext release];
-
- [super dealloc];
-}
-
-////////////////////////////////////////////////////////////
-/// Sets @aDelegate as the view delegate
-////////////////////////////////////////////////////////////
-- (void)setDelegate:(sf::priv::WindowImplCocoa *)aDelegate
-{
- myDelegate = aDelegate;
-}
-
-////////////////////////////////////////////////////////////
-/// Returns the view delegate
-////////////////////////////////////////////////////////////
-- (sf::priv::WindowImplCocoa *)delegate
-{
- return myDelegate;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Finish view setting (after having added it to the window)
-////////////////////////////////////////////////////////////
-- (void)finishInitialization
-{
- assert([self superview] != nil);
- assert(myGLContext != nil);
-
- // Attach the OpenGL context to our view
- [self clearGLContext];
- [self setOpenGLContext:myGLContext];
- [myGLContext setView:self];
-
- // Make our view the first responder
- [[self window] makeFirstResponder:self];
-}
-
-
-////////////////////////////////////////////////////////////
-/// Forward call to en/disable vertical synchronization
-////////////////////////////////////////////////////////////
-- (void)enableVerticalSync:(bool)flag
-{
- GLint enable = (flag) ? 1 : 0;
- [[self openGLContext] setValues:&enable forParameter:NSOpenGLCPSwapInterval];
-}
-
-
-////////////////////////////////////////////////////////////
-/// Forward call to set the OpenGL context as active according to @flag
-////////////////////////////////////////////////////////////
-- (void)setActive:(bool)flag
-{
- if (flag) {
- if ([NSOpenGLContext currentContext] != [self openGLContext])
- [[self openGLContext] makeCurrentContext];
- } else {
- if ([NSOpenGLContext currentContext] == [self openGLContext])
- [NSOpenGLContext clearCurrentContext];
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Forward call to flush the OpenGL context
-////////////////////////////////////////////////////////////
-- (void)flushBuffer
-{
- [[self openGLContext] flushBuffer];
-}
-
-
-////////////////////////////////////////////////////////////
-/// Send event to the linked window
-////////////////////////////////////////////////////////////
-- (void)pushEvent:(sf::Event)sfEvent
-{
- assert(myDelegate != NULL);
- myDelegate->HandleNotifiedEvent(sfEvent);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Notification method receiver when OpenGL view size changes
-////////////////////////////////////////////////////////////
-- (void)viewFrameDidChange:(NSNotification *)notification
-{
- [self update];
-
- sf::Event ev;
- ev.Type = sf::Event::Resized;
- ev.Size.Width = (unsigned) [self frame].size.width;
- ev.Size.Height = (unsigned) [self frame].size.height;
-
- [self pushEvent:ev];
-}
-
-
-////////////////////////////////////////////////////////////
-/// Receiver method called when a key is pressed
-////////////////////////////////////////////////////////////
-- (void)keyDown:(NSEvent *)theEvent
-{
- assert(myDelegate != NULL);
-
- if (sf::priv::WindowImplCocoa::IsTextEvent((void *)theEvent))
- {
- NSText *field = [[self window] fieldEditor:YES forObject:nil];
- [field interpretKeyEvents:[NSArray arrayWithObject:theEvent]];
- [field setString:@""];
- }
-
- myDelegate->HandleKeyDown(theEvent);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Receiver method called when a key is released
-////////////////////////////////////////////////////////////
-- (void)keyUp:(NSEvent *)theEvent
-{
- assert(myDelegate != NULL);
- myDelegate->HandleKeyUp(theEvent);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Receiver method called when a modifier flag has changed
-////////////////////////////////////////////////////////////
-- (void)flagsChanged:(NSEvent *)theEvent
-{
- assert(myDelegate != NULL);
- myDelegate->HandleModifierKey(theEvent);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Receiver method called when the mouse wheel has been used
-////////////////////////////////////////////////////////////
-- (void)scrollWheel:(NSEvent *)theEvent
-{
- assert(myDelegate != NULL);
- myDelegate->HandleMouseWheel(theEvent);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Receiver method called when left mouse click is pressed
-////////////////////////////////////////////////////////////
-- (void)mouseDown:(NSEvent *)theEvent
-{
- assert(myDelegate != NULL);
- myDelegate->HandleMouseDown(theEvent);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Receiver method called when right mouse click is pressed
-////////////////////////////////////////////////////////////
-- (void)rightMouseDown:(NSEvent *)theEvent
-{
- assert(myDelegate != NULL);
- myDelegate->HandleMouseDown(theEvent);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Receiver method called when left mouse click is released
-////////////////////////////////////////////////////////////
-- (void)mouseUp:(NSEvent *)theEvent
-{
- assert(myDelegate != NULL);
- myDelegate->HandleMouseUp(theEvent);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Receiver method called when right mouse click is released
-////////////////////////////////////////////////////////////
-- (void)rightMouseUp:(NSEvent *)theEvent
-{
- assert(myDelegate != NULL);
- myDelegate->HandleMouseUp(theEvent);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Receiver method called when mouse moves
-////////////////////////////////////////////////////////////
-- (void)mouseMoved:(NSEvent *)theEvent
-{
- assert(myDelegate != NULL);
- myDelegate->HandleMouseMove(theEvent);
-}
-
-////////////////////////////////////////////////////////////
-/// Receiver method called when mouse is pressed (on left button) and moves
-////////////////////////////////////////////////////////////
-- (void)mouseDragged:(NSEvent *)theEvent
-{
- assert(myDelegate != NULL);
- myDelegate->HandleMouseMove(theEvent);
-}
-
-////////////////////////////////////////////////////////////
-/// Receiver method called when mouse is pressed (on right button) and moves
-////////////////////////////////////////////////////////////
-- (void)rightMouseDragged:(NSEvent *)theEvent
-{
- assert(myDelegate != NULL);
- myDelegate->HandleMouseMove(theEvent);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Tells that the view can be focused
-////////////////////////////////////////////////////////////
-- (BOOL)acceptsFirstResponder
-{
- return YES;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Tells that the view can become the key responder (ie. can catch key events)
-////////////////////////////////////////////////////////////
-- (BOOL)canBecomeKeyView
-{
- return YES;
-}
-
-@end
-
-
-////////////////////////////////////////////////////////////
-/// Cocoa window category to let fullscreen windows
-/// catch key events
-////////////////////////////////////////////////////////////
-@implementation NSWindow (GLWindow)
-
-- (BOOL)canBecomeKeyWindow
-{
- return YES;
-}
-
-- (BOOL)canBecomeMainWindow
-{
- return YES;
-}
-
-@end
-
-
-
-@implementation sfPrivWindow
-
-- (void)dealloc
-{
- NSAutoreleasePool *localPool = [[NSAutoreleasePool alloc] init];
- // Remove the notification observer
- [[NSNotificationCenter defaultCenter] removeObserver:self];
-
- // Close the window
- [self show:false];
-
- // Release the window and view
- [[self view] removeFromSuperviewWithoutNeedingDisplay];
-
- [self setWindow:nil];
- [self setView:nil];
- [self setDelegate:nil];
-
- [super dealloc];
- [localPool release];
-}
-
-////////////////////////////////////////////////////////////
-/// Registers a reference to the internal Cocoa window
-////////////////////////////////////////////////////////////
-- (void)setWindow:(NSWindow *)aWindow
-{
- if (myWindow != aWindow)
- {
- NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
-
- // Drop the observers on the previously set window
- if ([self window]) {
- [nc removeObserver:self
- name:NSWindowDidBecomeMainNotification
- object:[self window]];
- [nc removeObserver:self
- name:NSWindowDidResignMainNotification
- object:[self window]];
- [nc removeObserver:self
- name:NSWindowWillCloseNotification
- object:[self window]];
- }
-
- [myWindow release];
- myWindow = [aWindow retain];
-
- // Set the new observers
- // We want to know when our window got the focus
- [nc addObserver:self
- selector:@selector(windowDidBecomeMain:)
- name:NSWindowDidBecomeMainNotification
- object:[self window]];
-
- // We want to know when our window lost the focus
- [nc addObserver:self
- selector:@selector(windowDidResignMain:)
- name:NSWindowDidResignMainNotification
- object:[self window]];
-
- // We want to know when the user closes the window
- [nc addObserver:self
- selector:@selector(windowWillClose:)
- name:NSWindowWillCloseNotification
- object:[self window]];
-
- }
-}
-
-////////////////////////////////////////////////////////////
-/// Return a reference to the internal Cocoa window
-////////////////////////////////////////////////////////////
-- (NSWindow *)window
-{
- return [[myWindow retain] autorelease];
-}
-
-
-////////////////////////////////////////////////////////////
-/// Registers the the OpenGL view and adds it to its parent container
-////////////////////////////////////////////////////////////
-- (void)putOpenGLView:(sfPrivGLView *)aView
-{
- [self setView:aView];
-
- // Finish setting up the view and window
- // Add the view to our window and tell it to the view
- [[[self window] contentView] addSubview:[self view]];
- [[self view] finishInitialization];
-}
-
-////////////////////////////////////////////////////////////
-/// Registers a reference to the internal Cocoa OpenGL view
-////////////////////////////////////////////////////////////
-- (void)setView:(sfPrivGLView *)aView
-{
- if (myView != aView)
- {
- [myView release];
- myView = [aView retain];
- }
-}
-
-////////////////////////////////////////////////////////////
-/// Return a reference to the internal Cocoa OpenGL view
-////////////////////////////////////////////////////////////
-- (sfPrivGLView *)view
-{
- return [[myView retain] autorelease];
-}
-
-////////////////////////////////////////////////////////////
-/// Sets @aDelegate as the window delegate
-////////////////////////////////////////////////////////////
-- (void)setDelegate:(sf::priv::WindowImplCocoa *)aDelegate
-{
- [[self view] setDelegate:aDelegate];
-}
-
-////////////////////////////////////////////////////////////
-/// Returns the window delegate
-////////////////////////////////////////////////////////////
-- (sf::priv::WindowImplCocoa *)delegate
-{
- return [[self view] delegate];
-}
-
-////////////////////////////////////////////////////////////
-/// Forward call to set the window position on screen
-////////////////////////////////////////////////////////////
-- (void)setPosition:(NSPoint)pos
-{
- NSAssert([self window] != nil, @"expected valid window");
-
- // Flip Y and set window position
- pos.y = [[[self window] screen] frame].size.height - pos.y;
- [[self window] setFrameTopLeftPoint:pos];
-}
-
-////////////////////////////////////////////////////////////
-/// Forward call to set the window size
-////////////////////////////////////////////////////////////
-- (void)setSize:(NSSize)size
-{
- NSAssert([self window] != nil, @"expected valid window");
-
- [[self window] setFrame:NSMakeRect([[self window] frame].origin.x,
- [[self window] frame].origin.y,
- size.width, size.height)
- display:YES];
-}
-
-////////////////////////////////////////////////////////////
-/// Return the mouse location relative to the internal window
-////////////////////////////////////////////////////////////
-- (NSPoint)mouseLocation
-{
- NSAssert([self view] != nil, @"expected valid window");
-
- NSPoint windowPoint = [[self window] convertScreenToBase:[NSEvent mouseLocation]];
- NSPoint viewPoint = [[self view] convertPoint:windowPoint fromView:[[[self window] contentView] superview]];
-
- viewPoint.y = [[self view] frame].size.height - viewPoint.y;
- return viewPoint;
-}
-
-////////////////////////////////////////////////////////////
-/// Return whether the mouse is on our window
-////////////////////////////////////////////////////////////
-- (BOOL)mouseInside
-{
- NSAssert([self window] != nil, @"expected valid window");
- NSAssert([self view] != nil, @"expected valid OpenGL view");
-
- BOOL flag = NO;
-
- if ([[self window] isVisible]) {
- NSPoint relativeToWindow = [[self window] mouseLocationOutsideOfEventStream];
- NSPoint relativeToView = [[self view] convertPoint:relativeToWindow fromView:nil];
-
- if (NSPointInRect (relativeToView, [[self view] bounds]))
- {
- flag = YES;
- }
- }
-
- return flag;
-}
-
-////////////////////////////////////////////////////////////
-/// Close or open the window
-////////////////////////////////////////////////////////////
-- (void)show:(bool)flag
-{
- NSAssert([self window] != nil, @"expected valid window");
-
- if (flag && ![[self window] isVisible]) {
- // Wanna open the closed window
-
- // Show the window
- [[self window] makeKeyAndOrderFront:nil];
- } else if (!flag && [[self window] isVisible]) {
- // Wanna close the opened window
-
- // Close the window
- [[self window] close];
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Forward call to en/disable the OpenGL view vertical synchronization
-////////////////////////////////////////////////////////////
-- (void)enableVerticalSync:(bool)flag
-{
- NSAssert([self view] != nil, @"expected valid OpenGL view");
- [[self view] enableVerticalSync:flag];
-}
-
-////////////////////////////////////////////////////////////
-/// Forward 'setActive' call the the OpenGL view
-////////////////////////////////////////////////////////////
-- (void)setActive:(bool)flag
-{
- NSAssert([self view] != nil, @"expected valid OpenGL view");
- [[self view] setActive:flag];
-}
-
-////////////////////////////////////////////////////////////
-/// Forward call to flush the OpenGL view
-////////////////////////////////////////////////////////////
-- (void)flushBuffer
-{
- NSAssert([self view] != nil, @"expected valid OpenGL view");
- [[self view] flushBuffer];
-}
-
-////////////////////////////////////////////////////////////
-/// Notification method receiver when the window gains focus
-////////////////////////////////////////////////////////////
-- (void)windowDidBecomeMain:(NSNotification *)notification
-{
- sf::Event ev;
- ev.Type = sf::Event::GainedFocus;
-
- [[self view] pushEvent:ev];
-}
-
-
-////////////////////////////////////////////////////////////
-/// Notification method receiver when the window loses focus
-////////////////////////////////////////////////////////////
-- (void)windowDidResignMain:(NSNotification *)notification
-{
- sf::Event ev;
- ev.Type = sf::Event::LostFocus;
-
- [[self view] pushEvent:ev];
-}
-
-
-////////////////////////////////////////////////////////////
-/// Notification method receiver when the window closes
-////////////////////////////////////////////////////////////
-- (void)windowWillClose:(NSNotification *)notification
-{
- sf::Event ev;
- ev.Type = sf::Event::Closed;
-
- [[self view] pushEvent:ev];
-}
-
-
-@end
-
-
-@implementation sfPrivOwnedWindow
-
-- (id)initWithVideoMode:(sf::VideoMode&)aMode
- settings:(sf::WindowSettings&)someSettings
- style:(unsigned long)aStyle
- title:(NSString *)aTitle
-{
- self = [super init];
- if (self)
- {
- if (aStyle & sf::Style::Fullscreen) {
- [self setFullscreen:YES];
- }
-
- NSRect frame = NSMakeRect (0.0f, 0.0f, (float) aMode.Width, (float) aMode.Height);
- unsigned int mask = 0;
-
- if (aStyle & sf::Style::Fullscreen) {
- // Check display mode and put new values in 'mode' if needed
- boolean_t exact = true;
-
- CFDictionaryRef properties =
- CGDisplayBestModeForParameters([sfPrivAppController primaryScreen],
- aMode.BitsPerPixel,
- aMode.Width,
- aMode.Height,
- &exact);
-
- if (!properties) {
- std::cerr
- << "Unable to get a display mode with the given parameters"
- << std::endl;
-
- [self autorelease];
- return nil;
- }
-
- if (exact == false) {
- CFNumberGetValue((CFNumberRef) CFDictionaryGetValue(properties,
- kCGDisplayWidth),
- kCFNumberIntType, &aMode.Width);
-
- CFNumberGetValue((CFNumberRef) CFDictionaryGetValue(properties,
- kCGDisplayHeight),
- kCFNumberIntType, &aMode.Height);
-
- CFNumberGetValue((CFNumberRef) CFDictionaryGetValue(properties,
- kCGDisplayBitsPerPixel),
- kCFNumberIntType, &aMode.BitsPerPixel);
-
- }
- }
-
- // We grab options from WindowStyle and add them to our window mask
- if (aStyle & sf::Style::None || aStyle & sf::Style::Fullscreen) {
- mask |= NSBorderlessWindowMask;
- } else {
- if (aStyle & sf::Style::Titlebar) {
- mask |= NSTitledWindowMask;
- mask |= NSMiniaturizableWindowMask;
- }
-
- if (aStyle & sf::Style::Resize) {
- mask |= NSTitledWindowMask;
- mask |= NSMiniaturizableWindowMask;
- mask |= NSResizableWindowMask;
- }
-
- if (aStyle & sf::Style::Close) {
- mask |= NSTitledWindowMask;
- mask |= NSClosableWindowMask;
- mask |= NSMiniaturizableWindowMask;
- }
- }
-
- // Now we make the window with the values we got
- // Note: defer flag set to NO to be able to use OpenGL in our window
- NSWindow *newWindow = [[NSWindow alloc]
- initWithContentRect:frame
- styleMask:mask
- backing:NSBackingStoreBuffered
- defer:NO];
-
- if (newWindow) {
- [self setWindow:[newWindow autorelease]];
- } else {
- std::cerr << "Unable to create the Cocoa window" << std::endl;
- [self autorelease];
- return nil;
- }
-
- // We set title and window position
- [[self window] setTitle:aTitle != nil ? aTitle : @""];
- [[self window] center];
-
- // Make the OpenGL view
- sfPrivGLView *newView = [[sfPrivGLView alloc]
- initWithFrame:[[[self window] contentView] frame]
- mode:aMode
- settings:someSettings];
-
- if (!newView) {
- std::cerr << "Unable to create the OpenGL view" << std::endl;
- [self autorelease];
- return nil;
- }
-
- // Put our view in the window
- [self putOpenGLView:[newView autorelease]];
-
- // I want to re-center the window if it's a full screen one and moved by Spaces
- [[NSNotificationCenter defaultCenter]
- addObserver:self
- selector:@selector(windowDidMove:)
- name:NSWindowDidMoveNotification
- object:[self window]];
-
- // Needed not to make application crash when releasing the window in our destructor
- // (I prefer to take control of everything :P)
- [[self window] setReleasedWhenClosed:NO];
- [[self window] setAcceptsMouseMovedEvents:YES];
-
- if ([self isFullscreen]) {
- myFullscreenMode = aMode;
-
- // Using this because full screen window was not always
- // in front of the other application windows when unhiding app
- [[self window] setLevel:NSFloatingWindowLevel];
- }
- }
- return self;
-}
-
-- (void)dealloc
-{
- [[NSNotificationCenter defaultCenter]
- removeObserver:self
- name:NSWindowDidMoveNotification
- object:[self window]];
- [super dealloc];
-}
-
-////////////////////////////////////////////////////////////
-/// Sets the window's fullscreen state
-////////////////////////////////////////////////////////////
-- (void)setFullscreen:(BOOL)aFlag
-{
- myIsFullscreen = aFlag;
-}
-
-////////////////////////////////////////////////////////////
-/// Returns the window's fullscreen state
-////////////////////////////////////////////////////////////
-- (BOOL)isFullscreen
-{
- return myIsFullscreen;
-}
-
-////////////////////////////////////////////////////////////
-/// Notification method receiver when the window finish moving
-////////////////////////////////////////////////////////////
-- (void)windowDidMove:(NSNotification *)notification
-{
- NSWindow *sender = [notification object];
-
- if (myIsFullscreen)
- [sender center];
-}
-
-////////////////////////////////////////////////////////////
-/// Close or open the window
-////////////////////////////////////////////////////////////
-- (void)show:(bool)flag
-{
- NSAssert([self window] != nil, @"expected valid window");
-
- if (flag && ![[self window] isVisible]) {
- // Wanna open the closed window
-
- if ([self isFullscreen]) {
- [[sfPrivAppController sharedController]
- setFullscreenWindow:self
- mode:&myFullscreenMode];
- } else {
- // Show the window
- [[self window] makeKeyAndOrderFront:nil];
- }
- } else if (!flag && [[self window] isVisible]) {
- // Wanna close the opened window
-
- if ([self isFullscreen]) {
- [[sfPrivAppController sharedController]
- setFullscreenWindow:nil
- mode:NULL];
- } else {
- // Close the window
- [[self window] close];
- }
- }
-}
-
-////////////////////////////////////////////////////////////
-/// Forward call to set the window position on screen
-////////////////////////////////////////////////////////////
-- (void)setPosition:(NSPoint)aPosition
-{
- if (![self isFullscreen]) {
- [super setPosition:aPosition];
- }
-}
-
-////////////////////////////////////////////////////////////
-/// Forward call to set the window size
-////////////////////////////////////////////////////////////
-- (void)setSize:(NSSize)size
-{
- if (![self isFullscreen]) {
- [super setSize:size];
- }
-}
-
-@end
-
-
-@implementation sfPrivImportedWindow
-
-- (id)initWithWindow:(NSWindow *)aWindow
- settings:(sf::WindowSettings&)someSettings
-{
- self = [super init];
-
- if (self) {
- [self setWindow:aWindow];
-
- // Make the OpenGL view
- sf::VideoMode mode([[[self window] contentView] frame].size.width,
- [[[self window] contentView] frame].size.height);
- sfPrivGLView *newView = [[sfPrivGLView alloc]
- initWithFrame:[[[self window] contentView] frame]
- mode:mode
- settings:someSettings];
-
- if (!newView) {
- std::cerr << "Unable to create the OpenGL view" << std::endl;
- [self autorelease];
- return nil;
- }
-
- [self putOpenGLView:[newView autorelease]];
-
- [[self window] setAcceptsMouseMovedEvents:YES];
- }
-
- return self;
-}
-
-@end
-
-
-@implementation sfPrivImportedView
-
-
-- (id)initWithView:(NSView *)aView
- settings:(sf::WindowSettings&)someSettings
-{
- self = [super init];
- if (self)
- {
- parentView = [aView retain];
- [self setWindow:[parentView window]];
-
- // Make the OpenGL view
- sf::VideoMode mode([parentView bounds].size.width,
- [parentView bounds].size.height);
- sfPrivGLView *newView = [[sfPrivGLView alloc]
- initWithFrame:[parentView bounds]
- mode:mode
- settings:someSettings];
-
- if (!newView) {
- std::cerr << "Unable to create the OpenGL view" << std::endl;
- [self autorelease];
- return nil;
- }
-
- [self putOpenGLView:[newView autorelease]];
- [[self window] setAcceptsMouseMovedEvents:YES];
- }
- return self;
-}
-
-- (void)dealloc
-{
- [parentView release];
- [super dealloc];
-}
-
-////////////////////////////////////////////////////////////
-/// Registers the the OpenGL view and adds it to its parent container
-////////////////////////////////////////////////////////////
-- (void)putOpenGLView:(sfPrivGLView *)aView
-{
- [self setView:aView];
-
- // Finish setting up the view and window
- NSRect originalFrame = [[self window] frame];
- NSRect tmpFrame = originalFrame;
- originalFrame.origin.x++;
-
- [[self window] setFrame:tmpFrame display:YES];
- [[self window] setFrame:originalFrame display:YES];
-
-
- // Add the view to our *parent view* and tell it to the view
- [parentView addSubview:[self view]];
- [[self view] finishInitialization];
-}
-
-////////////////////////////////////////////////////////////
-/// Forward call to set the window position on screen
-////////////////////////////////////////////////////////////
-- (void)setPosition:(NSPoint)aPosition
-{
- std::cerr
- << "Warning: called Window::SetPosition() on a window imported from a widget. "
- << "This method has been disabled in this case and has no effect. "
- << "Directly use the widget if you want to move it."
- << std::endl;
-}
-
-////////////////////////////////////////////////////////////
-/// Forward call to set the window size
-////////////////////////////////////////////////////////////
-- (void)setSize:(NSSize)size
-{
- std::cerr
- << "Warning: called Window::SetSize() on a window imported from a widget. "
- << "This method has been disabled in this case and has no effect. "
- << "Directly use the widget if you want to resize it."
- << std::endl;
-}
-
-@end
-
diff --git a/src/SFML/Window/Cocoa/VideoModeSupport.cpp b/src/SFML/Window/Cocoa/VideoModeSupport.cpp
deleted file mode 100755
index 9b5ebd0..0000000
--- a/src/SFML/Window/Cocoa/VideoModeSupport.cpp
+++ /dev/null
@@ -1,101 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Window/Cocoa/VideoModeSupport.hpp>
-#include <ApplicationServices/ApplicationServices.h>
-#include <algorithm>
-
-namespace sf
-{
-namespace priv
-{
-////////////////////////////////////////////////////////////
-/// Get supported video modes
-////////////////////////////////////////////////////////////
-void VideoModeSupport::GetSupportedVideoModes(std::vector<VideoMode>& Modes)
-{
- // Ceylo -- using same implementation as in OSXCarbon
-
- // First, clear array to fill
- Modes.clear();
-
- // Enumerate all available video modes for primary display adapter
- CFArrayRef DisplayModes = CGDisplayAvailableModes( kCGDirectMainDisplay );
- CFIndex DisplayModeCount = CFArrayGetCount( DisplayModes );
- CFDictionaryRef CurrentMode;
-
- for (int Count = 0; Count < DisplayModeCount; ++Count)
- {
- CurrentMode = (CFDictionaryRef)CFArrayGetValueAtIndex( DisplayModes, Count );
-
- VideoMode Mode;
-
- CFNumberGetValue((CFNumberRef)CFDictionaryGetValue(CurrentMode, kCGDisplayWidth), kCFNumberIntType, &(Mode.Width));
- CFNumberGetValue((CFNumberRef)CFDictionaryGetValue(CurrentMode, kCGDisplayHeight), kCFNumberIntType, &(Mode.Height));
- CFNumberGetValue((CFNumberRef)CFDictionaryGetValue(CurrentMode, kCGDisplayBitsPerPixel), kCFNumberIntType, &(Mode.BitsPerPixel));
-
- // Add it only if it is not already in the array
- if (std::find(Modes.begin(), Modes.end(), Mode) == Modes.end())
- Modes.push_back(Mode);
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get current desktop video mode
-////////////////////////////////////////////////////////////
-VideoMode VideoModeSupport::GetDesktopVideoMode()
-{
- // Ceylo -- using same implementation as in OSXCarbon
-
- CFDictionaryRef CurrentVideoMode = CGDisplayCurrentMode(kCGDirectMainDisplay);
-
- VideoMode DesktopMode;
-
-
- // Get video mode width
- CFNumberGetValue((CFNumberRef)CFDictionaryGetValue(CurrentVideoMode, kCGDisplayWidth),
- kCFNumberIntType,
- &(DesktopMode.Width));
-
- // Get video mode height
- CFNumberGetValue((CFNumberRef)CFDictionaryGetValue(CurrentVideoMode, kCGDisplayHeight),
- kCFNumberIntType,
- &(DesktopMode.Height));
-
- // Get video mode depth
- CFNumberGetValue((CFNumberRef)CFDictionaryGetValue(CurrentVideoMode, kCGDisplayBitsPerPixel),
- kCFNumberIntType,
- &(DesktopMode.BitsPerPixel));
-
-
- return DesktopMode;
-}
-
-} // namespace priv
-
-} // namespace sf
diff --git a/src/SFML/Window/Cocoa/WindowImplCocoa.hpp b/src/SFML/Window/Cocoa/WindowImplCocoa.hpp
deleted file mode 100755
index 62158f0..0000000
--- a/src/SFML/Window/Cocoa/WindowImplCocoa.hpp
+++ /dev/null
@@ -1,205 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Lucas Soltic (ceylow@gmail.com) and Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-#ifndef SFML_WINDOWIMPLCOCOA_HPP
-#define SFML_WINDOWIMPLCOCOA_HPP
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Window/Event.hpp>
-#include <SFML/Window/WindowImpl.hpp>
-#include <string>
-
-#ifdef __OBJC__
-@class sfPrivWindow;
-typedef sfPrivWindow* sfPrivWindowRef;
-#else
-typedef void* sfPrivWindowRef;
-#endif
-
-namespace sf
-{
-namespace priv
-{
-
-////////////////////////////////////////////////////////////
-/// WindowImplCocoa is the Cocoa implementation of WindowImpl
-////////////////////////////////////////////////////////////
-class WindowImplCocoa : public WindowImpl
-{
-public :
-
- ////////////////////////////////////////////////////////////
- /// Default constructor
- /// (creates a dummy window to provide a valid OpenGL context)
- ///
- ////////////////////////////////////////////////////////////
- WindowImplCocoa();
-
- ////////////////////////////////////////////////////////////
- /// Construct the window implementation from an existing control
- ///
- /// \param Handle : Platform-specific handle of the control
- /// \param Params : Creation parameters
- ///
- /// Note: the NSWindow object must not be defered !
- ////////////////////////////////////////////////////////////
- WindowImplCocoa(WindowHandle Handle, WindowSettings& params);
-
- ////////////////////////////////////////////////////////////
- /// Create the window implementation
- ///
- /// \param Mode : Video mode to use
- /// \param Title : Title of the window
- /// \param WindowStyle : Window style
- /// \param Params : Creation parameters
- ///
- ////////////////////////////////////////////////////////////
- WindowImplCocoa(VideoMode Mode, const std::string& Title, unsigned long WindowStyle, WindowSettings& params);
-
- ////////////////////////////////////////////////////////////
- /// Destructor
- ///
- ////////////////////////////////////////////////////////////
- ~WindowImplCocoa();
-
- ////////////////////////////////////////////////////////////
- /// Check if there's an active context on the current thread
- ///
- /// \return True if there's a context bound to the current thread
- ///
- ////////////////////////////////////////////////////////////
- static bool IsContextActive();
-
- ////////////////////////////////////////////////////////////
- /// Handle an event sent by the default NSNotificationCenter
- ////////////////////////////////////////////////////////////
- void HandleNotifiedEvent(Event& eventRef);
-
- ////////////////////////////////////////////////////////////
- /// Event handling for every event type.
- /// 'eventRef' is a NSEvent.
- ////////////////////////////////////////////////////////////
- void HandleKeyDown(void *eventRef);
- void HandleKeyUp(void *eventRef);
- void HandleModifierKey(void *eventRef);
- void HandleMouseDown(void *eventRef);
- void HandleMouseUp(void *eventRef);
- void HandleMouseMove(void *eventRef);
- void HandleMouseWheel(void *eventRef);
-
- ////////////////////////////////////////////////////////////
- /// Return whether 'ev' must be considered as a TextEntered event
- ////////////////////////////////////////////////////////////
- static bool IsTextEvent(void *event);
-private :
-
- ////////////////////////////////////////////////////////////
- /// see WindowImpl::Display
- ///
- ////////////////////////////////////////////////////////////
- virtual void Display();
-
- ////////////////////////////////////////////////////////////
- /// see WindowImpl::ProcessEvents
- ///
- ////////////////////////////////////////////////////////////
- virtual void ProcessEvents();
-
- ////////////////////////////////////////////////////////////
- /// see WindowImpl::MakeActive
- ///
- ////////////////////////////////////////////////////////////
- virtual void SetActive(bool Active = true) const;
-
- ////////////////////////////////////////////////////////////
- /// see WindowImpl::UseVerticalSync
- ///
- ////////////////////////////////////////////////////////////
- virtual void UseVerticalSync(bool Enabled);
-
- ////////////////////////////////////////////////////////////
- /// see WindowImpl::ShowMouseCursor
- ///
- ////////////////////////////////////////////////////////////
- virtual void ShowMouseCursor(bool Show);
-
- ////////////////////////////////////////////////////////////
- /// see WindowImpl::SetCursorPosition
- ///
- ////////////////////////////////////////////////////////////
- virtual void SetCursorPosition(unsigned int Left, unsigned int Top);
-
- ////////////////////////////////////////////////////////////
- /// see WindowImpl::SetPosition
- ///
- ////////////////////////////////////////////////////////////
- virtual void SetPosition(int Left, int Top);
-
- ////////////////////////////////////////////////////////////
- /// /see WindowImpl::SetSize
- ///
- ////////////////////////////////////////////////////////////
- virtual void SetSize(unsigned int Width, unsigned int Height);
-
- ////////////////////////////////////////////////////////////
- /// see WindowImpl::Show
- ///
- ////////////////////////////////////////////////////////////
- virtual void Show(bool State);
-
- ////////////////////////////////////////////////////////////
- /// see WindowImpl::EnableKeyRepeat
- ///
- ////////////////////////////////////////////////////////////
- virtual void EnableKeyRepeat(bool Enabled);
-
- ////////////////////////////////////////////////////////////
- /// see WindowImpl::SetIcon
- ///
- ////////////////////////////////////////////////////////////
- virtual void SetIcon(unsigned int Width, unsigned int Height, const Uint8* Pixels);
-
-
-
- ////////////////////////////////////////////////////////////
- /// My own part starts here !
- ////////////////////////////////////////////////////////////
-
-
- ////////////////////////////////////////////////////////////
- // Member data
- ////////////////////////////////////////////////////////////
- sfPrivWindowRef myWrapper;
- bool myUseKeyRepeat;
- bool myMouseIn;
- float myWheelStatus;
-};
-
-} // namespace priv
-
-} // namespace sf
-
-#endif // SFML_WINDOWIMPLCOCOA_HPP
diff --git a/src/SFML/Window/Cocoa/WindowImplCocoa.mm b/src/SFML/Window/Cocoa/WindowImplCocoa.mm
deleted file mode 100755
index 13dec83..0000000
--- a/src/SFML/Window/Cocoa/WindowImplCocoa.mm
+++ /dev/null
@@ -1,844 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Lucas Soltic (ceylow@gmail.com) and Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#import <SFML/Window/Cocoa/WindowImplCocoa.hpp>
-#import <SFML/Window/Cocoa/AppController.h>
-#import <SFML/Window/Cocoa/GLKit.h>
-#import <SFML/Window/WindowStyle.hpp>
-#import <SFML/System.hpp>
-#import <iostream>
-
-
-namespace sf
-{
-namespace priv
-{
-
-// Do something only once (useful in loops)
-#define ONCE(make) \
-{ static int __done = 0;\
-if (!__done) {\
-make;\
-__done = 1;\
-} }
-
-
-////////////////////////////////////////////////////////////
-/// Private function declarations
-////////////////////////////////////////////////////////////
-namespace {
- Key::Code KeyForVirtualCode(unsigned short vCode);
- Key::Code KeyForUnicode(unsigned short uniCode);
-} // anonymous namespace
-
-
-////////////////////////////////////////////////////////////
-/// Default constructor
-/// (creates a dummy window to provide a valid OpenGL context)
-////////////////////////////////////////////////////////////
-WindowImplCocoa::WindowImplCocoa() :
-myWrapper(nil),
-myUseKeyRepeat(false),
-myMouseIn(false),
-myWheelStatus(0.0f)
-{
- [sfPrivAppController sharedController];
-
- // Create the shared OpenGL context
- if ([sfPrivGLContext sharedContext]) {
- // Then we make it the current active OpenGL context
- SetActive();
- } else {
- std::cerr << "Unable to make the main shared OpenGL context" << std::endl;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Create the window implementation from an existing control
-////////////////////////////////////////////////////////////
-WindowImplCocoa::WindowImplCocoa(WindowHandle Handle, WindowSettings& params) :
-myWrapper(NULL),
-myUseKeyRepeat(false),
-myMouseIn(false),
-myWheelStatus(0.0f)
-{
- if (Handle) {
- // Classical window import
- if ([(id)Handle isKindOfClass:[NSWindow class]]) {
- myWrapper = [[sfPrivImportedWindow alloc]
- initWithWindow:(NSWindow *)Handle
- settings:params];
- }
- // Qt "window" import
- else if ([(id)Handle isKindOfClass:[NSView class]]) {
- myWrapper = [[sfPrivImportedView alloc]
- initWithView:(NSView *)Handle
- settings:params];
- } else {
- std::cerr
- << "Cannot import this Window Handle because it is neither"
- << "a <NSWindow *> nor <NSView *> object"
- << "(or any of its subclasses). You gave a <"
- << [[(id)Handle className] UTF8String]
- << "> object."
- << std::endl;
-
- }
-
- if (myWrapper) {
- [myWrapper setDelegate:this];
-
- // initial mouse state
- myMouseIn = [myWrapper mouseInside];
-
- // We set the myWidth and myHeight members to the correct values
- myWidth = (int) [[myWrapper view] frame].size.width;
- myHeight = (int) [[myWrapper view] frame].size.height;
- } else {
- std::cerr << "Failed to make the public window" << std::endl;
- }
- } else {
- std::cerr
- << "Invalid null handle given to "
- << "Window::Window(WindowHandle Handle, const WindowSettings& Params)"
- << std::endl;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Create the window implementation
-////////////////////////////////////////////////////////////
-WindowImplCocoa::WindowImplCocoa(VideoMode Mode, const std::string& Title, unsigned long WindowStyle, WindowSettings& params) :
-myWrapper(NULL),
-myUseKeyRepeat(false),
-myMouseIn(false),
-myWheelStatus(0.0f)
-{
- // Create a new window with given size, title and style
- // First we define some objects used for our window
- NSString *title = [NSString stringWithCString:(Title.c_str()) ? (Title.c_str()) : ""
- encoding:NSASCIIStringEncoding];
-
- // We create the window
- myWrapper = [[sfPrivOwnedWindow alloc]
- initWithVideoMode:Mode
- settings:params
- style:WindowStyle
- title:title];
-
-
-
- if (myWrapper)
- {
- [myWrapper setDelegate:this];
-
- // initial mouse state
- myMouseIn = [myWrapper mouseInside];
-
- // We set the myWidth and myHeight members to the correct values
- myWidth = Mode.Width;
- myHeight = Mode.Height;
- } else {
- std::cerr << "Failed to make the public window" << std::endl;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Destructor
-////////////////////////////////////////////////////////////
-WindowImplCocoa::~WindowImplCocoa()
-{
- // Release the window wrapper
- [myWrapper release];
-}
-
-
-////////////////////////////////////////////////////////////
-/// Check if there's an active context on the current thread
-////////////////////////////////////////////////////////////
-bool WindowImplCocoa::IsContextActive()
-{
- return ([NSOpenGLContext currentContext] != NULL);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Handle event sent by the default NSNotificationCenter
-////////////////////////////////////////////////////////////
-void WindowImplCocoa::HandleNotifiedEvent(Event& event)
-{
- // Set myWidth and myHeight to correct value if
- // window size changed
- switch (event.Type) {
- case Event::Resized:
- myWidth = event.Size.Width;
- myHeight = event.Size.Height;
- break;
-
- default:
- break;
- }
-
- // And send the event
- SendEvent(event);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Handle a key down event (NSEvent)
-////////////////////////////////////////////////////////////
-void WindowImplCocoa::HandleKeyDown(void *eventRef)
-{
- NSEvent *event = reinterpret_cast <NSEvent *> (eventRef);
-
- Event sfEvent;
- unichar chr = 0, rawchr = 0;
- unsigned long length = [[event characters] length];
- unsigned mods = [event modifierFlags];
-
- if (length) {
- chr = [[event characters] characterAtIndex:0];
-
- // Note : I got a crash (out of bounds exception) while typing so now I test...
- if ([[event charactersIgnoringModifiers] length])
- rawchr = [[event charactersIgnoringModifiers] characterAtIndex:0];
-
-
- // Don't handle repeated events if we chose not to send them
- if (!myUseKeyRepeat && [event isARepeat])
- return;
-
- // Is it also a text event ?
- if (IsTextEvent(event)) {
- // buffer for the UTF-32 characters
- Uint32 utf32Characters[2] = {0};
-
- // convert the characters
- // note: using CFString in order to keep compatibility with Mac OS X 10.4
- // (as NSUTF32StringEncoding is only being defined in Mac OS X 10.5 and later)
- if (!CFStringGetCString ((CFStringRef)[event characters],
- (char *)utf32Characters,
- sizeof(utf32Characters),
- kCFStringEncodingUTF32))
- {
- char asciiChar[3] = {0};
- if ([[event characters] lengthOfBytesUsingEncoding:NSASCIIStringEncoding])
- [[event characters] getCString:asciiChar
- maxLength:3
- encoding:NSASCIIStringEncoding];
-
- std::cerr << "Error while converting character to UTF32 : \""
- << asciiChar << "\"" << std::endl;
- }
- else
- {
- sfEvent.Type = Event::TextEntered;
- sfEvent.Text.Unicode = utf32Characters[0];
-
- SendEvent(sfEvent);
- }
- }
-
- // Anyway it's also a KeyPressed event
- sfEvent.Type = Event::KeyPressed;
-
- // Get the keys
- if (Key::Code(0) == (sfEvent.Key.Code = KeyForUnicode(rawchr))) {
- sfEvent.Key.Code = KeyForVirtualCode([event keyCode]);
- }
-
- // Get the modifiers
- sfEvent.Key.Alt = mods & NSAlternateKeyMask;
- sfEvent.Key.Control = mods & NSControlKeyMask;
- sfEvent.Key.Shift = mods & NSShiftKeyMask;
-
- // Send the event
- SendEvent(sfEvent);
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Handle a key up event (NSEvent)
-////////////////////////////////////////////////////////////
-void WindowImplCocoa::HandleKeyUp(void *eventRef)
-{
- NSEvent *event = reinterpret_cast <NSEvent *> (eventRef);
-
- Event sfEvent;
- unsigned mods = [event modifierFlags];
- unichar chr = 0, rawchr = 0;
-
- if ([[event characters] length]) {
- chr = [[event characters] characterAtIndex:0];
-
- if ([[event charactersIgnoringModifiers] length])
- rawchr = [[event charactersIgnoringModifiers] characterAtIndex:0];
-
- sfEvent.Type = Event::KeyReleased;
-
- // Get the code
- if (Key::Code(0) == (sfEvent.Key.Code = KeyForUnicode(rawchr))) {
- sfEvent.Key.Code = KeyForVirtualCode([event keyCode]);
- }
-
- // Get the modifiers
- sfEvent.Key.Alt = mods & NSAlternateKeyMask;
- sfEvent.Key.Control = mods & NSControlKeyMask;
- sfEvent.Key.Shift = mods & NSShiftKeyMask;
-
- // Send the event
- SendEvent(sfEvent);
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Handle a key modifier event [Command, Option, Control, Shift]
-////////////////////////////////////////////////////////////
-void WindowImplCocoa::HandleModifierKey(void *eventRef)
-{
- NSEvent *event = reinterpret_cast <NSEvent *> (eventRef);
- Event sfEvent;
- unsigned mods = [event modifierFlags];
-
- sfEvent.Type = Event::KeyPressed;
-
- // Get the code
- sfEvent.Key.Code = KeyForVirtualCode([event keyCode]);
-
- // Get the modifiers
- sfEvent.Key.Alt = mods & NSAlternateKeyMask;
- sfEvent.Key.Control = mods & NSControlKeyMask;
- sfEvent.Key.Shift = mods & NSShiftKeyMask;
-
- // Guess whether it's a pressed or released event
- // Note: this does not work fine is both left and right modifiers are pressed
- // I did not find any way to fix this.
- // TODO: fix handling of modifier flags for use of left and right key at the same time
- if (!(mods & NSAlternateKeyMask) &&
- (sfEvent.Key.Code == Key::LAlt || sfEvent.Key.Code == Key::RAlt)) {
- sfEvent.Type = Event::KeyReleased;
- }
-
- if (!(mods & NSControlKeyMask) &&
- (sfEvent.Key.Code == Key::LControl || sfEvent.Key.Code == Key::RControl)) {
- sfEvent.Type = Event::KeyReleased;
- }
-
- if (!(mods & NSShiftKeyMask) &&
- (sfEvent.Key.Code == Key::LShift || sfEvent.Key.Code == Key::RShift)) {
- sfEvent.Type = Event::KeyReleased;
- }
-
- if (!(mods & NSCommandKeyMask) &&
- (sfEvent.Key.Code == Key::LSystem || sfEvent.Key.Code == Key::RSystem)) {
- sfEvent.Type = Event::KeyReleased;
- }
-
- // Send the event
- SendEvent(sfEvent);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Handle a mouse down event (NSEvent)
-////////////////////////////////////////////////////////////
-void WindowImplCocoa::HandleMouseDown(void *eventRef)
-{
- NSEvent *event = reinterpret_cast <NSEvent *> (eventRef);
- Event sfEvent;
-
- // Get mouse position relative to the window
- NSPoint loc = [myWrapper mouseLocation];
- unsigned mods = [event modifierFlags];
-
- switch ([event type]) {
- case NSLeftMouseDown:
- sfEvent.Type = Event::MouseButtonPressed;
-
- // Guess whether it's a mouse left or mouse right event
- if (mods & NSControlKeyMask) {
- sfEvent.MouseButton.Button = Mouse::Right;
- } else {
- sfEvent.MouseButton.Button = Mouse::Left;
- }
-
- sfEvent.MouseButton.X = (int) loc.x;
- sfEvent.MouseButton.Y = (int) loc.y;
-
- // Send the event
- SendEvent(sfEvent);
- break;
-
- case NSRightMouseDown:
- sfEvent.Type = Event::MouseButtonPressed;
- sfEvent.MouseButton.Button = Mouse::Right;
-
- sfEvent.MouseButton.X = (int) loc.x;
- sfEvent.MouseButton.Y = (int) loc.y;
-
- // Send the event
- SendEvent(sfEvent);
- break;
-
- default:
- break;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Handle a mouse up event (NSEvent)
-////////////////////////////////////////////////////////////
-void WindowImplCocoa::HandleMouseUp(void *eventRef)
-{
- NSEvent *event = reinterpret_cast <NSEvent *> (eventRef);
- Event sfEvent;
-
- // Get mouse position relative to the window
- NSPoint loc = [myWrapper mouseLocation];
- unsigned mods = [event modifierFlags];
-
- switch ([event type]) {
- case NSLeftMouseUp:
- sfEvent.Type = Event::MouseButtonReleased;
-
- // Guess whether it's a mouse left or mouse right event
- if (mods & NSControlKeyMask) {
- sfEvent.MouseButton.Button = Mouse::Right;
- } else {
- sfEvent.MouseButton.Button = Mouse::Left;
- }
-
- sfEvent.MouseButton.X = (int) loc.x;
- sfEvent.MouseButton.Y = (int) loc.y;
-
- // Send the event
- SendEvent(sfEvent);
- break;
-
- case NSRightMouseUp:
- sfEvent.Type = Event::MouseButtonReleased;
- sfEvent.MouseButton.Button = Mouse::Right;
-
- sfEvent.MouseButton.X = (int) loc.x;
- sfEvent.MouseButton.Y = (int) loc.y;
-
- // Send the event
- SendEvent(sfEvent);
- break;
-
- default:
- break;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Handle a mouse move event (NSEvent)
-////////////////////////////////////////////////////////////
-void WindowImplCocoa::HandleMouseMove(void *eventRef)
-{
- Event sfEvent;
- NSPoint loc = [myWrapper mouseLocation];
- sfEvent.Type = Event::MouseMoved;
-
- sfEvent.MouseMove.X = (int) loc.x;
- sfEvent.MouseMove.Y = (int) loc.y;
-
- SendEvent(sfEvent);
-
- if ([myWrapper mouseInside] && !myMouseIn) {
- // If mouse IS inside but WAS not inside last time
- sfEvent.Type = Event::MouseEntered;
- myMouseIn = true;
-
- SendEvent(sfEvent);
- } else if (![myWrapper mouseInside] && myMouseIn) {
- // Is mouse WAS not inside but IS now inside
- sfEvent.Type = Event::MouseLeft;
- myMouseIn = false;
-
- SendEvent(sfEvent);
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Handle a mouse wheel event (NSEvent)
-////////////////////////////////////////////////////////////
-void WindowImplCocoa::HandleMouseWheel(void *eventRef)
-{
- NSEvent *event = reinterpret_cast <NSEvent *> (eventRef);
-
- // SFML uses integer values for delta but Cocoa uses float and it is mostly fewer than 1.0
- // Therefore I chose to add the float value to a 'wheel status' and
- // send a sf event only when it's greater than 1.0
- myWheelStatus += [event deltaY];
-
- if (fabs(myWheelStatus) > 1.0f) {
- // Make the event and send it
- Event sfEvent;
- sfEvent.Type = Event::MouseWheelMoved;
- sfEvent.MouseWheel.Delta = (int) myWheelStatus;
- SendEvent(sfEvent);
-
- // Remove as much integer units as the one that have been put in the event
- // (was a mistake to set this to 0)
- myWheelStatus -= (int) myWheelStatus;
- }
-}
-
-////////////////////////////////////////////////////////////
-/// Return whether 'ev' must be considered as a TextEntered event
-////////////////////////////////////////////////////////////
-bool WindowImplCocoa::IsTextEvent(void *eventRef)
-{
- NSEvent *event = (NSEvent *)eventRef;
- bool res = false;
-
- if (event && [event type] == NSKeyDown && [[event characters] length]) {
- unichar code = [[event characters] characterAtIndex:0];
-
- // Codes from 0xF700 to 0xF8FF are non text keys (see NSEvent.h)
- // 0x35 is the Escape key
- if ([event keyCode] != 0x35 && (code < 0xF700 || code > 0xF8FF))
- res = true;
- }
-
- return res;
-}
-
-////////////////////////////////////////////////////////////
-/// /see sfWindowImpl::Display
-////////////////////////////////////////////////////////////
-void WindowImplCocoa::Display()
-{
- // Forward flush call to the window
- [myWrapper flushBuffer];
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see sfWindowImpl::ProcessEvents
-////////////////////////////////////////////////////////////
-void WindowImplCocoa::ProcessEvents()
-{
- // Forward event handling call to the application controller
- [[sfPrivAppController sharedController] processEvents];
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see sfWindowImpl::MakeActive
-////////////////////////////////////////////////////////////
-void WindowImplCocoa::SetActive(bool Active) const
-{
- // Forward the call to the window
- if (myWrapper)
- [myWrapper setActive:Active];
- else {
- // Or directly activate the shared OpenGL context if we're not using a window
- if (Active) {
- if ([NSOpenGLContext currentContext] != [sfPrivGLContext sharedContext])
- [[sfPrivGLContext sharedContext] makeCurrentContext];
- } else {
- if ([NSOpenGLContext currentContext] == [sfPrivGLContext sharedContext])
- [NSOpenGLContext clearCurrentContext];
- }
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see sfWindowImpl::UseVerticalSync
-////////////////////////////////////////////////////////////
-void WindowImplCocoa::UseVerticalSync(bool Enabled)
-{
- // Forward the call to the window
- [myWrapper enableVerticalSync:Enabled];
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see sfWindowImpl::ShowMouseCursor
-////////////////////////////////////////////////////////////
-void WindowImplCocoa::ShowMouseCursor(bool flag)
-{
- if (flag) {
- [NSCursor unhide];
- } else {
- [NSCursor hide];
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see sfWindowImpl::SetCursorPosition
-////////////////////////////////////////////////////////////
-void WindowImplCocoa::SetCursorPosition(unsigned int Left, unsigned int Top)
-{
- NSPoint pos = NSMakePoint ((float) Left, (float) Top);
-
- if (myWrapper) {
- // Flip for SFML window coordinate system
- pos.y = [[myWrapper window] frame].size.height - pos.y;
-
- // Adjust for view reference instead of window
- pos.y -= [[myWrapper window] frame].size.height - [[myWrapper view] frame].size.height;
-
- // Convert to screen coordinates
- NSPoint absolute = [[myWrapper window] convertBaseToScreen:pos];
-
- // Flip screen coodinates
- absolute.y = [[NSScreen mainScreen] frame].size.height - absolute.y;
-
- // Move cursor
- CGDisplayMoveCursorToPoint([sfPrivAppController primaryScreen],
- CGPointMake(absolute.x, absolute.y));
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see sfWindowImpl::SetPosition
-////////////////////////////////////////////////////////////
-void WindowImplCocoa::SetPosition(int Left, int Top)
-{
- [myWrapper setPosition:NSMakePoint(Left, Top)];
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see WindowImpl::SetSize
-///
-////////////////////////////////////////////////////////////
-void WindowImplCocoa::SetSize(unsigned int Width, unsigned int Height)
-{
- [myWrapper setSize:NSMakeSize(Width, Height)];
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see sfWindowImpl::Show
-////////////////////////////////////////////////////////////
-void WindowImplCocoa::Show(bool State)
-{
- [myWrapper show:State];
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see sfWindowImpl::EnableKeyRepeat
-////////////////////////////////////////////////////////////
-void WindowImplCocoa::EnableKeyRepeat(bool Enabled)
-{
- myUseKeyRepeat = Enabled;
-}
-
-
-////////////////////////////////////////////////////////////
-/// see WindowImpl::SetIcon
-////////////////////////////////////////////////////////////
-void WindowImplCocoa::SetIcon(unsigned int Width, unsigned int Height, const Uint8* Pixels)
-{
- // Nothing to do
-}
-
-
-namespace {
- ////////////////////////////////////////////////////////////
- /// Return the SFML key corresponding to a key code
- ////////////////////////////////////////////////////////////
- Key::Code KeyForVirtualCode(unsigned short vCode)
- {
- static struct {
- unsigned short code;
- Key::Code sfKey;
- } virtualTable[] =
- {
- {0x35, Key::Escape},
- {0x31, Key::Space},
- {0x24, Key::Return}, // main Return key
- {0x4C, Key::Return}, // pav Return key
- {0x33, Key::Back},
- {0x30, Key::Tab},
- {0x74, Key::PageUp},
- {0x79, Key::PageDown},
- {0x77, Key::End},
- {0x73, Key::Home},
- {0x72, Key::Insert},
- {0x75, Key::Delete},
- {0x45, Key::Add},
- {0x4E, Key::Subtract},
- {0x43, Key::Multiply},
- {0x4B, Key::Divide},
-
- {0x7A, Key::F1}, {0x78, Key::F2}, {0x63, Key::F3},
- {0x76, Key::F4}, {0x60, Key::F5}, {0x61, Key::F6},
- {0x62, Key::F7}, {0x64, Key::F8}, {0x65, Key::F9},
- {0x6D, Key::F10}, {0x67, Key::F11}, {0x6F, Key::F12},
- {0x69, Key::F13}, {0x6B, Key::F14}, {0x71, Key::F15},
-
- {0x7B, Key::Left},
- {0x7C, Key::Right},
- {0x7E, Key::Up},
- {0x7D, Key::Down},
-
- {0x52, Key::Numpad0}, {0x53, Key::Numpad1}, {0x54, Key::Numpad2},
- {0x55, Key::Numpad3}, {0x56, Key::Numpad4}, {0x57, Key::Numpad5},
- {0x58, Key::Numpad6}, {0x59, Key::Numpad7}, {0x5B, Key::Numpad8},
- {0x5C, Key::Numpad9},
-
- {0x1D, Key::Num0}, {0x12, Key::Num1}, {0x13, Key::Num2},
- {0x14, Key::Num3}, {0x15, Key::Num4}, {0x17, Key::Num5},
- {0x16, Key::Num6}, {0x1A, Key::Num7}, {0x1C, Key::Num8},
- {0x19, Key::Num9},
-
- {0x3B, Key::LControl}, //< Left Ctrl
- {0x3A, Key::LAlt}, //< Left Option/Alt
- {0x37, Key::LSystem}, //< Left Command
- {0x38, Key::LShift}, //< Left Shift
- {0x3E, Key::RControl}, //< Right Ctrl
- {0x3D, Key::RAlt}, //< Right Option/Alt
- {0x36, Key::RSystem}, //< Right Command
- {0x3C, Key::RShift}, //< Right Shift
-
- {0x39, Key::Code(0)} //< Caps Lock (not handled by SFML for now)
- };
-
- Key::Code result = Key::Code(0);
-
- for (unsigned i = 0;virtualTable[i].code;i++) {
- if (virtualTable[i].code == vCode) {
- result = virtualTable[i].sfKey;
- break;
- }
- }
-
- return result;
- }
-
-
- ////////////////////////////////////////////////////////////
- /// Return the SFML key corresponding to a unicode code
- ////////////////////////////////////////////////////////////
- Key::Code KeyForUnicode(unsigned short uniCode)
- {
- // TODO: find a better way to get the language independant key
- static struct {
- unsigned short character;
- Key::Code sfKey;
- } unicodeTable[] =
- {
- {'!', Key::Code(0)}, //< No Key for this code
- {'"', Key::Code(0)}, //< No Key for this code
- {'#', Key::Code(0)}, //< No Key for this code
- {'$', Key::Code(0)}, //< No Key for this code
- {'%', Key::Code(0)}, //< No Key for this code
- {'&', Key::Code(0)}, //< No Key for this code
- {'\'', Key::Quote},
- {'(', Key::Code(0)}, //< No Key for this code
- {')', Key::Code(0)}, //< No Key for this code
- {'*', Key::Multiply},
- {'+', Key::Add},
- {',', Key::Comma},
- {'-', Key::Code(0)}, //< Handled by KeyForVirtualCode()
- {'.', Key::Period},
- {'/', Key::Code(0)}, //< Handled by KeyForVirtualCode()
- {'0', Key::Code(0)}, //< Handled by KeyForVirtualCode()
- {'1', Key::Code(0)}, //< Handled by KeyForVirtualCode()
- {'2', Key::Code(0)}, //< Handled by KeyForVirtualCode()
- {'3', Key::Code(0)}, //< Handled by KeyForVirtualCode()
- {'4', Key::Code(0)}, //< Handled by KeyForVirtualCode()
- {'5', Key::Code(0)}, //< Handled by KeyForVirtualCode()
- {'6', Key::Code(0)}, //< Handled by KeyForVirtualCode()
- {'7', Key::Code(0)}, //< Handled by KeyForVirtualCode()
- {'8', Key::Code(0)}, //< Handled by KeyForVirtualCode()
- {'9', Key::Code(0)}, //< Handled by KeyForVirtualCode()
- {':', Key::Code(0)}, //< No Key for this code
- {';', Key::SemiColon},
- {'<', Key::Code(0)}, //< No Key for this code
- {'=', Key::Equal},
- {'>', Key::Code(0)}, //< No Key for this code
- {'?', Key::Code(0)}, //< No Key for this code
- {'@', Key::Code(0)}, //< No Key for this code
- {'A', Key::A}, {'B', Key::B}, {'C', Key::C},
- {'D', Key::D}, {'E', Key::E}, {'F', Key::F},
- {'G', Key::G}, {'H', Key::H}, {'I', Key::I},
- {'J', Key::J}, {'K', Key::K}, {'L', Key::L},
- {'M', Key::M}, {'N', Key::N}, {'O', Key::O},
- {'P', Key::P}, {'Q', Key::Q}, {'R', Key::R},
- {'S', Key::S}, {'T', Key::T}, {'U', Key::U},
- {'V', Key::V}, {'W', Key::W}, {'X', Key::X},
- {'Y', Key::Y}, {'Z', Key::Z},
- {'[', Key::LBracket},
- {'\\', Key::BackSlash},
- {']', Key::RBracket},
- {'^', Key::Code(0)}, //< No Key for this code
- {'_', Key::Code(0)}, //< No Key for this code
- {'`', Key::Code(0)}, //< No Key for this code
- {'a', Key::A}, {'b', Key::B}, {'c', Key::C},
- {'d', Key::D}, {'e', Key::E}, {'f', Key::F},
- {'g', Key::G}, {'h', Key::H}, {'i', Key::I},
- {'j', Key::J}, {'k', Key::K}, {'l', Key::L},
- {'m', Key::M}, {'n', Key::N}, {'o', Key::O},
- {'p', Key::P}, {'q', Key::Q}, {'r', Key::R},
- {'s', Key::S}, {'t', Key::T}, {'u', Key::U},
- {'v', Key::V}, {'w', Key::W}, {'x', Key::X},
- {'y', Key::Y}, {'z', Key::Z},
- {'{', Key::Code(0)}, //< No Key for this code
- {'|', Key::Code(0)}, //< No Key for this code
- {'}', Key::Code(0)}, //< No Key for this code
- {'~', Key::Tilde},
- {0, Key::Code(0)}
- };
-
- Key::Code result = Key::Code(0);
-
- for (unsigned i = 0;unicodeTable[i].character;i++) {
- if (unicodeTable[i].character == uniCode) {
- result = unicodeTable[i].sfKey;
- break;
- }
- }
-
- return result;
- }
-
-} // anonymous namespace
-
-
-} // namespace priv
-
-} // namespace sf
-
diff --git a/src/SFML/Window/Context.cpp b/src/SFML/Window/Context.cpp
index 107bc6e..6b6bb6b 100755..100644
--- a/src/SFML/Window/Context.cpp
+++ b/src/SFML/Window/Context.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -26,62 +26,38 @@
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Window/Context.hpp>
-#include <SFML/Window/WindowImpl.hpp>
-
-
-namespace
-{
- // Make sure the dummy context is created at global startup
- sf::Context& Dummy = sf::Context::GetGlobal();
-}
+#include <SFML/Window/GlContext.hpp>
namespace sf
{
////////////////////////////////////////////////////////////
-/// Default constructor, create the context
-////////////////////////////////////////////////////////////
Context::Context()
{
- myDummyWindow = priv::WindowImpl::New();
+ m_context = priv::GlContext::create();
+ setActive(true);
}
////////////////////////////////////////////////////////////
-/// Destructor, destroy the context
-////////////////////////////////////////////////////////////
Context::~Context()
{
- delete myDummyWindow;
+ delete m_context;
}
////////////////////////////////////////////////////////////
-/// Activate or deactivate the context
-////////////////////////////////////////////////////////////
-void Context::SetActive(bool Active)
+bool Context::setActive(bool active)
{
- myDummyWindow->SetActive(Active);
+ return m_context->setActive(active);
}
////////////////////////////////////////////////////////////
-/// Check if there's a context bound to the current thread
-////////////////////////////////////////////////////////////
-bool Context::IsContextActive()
+Context::Context(const ContextSettings& settings, unsigned int width, unsigned int height)
{
- return priv::WindowImpl::IsContextActive();
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the global context
-////////////////////////////////////////////////////////////
-Context& Context::GetGlobal()
-{
- static Context* GlobalContext = new Context; // Never deleted, on purpose
-
- return *GlobalContext;
+ m_context = priv::GlContext::create(settings, width, height);
+ setActive(true);
}
} // namespace sf
diff --git a/src/SFML/Window/GlContext.cpp b/src/SFML/Window/GlContext.cpp
new file mode 100644
index 0000000..ce4bfec
--- /dev/null
+++ b/src/SFML/Window/GlContext.cpp
@@ -0,0 +1,280 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/GlContext.hpp>
+#include <SFML/System/ThreadLocalPtr.hpp>
+#include <SFML/System/Mutex.hpp>
+#include <SFML/System/Lock.hpp>
+#include <SFML/OpenGL.hpp>
+#include <SFML/Window/glext/glext.h>
+#include <set>
+#include <cstdlib>
+#include <cassert>
+
+
+#if defined(SFML_SYSTEM_WINDOWS)
+
+ #include <SFML/Window/Win32/WglContext.hpp>
+ typedef sf::priv::WglContext ContextType;
+
+#elif defined(SFML_SYSTEM_LINUX) || defined(SFML_SYSTEM_FREEBSD)
+
+ #include <SFML/Window/Linux/GlxContext.hpp>
+ typedef sf::priv::GlxContext ContextType;
+
+#elif defined(SFML_SYSTEM_MACOS)
+
+ #include <SFML/Window/OSX/SFContext.hpp>
+ typedef sf::priv::SFContext ContextType;
+
+#endif
+
+
+namespace
+{
+ // This per-thread variable holds the current context for each thread
+ sf::ThreadLocalPtr<sf::priv::GlContext> currentContext(NULL);
+
+ // The hidden, inactive context that will be shared with all other contexts
+ ContextType* sharedContext = NULL;
+
+ // Internal contexts
+ sf::ThreadLocalPtr<sf::priv::GlContext> internalContext(NULL);
+ std::set<sf::priv::GlContext*> internalContexts;
+ sf::Mutex internalContextsMutex;
+
+ // Check if the internal context of the current thread is valid
+ bool hasInternalContext()
+ {
+ // The internal context can be null...
+ if (!internalContext)
+ return false;
+
+ // ... or non-null but deleted from the list of internal contexts
+ sf::Lock lock(internalContextsMutex);
+ return internalContexts.find(internalContext) != internalContexts.end();
+ }
+
+ // Retrieve the internal context for the current thread
+ sf::priv::GlContext* getInternalContext()
+ {
+ if (!hasInternalContext())
+ {
+ internalContext = sf::priv::GlContext::create();
+ sf::Lock lock(internalContextsMutex);
+ internalContexts.insert(internalContext);
+ }
+
+ return internalContext;
+ }
+}
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+void GlContext::globalInit()
+{
+ // Create the shared context
+ sharedContext = new ContextType(NULL);
+ sharedContext->initialize();
+
+ // This call makes sure that:
+ // - the shared context is inactive (it must never be)
+ // - another valid context is activated in the current thread
+ sharedContext->setActive(false);
+}
+
+
+////////////////////////////////////////////////////////////
+void GlContext::globalCleanup()
+{
+ // Destroy the shared context
+ delete sharedContext;
+ sharedContext = NULL;
+
+ // Destroy the internal contexts
+ sf::Lock lock(internalContextsMutex);
+ for (std::set<GlContext*>::iterator it = internalContexts.begin(); it != internalContexts.end(); ++it)
+ delete *it;
+ internalContexts.clear();
+}
+
+
+////////////////////////////////////////////////////////////
+void GlContext::ensureContext()
+{
+ // If there's no active context on the current thread, activate an internal one
+ if (!currentContext)
+ getInternalContext()->setActive(true);
+}
+
+
+////////////////////////////////////////////////////////////
+GlContext* GlContext::create()
+{
+ GlContext* context = new ContextType(sharedContext);
+ context->initialize();
+
+ return context;
+}
+
+
+////////////////////////////////////////////////////////////
+GlContext* GlContext::create(const ContextSettings& settings, const WindowImpl* owner, unsigned int bitsPerPixel)
+{
+ // Make sure that there's an active context (context creation may need extensions, and thus a valid context)
+ ensureContext();
+
+ // Create the context
+ GlContext* context = new ContextType(sharedContext, settings, owner, bitsPerPixel);
+ context->initialize();
+
+ return context;
+}
+
+
+////////////////////////////////////////////////////////////
+GlContext* GlContext::create(const ContextSettings& settings, unsigned int width, unsigned int height)
+{
+ // Make sure that there's an active context (context creation may need extensions, and thus a valid context)
+ ensureContext();
+
+ // Create the context
+ GlContext* context = new ContextType(sharedContext, settings, width, height);
+ context->initialize();
+
+ return context;
+}
+
+
+////////////////////////////////////////////////////////////
+GlContext::~GlContext()
+{
+ // Deactivate the context before killing it, unless we're inside Cleanup()
+ if (sharedContext)
+ setActive(false);
+}
+
+
+////////////////////////////////////////////////////////////
+const ContextSettings& GlContext::getSettings() const
+{
+ return m_settings;
+}
+
+
+////////////////////////////////////////////////////////////
+bool GlContext::setActive(bool active)
+{
+ if (active)
+ {
+ if (this != currentContext)
+ {
+ // Activate the context
+ if (makeCurrent())
+ {
+ // Set it as the new current context for this thread
+ currentContext = this;
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+ }
+ else
+ {
+ // This context is already the active one on this thread, don't do anything
+ return true;
+ }
+ }
+ else
+ {
+ if (this == currentContext)
+ {
+ // To deactivate the context, we actually activate another one so that we make
+ // sure that there is always an active context for subsequent graphics operations
+ return getInternalContext()->setActive(true);
+ }
+ else
+ {
+ // This context is not the active one on this thread, don't do anything
+ return true;
+ }
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+GlContext::GlContext()
+{
+ // Nothing to do
+}
+
+
+////////////////////////////////////////////////////////////
+int GlContext::evaluateFormat(unsigned int bitsPerPixel, const ContextSettings& settings, int colorBits, int depthBits, int stencilBits, int antialiasing)
+{
+ return std::abs(static_cast<int>(bitsPerPixel - colorBits)) +
+ std::abs(static_cast<int>(settings.depthBits - depthBits)) +
+ std::abs(static_cast<int>(settings.stencilBits - stencilBits)) +
+ std::abs(static_cast<int>(settings.antialiasingLevel - antialiasing));
+}
+
+
+////////////////////////////////////////////////////////////
+void GlContext::initialize()
+{
+ // Activate the context
+ setActive(true);
+
+ // Retrieve the context version number
+ const GLubyte* version = glGetString(GL_VERSION);
+ if (version)
+ {
+ // The beginning of the returned string is "major.minor" (this is standard)
+ m_settings.majorVersion = version[0] - '0';
+ m_settings.minorVersion = version[2] - '0';
+ }
+ else
+ {
+ // Can't get the version number, assume 2.0
+ m_settings.majorVersion = 2;
+ m_settings.minorVersion = 0;
+ }
+
+ // Enable antialiasing if needed
+ if (m_settings.antialiasingLevel > 0)
+ glEnable(GL_MULTISAMPLE_ARB);
+}
+
+} // namespace priv
+
+} // namespace sf
diff --git a/src/SFML/Window/GlContext.hpp b/src/SFML/Window/GlContext.hpp
new file mode 100644
index 0000000..7f8f4c0
--- /dev/null
+++ b/src/SFML/Window/GlContext.hpp
@@ -0,0 +1,234 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_GLCONTEXT_HPP
+#define SFML_GLCONTEXT_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Config.hpp>
+#include <SFML/Window/ContextSettings.hpp>
+#include <SFML/System/NonCopyable.hpp>
+
+
+namespace sf
+{
+namespace priv
+{
+class WindowImpl;
+
+////////////////////////////////////////////////////////////
+/// \brief Abstract class representing an OpenGL context
+///
+////////////////////////////////////////////////////////////
+class GlContext : NonCopyable
+{
+public :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Perform the global initialization
+ ///
+ /// This function is called once, before the very first OpenGL
+ /// resource is created. It makes sure that everything is ready
+ /// for contexts to work properly.
+ /// Note: this function doesn't need to be thread-safe, as it
+ /// can be called only once.
+ ///
+ ////////////////////////////////////////////////////////////
+ static void globalInit();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Perform the global cleanup
+ ///
+ /// This function is called after the very last OpenGL resource
+ /// is destroyed. It makes sure that everything that was
+ /// created by initialize() is properly released.
+ /// Note: this function doesn't need to be thread-safe, as it
+ /// can be called only once.
+ ///
+ ////////////////////////////////////////////////////////////
+ static void globalCleanup();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Ensures that an OpenGL context is active in the current thread
+ ///
+ ////////////////////////////////////////////////////////////
+ static void ensureContext();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Create a new context, not associated to a window
+ ///
+ /// This function automatically chooses the specialized class
+ /// to use according to the OS.
+ ///
+ /// \return Pointer to the created context (don't forget to delete it)
+ ///
+ ////////////////////////////////////////////////////////////
+ static GlContext* create();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Create a new context attached to a window
+ ///
+ /// This function automatically chooses the specialized class
+ /// to use according to the OS.
+ ///
+ /// \param settings Creation parameters
+ /// \param owner Pointer to the owner window
+ /// \param bitsPerPixel Pixel depth (in bits per pixel)
+ ///
+ /// \return Pointer to the created context
+ ///
+ ////////////////////////////////////////////////////////////
+ static GlContext* create(const ContextSettings& settings, const WindowImpl* owner, unsigned int bitsPerPixel);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Create a new context that embeds its own rendering target
+ ///
+ /// This function automatically chooses the specialized class
+ /// to use according to the OS.
+ ///
+ /// \param settings Creation parameters
+ /// \param width Back buffer width
+ /// \param height Back buffer height
+ ///
+ /// \return Pointer to the created context
+ ///
+ ////////////////////////////////////////////////////////////
+ static GlContext* create(const ContextSettings& settings, unsigned int width, unsigned int height);
+
+public :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Destructor
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual ~GlContext();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Get the settings of the context
+ ///
+ /// Note that these settings may be different than the ones
+ /// passed to the constructor; they are indeed adjusted if the
+ /// original settings are not directly supported by the system.
+ ///
+ /// \return Structure containing the settings
+ ///
+ ////////////////////////////////////////////////////////////
+ const ContextSettings& getSettings() const;
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Activate or deactivate the context as the current target for rendering
+ ///
+ /// A context is active only on the current thread, if you want to
+ /// make it active on another thread you have to deactivate it
+ /// on the previous thread first if it was active.
+ /// Only one context can be active on a thread at a time, thus
+ /// the context previously active (if any) automatically gets deactivated.
+ ///
+ /// \param active True to activate, false to deactivate
+ ///
+ /// \return True if operation was successful, false otherwise
+ ///
+ ////////////////////////////////////////////////////////////
+ bool setActive(bool active);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Display what has been rendered to the context so far
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual void display() = 0;
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Enable or disable vertical synchronization
+ ///
+ /// Activating vertical synchronization will limit the number
+ /// of frames displayed to the refresh rate of the monitor.
+ /// This can avoid some visual artifacts, and limit the framerate
+ /// to a good value (but not constant across different computers).
+ ///
+ /// \param enabled True to enable v-sync, false to deactivate
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual void setVerticalSyncEnabled(bool enabled) = 0;
+
+protected :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Default constructor
+ ///
+ /// This constructor is meant for derived classes only.
+ ///
+ ////////////////////////////////////////////////////////////
+ GlContext();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Activate the context as the current target
+ /// for rendering
+ ///
+ /// \return True on success, false if any error happened
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual bool makeCurrent() = 0;
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Evaluate a pixel format configuration
+ ///
+ /// This functions can be used by implementations that have
+ /// several valid formats and want to get the best one.
+ /// A score is returned for the given configuration: the
+ /// lower the score is, the better the configuration is.
+ ///
+ /// \param bitsPerPixel Requested pixel depth (bits per pixel)
+ /// \param settings Requested additionnal settings
+ /// \param colorBits Color bits of the configuration to evaluate
+ /// \param depthBits Depth bits of the configuration to evaluate
+ /// \param stencilBits Stencil bits of the configuration to evaluate
+ /// \param antialiasing Antialiasing level of the configuration to evaluate
+ ///
+ /// \return Score of the configuration
+ ///
+ ////////////////////////////////////////////////////////////
+ static int evaluateFormat(unsigned int bitsPerPixel, const ContextSettings& settings, int colorBits, int depthBits, int stencilBits, int antialiasing);
+
+ ////////////////////////////////////////////////////////////
+ // Member data
+ ////////////////////////////////////////////////////////////
+ ContextSettings m_settings; ///< Creation settings of the context
+
+private:
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Perform various initializations after the context construction
+ ///
+ ////////////////////////////////////////////////////////////
+ void initialize();
+};
+
+} // namespace priv
+
+} // namespace sf
+
+
+#endif // SFML_GLCONTEXT_HPP
diff --git a/src/SFML/Window/GlResource.cpp b/src/SFML/Window/GlResource.cpp
new file mode 100644
index 0000000..dda11a7
--- /dev/null
+++ b/src/SFML/Window/GlResource.cpp
@@ -0,0 +1,85 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/GlResource.hpp>
+#include <SFML/Window/GlContext.hpp>
+#include <SFML/System/Mutex.hpp>
+#include <SFML/System/Lock.hpp>
+
+
+namespace
+{
+ // OpenGL resources counter and its mutex
+ unsigned int count = 0;
+ sf::Mutex mutex;
+}
+
+
+namespace sf
+{
+////////////////////////////////////////////////////////////
+GlResource::GlResource()
+{
+ {
+ // Protect from concurrent access
+ Lock lock(mutex);
+
+ // If this is the very first resource, trigger the global context initialization
+ if (count == 0)
+ priv::GlContext::globalInit();
+
+ // Increment the resources counter
+ count++;
+ }
+
+ // Now make sure that there is an active OpenGL context in the current thread
+ priv::GlContext::ensureContext();
+}
+
+
+////////////////////////////////////////////////////////////
+GlResource::~GlResource()
+{
+ // Protect from concurrent access
+ Lock lock(mutex);
+
+ // Decrement the resources counter
+ count--;
+
+ // If there's no more resource alive, we can trigger the global context cleanup
+ if (count == 0)
+ priv::GlContext::globalCleanup();
+}
+
+
+////////////////////////////////////////////////////////////
+void GlResource::ensureGlContext()
+{
+ priv::GlContext::ensureContext();
+}
+
+} // namespace sf
diff --git a/src/SFML/Window/Input.cpp b/src/SFML/Window/Input.cpp
deleted file mode 100755
index 01dd54f..0000000
--- a/src/SFML/Window/Input.cpp
+++ /dev/null
@@ -1,169 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Window/Input.hpp>
-
-
-namespace sf
-{
-////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
-Input::Input() :
-myMouseX(0),
-myMouseY(0)
-{
- ResetStates();
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the state of a key
-////////////////////////////////////////////////////////////
-bool Input::IsKeyDown(Key::Code KeyCode) const
-{
- return myKeys[KeyCode];
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the state of a mouse button
-////////////////////////////////////////////////////////////
-bool Input::IsMouseButtonDown(Mouse::Button Button) const
-{
- return myMouseButtons[Button];
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the state of a joystick button
-////////////////////////////////////////////////////////////
-bool Input::IsJoystickButtonDown(unsigned int JoyId, unsigned int Button) const
-{
- if ((JoyId < Joy::Count) && (Button < Joy::ButtonCount))
- return myJoystickButtons[JoyId][Button];
- else
- return false;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the mouse left position
-////////////////////////////////////////////////////////////
-int Input::GetMouseX() const
-{
- return myMouseX;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the mouse top position
-////////////////////////////////////////////////////////////
-int Input::GetMouseY() const
-{
- return myMouseY;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get a joystick axis position
-////////////////////////////////////////////////////////////
-float Input::GetJoystickAxis(unsigned int JoyId, Joy::Axis Axis) const
-{
- if (JoyId < Joy::Count)
- return myJoystickAxis[JoyId][Axis];
- else
- return 0.f;
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see WindowListener::OnEvent
-////////////////////////////////////////////////////////////
-void Input::OnEvent(const Event& EventReceived)
-{
- switch (EventReceived.Type)
- {
- // Key events
- case Event::KeyPressed : myKeys[EventReceived.Key.Code] = true; break;
- case Event::KeyReleased : myKeys[EventReceived.Key.Code] = false; break;
-
- // Mouse event
- case Event::MouseButtonPressed : myMouseButtons[EventReceived.MouseButton.Button] = true; break;
- case Event::MouseButtonReleased : myMouseButtons[EventReceived.MouseButton.Button] = false; break;
-
- // Mouse move event
- case Event::MouseMoved :
- myMouseX = EventReceived.MouseMove.X;
- myMouseY = EventReceived.MouseMove.Y;
- break;
-
- // Joystick button events
- case Event::JoyButtonPressed : myJoystickButtons[EventReceived.JoyButton.JoystickId][EventReceived.JoyButton.Button] = true; break;
- case Event::JoyButtonReleased : myJoystickButtons[EventReceived.JoyButton.JoystickId][EventReceived.JoyButton.Button] = false; break;
-
- // Joystick move event
- case Event::JoyMoved :
- myJoystickAxis[EventReceived.JoyMove.JoystickId][EventReceived.JoyMove.Axis] = EventReceived.JoyMove.Position;
- break;
-
- // Lost focus event : we must reset all persistent states
- case Event::LostFocus :
- {
- ResetStates();
- break;
- }
-
- default :
- break;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Reset all the states
-////////////////////////////////////////////////////////////
-void Input::ResetStates()
-{
- for (int i = 0; i < Key::Count; ++i)
- myKeys[i] = false;
-
- for (int i = 0; i < Mouse::ButtonCount; ++i)
- myMouseButtons[i] = false;
-
- for (int i = 0; i < Joy::Count; ++i)
- {
- for (int j = 0; j < Joy::ButtonCount; ++j)
- myJoystickButtons[i][j] = false;
-
- for (int j = 0; j < Joy::AxisCount; ++j)
- myJoystickAxis[i][j] = 0.f;
- myJoystickAxis[i][Joy::AxisPOV] = -1.f;
- }
-}
-
-} // namespace sf
diff --git a/src/SFML/Window/VideoModeSupport.hpp b/src/SFML/Window/InputImpl.hpp
index caa94aa..0e2069d 100755..100644
--- a/src/SFML/Window/VideoModeSupport.hpp
+++ b/src/SFML/Window/InputImpl.hpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -22,28 +22,21 @@
//
////////////////////////////////////////////////////////////
-#ifndef SFML_VIDEOMODESUPPORT_HPP
-#define SFML_VIDEOMODESUPPORT_HPP
+#ifndef SFML_INPUTIMPL_HPP
+#define SFML_INPUTIMPL_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Config.hpp>
-
#if defined(SFML_SYSTEM_WINDOWS)
-
- #include <SFML/Window/Win32/VideoModeSupport.hpp>
-
+ #include <SFML/Window/Win32/InputImpl.hpp>
#elif defined(SFML_SYSTEM_LINUX) || defined(SFML_SYSTEM_FREEBSD)
-
- #include <SFML/Window/Linux/VideoModeSupport.hpp>
-
+ #include <SFML/Window/Linux/InputImpl.hpp>
#elif defined(SFML_SYSTEM_MACOS)
-
- #include <SFML/Window/Cocoa/VideoModeSupport.hpp>
-
+ #include <SFML/Window/OSX/InputImpl.hpp>
#endif
-#endif // SFML_VIDEOMODESUPPORT_HPP
+#endif // SFML_INPUTIMPL_HPP
diff --git a/src/SFML/Window/Joystick.cpp b/src/SFML/Window/Joystick.cpp
new file mode 100644
index 0000000..e307948
--- /dev/null
+++ b/src/SFML/Window/Joystick.cpp
@@ -0,0 +1,75 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/Joystick.hpp>
+#include <SFML/Window/JoystickManager.hpp>
+
+
+namespace sf
+{
+////////////////////////////////////////////////////////////
+bool Joystick::isConnected(unsigned int joystick)
+{
+ return priv::JoystickManager::getInstance().getState(joystick).connected;
+}
+
+
+////////////////////////////////////////////////////////////
+unsigned int Joystick::getButtonCount(unsigned int joystick)
+{
+ return priv::JoystickManager::getInstance().getCapabilities(joystick).buttonCount;
+}
+
+
+////////////////////////////////////////////////////////////
+bool Joystick::hasAxis(unsigned int joystick, Axis axis)
+{
+ return priv::JoystickManager::getInstance().getCapabilities(joystick).axes[axis];
+}
+
+
+////////////////////////////////////////////////////////////
+bool Joystick::isButtonPressed(unsigned int joystick, unsigned int button)
+{
+ return priv::JoystickManager::getInstance().getState(joystick).buttons[button];
+}
+
+
+////////////////////////////////////////////////////////////
+float Joystick::getAxisPosition(unsigned int joystick, Axis axis)
+{
+ return priv::JoystickManager::getInstance().getState(joystick).axes[axis];
+}
+
+
+////////////////////////////////////////////////////////////
+void Joystick::update()
+{
+ return priv::JoystickManager::getInstance().update();
+}
+
+} // namespace sf
diff --git a/src/SFML/Window/Win32/VideoModeSupport.cpp b/src/SFML/Window/JoystickImpl.hpp
index 8b98e74..1837ab4 100755..100644
--- a/src/SFML/Window/Win32/VideoModeSupport.cpp
+++ b/src/SFML/Window/JoystickImpl.hpp
@@ -1,74 +1,89 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Window/Win32/VideoModeSupport.hpp>
-#include <windows.h>
-#include <algorithm>
-
-
-namespace sf
-{
-namespace priv
-{
-////////////////////////////////////////////////////////////
-/// Get supported video modes
-////////////////////////////////////////////////////////////
-void VideoModeSupport::GetSupportedVideoModes(std::vector<VideoMode>& Modes)
-{
- // First, clear array to fill
- Modes.clear();
-
- // Enumerate all available video modes for primary display adapter
- DEVMODE Win32Mode;
- Win32Mode.dmSize = sizeof(DEVMODE);
- for (int Count = 0; EnumDisplaySettings(NULL, Count, &Win32Mode); ++Count)
- {
- // Convert to sfVideoMode
- VideoMode Mode(Win32Mode.dmPelsWidth, Win32Mode.dmPelsHeight, Win32Mode.dmBitsPerPel);
-
- // Add it only if it is not already in the array
- if (std::find(Modes.begin(), Modes.end(), Mode) == Modes.end())
- Modes.push_back(Mode);
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get current desktop video mode
-////////////////////////////////////////////////////////////
-VideoMode VideoModeSupport::GetDesktopVideoMode()
-{
- DEVMODE Win32Mode;
- Win32Mode.dmSize = sizeof(DEVMODE);
- EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &Win32Mode);
-
- return VideoMode(Win32Mode.dmPelsWidth, Win32Mode.dmPelsHeight, Win32Mode.dmBitsPerPel);
-}
-
-} // namespace priv
-
-} // namespace sf
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_JOYSTICKIMPL_HPP
+#define SFML_JOYSTICKIMPL_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Config.hpp>
+#include <SFML/Window/Joystick.hpp>
+#include <algorithm>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief Structure holding a joystick's capabilities
+///
+////////////////////////////////////////////////////////////
+struct JoystickCaps
+{
+ JoystickCaps()
+ {
+ buttonCount = 0;
+ std::fill(axes, axes + Joystick::AxisCount, false);
+ }
+
+ unsigned int buttonCount; ///< Number of buttons supported by the joystick
+ bool axes[Joystick::AxisCount]; ///< Support for each axis
+};
+
+
+////////////////////////////////////////////////////////////
+/// \brief Structure holding a joystick's state
+///
+////////////////////////////////////////////////////////////
+struct JoystickState
+{
+ JoystickState()
+ {
+ connected = false;
+ std::fill(axes, axes + Joystick::AxisCount, 0.f);
+ std::fill(buttons, buttons + Joystick::ButtonCount, false);
+ }
+
+ bool connected; ///< Is the joystick currently connected?
+ float axes[Joystick::AxisCount]; ///< Position of each axis, in range [-100, 100]
+ bool buttons[Joystick::ButtonCount]; ///< Status of each button (true = pressed)
+};
+
+} // namespace priv
+
+} // namespace sf
+
+
+#if defined(SFML_SYSTEM_WINDOWS)
+ #include <SFML/Window/Win32/JoystickImpl.hpp>
+#elif defined(SFML_SYSTEM_LINUX) || defined(SFML_SYSTEM_FREEBSD)
+ #include <SFML/Window/Linux/JoystickImpl.hpp>
+#elif defined(SFML_SYSTEM_MACOS)
+ #include <SFML/Window/OSX/JoystickImpl.hpp>
+#endif
+
+
+#endif // SFML_JOYSTICKIMPL_HPP
diff --git a/src/SFML/Window/JoystickManager.cpp b/src/SFML/Window/JoystickManager.cpp
new file mode 100644
index 0000000..2ddcdfa
--- /dev/null
+++ b/src/SFML/Window/JoystickManager.cpp
@@ -0,0 +1,114 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/JoystickManager.hpp>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+JoystickManager& JoystickManager::getInstance()
+{
+ static JoystickManager instance;
+ return instance;
+}
+
+
+////////////////////////////////////////////////////////////
+const JoystickCaps& JoystickManager::getCapabilities(unsigned int joystick) const
+{
+ return m_joysticks[joystick].capabilities;
+}
+
+
+////////////////////////////////////////////////////////////
+const JoystickState& JoystickManager::getState(unsigned int joystick) const
+{
+ return m_joysticks[joystick].state;
+}
+
+
+////////////////////////////////////////////////////////////
+void JoystickManager::update()
+{
+ for (int i = 0; i < Joystick::Count; ++i)
+ {
+ Item& item = m_joysticks[i];
+
+ if (item.state.connected)
+ {
+ // Get the current state of the joystick
+ item.state = item.joystick.update();
+
+ // Check if it's still connected
+ if (!item.state.connected)
+ {
+ item.joystick.close();
+ item.capabilities = JoystickCaps();
+ item.state = JoystickState();
+ }
+ }
+ else
+ {
+ // Check if the joystick was connected since last update
+ if (JoystickImpl::isConnected(i))
+ {
+ if (item.joystick.open(i))
+ {
+ item.capabilities = item.joystick.getCapabilities();
+ item.state = item.joystick.update();
+ }
+ }
+ }
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+JoystickManager::JoystickManager()
+{
+ JoystickImpl::initialize();
+}
+
+
+////////////////////////////////////////////////////////////
+JoystickManager::~JoystickManager()
+{
+ for (int i = 0; i < Joystick::Count; ++i)
+ {
+ if (m_joysticks[i].state.connected)
+ m_joysticks[i].joystick.close();
+ }
+
+ JoystickImpl::cleanup();
+}
+
+} // namespace priv
+
+} // namespace sf
diff --git a/src/SFML/Graphics/FontLoader.hpp b/src/SFML/Window/JoystickManager.hpp
index e52d147..fda8c22 100755..100644
--- a/src/SFML/Graphics/FontLoader.hpp
+++ b/src/SFML/Window/JoystickManager.hpp
@@ -1,132 +1,118 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-#ifndef SFML_FONTLOADER_HPP
-#define SFML_FONTLOADER_HPP
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/System/NonCopyable.hpp>
-#include <SFML/System/Unicode.hpp>
-#include <ft2build.h>
-#include FT_FREETYPE_H
-#include <string>
-
-
-namespace sf
-{
-class Font;
-
-namespace priv
-{
-////////////////////////////////////////////////////////////
-/// FontLoader loads and saves character fonts
-////////////////////////////////////////////////////////////
-class FontLoader : NonCopyable
-{
-public :
-
- ////////////////////////////////////////////////////////////
- /// Get the unique instance of the class
- ///
- /// \return Reference to the FontLoader instance
- ///
- ////////////////////////////////////////////////////////////
- static FontLoader& GetInstance();
-
- ////////////////////////////////////////////////////////////
- /// Load a font from a file
- ///
- /// \param Filename : Path of the font file to load
- /// \param CharSize : Size of characters in bitmap - the bigger, the higher quality
- /// \param Charset : Characters set to generate
- /// \param LoadedFont : Font object to fill up
- ///
- /// \return True if loading was successful
- ///
- ////////////////////////////////////////////////////////////
- bool LoadFontFromFile(const std::string& Filename, unsigned int CharSize, const Unicode::UTF32String& Charset, Font& LoadedFont);
-
- ////////////////////////////////////////////////////////////
- /// Load the font from a file in memory
- ///
- /// \param Data : Pointer to the data to load
- /// \param SizeInBytes : Size of the data, in bytes
- /// \param CharSize : Size of characters in bitmap - the bigger, the higher quality
- /// \param Charset : Characters set to generate
- /// \param LoadedFont : Font object to fill up
- ///
- /// \return True if loading was successful
- ///
- ////////////////////////////////////////////////////////////
- bool LoadFontFromMemory(const char* Data, std::size_t SizeInBytes, unsigned int CharSize, const Unicode::UTF32String& Charset, Font& LoadedFont);
-
-private :
-
- ////////////////////////////////////////////////////////////
- /// Default constructor
- ///
- ////////////////////////////////////////////////////////////
- FontLoader();
-
- ////////////////////////////////////////////////////////////
- /// Destructor
- ///
- ////////////////////////////////////////////////////////////
- ~FontLoader();
-
- ////////////////////////////////////////////////////////////
- /// Create a bitmap font from a font face and a characters set
- ///
- /// \param FontFace : Font face containing the loaded font
- /// \param CharSize : Size of characters in bitmap
- /// \param Charset : Characters set to generate
- /// \param LoadedFont : Font object to fill up
- ///
- ////////////////////////////////////////////////////////////
- FT_Error CreateBitmapFont(FT_Face FontFace, unsigned int CharSize, const Unicode::UTF32String& Charset, Font& LoadedFont);
-
- ////////////////////////////////////////////////////////////
- /// Get a description from a FT error code
- ///
- /// \param Error : FreeType error code
- ///
- /// \return Error description
- ///
- ////////////////////////////////////////////////////////////
- static std::string GetErrorDesc(FT_Error Error);
-
- ////////////////////////////////////////////////////////////
- // Member data
- ////////////////////////////////////////////////////////////
- FT_Library myLibrary; ///< Handle to the Freetype library
-};
-
-} // namespace priv
-
-} // namespace sf
-
-
-#endif // SFML_FONTLOADER_HPP
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_JOYSTICKMANAGER_HPP
+#define SFML_JOYSTICKMANAGER_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/Joystick.hpp>
+#include <SFML/Window/JoystickImpl.hpp>
+#include <SFML/System/NonCopyable.hpp>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief Global joystick manager
+///
+////////////////////////////////////////////////////////////
+class JoystickManager : NonCopyable
+{
+public :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Get the global unique instance of the manager
+ ///
+ /// \return Unique instance of the joystick manager
+ ///
+ ////////////////////////////////////////////////////////////
+ static JoystickManager& getInstance();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Get the capabilities of an open joystick
+ ///
+ /// \param joystick Index of the joystick
+ ///
+ /// \return Capabilities of the joystick
+ ///
+ ////////////////////////////////////////////////////////////
+ const JoystickCaps& getCapabilities(unsigned int joystick) const;
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Get the current state of an open joystick
+ ///
+ /// \param joystick Index of the joystick
+ ///
+ /// \return Current state of the joystick
+ ///
+ ////////////////////////////////////////////////////////////
+ const JoystickState& getState(unsigned int joystick) const;
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Update the state of all the joysticks
+ ///
+ ////////////////////////////////////////////////////////////
+ void update();
+
+private:
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Default constructor
+ ///
+ ////////////////////////////////////////////////////////////
+ JoystickManager();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Destructor
+ ///
+ ////////////////////////////////////////////////////////////
+ ~JoystickManager();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Joystick information and state
+ ///
+ ////////////////////////////////////////////////////////////
+ struct Item
+ {
+ JoystickImpl joystick; ///< Joystick implementation
+ JoystickState state; ///< The current joystick state
+ JoystickCaps capabilities; ///< The joystick capabilities
+ };
+
+ ////////////////////////////////////////////////////////////
+ // Member data
+ ////////////////////////////////////////////////////////////
+ Item m_joysticks[Joystick::Count]; ///< Joysticks information and state
+};
+
+} // namespace priv
+
+} // namespace sf
+
+
+#endif // SFML_JOYSTICKMANAGER_HPP
diff --git a/src/SFML/Window/Keyboard.cpp b/src/SFML/Window/Keyboard.cpp
new file mode 100644
index 0000000..0d30f3c
--- /dev/null
+++ b/src/SFML/Window/Keyboard.cpp
@@ -0,0 +1,40 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/Keyboard.hpp>
+#include <SFML/Window/InputImpl.hpp>
+
+
+namespace sf
+{
+////////////////////////////////////////////////////////////
+bool Keyboard::isKeyPressed(Key key)
+{
+ return priv::InputImpl::isKeyPressed(key);
+}
+
+} // namespace sf
diff --git a/src/SFML/Window/Linux/Display.cpp b/src/SFML/Window/Linux/Display.cpp
new file mode 100644
index 0000000..557f8d6
--- /dev/null
+++ b/src/SFML/Window/Linux/Display.cpp
@@ -0,0 +1,65 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/Linux/Display.hpp>
+#include <cassert>
+
+
+namespace
+{
+ // The shared display and its reference counter
+ Display* sharedDisplay = NULL;
+ unsigned int referenceCount = 0;
+}
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+Display* OpenDisplay()
+{
+ if (referenceCount == 0)
+ sharedDisplay = XOpenDisplay(NULL);
+ referenceCount++;
+ return sharedDisplay;
+}
+
+
+////////////////////////////////////////////////////////////
+void CloseDisplay(Display* display)
+{
+ assert(display == sharedDisplay);
+
+ referenceCount--;
+ if (referenceCount == 0)
+ XCloseDisplay(display);
+}
+
+} // namespace priv
+
+} // namespace sf
diff --git a/src/SFML/Window/Linux/Display.hpp b/src/SFML/Window/Linux/Display.hpp
new file mode 100644
index 0000000..94bc98c
--- /dev/null
+++ b/src/SFML/Window/Linux/Display.hpp
@@ -0,0 +1,62 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_SHAREDDISPLAY_HPP
+#define SFML_SHAREDDISPLAY_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <X11/Xlib.h>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief Get the shared Display
+///
+/// This function increments the reference count of the display,
+/// it must be matched with a call to CloseDisplay.
+///
+/// \return Pointer to the shared display
+///
+////////////////////////////////////////////////////////////
+Display* OpenDisplay();
+
+////////////////////////////////////////////////////////////
+/// \brief Release a reference to the shared
+///
+/// \param display Display to release
+///
+////////////////////////////////////////////////////////////
+void CloseDisplay(Display* display);
+
+} // namespace priv
+
+} // namespace sf
+
+
+#endif // SFML_SHAREDDISPLAY_HPP
diff --git a/src/SFML/Window/Linux/GlxContext.cpp b/src/SFML/Window/Linux/GlxContext.cpp
new file mode 100644
index 0000000..6454d78
--- /dev/null
+++ b/src/SFML/Window/Linux/GlxContext.cpp
@@ -0,0 +1,343 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#define GLX_GLXEXT_LEGACY // so that our local glxext.h is used instead of the system one
+#include <SFML/Window/Linux/GlxContext.hpp>
+#include <SFML/Window/Linux/WindowImplX11.hpp>
+#include <SFML/Window/Linux/Display.hpp>
+#include <SFML/OpenGL.hpp>
+#include <SFML/Window/glext/glxext.h>
+#include <SFML/System/Err.hpp>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+GlxContext::GlxContext(GlxContext* shared) :
+m_window (0),
+m_context (NULL),
+m_ownsWindow(true)
+{
+ // Open a connection with the X server
+ m_display = OpenDisplay();
+
+ // Create a dummy window (disabled and hidden)
+ int screen = DefaultScreen(m_display);
+ m_window = XCreateWindow(m_display,
+ RootWindow(m_display, screen),
+ 0, 0,
+ 1, 1,
+ 0,
+ DefaultDepth(m_display, screen),
+ InputOutput,
+ DefaultVisual(m_display, screen),
+ 0, NULL);
+
+ // Create the context
+ createContext(shared, VideoMode::getDesktopMode().bitsPerPixel, ContextSettings());
+}
+
+
+////////////////////////////////////////////////////////////
+GlxContext::GlxContext(GlxContext* shared, const ContextSettings& settings, const WindowImpl* owner, unsigned int bitsPerPixel) :
+m_window (0),
+m_context (NULL),
+m_ownsWindow(false)
+{
+ // Open a connection with the X server
+ // (important: must be the same display as the owner window)
+ m_display = OpenDisplay();
+
+ // Get the owner window and its device context
+ m_window = static_cast< ::Window>(owner->getSystemHandle());
+
+ // Create the context
+ if (m_window)
+ createContext(shared, bitsPerPixel, settings);
+}
+
+
+////////////////////////////////////////////////////////////
+GlxContext::GlxContext(GlxContext* shared, const ContextSettings& settings, unsigned int width, unsigned int height) :
+m_window (0),
+m_context (NULL),
+m_ownsWindow(true)
+{
+ // Open a connection with the X server
+ m_display = OpenDisplay();
+
+ // Create the hidden window
+ int screen = DefaultScreen(m_display);
+ m_window = XCreateWindow(m_display,
+ RootWindow(m_display, screen),
+ 0, 0,
+ width, height,
+ 0,
+ DefaultDepth(m_display, screen),
+ InputOutput,
+ DefaultVisual(m_display, screen),
+ 0, NULL);
+
+ // Create the context
+ createContext(shared, VideoMode::getDesktopMode().bitsPerPixel, settings);
+}
+
+
+////////////////////////////////////////////////////////////
+GlxContext::~GlxContext()
+{
+ // Destroy the context
+ if (m_context)
+ {
+ if (glXGetCurrentContext() == m_context)
+ glXMakeCurrent(m_display, None, NULL);
+ glXDestroyContext(m_display, m_context);
+ }
+
+ // Destroy the window if we own it
+ if (m_window && m_ownsWindow)
+ {
+ XDestroyWindow(m_display, m_window);
+ XFlush(m_display);
+ }
+
+ // Close the connection with the X server
+ CloseDisplay(m_display);
+}
+
+
+////////////////////////////////////////////////////////////
+bool GlxContext::makeCurrent()
+{
+ return m_context && glXMakeCurrent(m_display, m_window, m_context);
+}
+
+
+////////////////////////////////////////////////////////////
+void GlxContext::display()
+{
+ if (m_window)
+ glXSwapBuffers(m_display, m_window);
+}
+
+
+////////////////////////////////////////////////////////////
+void GlxContext::setVerticalSyncEnabled(bool enabled)
+{
+ const GLubyte* name = reinterpret_cast<const GLubyte*>("glXSwapIntervalSGI");
+ PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalSGI = reinterpret_cast<PFNGLXSWAPINTERVALSGIPROC>(glXGetProcAddress(name));
+ if (glXSwapIntervalSGI)
+ glXSwapIntervalSGI(enabled ? 1 : 0);
+}
+
+
+////////////////////////////////////////////////////////////
+XVisualInfo GlxContext::selectBestVisual(::Display* display, unsigned int bitsPerPixel, const ContextSettings& settings)
+{
+ // Retrieve all the visuals
+ int count;
+ XVisualInfo* visuals = XGetVisualInfo(display, 0, NULL, &count);
+ if (visuals)
+ {
+ // Evaluate all the returned visuals, and pick the best one1
+ int bestScore = 0xFFFF;
+ XVisualInfo bestVisual;
+ for (int i = 0; i < count; ++i)
+ {
+ // Check mandatory attributes
+ int doubleBuffer;
+ glXGetConfig(display, &visuals[i], GLX_DOUBLEBUFFER, &doubleBuffer);
+ if (!doubleBuffer)
+ continue;
+
+ // Extract the components of the current visual
+ int red, green, blue, alpha, depth, stencil, multiSampling, samples;
+ glXGetConfig(display, &visuals[i], GLX_RED_SIZE, &red);
+ glXGetConfig(display, &visuals[i], GLX_GREEN_SIZE, &green);
+ glXGetConfig(display, &visuals[i], GLX_BLUE_SIZE, &blue);
+ glXGetConfig(display, &visuals[i], GLX_ALPHA_SIZE, &alpha);
+ glXGetConfig(display, &visuals[i], GLX_DEPTH_SIZE, &depth);
+ glXGetConfig(display, &visuals[i], GLX_STENCIL_SIZE, &stencil);
+ glXGetConfig(display, &visuals[i], GLX_SAMPLE_BUFFERS_ARB, &multiSampling);
+ glXGetConfig(display, &visuals[i], GLX_SAMPLES_ARB, &samples);
+
+ // Evaluate the visual
+ int color = red + green + blue + alpha;
+ int score = evaluateFormat(bitsPerPixel, settings, color, depth, stencil, multiSampling ? samples : 0);
+
+ // If it's better than the current best, make it the new best
+ if (score < bestScore)
+ {
+ bestScore = score;
+ bestVisual = visuals[i];
+ }
+ }
+
+ // Free the array of visuals
+ XFree(visuals);
+
+ return bestVisual;
+ }
+ else
+ {
+ // Should never happen...
+ err() << "No GLX visual found. You should check your graphics driver" << std::endl;
+
+ return XVisualInfo();
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void GlxContext::createContext(GlxContext* shared, unsigned int bitsPerPixel, const ContextSettings& settings)
+{
+ XVisualInfo* visualInfo = NULL;
+
+ // Save the creation settings
+ m_settings = settings;
+
+ // Get the context to share display lists with
+ GLXContext toShare = shared ? shared->m_context : NULL;
+
+ // Create the OpenGL context -- first try context versions >= 3.0 if it is requested (they require special code)
+ if (m_settings.majorVersion >= 3)
+ {
+ const GLubyte* name = reinterpret_cast<const GLubyte*>("glXCreateContextAttribsARB");
+ PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = reinterpret_cast<PFNGLXCREATECONTEXTATTRIBSARBPROC>(glXGetProcAddress(name));
+ if (glXCreateContextAttribsARB)
+ {
+ // Select a GLXFB config that matches the requested context settings
+ int nbConfigs = 0;
+ int fbAttributes[] =
+ {
+ GLX_DEPTH_SIZE, settings.depthBits,
+ GLX_STENCIL_SIZE, settings.stencilBits,
+ GLX_SAMPLE_BUFFERS, settings.antialiasingLevel > 0,
+ GLX_SAMPLES, settings.antialiasingLevel,
+ GLX_RED_SIZE, 8,
+ GLX_GREEN_SIZE, 8,
+ GLX_BLUE_SIZE, 8,
+ GLX_ALPHA_SIZE, bitsPerPixel == 32 ? 8 : 0,
+ GLX_DOUBLEBUFFER, True,
+ GLX_X_RENDERABLE, True,
+ GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
+ GLX_RENDER_TYPE, GLX_RGBA_BIT,
+ GLX_CONFIG_CAVEAT, GLX_NONE,
+ None
+ };
+ GLXFBConfig* configs = glXChooseFBConfig(m_display, DefaultScreen(m_display), fbAttributes, &nbConfigs);
+ if (configs && nbConfigs)
+ {
+ while (!m_context && (m_settings.majorVersion >= 3))
+ {
+ // Create the context
+ int attributes[] =
+ {
+ GLX_CONTEXT_MAJOR_VERSION_ARB, static_cast<int>(m_settings.majorVersion),
+ GLX_CONTEXT_MINOR_VERSION_ARB, static_cast<int>(m_settings.minorVersion),
+ GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB,
+ 0, 0
+ };
+ m_context = glXCreateContextAttribsARB(m_display, configs[0], toShare, true, attributes);
+
+ if (m_context)
+ {
+ // Ok: retrieve the config's visual
+ visualInfo = glXGetVisualFromFBConfig(m_display, configs[0]);
+ }
+ else
+ {
+ // If we couldn't create the context, lower the version number and try again -- stop at 3.0
+ // Invalid version numbers will be generated by this algorithm (like 3.9), but we really don't care
+ if (m_settings.minorVersion > 0)
+ {
+ // If the minor version is not 0, we decrease it and try again
+ m_settings.minorVersion--;
+ }
+ else
+ {
+ // If the minor version is 0, we decrease the major version
+ m_settings.majorVersion--;
+ m_settings.minorVersion = 9;
+ }
+ }
+ }
+ XFree(configs);
+ }
+ }
+ }
+
+ // If the OpenGL >= 3.0 context failed or if we don't want one, create a regular OpenGL 1.x/2.x context
+ if (!m_context)
+ {
+ // set the context version to 2.0 (arbitrary)
+ m_settings.majorVersion = 2;
+ m_settings.minorVersion = 0;
+
+ // Retrieve the attributes of the target window
+ XWindowAttributes windowAttributes;
+ if (XGetWindowAttributes(m_display, m_window, &windowAttributes) == 0)
+ {
+ err() << "Failed to get the window attributes" << std::endl;
+ return;
+ }
+
+ // Get its visual
+ XVisualInfo tpl;
+ tpl.screen = DefaultScreen(m_display);
+ tpl.visualid = XVisualIDFromVisual(windowAttributes.visual);
+ int nbVisuals = 0;
+ visualInfo = XGetVisualInfo(m_display, VisualIDMask | VisualScreenMask, &tpl, &nbVisuals);
+
+ // Create the context, using the target window's visual
+ m_context = glXCreateContext(m_display, visualInfo, toShare, true);
+ if (!m_context)
+ {
+ err() << "Failed to create an OpenGL context for this window" << std::endl;
+ return;
+ }
+ }
+
+ // Update the creation settings from the chosen format
+ int depth, stencil, multiSampling, samples;
+ glXGetConfig(m_display, visualInfo, GLX_DEPTH_SIZE, &depth);
+ glXGetConfig(m_display, visualInfo, GLX_STENCIL_SIZE, &stencil);
+ glXGetConfig(m_display, visualInfo, GLX_SAMPLE_BUFFERS_ARB, &multiSampling);
+ glXGetConfig(m_display, visualInfo, GLX_SAMPLES_ARB, &samples);
+ m_settings.depthBits = static_cast<unsigned int>(depth);
+ m_settings.stencilBits = static_cast<unsigned int>(stencil);
+ m_settings.antialiasingLevel = multiSampling ? samples : 0;
+
+ // Free the visual info
+ XFree(visualInfo);
+}
+
+} // namespace priv
+
+} // namespace sf
diff --git a/src/SFML/Window/Linux/GlxContext.hpp b/src/SFML/Window/Linux/GlxContext.hpp
new file mode 100644
index 0000000..493c858
--- /dev/null
+++ b/src/SFML/Window/Linux/GlxContext.hpp
@@ -0,0 +1,148 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_GLXCONTEXT_HPP
+#define SFML_GLXCONTEXT_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/GlContext.hpp>
+#include <X11/Xlib.h>
+#include <GL/glx.h>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief Linux (GLX) implementation of OpenGL contexts
+///
+////////////////////////////////////////////////////////////
+class GlxContext : public GlContext
+{
+public :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Create a new default context
+ ///
+ /// \param shared Context to share the new one with (can be NULL)
+ ///
+ ////////////////////////////////////////////////////////////
+ GlxContext(GlxContext* shared);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Create a new context attached to a window
+ ///
+ /// \param shared Context to share the new one with
+ /// \param settings Creation parameters
+ /// \param owner Pointer to the owner window
+ /// \param bitsPerPixel Pixel depth, in bits per pixel
+ ///
+ ////////////////////////////////////////////////////////////
+ GlxContext(GlxContext* shared, const ContextSettings& settings, const WindowImpl* owner, unsigned int bitsPerPixel);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Create a new context that embeds its own rendering target
+ ///
+ /// \param shared Context to share the new one with
+ /// \param settings Creation parameters
+ /// \param width Back buffer width, in pixels
+ /// \param height Back buffer height, in pixels
+ ///
+ ////////////////////////////////////////////////////////////
+ GlxContext(GlxContext* shared, const ContextSettings& settings, unsigned int width, unsigned int height);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Destructor
+ ///
+ ////////////////////////////////////////////////////////////
+ ~GlxContext();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Activate the context as the current target for rendering
+ ///
+ /// \return True on success, false if any error happened
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual bool makeCurrent();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Display what has been rendered to the context so far
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual void display();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Enable or disable vertical synchronization
+ ///
+ /// Activating vertical synchronization will limit the number
+ /// of frames displayed to the refresh rate of the monitor.
+ /// This can avoid some visual artifacts, and limit the framerate
+ /// to a good value (but not constant across different computers).
+ ///
+ /// \param enabled True to enable v-sync, false to deactivate
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual void setVerticalSyncEnabled(bool enabled);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Select the best GLX visual for a given set of settings
+ ///
+ /// \param display X display
+ /// \param bitsPerPixel Pixel depth, in bits per pixel
+ /// \param settings Requested context settings
+ ///
+ /// \return The best visual
+ ///
+ ////////////////////////////////////////////////////////////
+ static XVisualInfo selectBestVisual(::Display* display, unsigned int bitsPerPixel, const ContextSettings& settings);
+
+private :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Create the context
+ ///
+ /// \param shared Context to share the new one with (can be NULL)
+ /// \param bitsPerPixel Pixel depth, in bits per pixel
+ /// \param settings Creation parameters
+ ///
+ ////////////////////////////////////////////////////////////
+ void createContext(GlxContext* shared, unsigned int bitsPerPixel, const ContextSettings& settings);
+
+ ////////////////////////////////////////////////////////////
+ // Member data
+ ////////////////////////////////////////////////////////////
+ ::Display* m_display; ///< Connection to the X server
+ ::Window m_window; ///< Window to which the context is attached
+ GLXContext m_context; ///< OpenGL context
+ bool m_ownsWindow; ///< Do we own the window associated to the context?
+};
+
+} // namespace priv
+
+} // namespace sf
+
+#endif // SFML_GLXCONTEXT_HPP
diff --git a/src/SFML/Window/Linux/InputImpl.cpp b/src/SFML/Window/Linux/InputImpl.cpp
new file mode 100644
index 0000000..a9362ff
--- /dev/null
+++ b/src/SFML/Window/Linux/InputImpl.cpp
@@ -0,0 +1,293 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/Linux/InputImpl.hpp>
+#include <SFML/Window/Window.hpp>
+#include <SFML/Window/Linux/Display.hpp>
+#include <X11/Xlib.h>
+#include <X11/keysym.h>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+bool InputImpl::isKeyPressed(Keyboard::Key key)
+{
+ // Get the corresponding X11 keysym
+ KeySym keysym = 0;
+ switch (key)
+ {
+ case Keyboard::A: keysym = XK_A; break;
+ case Keyboard::B: keysym = XK_B; break;
+ case Keyboard::C: keysym = XK_C; break;
+ case Keyboard::D: keysym = XK_D; break;
+ case Keyboard::E: keysym = XK_E; break;
+ case Keyboard::F: keysym = XK_F; break;
+ case Keyboard::G: keysym = XK_G; break;
+ case Keyboard::H: keysym = XK_H; break;
+ case Keyboard::I: keysym = XK_I; break;
+ case Keyboard::J: keysym = XK_J; break;
+ case Keyboard::K: keysym = XK_K; break;
+ case Keyboard::L: keysym = XK_L; break;
+ case Keyboard::M: keysym = XK_M; break;
+ case Keyboard::N: keysym = XK_N; break;
+ case Keyboard::O: keysym = XK_O; break;
+ case Keyboard::P: keysym = XK_P; break;
+ case Keyboard::Q: keysym = XK_Q; break;
+ case Keyboard::R: keysym = XK_R; break;
+ case Keyboard::S: keysym = XK_S; break;
+ case Keyboard::T: keysym = XK_T; break;
+ case Keyboard::U: keysym = XK_U; break;
+ case Keyboard::V: keysym = XK_V; break;
+ case Keyboard::W: keysym = XK_W; break;
+ case Keyboard::X: keysym = XK_X; break;
+ case Keyboard::Y: keysym = XK_Y; break;
+ case Keyboard::Z: keysym = XK_Z; break;
+ case Keyboard::Num0: keysym = XK_0; break;
+ case Keyboard::Num1: keysym = XK_1; break;
+ case Keyboard::Num2: keysym = XK_2; break;
+ case Keyboard::Num3: keysym = XK_3; break;
+ case Keyboard::Num4: keysym = XK_4; break;
+ case Keyboard::Num5: keysym = XK_5; break;
+ case Keyboard::Num6: keysym = XK_6; break;
+ case Keyboard::Num7: keysym = XK_7; break;
+ case Keyboard::Num8: keysym = XK_8; break;
+ case Keyboard::Num9: keysym = XK_9; break;
+ case Keyboard::Escape: keysym = XK_Escape; break;
+ case Keyboard::LControl: keysym = XK_Control_L; break;
+ case Keyboard::LShift: keysym = XK_Shift_L; break;
+ case Keyboard::LAlt: keysym = XK_Alt_L; break;
+ case Keyboard::LSystem: keysym = XK_Super_L; break;
+ case Keyboard::RControl: keysym = XK_Control_R; break;
+ case Keyboard::RShift: keysym = XK_Shift_R; break;
+ case Keyboard::RAlt: keysym = XK_Alt_R; break;
+ case Keyboard::RSystem: keysym = XK_Super_R; break;
+ case Keyboard::Menu: keysym = XK_Menu; break;
+ case Keyboard::LBracket: keysym = XK_bracketleft; break;
+ case Keyboard::RBracket: keysym = XK_bracketright; break;
+ case Keyboard::SemiColon: keysym = XK_semicolon; break;
+ case Keyboard::Comma: keysym = XK_comma; break;
+ case Keyboard::Period: keysym = XK_period; break;
+ case Keyboard::Quote: keysym = XK_dead_acute; break;
+ case Keyboard::Slash: keysym = XK_slash; break;
+ case Keyboard::BackSlash: keysym = XK_backslash; break;
+ case Keyboard::Tilde: keysym = XK_dead_grave; break;
+ case Keyboard::Equal: keysym = XK_equal; break;
+ case Keyboard::Dash: keysym = XK_minus; break;
+ case Keyboard::Space: keysym = XK_space; break;
+ case Keyboard::Return: keysym = XK_Return; break;
+ case Keyboard::BackSpace: keysym = XK_BackSpace; break;
+ case Keyboard::Tab: keysym = XK_Tab; break;
+ case Keyboard::PageUp: keysym = XK_Prior; break;
+ case Keyboard::PageDown: keysym = XK_Next; break;
+ case Keyboard::End: keysym = XK_End; break;
+ case Keyboard::Home: keysym = XK_Home; break;
+ case Keyboard::Insert: keysym = XK_Insert; break;
+ case Keyboard::Delete: keysym = XK_Delete; break;
+ case Keyboard::Add: keysym = XK_KP_Add; break;
+ case Keyboard::Subtract: keysym = XK_KP_Subtract; break;
+ case Keyboard::Multiply: keysym = XK_KP_Multiply; break;
+ case Keyboard::Divide: keysym = XK_KP_Divide; break;
+ case Keyboard::Left: keysym = XK_Left; break;
+ case Keyboard::Right: keysym = XK_Right; break;
+ case Keyboard::Up: keysym = XK_Up; break;
+ case Keyboard::Down: keysym = XK_Down; break;
+ case Keyboard::Numpad0: keysym = XK_KP_0; break;
+ case Keyboard::Numpad1: keysym = XK_KP_1; break;
+ case Keyboard::Numpad2: keysym = XK_KP_2; break;
+ case Keyboard::Numpad3: keysym = XK_KP_3; break;
+ case Keyboard::Numpad4: keysym = XK_KP_4; break;
+ case Keyboard::Numpad5: keysym = XK_KP_5; break;
+ case Keyboard::Numpad6: keysym = XK_KP_6; break;
+ case Keyboard::Numpad7: keysym = XK_KP_7; break;
+ case Keyboard::Numpad8: keysym = XK_KP_8; break;
+ case Keyboard::Numpad9: keysym = XK_KP_9; break;
+ case Keyboard::F1: keysym = XK_F1; break;
+ case Keyboard::F2: keysym = XK_F2; break;
+ case Keyboard::F3: keysym = XK_F3; break;
+ case Keyboard::F4: keysym = XK_F4; break;
+ case Keyboard::F5: keysym = XK_F5; break;
+ case Keyboard::F6: keysym = XK_F6; break;
+ case Keyboard::F7: keysym = XK_F7; break;
+ case Keyboard::F8: keysym = XK_F8; break;
+ case Keyboard::F9: keysym = XK_F9; break;
+ case Keyboard::F10: keysym = XK_F10; break;
+ case Keyboard::F11: keysym = XK_F11; break;
+ case Keyboard::F12: keysym = XK_F12; break;
+ case Keyboard::F13: keysym = XK_F13; break;
+ case Keyboard::F14: keysym = XK_F14; break;
+ case Keyboard::F15: keysym = XK_F15; break;
+ case Keyboard::Pause: keysym = XK_Pause; break;
+ default: keysym = 0; break;
+ }
+
+ // Open a connection with the X server
+ Display* display = OpenDisplay();
+
+ // Convert to keycode
+ KeyCode keycode = XKeysymToKeycode(display, keysym);
+ if (keycode != 0)
+ {
+ // Get the whole keyboard state
+ char keys[32];
+ XQueryKeymap(display, keys);
+
+ // Close the connection with the X server
+ CloseDisplay(display);
+
+ // Check our keycode
+ return (keys[keycode / 8] & (1 << (keycode % 8))) != 0;
+ }
+ else
+ {
+ // Close the connection with the X server
+ CloseDisplay(display);
+
+ return false;
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+bool InputImpl::isMouseButtonPressed(Mouse::Button button)
+{
+ // Open a connection with the X server
+ Display* display = OpenDisplay();
+
+ // we don't care about these but they are required
+ ::Window root, child;
+ int wx, wy;
+ int gx, gy;
+
+ unsigned int buttons = 0;
+ XQueryPointer(display, DefaultRootWindow(display), &root, &child, &gx, &gy, &wx, &wy, &buttons);
+
+ // Close the connection with the X server
+ CloseDisplay(display);
+
+ switch (button)
+ {
+ case Mouse::Left: return buttons & Button1Mask;
+ case Mouse::Right: return buttons & Button3Mask;
+ case Mouse::Middle: return buttons & Button2Mask;
+ case Mouse::XButton1: return false; // not supported by X
+ case Mouse::XButton2: return false; // not supported by X
+ default: return false;
+ }
+
+ return false;
+}
+
+
+////////////////////////////////////////////////////////////
+Vector2i InputImpl::getMousePosition()
+{
+ // Open a connection with the X server
+ Display* display = OpenDisplay();
+
+ // we don't care about these but they are required
+ ::Window root, child;
+ int x, y;
+ unsigned int buttons;
+
+ int gx = 0;
+ int gy = 0;
+ XQueryPointer(display, DefaultRootWindow(display), &root, &child, &gx, &gy, &x, &y, &buttons);
+
+ // Close the connection with the X server
+ CloseDisplay(display);
+
+ return Vector2i(gx, gy);
+}
+
+
+////////////////////////////////////////////////////////////
+Vector2i InputImpl::getMousePosition(const Window& relativeTo)
+{
+ WindowHandle handle = relativeTo.getSystemHandle();
+ if (handle)
+ {
+ // Open a connection with the X server
+ Display* display = OpenDisplay();
+
+ // we don't care about these but they are required
+ ::Window root, child;
+ int gx, gy;
+ unsigned int buttons;
+
+ int x = 0;
+ int y = 0;
+ XQueryPointer(display, handle, &root, &child, &gx, &gy, &x, &y, &buttons);
+
+ // Close the connection with the X server
+ CloseDisplay(display);
+
+ return Vector2i(x, y);
+ }
+ else
+ {
+ return Vector2i();
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void InputImpl::setMousePosition(const Vector2i& position)
+{
+ // Open a connection with the X server
+ Display* display = OpenDisplay();
+
+ XWarpPointer(display, None, DefaultRootWindow(display), 0, 0, 0, 0, position.x, position.y);
+ XFlush(display);
+
+ // Close the connection with the X server
+ CloseDisplay(display);
+}
+
+
+////////////////////////////////////////////////////////////
+void InputImpl::setMousePosition(const Vector2i& position, const Window& relativeTo)
+{
+ // Open a connection with the X server
+ Display* display = OpenDisplay();
+
+ WindowHandle handle = relativeTo.getSystemHandle();
+ if (handle)
+ {
+ XWarpPointer(display, None, handle, 0, 0, 0, 0, position.x, position.y);
+ XFlush(display);
+ }
+
+ // Close the connection with the X server
+ CloseDisplay(display);
+}
+
+} // namespace priv
+
+} // namespace sf
diff --git a/src/SFML/Window/Linux/InputImpl.hpp b/src/SFML/Window/Linux/InputImpl.hpp
new file mode 100644
index 0000000..22ba5fd
--- /dev/null
+++ b/src/SFML/Window/Linux/InputImpl.hpp
@@ -0,0 +1,123 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_INPUTIMPLX11_HPP
+#define SFML_INPUTIMPLX11_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/Keyboard.hpp>
+#include <SFML/Window/Mouse.hpp>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief Linux (X11) implementation of inputs (keyboard + mouse)
+///
+////////////////////////////////////////////////////////////
+class InputImpl
+{
+public :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Check if a key is pressed
+ ///
+ /// \param key Key to check
+ ///
+ /// \return True if the key is pressed, false otherwise
+ ///
+ ////////////////////////////////////////////////////////////
+ static bool isKeyPressed(Keyboard::Key key);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Check if a mouse button is pressed
+ ///
+ /// \param button Button to check
+ ///
+ /// \return True if the button is pressed, false otherwise
+ ///
+ ////////////////////////////////////////////////////////////
+ static bool isMouseButtonPressed(Mouse::Button button);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Get the current position of the mouse in desktop coordinates
+ ///
+ /// This function returns the current position of the mouse
+ /// cursor, in global (desktop) coordinates.
+ ///
+ /// \return Current position of the mouse
+ ///
+ ////////////////////////////////////////////////////////////
+ static Vector2i getMousePosition();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Get the current position of the mouse in window coordinates
+ ///
+ /// This function returns the current position of the mouse
+ /// cursor, relative to the given window.
+ /// If no window is used, it returns desktop coordinates.
+ ///
+ /// \param relativeTo Reference window
+ ///
+ /// \return Current position of the mouse
+ ///
+ ////////////////////////////////////////////////////////////
+ static Vector2i getMousePosition(const Window& relativeTo);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Set the current position of the mouse in desktop coordinates
+ ///
+ /// This function sets the current position of the mouse
+ /// cursor in global (desktop) coordinates.
+ /// If no window is used, it sets the position in desktop coordinates.
+ ///
+ /// \param position New position of the mouse
+ ///
+ ////////////////////////////////////////////////////////////
+ static void setMousePosition(const Vector2i& position);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Set the current position of the mouse in window coordinates
+ ///
+ /// This function sets the current position of the mouse
+ /// cursor, relative to the given window.
+ /// If no window is used, it sets the position in desktop coordinates.
+ ///
+ /// \param position New position of the mouse
+ /// \param relativeTo Reference window
+ ///
+ ////////////////////////////////////////////////////////////
+ static void setMousePosition(const Vector2i& position, const Window& relativeTo);
+};
+
+} // namespace priv
+
+} // namespace sf
+
+
+#endif // SFML_INPUTIMPLX11_HPP
diff --git a/src/SFML/Window/Linux/Joystick.cpp b/src/SFML/Window/Linux/Joystick.cpp
deleted file mode 100755
index 829a741..0000000
--- a/src/SFML/Window/Linux/Joystick.cpp
+++ /dev/null
@@ -1,219 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Window/Joystick.hpp>
-#include <sstream>
-
-
-namespace sf
-{
-namespace priv
-{
-#if defined(SFML_SYSTEM_LINUX)
-
-////////////////////////////////////////////////////////////
-/// Initialize the instance and bind it to a physical joystick
-////////////////////////////////////////////////////////////
-void Joystick::Initialize(unsigned int Index)
-{
- // Initial state
- myNbButtons = 0;
- myPovX = 0;
- myPovY = 0;
- for (int i = 0; i < Joy::ButtonCount; ++i)
- {
- myState.Buttons[i] = false;
- }
- for (int i = 0; i < Joy::AxisCount; ++i)
- {
- myState.Axis[i] = 0.f;
- myAxes[i] = false;
- }
-
- // Open the joystick handle
- std::ostringstream oss;
- oss << "/dev/input/js" << Index;
- myDescriptor = open(oss.str().c_str(), O_RDONLY);
- if (myDescriptor > 0)
- {
- // Use non-blocking mode
- fcntl(myDescriptor, F_SETFL, O_NONBLOCK);
-
- // Get number of buttons
- char NbButtons;
- ioctl(myDescriptor, JSIOCGBUTTONS, &NbButtons);
- myNbButtons = NbButtons;
- if (myNbButtons > Joy::ButtonCount)
- myNbButtons = Joy::ButtonCount;
-
- // Get the supported axes
- char NbAxes;
- ioctl(myDescriptor, JSIOCGAXES, &NbAxes);
- ioctl(myDescriptor, JSIOCGAXMAP, myAxesMapping);
- for (int i = 0; i < NbAxes; ++i)
- {
- switch (myAxesMapping[i])
- {
- case ABS_X : myAxes[Joy::AxisX] = true; break;
- case ABS_Y : myAxes[Joy::AxisY] = true; break;
- case ABS_Z : case ABS_THROTTLE : myAxes[Joy::AxisZ] = true; break;
- case ABS_RZ: case ABS_RUDDER: myAxes[Joy::AxisR] = true; break;
- case ABS_RX : myAxes[Joy::AxisU] = true; break;
- case ABS_RY : myAxes[Joy::AxisV] = true; break;
- case ABS_HAT0X : case ABS_HAT0Y : myAxes[Joy::AxisPOV] = true; break;
- default : break;
- }
- }
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Update the current joystick and return its new state
-////////////////////////////////////////////////////////////
-JoystickState Joystick::UpdateState()
-{
- if (myDescriptor > 0)
- {
- js_event JoyState;
- while (read(myDescriptor, &JoyState, sizeof(JoyState)) > 0)
- {
- switch (JoyState.type & ~JS_EVENT_INIT)
- {
- // An axis has been moved
- case JS_EVENT_AXIS :
- {
- switch (myAxesMapping[JoyState.number])
- {
- case ABS_X : myState.Axis[Joy::AxisX] = JoyState.value * 100.f / 32767.f; break;
- case ABS_Y : myState.Axis[Joy::AxisY] = JoyState.value * 100.f / 32767.f; break;
- case ABS_Z : case ABS_THROTTLE : myState.Axis[Joy::AxisZ] = JoyState.value * 100.f / 32767.f; break;
- case ABS_RZ: case ABS_RUDDER: myState.Axis[Joy::AxisR] = JoyState.value * 100.f / 32767.f; break;
- case ABS_RX : myState.Axis[Joy::AxisU] = JoyState.value * 100.f / 32767.f; break;
- case ABS_RY : myState.Axis[Joy::AxisV] = JoyState.value * 100.f / 32767.f; break;
- case ABS_HAT0X : myPovX = JoyState.value; break;
- case ABS_HAT0Y : myPovY = JoyState.value; break;
- default : break;
- }
-
- // Compute the new POV angle
- if (myPovX > 0)
- {
- if (myPovY > 0) myState.Axis[Joy::AxisPOV] = 135.f;
- else if (myPovY < 0) myState.Axis[Joy::AxisPOV] = 45.f;
- else myState.Axis[Joy::AxisPOV] = 90.f;
- }
- else if (myPovX < 0)
- {
- if (myPovY > 0) myState.Axis[Joy::AxisPOV] = 225.f;
- else if (myPovY < 0) myState.Axis[Joy::AxisPOV] = 315.f;
- else myState.Axis[Joy::AxisPOV] = 270.f;
- }
- else
- {
- if (myPovY > 0) myState.Axis[Joy::AxisPOV] = 180.f;
- else if (myPovY < 0) myState.Axis[Joy::AxisPOV] = 0.f;
- else myState.Axis[Joy::AxisPOV] = -1.f;
- }
- break;
- }
-
- // A button has been pressed
- case JS_EVENT_BUTTON :
- {
- if (JoyState.number < GetButtonsCount())
- myState.Buttons[JoyState.number] = (JoyState.value != 0);
- break;
- }
- }
- }
- }
-
- return myState;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Check if the joystick supports the given axis
-////////////////////////////////////////////////////////////
-bool Joystick::HasAxis(Joy::Axis Axis) const
-{
- return myAxes[Axis];
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the number of buttons supported by the joystick
-////////////////////////////////////////////////////////////
-unsigned int Joystick::GetButtonsCount() const
-{
- return myNbButtons;
-}
-
-
-#elif defined(SFML_SYSTEM_FREEBSD)
-
-
-////////////////////////////////////////////////////////////
-/// Initialize the instance and bind it to a physical joystick
-////////////////////////////////////////////////////////////
-void Joystick::Initialize(unsigned int Index)
-{
-}
-
-
-////////////////////////////////////////////////////////////
-/// Update the current joystick and return its new state
-////////////////////////////////////////////////////////////
-JoystickState Joystick::UpdateState()
-{
- return JoystickState();
-}
-
-
-////////////////////////////////////////////////////////////
-/// Check if the joystick supports the given axis
-////////////////////////////////////////////////////////////
-bool Joystick::HasAxis(Joy::Axis Axis) const
-{
- return false;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the number of buttons supported by the joystick
-////////////////////////////////////////////////////////////
-unsigned int Joystick::GetButtonsCount() const
-{
- return 0;
-}
-
-#endif // defined(SFML_SYSTEM_FREEBSD)
-
-} // namespace priv
-
-} // namespace sf
diff --git a/src/SFML/Window/Linux/JoystickImpl.cpp b/src/SFML/Window/Linux/JoystickImpl.cpp
new file mode 100644
index 0000000..4db4b91
--- /dev/null
+++ b/src/SFML/Window/Linux/JoystickImpl.cpp
@@ -0,0 +1,256 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/JoystickImpl.hpp>
+#include <SFML/System/Err.hpp>
+#include <sys/inotify.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <errno.h>
+#include <cstdio>
+
+
+namespace
+{
+ int notifyFd = -1;
+ int inputFd = -1;
+ bool plugged[sf::Joystick::Count];
+
+ void updatePluggedList()
+ {
+ for (unsigned int i = 0; i < sf::Joystick::Count; ++i)
+ {
+ char name[32];
+ std::snprintf(name, sizeof(name), "/dev/input/js%u", i);
+ struct stat info;
+ plugged[i] = (stat(name, &info) == 0);
+ }
+ }
+
+ bool canRead(int descriptor)
+ {
+ fd_set set;
+ FD_ZERO(&set);
+ FD_SET(descriptor, &set);
+ timeval timeout = {0, 0};
+ return select(descriptor + 1, &set, NULL, NULL, &timeout) > 0 &&
+ FD_ISSET(notifyFd, &set);
+ }
+}
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+void JoystickImpl::initialize()
+{
+ // Reset the array of plugged joysticks
+ std::fill(plugged, plugged + Joystick::Count, false);
+
+ // Create the inotify instance
+ notifyFd = inotify_init();
+ if (notifyFd < 0)
+ {
+ err() << "Failed to initialize inotify, joystick connections and disconnections won't be notified" << std::endl;
+ return;
+ }
+
+ // Watch nodes created and deleted in the /dev/input directory
+ inputFd = inotify_add_watch(notifyFd, "/dev/input", IN_CREATE | IN_DELETE);
+ if (inputFd < 0)
+ {
+ err() << "Failed to initialize inotify, joystick connections and disconnections won't be notified" << std::endl;
+ return;
+ }
+
+ // Do an initial scan
+ updatePluggedList();
+}
+
+
+////////////////////////////////////////////////////////////
+void JoystickImpl::cleanup()
+{
+ // Stop watching the /dev/input directory
+ if (inputFd >= 0)
+ inotify_rm_watch(notifyFd, inputFd);
+
+ // Close the inotify file descriptor
+ if (inputFd >= 0)
+ ::close(notifyFd);
+}
+
+
+////////////////////////////////////////////////////////////
+bool JoystickImpl::isConnected(unsigned int index)
+{
+ // First check if new joysticks were added/removed since last update
+ if (canRead(notifyFd))
+ {
+ // Don't bother decomposing and interpreting the filename, just do a full scan
+ updatePluggedList();
+
+ // Flush all the pending events
+ while (canRead(notifyFd))
+ {
+ char buffer[128];
+ read(notifyFd, buffer, sizeof(buffer));
+ }
+ }
+
+ // Then check if the joystick is connected
+ return plugged[index];
+}
+
+
+////////////////////////////////////////////////////////////
+bool JoystickImpl::open(unsigned int index)
+{
+ if (plugged[index])
+ {
+ char name[32];
+ std::snprintf(name, sizeof(name), "/dev/input/js%u", index);
+
+ // Open the joystick's file descriptor (read-only and non-blocking)
+ m_file = ::open(name, O_RDONLY | O_NONBLOCK);
+ if (m_file >= 0)
+ {
+ // Retrieve the axes mapping
+ ioctl(m_file, JSIOCGAXMAP, m_mapping);
+
+ // Reset the joystick state
+ m_state = JoystickState();
+
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+ }
+ else
+ {
+ return false;
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void JoystickImpl::close()
+{
+ ::close(m_file);
+}
+
+
+////////////////////////////////////////////////////////////
+JoystickCaps JoystickImpl::getCapabilities() const
+{
+ JoystickCaps caps;
+
+ // Get the number of buttons
+ char buttonCount;
+ ioctl(m_file, JSIOCGBUTTONS, &buttonCount);
+ caps.buttonCount = buttonCount;
+ if (caps.buttonCount > Joystick::ButtonCount)
+ caps.buttonCount = Joystick::ButtonCount;
+
+ // Get the supported axes
+ char axesCount;
+ ioctl(m_file, JSIOCGAXES, &axesCount);
+ for (int i = 0; i < axesCount; ++i)
+ {
+ switch (m_mapping[i])
+ {
+ case ABS_X : caps.axes[Joystick::X] = true; break;
+ case ABS_Y : caps.axes[Joystick::Y] = true; break;
+ case ABS_Z :
+ case ABS_THROTTLE : caps.axes[Joystick::Z] = true; break;
+ case ABS_RZ:
+ case ABS_RUDDER: caps.axes[Joystick::R] = true; break;
+ case ABS_RX : caps.axes[Joystick::U] = true; break;
+ case ABS_RY : caps.axes[Joystick::V] = true; break;
+ case ABS_HAT0X : caps.axes[Joystick::PovX] = true; break;
+ case ABS_HAT0Y : caps.axes[Joystick::PovY] = true; break;
+ default : break;
+ }
+ }
+
+ return caps;
+}
+
+
+////////////////////////////////////////////////////////////
+JoystickState JoystickImpl::JoystickImpl::update()
+{
+ // pop events from the joystick file
+ js_event joyState;
+ while (read(m_file, &joyState, sizeof(joyState)) > 0)
+ {
+ switch (joyState.type & ~JS_EVENT_INIT)
+ {
+ // An axis was moved
+ case JS_EVENT_AXIS :
+ {
+ float value = joyState.value * 100.f / 32767.f;
+ switch (m_mapping[joyState.number])
+ {
+ case ABS_X : m_state.axes[Joystick::X] = value; break;
+ case ABS_Y : m_state.axes[Joystick::Y] = value; break;
+ case ABS_Z :
+ case ABS_THROTTLE : m_state.axes[Joystick::Z] = value; break;
+ case ABS_RZ:
+ case ABS_RUDDER: m_state.axes[Joystick::R] = value; break;
+ case ABS_RX : m_state.axes[Joystick::U] = value; break;
+ case ABS_RY : m_state.axes[Joystick::V] = value; break;
+ case ABS_HAT0X : m_state.axes[Joystick::PovX] = value; break;
+ case ABS_HAT0Y : m_state.axes[Joystick::PovY] = value; break;
+ default : break;
+ }
+ break;
+ }
+
+ // A button was pressed
+ case JS_EVENT_BUTTON :
+ {
+ if (joyState.number < Joystick::ButtonCount)
+ m_state.buttons[joyState.number] = (joyState.value != 0);
+ break;
+ }
+ }
+ }
+
+ // Check the connection state of the joystick (read() fails with an error != EGAIN if it's no longer connected)
+ m_state.connected = (errno == EAGAIN);
+
+ return m_state;
+}
+
+} // namespace priv
+
+} // namespace sf
diff --git a/src/SFML/Audio/SoundFileOgg.hpp b/src/SFML/Window/Linux/JoystickImpl.hpp
index 98f4799..869f185 100755..100644
--- a/src/SFML/Audio/SoundFileOgg.hpp
+++ b/src/SFML/Window/Linux/JoystickImpl.hpp
@@ -1,114 +1,121 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-#ifndef SFML_SOUNDFILEOGG_HPP
-#define SFML_SOUNDFILEOGG_HPP
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Audio/SoundFile.hpp>
-
-struct stb_vorbis;
-
-
-namespace sf
-{
-namespace priv
-{
-////////////////////////////////////////////////////////////
-/// Specialization of SoundFile that handles ogg-vorbis files (.ogg)
-/// (does not support variable bitrate / channels and writing)
-////////////////////////////////////////////////////////////
-class SoundFileOgg : public SoundFile
-{
-public :
-
- ////////////////////////////////////////////////////////////
- /// Default constructor
- ///
- ////////////////////////////////////////////////////////////
- SoundFileOgg();
-
- ////////////////////////////////////////////////////////////
- /// Destructor
- ///
- ////////////////////////////////////////////////////////////
- ~SoundFileOgg();
-
- ////////////////////////////////////////////////////////////
- /// Check if a given file is supported by this loader
- ///
- /// \param Filename : Path of the file to check
- /// \param Read : Is the file opened for reading or writing ?
- ///
- /// \param return True if the loader can handle this file
- ///
- ////////////////////////////////////////////////////////////
- static bool IsFileSupported(const std::string& Filename, bool Read);
-
- ////////////////////////////////////////////////////////////
- /// Check if a given file in memory is supported by this loader
- ///
- /// \param Data : Pointer to the file data in memory
- /// \param SizeInBytes : Size of the data to load, in bytes
- ///
- /// \param return True if the loader can handle this file
- ///
- ////////////////////////////////////////////////////////////
- static bool IsFileSupported(const char* Data, std::size_t SizeInBytes);
-
- ////////////////////////////////////////////////////////////
- /// /see sf::SoundFile::Read
- ///
- ////////////////////////////////////////////////////////////
- virtual std::size_t Read(Int16* Data, std::size_t NbSamples);
-
-private :
-
- ////////////////////////////////////////////////////////////
- /// /see sf::SoundFile::OpenRead
- ///
- ////////////////////////////////////////////////////////////
- virtual bool OpenRead(const std::string& Filename, std::size_t& NbSamples, unsigned int& ChannelsCount, unsigned int& SampleRate);
-
- ////////////////////////////////////////////////////////////
- /// /see sf::SoundFile::OpenRead
- ///
- ////////////////////////////////////////////////////////////
- virtual bool OpenRead(const char* Data, std::size_t SizeInBytes, std::size_t& NbSamples, unsigned int& ChannelsCount, unsigned int& SampleRate);
-
- ////////////////////////////////////////////////////////////
- // Member data
- ////////////////////////////////////////////////////////////
- stb_vorbis* myStream; ///< Vorbis stream
- unsigned int myChannelsCount; ///< Number of channels (1 = mono, 2 = stereo)
-};
-
-} // namespace priv
-
-} // namespace sf
-
-
-#endif // SFML_SOUNDFILEOGG_HPP
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_JOYSTICKIMPLLINUX_HPP
+#define SFML_JOYSTICKIMPLLINUX_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#if defined(SFML_SYSTEM_LINUX)
+ #include <linux/joystick.h>
+ #include <fcntl.h>
+#elif defined(SFML_SYSTEM_FREEBSD)
+ // #include <sys/joystick.h> ?
+ #define ABS_MAX 1
+#endif
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief Linux implementation of joysticks
+///
+////////////////////////////////////////////////////////////
+class JoystickImpl
+{
+public :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Perform the global initialization of the joystick module
+ ///
+ ////////////////////////////////////////////////////////////
+ static void initialize();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Perform the global cleanup of the joystick module
+ ///
+ ////////////////////////////////////////////////////////////
+ static void cleanup();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Check if a joystick is currently connected
+ ///
+ /// \param index Index of the joystick to check
+ ///
+ /// \return True if the joystick is connected, false otherwise
+ ///
+ ////////////////////////////////////////////////////////////
+ static bool isConnected(unsigned int index);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Open the joystick
+ ///
+ /// \param index Index assigned to the joystick
+ ///
+ /// \return True on success, false on failure
+ ///
+ ////////////////////////////////////////////////////////////
+ bool open(unsigned int index);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Close the joystick
+ ///
+ ////////////////////////////////////////////////////////////
+ void close();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Get the joystick capabilities
+ ///
+ /// \return Joystick capabilities
+ ///
+ ////////////////////////////////////////////////////////////
+ JoystickCaps getCapabilities() const;
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Update the joystick and get its new state
+ ///
+ /// \return Joystick state
+ ///
+ ////////////////////////////////////////////////////////////
+ JoystickState update();
+
+private :
+
+ ////////////////////////////////////////////////////////////
+ // Member data
+ ////////////////////////////////////////////////////////////
+ int m_file; ///< File descriptor of the joystick
+ char m_mapping[ABS_MAX + 1]; ///< Axes mapping (index to axis id)
+ JoystickState m_state; ///< Current state of the joystick
+};
+
+} // namespace priv
+
+} // namespace sf
+
+
+#endif // SFML_JOYSTICKIMPLLINUX_HPP
diff --git a/src/SFML/Window/Linux/VideoModeImpl.cpp b/src/SFML/Window/Linux/VideoModeImpl.cpp
new file mode 100644
index 0000000..c669a13
--- /dev/null
+++ b/src/SFML/Window/Linux/VideoModeImpl.cpp
@@ -0,0 +1,176 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/VideoModeImpl.hpp>
+#include <SFML/Window/Linux/Display.hpp>
+#include <SFML/System/Err.hpp>
+#include <X11/Xlib.h>
+#include <X11/extensions/Xrandr.h>
+#include <algorithm>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+std::vector<VideoMode> VideoModeImpl::getFullscreenModes()
+{
+ std::vector<VideoMode> modes;
+
+ // Open a connection with the X server
+ Display* display = OpenDisplay();
+ if (display)
+ {
+ // Retrieve the default screen number
+ int screen = DefaultScreen(display);
+
+ // Check if the XRandR extension is present
+ int version;
+ if (XQueryExtension(display, "RANDR", &version, &version, &version))
+ {
+ // Get the current configuration
+ XRRScreenConfiguration* config = XRRGetScreenInfo(display, RootWindow(display, screen));
+ if (config)
+ {
+ // Get the available screen sizes
+ int nbSizes;
+ XRRScreenSize* sizes = XRRConfigSizes(config, &nbSizes);
+ if (sizes && (nbSizes > 0))
+ {
+ // Get the list of supported depths
+ int nbDepths = 0;
+ int* depths = XListDepths(display, screen, &nbDepths);
+ if (depths && (nbDepths > 0))
+ {
+ // Combine depths and sizes to fill the array of supported modes
+ for (int i = 0; i < nbDepths; ++i)
+ {
+ for (int j = 0; j < nbSizes; ++j)
+ {
+ // Convert to VideoMode
+ VideoMode mode(sizes[j].width, sizes[j].height, depths[i]);
+
+ // Add it only if it is not already in the array
+ if (std::find(modes.begin(), modes.end(), mode) == modes.end())
+ modes.push_back(mode);
+ }
+ }
+
+ // Free the array of depths
+ XFree(depths);
+ }
+ }
+
+ // Free the configuration instance
+ XRRFreeScreenConfigInfo(config);
+ }
+ else
+ {
+ // Failed to get the screen configuration
+ err() << "Failed to retrieve the screen configuration while trying to get the supported video modes" << std::endl;
+ }
+ }
+ else
+ {
+ // XRandr extension is not supported : we cannot get the video modes
+ err() << "Failed to use the XRandR extension while trying to get the supported video modes" << std::endl;
+ }
+
+ // Close the connection with the X server
+ CloseDisplay(display);
+ }
+ else
+ {
+ // We couldn't connect to the X server
+ err() << "Failed to connect to the X server while trying to get the supported video modes" << std::endl;
+ }
+
+ return modes;
+}
+
+
+////////////////////////////////////////////////////////////
+VideoMode VideoModeImpl::getDesktopMode()
+{
+ VideoMode desktopMode;
+
+ // Open a connection with the X server
+ Display* display = OpenDisplay();
+ if (display)
+ {
+ // Retrieve the default screen number
+ int screen = DefaultScreen(display);
+
+ // Check if the XRandR extension is present
+ int version;
+ if (XQueryExtension(display, "RANDR", &version, &version, &version))
+ {
+ // Get the current configuration
+ XRRScreenConfiguration* config = XRRGetScreenInfo(display, RootWindow(display, screen));
+ if (config)
+ {
+ // Get the current video mode
+ Rotation currentRotation;
+ int currentMode = XRRConfigCurrentConfiguration(config, &currentRotation);
+
+ // Get the available screen sizes
+ int nbSizes;
+ XRRScreenSize* sizes = XRRConfigSizes(config, &nbSizes);
+ if (sizes && (nbSizes > 0))
+ desktopMode = VideoMode(sizes[currentMode].width, sizes[currentMode].height, DefaultDepth(display, screen));
+
+ // Free the configuration instance
+ XRRFreeScreenConfigInfo(config);
+ }
+ else
+ {
+ // Failed to get the screen configuration
+ err() << "Failed to retrieve the screen configuration while trying to get the desktop video modes" << std::endl;
+ }
+ }
+ else
+ {
+ // XRandr extension is not supported : we cannot get the video modes
+ err() << "Failed to use the XRandR extension while trying to get the desktop video modes" << std::endl;
+ }
+
+ // Close the connection with the X server
+ CloseDisplay(display);
+ }
+ else
+ {
+ // We couldn't connect to the X server
+ err() << "Failed to connect to the X server while trying to get the desktop video modes" << std::endl;
+ }
+
+ return desktopMode;
+}
+
+} // namespace priv
+
+} // namespace sf
diff --git a/src/SFML/Window/Linux/VideoModeSupport.cpp b/src/SFML/Window/Linux/VideoModeSupport.cpp
deleted file mode 100755
index add99b2..0000000
--- a/src/SFML/Window/Linux/VideoModeSupport.cpp
+++ /dev/null
@@ -1,144 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Window/Linux/VideoModeSupport.hpp>
-#include <SFML/Window/Linux/WindowImplX11.hpp>
-#include <X11/Xlib.h>
-#include <X11/extensions/Xrandr.h>
-#include <algorithm>
-#include <iostream>
-
-
-namespace sf
-{
-namespace priv
-{
-////////////////////////////////////////////////////////////
-/// Get supported video modes
-////////////////////////////////////////////////////////////
-void VideoModeSupport::GetSupportedVideoModes(std::vector<VideoMode>& Modes)
-{
- // First, clear array to fill
- Modes.clear();
-
- // Get the display and screen from WindowImplUnix
- WindowImplX11::OpenDisplay(false);
- Display* Disp = WindowImplX11::ourDisplay;
- int Screen = WindowImplX11::ourScreen;
-
- // Check if the XRandR extension is present
- int Version;
- if (XQueryExtension(Disp, "RANDR", &Version, &Version, &Version))
- {
- // Get the current configuration
- XRRScreenConfiguration* Config = XRRGetScreenInfo(Disp, RootWindow(Disp, Screen));
- if (Config)
- {
- // Get the available screen sizes
- int NbSizes;
- XRRScreenSize* Sizes = XRRConfigSizes(Config, &NbSizes);
- if (Sizes && (NbSizes > 0))
- {
- // Get the list of supported depths
- int NbDepths = 0;
- int* Depths = XListDepths(Disp, Screen, &NbDepths);
- if (Depths && (NbDepths > 0))
- {
- // Combine depths and sizes to fill the array of supported modes
- for (int i = 0; i < NbDepths; ++i)
- {
- for (int j = 0; j < NbSizes; ++j)
- {
- // Convert to VideoMode
- VideoMode Mode(Sizes[j].width, Sizes[j].height, Depths[i]);
-
- // Add it only if it is not already in the array
- if (std::find(Modes.begin(), Modes.end(), Mode) == Modes.end())
- Modes.push_back(Mode);
- }
- }
- }
- }
-
- // Free the configuration instance
- XRRFreeScreenConfigInfo(Config);
- }
- else
- {
- // Failed to get the screen configuration
- std::cerr << "Failed to get the list of available video modes" << std::endl;
- }
- }
- else
- {
- // XRandr extension is not supported : we cannot get the video modes
- std::cerr << "Failed to get the list of available video modes" << std::endl;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get current desktop video mode
-////////////////////////////////////////////////////////////
-VideoMode VideoModeSupport::GetDesktopVideoMode()
-{
- VideoMode DesktopMode;
-
- // Get the display and screen from WindowImplUnix
- WindowImplX11::OpenDisplay(false);
- Display* Disp = WindowImplX11::ourDisplay;
- int Screen = WindowImplX11::ourScreen;
-
- // Check if the XRandR extension is present
- int Version;
- if (XQueryExtension(Disp, "RANDR", &Version, &Version, &Version))
- {
- // Get the current configuration
- XRRScreenConfiguration* Config = XRRGetScreenInfo(Disp, RootWindow(Disp, Screen));
- if (Config)
- {
- // Get the current video mode
- Rotation CurrentRotation;
- int CurrentMode = XRRConfigCurrentConfiguration(Config, &CurrentRotation);
-
- // Get the available screen sizes
- int NbSizes;
- XRRScreenSize* Sizes = XRRConfigSizes(Config, &NbSizes);
- if (Sizes && (NbSizes > 0))
- DesktopMode = VideoMode(Sizes[CurrentMode].width, Sizes[CurrentMode].height, DefaultDepth(Disp, Screen));
-
- // Free the configuration instance
- XRRFreeScreenConfigInfo(Config);
- }
- }
-
- return DesktopMode;
-}
-
-} // namespace priv
-
-} // namespace sf
diff --git a/src/SFML/Window/Linux/VideoModeSupport.hpp b/src/SFML/Window/Linux/VideoModeSupport.hpp
deleted file mode 100755
index 9160ff5..0000000
--- a/src/SFML/Window/Linux/VideoModeSupport.hpp
+++ /dev/null
@@ -1,69 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-#ifndef SFML_VIDEOMODESUPPORTLINUX_HPP
-#define SFML_VIDEOMODESUPPORTLINUX_HPP
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Window/VideoMode.hpp>
-#include <vector>
-
-
-namespace sf
-{
-namespace priv
-{
-////////////////////////////////////////////////////////////
-/// Linux implementation of VideoModeSupport
-/// Give access to video mode related OS-specific functions
-////////////////////////////////////////////////////////////
-class VideoModeSupport
-{
-public :
-
- ////////////////////////////////////////////////////////////
- /// Get supported video modes
- ///
- /// \param Modes : Array to fill with available video modes
- ///
- ////////////////////////////////////////////////////////////
- static void GetSupportedVideoModes(std::vector<VideoMode>& Modes);
-
- ////////////////////////////////////////////////////////////
- /// Get current desktop video mode
- ///
- /// \return Current desktop video mode
- ///
- ////////////////////////////////////////////////////////////
- static VideoMode GetDesktopVideoMode();
-};
-
-} // namespace priv
-
-} // namespace sf
-
-
-#endif // SFML_VIDEOMODESUPPORTLINUX_HPP
diff --git a/src/SFML/Window/Linux/WindowImplX11.cpp b/src/SFML/Window/Linux/WindowImplX11.cpp
index edec19b..1b71210 100755..100644
--- a/src/SFML/Window/Linux/WindowImplX11.cpp
+++ b/src/SFML/Window/Linux/WindowImplX11.cpp
@@ -1,1249 +1,1002 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Window/WindowStyle.hpp> // important to be included first (conflict with None)
-#include <SFML/Window/Linux/WindowImplX11.hpp>
-#include <SFML/Window/glext/glxext.h>
-#include <SFML/Window/glext/glext.h>
-#include <SFML/System/Unicode.hpp>
-#include <X11/keysym.h>
-#include <X11/extensions/Xrandr.h>
-#include <iostream>
-#include <sstream>
-#include <vector>
-
-
-namespace
-{
- ////////////////////////////////////////////////////////////
- /// Filter the events received by windows
- /// (only allow those matching a specific window)
- ////////////////////////////////////////////////////////////
- Bool CheckEvent(::Display*, XEvent* Event, XPointer UserData)
- {
- // Just check if the event matches the window
- return Event->xany.window == reinterpret_cast< ::Window >(UserData);
- }
-}
-
-namespace sf
-{
-namespace priv
-{
-////////////////////////////////////////////////////////////
-// Static member data
-////////////////////////////////////////////////////////////
-Display* WindowImplX11::ourDisplay = NULL;
-int WindowImplX11::ourScreen = 0;
-WindowImplX11* WindowImplX11::ourFullscreenWindow = NULL;
-unsigned int WindowImplX11::ourWindowsCount = 0;
-XIM WindowImplX11::ourInputMethod = NULL;
-unsigned long WindowImplX11::ourEventMask = FocusChangeMask | ButtonPressMask | ButtonReleaseMask | ButtonMotionMask |
- PointerMotionMask | KeyPressMask | KeyReleaseMask | StructureNotifyMask |
- EnterWindowMask | LeaveWindowMask;
-
-
-////////////////////////////////////////////////////////////
-/// Default constructor
-/// (creates a dummy window to provide a valid OpenGL context)
-////////////////////////////////////////////////////////////
-WindowImplX11::WindowImplX11() :
-myWindow (0),
-myIsExternal (false),
-myGLContext (NULL),
-myAtomClose (0),
-myOldVideoMode(-1),
-myHiddenCursor(0),
-myInputContext(NULL),
-myKeyRepeat (true)
-{
- // Open the display at first call
- if (!OpenDisplay())
- return;
-
- // Use small dimensions
- myWidth = 1;
- myHeight = 1;
-
- // Create the rendering context
- XVisualInfo Visual;
- WindowSettings Params(0, 0, 0);
- if (!CreateContext(VideoMode(myWidth, myHeight, 32), Visual, Params))
- return;
-
- // Create a new color map with the chosen visual
- Colormap ColMap = XCreateColormap(ourDisplay, RootWindow(ourDisplay, ourScreen), Visual.visual, AllocNone);
-
- // Define the window attributes
- XSetWindowAttributes Attributes;
- Attributes.colormap = ColMap;
-
- // Create a dummy window (disabled and hidden)
- myWindow = XCreateWindow(ourDisplay,
- RootWindow(ourDisplay, ourScreen),
- 0, 0,
- myWidth, myHeight,
- 0,
- Visual.depth,
- InputOutput,
- Visual.visual,
- CWColormap, &Attributes);
-
- // Don't activate the dummy context by default
-}
-
-
-////////////////////////////////////////////////////////////
-/// Create the window implementation from an existing control
-////////////////////////////////////////////////////////////
-WindowImplX11::WindowImplX11(WindowHandle Handle, WindowSettings& Params) :
-myWindow (0),
-myIsExternal (true),
-myGLContext (NULL),
-myAtomClose (0),
-myOldVideoMode(-1),
-myHiddenCursor(0),
-myInputContext(NULL),
-myKeyRepeat (true)
-{
- // Open the display at first call
- if (!OpenDisplay())
- return;
-
- // Save the window handle
- myWindow = Handle;
-
- if (myWindow)
- {
- // Get the window size
- XWindowAttributes WindowAttributes;
- if (XGetWindowAttributes(ourDisplay, myWindow, &WindowAttributes) == 0)
- {
- std::cerr << "Failed to get the window attributes" << std::endl;
- return;
- }
- myWidth = WindowAttributes.width;
- myHeight = WindowAttributes.height;
-
- // Setup the visual infos to match
- XVisualInfo Template;
- Template.depth = WindowAttributes.depth;
- Template.visualid = XVisualIDFromVisual(WindowAttributes.visual);
- unsigned long Mask = VisualDepthMask | VisualIDMask;
-
- // Create the rendering context
- VideoMode Mode(myWidth, myHeight, VideoMode::GetDesktopMode().BitsPerPixel);
- XVisualInfo Visual;
- if (!CreateContext(Mode, Visual, Params, Template, Mask))
- return;
-
- // Create a new color map with the chosen visual
- Colormap ColMap = XCreateColormap(ourDisplay, RootWindow(ourDisplay, ourScreen), Visual.visual, AllocNone);
- XSetWindowColormap(ourDisplay, myWindow, ColMap);
-
- // Make sure the window is listening to all the requiered events
- XSelectInput(ourDisplay, myWindow, ourEventMask & ~ButtonPressMask);
-
- // Do some common initializations
- Initialize();
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Create the window implementation
-////////////////////////////////////////////////////////////
-WindowImplX11::WindowImplX11(VideoMode Mode, const std::string& Title, unsigned long WindowStyle, WindowSettings& Params) :
-myWindow (0),
-myIsExternal (false),
-myGLContext (NULL),
-myAtomClose (0),
-myOldVideoMode(-1),
-myHiddenCursor(0),
-myInputContext(NULL),
-myKeyRepeat (true)
-{
- // Open the display at first call
- if (!OpenDisplay())
- return;
-
- // Compute position and size
- int Left, Top;
- bool Fullscreen = (WindowStyle & Style::Fullscreen) != 0;
- if (!Fullscreen)
- {
- Left = (DisplayWidth(ourDisplay, ourScreen) - Mode.Width) / 2;
- Top = (DisplayHeight(ourDisplay, ourScreen) - Mode.Height) / 2;
- }
- else
- {
- Left = 0;
- Top = 0;
- }
- int Width = myWidth = Mode.Width;
- int Height = myHeight = Mode.Height;
-
- // Switch to fullscreen if necessary
- if (Fullscreen)
- SwitchToFullscreen(Mode);
-
- // Create the rendering context
- XVisualInfo Visual;
- if (!CreateContext(Mode, Visual, Params))
- return;
-
- // Create a new color map with the chosen visual
- Colormap ColMap = XCreateColormap(ourDisplay, RootWindow(ourDisplay, ourScreen), Visual.visual, AllocNone);
-
- // Define the window attributes
- XSetWindowAttributes Attributes;
- Attributes.event_mask = ourEventMask;
- Attributes.colormap = ColMap;
- Attributes.override_redirect = Fullscreen;
-
- // Create the window
- myWindow = XCreateWindow(ourDisplay,
- RootWindow(ourDisplay, ourScreen),
- Left, Top,
- Width, Height,
- 0,
- Visual.depth,
- InputOutput,
- Visual.visual,
- CWEventMask | CWColormap | CWOverrideRedirect, &Attributes);
- if (!myWindow)
- {
- std::cerr << "Failed to create window" << std::endl;
- return;
- }
-
- // Set the window's name
- XStoreName(ourDisplay, myWindow, Title.c_str());
-
- // Set the window's style (tell the windows manager to change our window's decorations and functions according to the requested style)
- if (!Fullscreen)
- {
- Atom WMHintsAtom = XInternAtom(ourDisplay, "_MOTIF_WM_HINTS", false);
- if (WMHintsAtom)
- {
- static const unsigned long MWM_HINTS_FUNCTIONS = 1 << 0;
- static const unsigned long MWM_HINTS_DECORATIONS = 1 << 1;
-
- //static const unsigned long MWM_DECOR_ALL = 1 << 0;
- static const unsigned long MWM_DECOR_BORDER = 1 << 1;
- static const unsigned long MWM_DECOR_RESIZEH = 1 << 2;
- static const unsigned long MWM_DECOR_TITLE = 1 << 3;
- static const unsigned long MWM_DECOR_MENU = 1 << 4;
- static const unsigned long MWM_DECOR_MINIMIZE = 1 << 5;
- static const unsigned long MWM_DECOR_MAXIMIZE = 1 << 6;
-
- //static const unsigned long MWM_FUNC_ALL = 1 << 0;
- static const unsigned long MWM_FUNC_RESIZE = 1 << 1;
- static const unsigned long MWM_FUNC_MOVE = 1 << 2;
- static const unsigned long MWM_FUNC_MINIMIZE = 1 << 3;
- static const unsigned long MWM_FUNC_MAXIMIZE = 1 << 4;
- static const unsigned long MWM_FUNC_CLOSE = 1 << 5;
-
- struct WMHints
- {
- unsigned long Flags;
- unsigned long Functions;
- unsigned long Decorations;
- long InputMode;
- unsigned long State;
- };
-
- WMHints Hints;
- Hints.Flags = MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS;
- Hints.Decorations = 0;
- Hints.Functions = 0;
-
- if (WindowStyle & Style::Titlebar)
- {
- Hints.Decorations |= MWM_DECOR_BORDER | MWM_DECOR_TITLE | MWM_DECOR_MINIMIZE | MWM_DECOR_MENU;
- Hints.Functions |= MWM_FUNC_MOVE | MWM_FUNC_MINIMIZE;
- }
- if (WindowStyle & Style::Resize)
- {
- Hints.Decorations |= MWM_DECOR_MAXIMIZE | MWM_DECOR_RESIZEH;
- Hints.Functions |= MWM_FUNC_MAXIMIZE | MWM_FUNC_RESIZE;
- }
- if (WindowStyle & Style::Close)
- {
- Hints.Decorations |= 0;
- Hints.Functions |= MWM_FUNC_CLOSE;
- }
-
- const unsigned char* HintsPtr = reinterpret_cast<const unsigned char*>(&Hints);
- XChangeProperty(ourDisplay, myWindow, WMHintsAtom, WMHintsAtom, 32, PropModeReplace, HintsPtr, 5);
- }
-
- // This is a hack to force some windows managers to disable resizing
- if (!(WindowStyle & Style::Resize))
- {
- XSizeHints XSizeHints;
- XSizeHints.flags = PMinSize | PMaxSize;
- XSizeHints.min_width = XSizeHints.max_width = Width;
- XSizeHints.min_height = XSizeHints.max_height = Height;
- XSetWMNormalHints(ourDisplay, myWindow, &XSizeHints);
- }
- }
-
- // Do some common initializations
- Initialize();
-
- // In fullscreen mode, we must grab keyboard and mouse inputs
- if (Fullscreen)
- {
- XGrabPointer(ourDisplay, myWindow, true, 0, GrabModeAsync, GrabModeAsync, myWindow, None, CurrentTime);
- XGrabKeyboard(ourDisplay, myWindow, true, GrabModeAsync, GrabModeAsync, CurrentTime);
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Destructor
-////////////////////////////////////////////////////////////
-WindowImplX11::~WindowImplX11()
-{
- // Cleanup graphical resources
- CleanUp();
-
- // Destroy the input context
- if (myInputContext)
- {
- XDestroyIC(myInputContext);
- }
-
- // Destroy the window
- if (myWindow && !myIsExternal)
- {
- XDestroyWindow(ourDisplay, myWindow);
- XFlush(ourDisplay);
- }
-
- // Close the display
- CloseDisplay();
-}
-
-
-////////////////////////////////////////////////////////////
-/// Check if there's an active context on the current thread
-////////////////////////////////////////////////////////////
-bool WindowImplX11::IsContextActive()
-{
- return glXGetCurrentContext() != NULL;
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see WindowImpl::Display
-////////////////////////////////////////////////////////////
-void WindowImplX11::Display()
-{
- if (myWindow && myGLContext)
- glXSwapBuffers(ourDisplay, myWindow);
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see WindowImpl::ProcessEvents
-////////////////////////////////////////////////////////////
-void WindowImplX11::ProcessEvents()
-{
- // This function implements a workaround to properly discard
- // repeated key events when necessary. The problem is that the
- // system's key events policy doesn't match SFML's one: X server will generate
- // both repeated KeyPress and KeyRelease events when maintaining a key down, while
- // SFML only wants repeated KeyPress events. Thus, we have to:
- // - Discard duplicated KeyRelease events when EnableKeyRepeat is true
- // - Discard both duplicated KeyPress and KeyRelease events when EnableKeyRepeat is false
-
-
- // Process any event in the queue matching our window
- XEvent Event;
- while (XCheckIfEvent(ourDisplay, &Event, &CheckEvent, reinterpret_cast<XPointer>(myWindow)))
- {
- // Detect repeated key events
- if ((Event.type == KeyPress) || (Event.type == KeyRelease))
- {
- if (Event.xkey.keycode < 256)
- {
- // To detect if it is a repeated key event, we check the current state of the key.
- // - If the state is "down", KeyReleased events must obviously be discarded.
- // - KeyPress events are a little bit harder to handle: they depend on the EnableKeyRepeat state,
- // and we need to properly forward the first one.
- char Keys[32];
- XQueryKeymap(ourDisplay, Keys);
- if (Keys[Event.xkey.keycode >> 3] & (1 << (Event.xkey.keycode % 8)))
- {
- // KeyRelease event + key down = repeated event --> discard
- if (Event.type == KeyRelease)
- {
- myLastKeyReleaseEvent = Event;
- continue;
- }
-
- // KeyPress event + key repeat disabled + matching KeyRelease event = repeated event --> discard
- if ((Event.type == KeyPress) && !myKeyRepeat &&
- (myLastKeyReleaseEvent.xkey.keycode == Event.xkey.keycode) &&
- (myLastKeyReleaseEvent.xkey.time == Event.xkey.time))
- {
- continue;
- }
- }
- }
- }
-
- // Process the event
- ProcessEvent(Event);
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see WindowImpl::SetActive
-////////////////////////////////////////////////////////////
-void WindowImplX11::SetActive(bool Active) const
-{
- if (Active)
- {
- if (myWindow && myGLContext && (glXGetCurrentContext() != myGLContext))
- glXMakeCurrent(ourDisplay, myWindow, myGLContext);
- }
- else
- {
- if (glXGetCurrentContext() == myGLContext)
- glXMakeCurrent(ourDisplay, None, NULL);
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see WindowImpl::UseVerticalSync
-////////////////////////////////////////////////////////////
-void WindowImplX11::UseVerticalSync(bool Enabled)
-{
- const GLubyte* ProcAddress = reinterpret_cast<const GLubyte*>("glXSwapIntervalSGI");
- PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalSGI = reinterpret_cast<PFNGLXSWAPINTERVALSGIPROC>(glXGetProcAddress(ProcAddress));
- if (glXSwapIntervalSGI)
- glXSwapIntervalSGI(Enabled ? 1 : 0);
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see WindowImpl::ShowMouseCursor
-////////////////////////////////////////////////////////////
-void WindowImplX11::ShowMouseCursor(bool Show)
-{
- XDefineCursor(ourDisplay, myWindow, Show ? None : myHiddenCursor);
- XFlush(ourDisplay);
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see sfWindowImpl::SetCursorPosition
-////////////////////////////////////////////////////////////
-void WindowImplX11::SetCursorPosition(unsigned int Left, unsigned int Top)
-{
- XWarpPointer(ourDisplay, None, myWindow, 0, 0, 0, 0, Left, Top);
- XFlush(ourDisplay);
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see sfWindowImpl::SetPosition
-////////////////////////////////////////////////////////////
-void WindowImplX11::SetPosition(int Left, int Top)
-{
- XMoveWindow(ourDisplay, myWindow, Left, Top);
- XFlush(ourDisplay);
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see WindowImpl::SetSize
-////////////////////////////////////////////////////////////
-void WindowImplX11::SetSize(unsigned int Width, unsigned int Height)
-{
- XResizeWindow(ourDisplay, myWindow, Width, Height);
- XFlush(ourDisplay);
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see sfWindowImpl::Show
-////////////////////////////////////////////////////////////
-void WindowImplX11::Show(bool State)
-{
- if (State)
- XMapWindow(ourDisplay, myWindow);
- else
- XUnmapWindow(ourDisplay, myWindow);
-
- XFlush(ourDisplay);
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see sfWindowImpl::EnableKeyRepeat
-////////////////////////////////////////////////////////////
-void WindowImplX11::EnableKeyRepeat(bool Enabled)
-{
- myKeyRepeat = Enabled;
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see WindowImpl::SetIcon
-////////////////////////////////////////////////////////////
-void WindowImplX11::SetIcon(unsigned int Width, unsigned int Height, const Uint8* Pixels)
-{
- // X11 wants BGRA pixels : swap red and blue channels
- // Note : this memory will never be freed, but it seems to cause a bug on exit if I do so
- Uint8* IconPixels = new Uint8[Width * Height * 4];
- for (std::size_t i = 0; i < Width * Height; ++i)
- {
- IconPixels[i * 4 + 0] = Pixels[i * 4 + 2];
- IconPixels[i * 4 + 1] = Pixels[i * 4 + 1];
- IconPixels[i * 4 + 2] = Pixels[i * 4 + 0];
- IconPixels[i * 4 + 3] = Pixels[i * 4 + 3];
- }
-
- // Create the icon pixmap
- Visual* DefVisual = DefaultVisual(ourDisplay, ourScreen);
- unsigned int DefDepth = DefaultDepth(ourDisplay, ourScreen);
- XImage* IconImage = XCreateImage(ourDisplay, DefVisual, DefDepth, ZPixmap, 0, (char*)IconPixels, Width, Height, 32, 0);
- if (!IconImage)
- {
- std::cerr << "Failed to set the window's icon" << std::endl;
- return;
- }
- Pixmap IconPixmap = XCreatePixmap(ourDisplay, RootWindow(ourDisplay, ourScreen), Width, Height, DefDepth);
- XGCValues Values;
- GC IconGC = XCreateGC(ourDisplay, IconPixmap, 0, &Values);
- XPutImage(ourDisplay, IconPixmap, IconGC, IconImage, 0, 0, 0, 0, Width, Height);
- XFreeGC(ourDisplay, IconGC);
- XDestroyImage(IconImage);
-
- // Create the mask pixmap (must have 1 bit depth)
- std::size_t Pitch = (Width + 7) / 8;
- static std::vector<Uint8> MaskPixels(Pitch * Height, 0);
- for (std::size_t j = 0; j < Height; ++j)
- {
- for (std::size_t i = 0; i < Pitch; ++i)
- {
- for (std::size_t k = 0; k < 8; ++k)
- {
- if (i * 8 + k < Width)
- {
- Uint8 Opacity = (Pixels[(i * 8 + k + j * Width) * 4 + 3] > 0) ? 1 : 0;
- MaskPixels[i + j * Pitch] |= (Opacity << k);
- }
- }
- }
- }
- Pixmap MaskPixmap = XCreatePixmapFromBitmapData(ourDisplay, myWindow, (char*)&MaskPixels[0], Width, Height, 1, 0, 1);
-
- // Send our new icon to the window through the WMHints
- XWMHints* Hints = XAllocWMHints();
- Hints->flags = IconPixmapHint | IconMaskHint;
- Hints->icon_pixmap = IconPixmap;
- Hints->icon_mask = MaskPixmap;
- XSetWMHints(ourDisplay, myWindow, Hints);
- XFree(Hints);
-
- XFlush(ourDisplay);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Switch to fullscreen mode
-////////////////////////////////////////////////////////////
-void WindowImplX11::SwitchToFullscreen(const VideoMode& Mode)
-{
- // Check if the XRandR extension is present
- int Version;
- if (XQueryExtension(ourDisplay, "RANDR", &Version, &Version, &Version))
- {
- // Get the current configuration
- XRRScreenConfiguration* Config = XRRGetScreenInfo(ourDisplay, RootWindow(ourDisplay, ourScreen));
- if (Config)
- {
- // Get the current rotation
- Rotation CurrentRotation;
- myOldVideoMode = XRRConfigCurrentConfiguration(Config, &CurrentRotation);
-
- // Get the available screen sizes
- int NbSizes;
- XRRScreenSize* Sizes = XRRConfigSizes(Config, &NbSizes);
- if (Sizes && (NbSizes > 0))
- {
- // Search a matching size
- for (int i = 0; i < NbSizes; ++i)
- {
- if ((Sizes[i].width == static_cast<int>(Mode.Width)) && (Sizes[i].height == static_cast<int>(Mode.Height)))
- {
- // Switch to fullscreen mode
- XRRSetScreenConfig(ourDisplay, Config, RootWindow(ourDisplay, ourScreen), i, CurrentRotation, CurrentTime);
-
- // Set "this" as the current fullscreen window
- ourFullscreenWindow = this;
- break;
- }
- }
- }
-
- // Free the configuration instance
- XRRFreeScreenConfigInfo(Config);
- }
- else
- {
- // Failed to get the screen configuration
- std::cerr << "Failed to get the current screen configuration for fullscreen mode, switching to windiw mode" << std::endl;
- }
- }
- else
- {
- // XRandr extension is not supported : we cannot use fullscreen mode
- std::cerr << "Fullscreen is not supported, switching to window mode" << std::endl;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Create the OpenGL rendering context
-////////////////////////////////////////////////////////////
-bool WindowImplX11::CreateContext(const VideoMode& Mode, XVisualInfo& ChosenVisual, WindowSettings& Params, XVisualInfo Template, unsigned long Mask)
-{
- // Get all the visuals matching the template
- Template.screen = ourScreen;
- int NbVisuals = 0;
- XVisualInfo* Visuals = XGetVisualInfo(ourDisplay, Mask | VisualScreenMask, &Template, &NbVisuals);
- if (!Visuals || (NbVisuals == 0))
- {
- if (Visuals)
- XFree(Visuals);
- std::cerr << "There is no valid visual for the selected screen" << std::endl;
- return false;
- }
-
- // Find the best visual
- int BestScore = 0xFFFF;
- XVisualInfo* BestVisual = NULL;
- while (!BestVisual)
- {
- for (int i = 0; i < NbVisuals; ++i)
- {
- // Get the current visual attributes
- int RGBA, DoubleBuffer, Red, Green, Blue, Alpha, Depth, Stencil, MultiSampling, Samples;
- glXGetConfig(ourDisplay, &Visuals[i], GLX_RGBA, &RGBA);
- glXGetConfig(ourDisplay, &Visuals[i], GLX_DOUBLEBUFFER, &DoubleBuffer);
- glXGetConfig(ourDisplay, &Visuals[i], GLX_RED_SIZE, &Red);
- glXGetConfig(ourDisplay, &Visuals[i], GLX_GREEN_SIZE, &Green);
- glXGetConfig(ourDisplay, &Visuals[i], GLX_BLUE_SIZE, &Blue);
- glXGetConfig(ourDisplay, &Visuals[i], GLX_ALPHA_SIZE, &Alpha);
- glXGetConfig(ourDisplay, &Visuals[i], GLX_DEPTH_SIZE, &Depth);
- glXGetConfig(ourDisplay, &Visuals[i], GLX_STENCIL_SIZE, &Stencil);
- glXGetConfig(ourDisplay, &Visuals[i], GLX_SAMPLE_BUFFERS_ARB, &MultiSampling);
- glXGetConfig(ourDisplay, &Visuals[i], GLX_SAMPLES_ARB, &Samples);
-
- // First check the mandatory parameters
- if ((RGBA == 0) || (DoubleBuffer == 0))
- continue;
-
- // Evaluate the current configuration
- int Color = Red + Green + Blue + Alpha;
- int Score = EvaluateConfig(Mode, Params, Color, Depth, Stencil, MultiSampling ? Samples : 0);
-
- // Keep it if it's better than the current best
- if (Score < BestScore)
- {
- BestScore = Score;
- BestVisual = &Visuals[i];
- }
- }
-
- // If no visual has been found, try a lower level of antialiasing
- if (!BestVisual)
- {
- if (Params.AntialiasingLevel > 2)
- {
- std::cerr << "Failed to find a pixel format supporting "
- << Params.AntialiasingLevel << " antialiasing levels ; trying with 2 levels" << std::endl;
- Params.AntialiasingLevel = 2;
- }
- else if (Params.AntialiasingLevel > 0)
- {
- std::cerr << "Failed to find a pixel format supporting antialiasing ; antialiasing will be disabled" << std::endl;
- Params.AntialiasingLevel = 0;
- }
- else
- {
- std::cerr << "Failed to find a suitable pixel format for the window -- cannot create OpenGL context" << std::endl;
- return false;
- }
- }
- }
-
- // Create the OpenGL context
- myGLContext = glXCreateContext(ourDisplay, BestVisual, glXGetCurrentContext(), true);
- if (myGLContext == NULL)
- {
- std::cerr << "Failed to create an OpenGL context for this window" << std::endl;
- return false;
- }
-
- // Update the creation settings from the chosen format
- int Depth, Stencil;
- glXGetConfig(ourDisplay, BestVisual, GLX_DEPTH_SIZE, &Depth);
- glXGetConfig(ourDisplay, BestVisual, GLX_STENCIL_SIZE, &Stencil);
- Params.DepthBits = static_cast<unsigned int>(Depth);
- Params.StencilBits = static_cast<unsigned int>(Stencil);
-
- // Assign the chosen visual, and free the temporary visuals array
- ChosenVisual = *BestVisual;
- XFree(Visuals);
-
- // Activate the context
- SetActive(true);
-
- // Enable multisampling if needed
- if (Params.AntialiasingLevel > 0)
- glEnable(GL_MULTISAMPLE_ARB);
-
- return true;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Do some common initializations after the window has been created
-////////////////////////////////////////////////////////////
-void WindowImplX11::Initialize()
-{
- // Make sure the "last key release" is initialized with invalid values
- myLastKeyReleaseEvent.type = -1;
-
- // Get the atom defining the close event
- myAtomClose = XInternAtom(ourDisplay, "WM_DELETE_WINDOW", false);
- XSetWMProtocols(ourDisplay, myWindow, &myAtomClose, 1);
-
- // Create the input context
- if (ourInputMethod)
- {
- myInputContext = XCreateIC(ourInputMethod,
- XNClientWindow, myWindow,
- XNFocusWindow, myWindow,
- XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
- NULL);
-
- if (!myInputContext)
- std::cerr << "Failed to create input context for window -- TextEntered event won't be able to return unicode" << std::endl;
- }
-
- // Show the window
- XMapWindow(ourDisplay, myWindow);
- XFlush(ourDisplay);
-
- // Create the hiden cursor
- CreateHiddenCursor();
-
- // Set our context as the current OpenGL context for rendering
- SetActive();
-
- // Flush the commands queue
- XFlush(ourDisplay);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Create a transparent mouse cursor
-////////////////////////////////////////////////////////////
-void WindowImplX11::CreateHiddenCursor()
-{
- // Create the cursor's pixmap (1x1 pixels)
- Pixmap CursorPixmap = XCreatePixmap(ourDisplay, myWindow, 1, 1, 1);
- GC GraphicsContext = XCreateGC(ourDisplay, CursorPixmap, 0, NULL);
- XDrawPoint(ourDisplay, CursorPixmap, GraphicsContext, 0, 0);
- XFreeGC(ourDisplay, GraphicsContext);
-
- // Create the cursor, using the pixmap as both the shape and the mask of the cursor
- XColor Color;
- Color.flags = DoRed | DoGreen | DoBlue;
- Color.red = Color.blue = Color.green = 0;
- myHiddenCursor = XCreatePixmapCursor(ourDisplay, CursorPixmap, CursorPixmap, &Color, &Color, 0, 0);
-
- // We don't need the pixmap any longer, free it
- XFreePixmap(ourDisplay, CursorPixmap);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Cleanup graphical resources attached to the window
-////////////////////////////////////////////////////////////
-void WindowImplX11::CleanUp()
-{
- // Restore the previous video mode (in case we were running in fullscreen)
- if (ourFullscreenWindow == this)
- {
- // Get current screen info
- XRRScreenConfiguration* Config = XRRGetScreenInfo(ourDisplay, RootWindow(ourDisplay, ourScreen));
- if (Config)
- {
- // Get the current rotation
- Rotation CurrentRotation;
- XRRConfigCurrentConfiguration(Config, &CurrentRotation);
-
- // Reset the video mode
- XRRSetScreenConfig(ourDisplay, Config, RootWindow(ourDisplay, ourScreen), myOldVideoMode, CurrentRotation, CurrentTime);
-
- // Free the configuration instance
- XRRFreeScreenConfigInfo(Config);
- }
-
- // Reset the fullscreen window
- ourFullscreenWindow = NULL;
- }
-
- // Unhide the mouse cursor (in case it was hidden)
- ShowMouseCursor(true);
-
- // Destroy the OpenGL context
- if (myGLContext)
- {
- glXDestroyContext(ourDisplay, myGLContext);
- myGLContext = NULL;
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Process an incoming event from the window
-////////////////////////////////////////////////////////////
-void WindowImplX11::ProcessEvent(XEvent WinEvent)
-{
- switch (WinEvent.type)
- {
- // Destroy event
- case DestroyNotify :
- {
- // The window is about to be destroyed : we must cleanup resources
- CleanUp();
- break;
- }
-
- // Gain focus event
- case FocusIn :
- {
- // Update the input context
- if (myInputContext)
- XSetICFocus(myInputContext);
-
- Event Evt;
- Evt.Type = Event::GainedFocus;
- SendEvent(Evt);
- break;
- }
-
- // Lost focus event
- case FocusOut :
- {
- // Update the input context
- if (myInputContext)
- XUnsetICFocus(myInputContext);
-
- Event Evt;
- Evt.Type = Event::LostFocus;
- SendEvent(Evt);
- break;
- }
-
- // Resize event
- case ConfigureNotify :
- {
- if ((WinEvent.xconfigure.width != static_cast<int>(myWidth)) || (WinEvent.xconfigure.height != static_cast<int>(myHeight)))
- {
- myWidth = WinEvent.xconfigure.width;
- myHeight = WinEvent.xconfigure.height;
-
- Event Evt;
- Evt.Type = Event::Resized;
- Evt.Size.Width = myWidth;
- Evt.Size.Height = myHeight;
- SendEvent(Evt);
- }
- break;
- }
-
- // Close event
- case ClientMessage :
- {
- if ((WinEvent.xclient.format == 32) && (WinEvent.xclient.data.l[0]) == static_cast<long>(myAtomClose))
- {
- Event Evt;
- Evt.Type = Event::Closed;
- SendEvent(Evt);
- }
- break;
- }
-
- // Key down event
- case KeyPress :
- {
- // Get the keysym of the key that has been pressed
- static XComposeStatus KeyboardStatus;
- char Buffer[32];
- KeySym Sym;
- XLookupString(&WinEvent.xkey, Buffer, sizeof(Buffer), &Sym, &KeyboardStatus);
-
- // Fill the event parameters
- Event Evt;
- Evt.Type = Event::KeyPressed;
- Evt.Key.Code = KeysymToSF(Sym);
- Evt.Key.Alt = WinEvent.xkey.state & Mod1Mask;
- Evt.Key.Control = WinEvent.xkey.state & ControlMask;
- Evt.Key.Shift = WinEvent.xkey.state & ShiftMask;
- SendEvent(Evt);
-
- // Generate a TextEntered event
- if (!XFilterEvent(&WinEvent, None))
- {
- #ifdef X_HAVE_UTF8_STRING
- if (myInputContext)
- {
- Status ReturnedStatus;
- Uint8 KeyBuffer[16];
- int Length = Xutf8LookupString(myInputContext, &WinEvent.xkey, reinterpret_cast<char*>(KeyBuffer), sizeof(KeyBuffer), NULL, &ReturnedStatus);
- if (Length > 0)
- {
- Uint32 Unicode[2]; // just in case, but 1 character should be enough
- const Uint32* End = Unicode::UTF8ToUTF32(KeyBuffer, KeyBuffer + Length, Unicode);
-
- if (End > Unicode)
- {
- Event TextEvt;
- TextEvt.Type = Event::TextEntered;
- TextEvt.Text.Unicode = Unicode[0];
- SendEvent(TextEvt);
- }
- }
- }
- else
- #endif
- {
- static XComposeStatus ComposeStatus;
- char KeyBuffer[16];
- if (XLookupString(&WinEvent.xkey, KeyBuffer, sizeof(KeyBuffer), NULL, &ComposeStatus))
- {
- Event TextEvt;
- TextEvt.Type = Event::TextEntered;
- TextEvt.Text.Unicode = static_cast<Uint32>(KeyBuffer[0]);
- SendEvent(TextEvt);
- }
- }
- }
-
- break;
- }
-
- // Key up event
- case KeyRelease :
- {
- // Get the keysym of the key that has been pressed
- char Buffer[32];
- KeySym Sym;
- XLookupString(&WinEvent.xkey, Buffer, 32, &Sym, NULL);
-
- // Fill the event parameters
- Event Evt;
- Evt.Type = Event::KeyReleased;
- Evt.Key.Code = KeysymToSF(Sym);
- Evt.Key.Alt = WinEvent.xkey.state & Mod1Mask;
- Evt.Key.Control = WinEvent.xkey.state & ControlMask;
- Evt.Key.Shift = WinEvent.xkey.state & ShiftMask;
-
- SendEvent(Evt);
- break;
- }
-
- // Mouse button pressed
- case ButtonPress :
- {
- unsigned int Button = WinEvent.xbutton.button;
- if ((Button == Button1) || (Button == Button2) || (Button == Button3) || (Button == 8) || (Button == 9))
- {
- Event Evt;
- Evt.Type = Event::MouseButtonPressed;
- Evt.MouseButton.X = WinEvent.xbutton.x;
- Evt.MouseButton.Y = WinEvent.xbutton.y;
- switch (Button)
- {
- case Button1 : Evt.MouseButton.Button = Mouse::Left; break;
- case Button2 : Evt.MouseButton.Button = Mouse::Middle; break;
- case Button3 : Evt.MouseButton.Button = Mouse::Right; break;
- case 8 : Evt.MouseButton.Button = Mouse::XButton1; break;
- case 9 : Evt.MouseButton.Button = Mouse::XButton2; break;
- }
- SendEvent(Evt);
- }
- break;
- }
-
- // Mouse button released
- case ButtonRelease :
- {
- unsigned int Button = WinEvent.xbutton.button;
- if ((Button == Button1) || (Button == Button2) || (Button == Button3) || (Button == 8) || (Button == 9))
- {
- Event Evt;
- Evt.Type = Event::MouseButtonReleased;
- Evt.MouseButton.X = WinEvent.xbutton.x;
- Evt.MouseButton.Y = WinEvent.xbutton.y;
- switch (Button)
- {
- case Button1 : Evt.MouseButton.Button = Mouse::Left; break;
- case Button2 : Evt.MouseButton.Button = Mouse::Middle; break;
- case Button3 : Evt.MouseButton.Button = Mouse::Right; break;
- case 8 : Evt.MouseButton.Button = Mouse::XButton1; break;
- case 9 : Evt.MouseButton.Button = Mouse::XButton2; break;
- }
- SendEvent(Evt);
- }
- else if ((Button == Button4) || (Button == Button5))
- {
- Event Evt;
- Evt.Type = Event::MouseWheelMoved;
- Evt.MouseWheel.Delta = WinEvent.xbutton.button == Button4 ? 1 : -1;
- SendEvent(Evt);
- }
- break;
- }
-
- // Mouse moved
- case MotionNotify :
- {
- Event Evt;
- Evt.Type = Event::MouseMoved;
- Evt.MouseMove.X = WinEvent.xmotion.x;
- Evt.MouseMove.Y = WinEvent.xmotion.y;
- SendEvent(Evt);
- break;
- }
-
- // Mouse entered
- case EnterNotify :
- {
- Event Evt;
- Evt.Type = Event::MouseEntered;
- SendEvent(Evt);
- break;
- }
-
- // Mouse left
- case LeaveNotify :
- {
- Event Evt;
- Evt.Type = Event::MouseLeft;
- SendEvent(Evt);
- break;
- }
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Convert a X11 keysym to SFML key code
-////////////////////////////////////////////////////////////
-Key::Code WindowImplX11::KeysymToSF(KeySym Sym)
-{
- // First convert to uppercase (to avoid dealing with two different keysyms for the same key)
- KeySym Lower, Key;
- XConvertCase(Sym, &Lower, &Key);
-
- switch (Key)
- {
- case XK_Shift_L : return Key::LShift;
- case XK_Shift_R : return Key::RShift;
- case XK_Control_L : return Key::LControl;
- case XK_Control_R : return Key::RControl;
- case XK_Alt_L : return Key::LAlt;
- case XK_Alt_R : return Key::RAlt;
- case XK_Super_L : return Key::LSystem;
- case XK_Super_R : return Key::RSystem;
- case XK_Menu : return Key::Menu;
- case XK_Escape : return Key::Escape;
- case XK_semicolon : return Key::SemiColon;
- case XK_slash : return Key::Slash;
- case XK_equal : return Key::Equal;
- case XK_minus : return Key::Dash;
- case XK_bracketleft : return Key::LBracket;
- case XK_bracketright : return Key::RBracket;
- case XK_comma : return Key::Comma;
- case XK_period : return Key::Period;
- case XK_dead_acute : return Key::Quote;
- case XK_backslash : return Key::BackSlash;
- case XK_dead_grave : return Key::Tilde;
- case XK_space : return Key::Space;
- case XK_Return : return Key::Return;
- case XK_KP_Enter : return Key::Return;
- case XK_BackSpace : return Key::Back;
- case XK_Tab : return Key::Tab;
- case XK_Prior : return Key::PageUp;
- case XK_Next : return Key::PageDown;
- case XK_End : return Key::End;
- case XK_Home : return Key::Home;
- case XK_Insert : return Key::Insert;
- case XK_Delete : return Key::Delete;
- case XK_KP_Add : return Key::Add;
- case XK_KP_Subtract : return Key::Subtract;
- case XK_KP_Multiply : return Key::Multiply;
- case XK_KP_Divide : return Key::Divide;
- case XK_Pause : return Key::Pause;
- case XK_F1 : return Key::F1;
- case XK_F2 : return Key::F2;
- case XK_F3 : return Key::F3;
- case XK_F4 : return Key::F4;
- case XK_F5 : return Key::F5;
- case XK_F6 : return Key::F6;
- case XK_F7 : return Key::F7;
- case XK_F8 : return Key::F8;
- case XK_F9 : return Key::F9;
- case XK_F10 : return Key::F10;
- case XK_F11 : return Key::F11;
- case XK_F12 : return Key::F12;
- case XK_F13 : return Key::F13;
- case XK_F14 : return Key::F14;
- case XK_F15 : return Key::F15;
- case XK_Left : return Key::Left;
- case XK_Right : return Key::Right;
- case XK_Up : return Key::Up;
- case XK_Down : return Key::Down;
- case XK_KP_0 : return Key::Numpad0;
- case XK_KP_1 : return Key::Numpad1;
- case XK_KP_2 : return Key::Numpad2;
- case XK_KP_3 : return Key::Numpad3;
- case XK_KP_4 : return Key::Numpad4;
- case XK_KP_5 : return Key::Numpad5;
- case XK_KP_6 : return Key::Numpad6;
- case XK_KP_7 : return Key::Numpad7;
- case XK_KP_8 : return Key::Numpad8;
- case XK_KP_9 : return Key::Numpad9;
- case XK_A : return Key::A;
- case XK_Z : return Key::Z;
- case XK_E : return Key::E;
- case XK_R : return Key::R;
- case XK_T : return Key::T;
- case XK_Y : return Key::Y;
- case XK_U : return Key::U;
- case XK_I : return Key::I;
- case XK_O : return Key::O;
- case XK_P : return Key::P;
- case XK_Q : return Key::Q;
- case XK_S : return Key::S;
- case XK_D : return Key::D;
- case XK_F : return Key::F;
- case XK_G : return Key::G;
- case XK_H : return Key::H;
- case XK_J : return Key::J;
- case XK_K : return Key::K;
- case XK_L : return Key::L;
- case XK_M : return Key::M;
- case XK_W : return Key::W;
- case XK_X : return Key::X;
- case XK_C : return Key::C;
- case XK_V : return Key::V;
- case XK_B : return Key::B;
- case XK_N : return Key::N;
- case XK_0 : return Key::Num0;
- case XK_1 : return Key::Num1;
- case XK_2 : return Key::Num2;
- case XK_3 : return Key::Num3;
- case XK_4 : return Key::Num4;
- case XK_5 : return Key::Num5;
- case XK_6 : return Key::Num6;
- case XK_7 : return Key::Num7;
- case XK_8 : return Key::Num8;
- case XK_9 : return Key::Num9;
- }
-
- return Key::Code(0);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Open the display (if not already done)
-////////////////////////////////////////////////////////////
-bool WindowImplX11::OpenDisplay(bool AddWindow)
-{
- // If no display has been opened yet, open it
- if (ourDisplay == NULL)
- {
- ourDisplay = XOpenDisplay(NULL);
- if (ourDisplay)
- {
- ourScreen = DefaultScreen(ourDisplay);
-
- // Get the input method (XIM) object
- ourInputMethod = XOpenIM(ourDisplay, NULL, NULL, NULL);
- }
- else
- {
- std::cerr << "Failed to open a connection with the X server" << std::endl;
- }
- }
-
- // Increase the number of windows
- if (AddWindow)
- ourWindowsCount++;
-
- return ourDisplay != NULL;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Close the display
-////////////////////////////////////////////////////////////
-void WindowImplX11::CloseDisplay()
-{
- // Decrease the number of windows
- ourWindowsCount--;
-
- // If all windows have been destroyed, then we can close the display
- if (ourWindowsCount == 0)
- {
- // Close the input method object
- if (ourInputMethod)
- XCloseIM(ourInputMethod);
-
- XCloseDisplay(ourDisplay);
- ourDisplay = NULL;
- }
-}
-
-} // namespace priv
-
-} // namespace sf
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/WindowStyle.hpp> // important to be included first (conflict with None)
+#include <SFML/Window/Linux/WindowImplX11.hpp>
+#include <SFML/Window/Linux/GlxContext.hpp>
+#include <SFML/Window/Linux/Display.hpp>
+#include <SFML/System/Utf.hpp>
+#include <SFML/System/Err.hpp>
+#include <X11/Xutil.h>
+#include <X11/keysym.h>
+#include <X11/extensions/Xrandr.h>
+#include <unistd.h>
+#include <cstring>
+#include <sstream>
+#include <vector>
+#include <string>
+#include <iterator>
+
+
+////////////////////////////////////////////////////////////
+// Private data
+////////////////////////////////////////////////////////////
+namespace
+{
+ sf::priv::WindowImplX11* fullscreenWindow = NULL;
+ unsigned long eventMask = FocusChangeMask | ButtonPressMask | ButtonReleaseMask | ButtonMotionMask |
+ PointerMotionMask | KeyPressMask | KeyReleaseMask | StructureNotifyMask |
+ EnterWindowMask | LeaveWindowMask;
+
+ // Filter the events received by windows (only allow those matching a specific window)
+ Bool checkEvent(::Display*, XEvent* event, XPointer userData)
+ {
+ // Just check if the event matches the window
+ return event->xany.window == reinterpret_cast< ::Window >(userData);
+ }
+
+ // Find the name of the current executable
+ void findExecutableName(char* buffer, std::size_t bufferSize)
+ {
+ //Default fallback name
+ const char* executableName = "sfml";
+ std::size_t length = readlink("/proc/self/exe", buffer, bufferSize);
+ if ((length > 0) && (length < bufferSize))
+ {
+ // Remove the path to keep the executable name only
+ buffer[length] = '\0';
+ executableName = basename(buffer);
+ }
+ std::memmove(buffer, executableName, std::strlen(executableName) + 1);
+ }
+}
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+WindowImplX11::WindowImplX11(WindowHandle handle) :
+m_window (0),
+m_inputMethod (NULL),
+m_inputContext(NULL),
+m_isExternal (true),
+m_atomClose (0),
+m_oldVideoMode(-1),
+m_hiddenCursor(0),
+m_keyRepeat (true),
+m_previousSize(-1, -1)
+{
+ // Open a connection with the X server
+ m_display = OpenDisplay();
+ m_screen = DefaultScreen(m_display);
+
+ // Save the window handle
+ m_window = handle;
+
+ if (m_window)
+ {
+ // Make sure the window is listening to all the requiered events
+ XSelectInput(m_display, m_window, eventMask & ~ButtonPressMask);
+
+ // Do some common initializations
+ initialize();
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+WindowImplX11::WindowImplX11(VideoMode mode, const String& title, unsigned long style, const ContextSettings& settings) :
+m_window (0),
+m_inputMethod (NULL),
+m_inputContext(NULL),
+m_isExternal (false),
+m_atomClose (0),
+m_oldVideoMode(-1),
+m_hiddenCursor(0),
+m_keyRepeat (true),
+m_previousSize(-1, -1)
+{
+ // Open a connection with the X server
+ m_display = OpenDisplay();
+ m_screen = DefaultScreen(m_display);
+ ::Window root = RootWindow(m_display, m_screen);
+
+ // Compute position and size
+ int left, top;
+ bool fullscreen = (style & Style::Fullscreen) != 0;
+ if (!fullscreen)
+ {
+ left = (DisplayWidth(m_display, m_screen) - mode.width) / 2;
+ top = (DisplayHeight(m_display, m_screen) - mode.height) / 2;
+ }
+ else
+ {
+ left = 0;
+ top = 0;
+ }
+ int width = mode.width;
+ int height = mode.height;
+
+ // Switch to fullscreen if necessary
+ if (fullscreen)
+ switchToFullscreen(mode);
+
+ // Choose the visual according to the context settings
+ XVisualInfo visualInfo = GlxContext::selectBestVisual(m_display, mode.bitsPerPixel, settings);
+
+ // Define the window attributes
+ XSetWindowAttributes attributes;
+ attributes.override_redirect = fullscreen;
+ attributes.event_mask = eventMask;
+ attributes.colormap = XCreateColormap(m_display, root, visualInfo.visual, AllocNone);
+
+ // Create the window
+ m_window = XCreateWindow(m_display,
+ root,
+ left, top,
+ width, height,
+ 0,
+ visualInfo.depth,
+ InputOutput,
+ visualInfo.visual,
+ CWEventMask | CWOverrideRedirect | CWColormap, &attributes);
+ if (!m_window)
+ {
+ err() << "Failed to create window" << std::endl;
+ return;
+ }
+
+ // Set the window's name
+ setTitle(title);
+
+ // Set the window's style (tell the windows manager to change our window's decorations and functions according to the requested style)
+ if (!fullscreen)
+ {
+ Atom WMHintsAtom = XInternAtom(m_display, "_MOTIF_WM_HINTS", false);
+ if (WMHintsAtom)
+ {
+ static const unsigned long MWM_HINTS_FUNCTIONS = 1 << 0;
+ static const unsigned long MWM_HINTS_DECORATIONS = 1 << 1;
+
+ //static const unsigned long MWM_DECOR_ALL = 1 << 0;
+ static const unsigned long MWM_DECOR_BORDER = 1 << 1;
+ static const unsigned long MWM_DECOR_RESIZEH = 1 << 2;
+ static const unsigned long MWM_DECOR_TITLE = 1 << 3;
+ static const unsigned long MWM_DECOR_MENU = 1 << 4;
+ static const unsigned long MWM_DECOR_MINIMIZE = 1 << 5;
+ static const unsigned long MWM_DECOR_MAXIMIZE = 1 << 6;
+
+ //static const unsigned long MWM_FUNC_ALL = 1 << 0;
+ static const unsigned long MWM_FUNC_RESIZE = 1 << 1;
+ static const unsigned long MWM_FUNC_MOVE = 1 << 2;
+ static const unsigned long MWM_FUNC_MINIMIZE = 1 << 3;
+ static const unsigned long MWM_FUNC_MAXIMIZE = 1 << 4;
+ static const unsigned long MWM_FUNC_CLOSE = 1 << 5;
+
+ struct WMHints
+ {
+ unsigned long flags;
+ unsigned long functions;
+ unsigned long decorations;
+ long inputMode;
+ unsigned long state;
+ };
+
+ WMHints hints;
+ hints.flags = MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS;
+ hints.decorations = 0;
+ hints.functions = 0;
+
+ if (style & Style::Titlebar)
+ {
+ hints.decorations |= MWM_DECOR_BORDER | MWM_DECOR_TITLE | MWM_DECOR_MINIMIZE | MWM_DECOR_MENU;
+ hints.functions |= MWM_FUNC_MOVE | MWM_FUNC_MINIMIZE;
+ }
+ if (style & Style::Resize)
+ {
+ hints.decorations |= MWM_DECOR_MAXIMIZE | MWM_DECOR_RESIZEH;
+ hints.functions |= MWM_FUNC_MAXIMIZE | MWM_FUNC_RESIZE;
+ }
+ if (style & Style::Close)
+ {
+ hints.decorations |= 0;
+ hints.functions |= MWM_FUNC_CLOSE;
+ }
+
+ const unsigned char* ptr = reinterpret_cast<const unsigned char*>(&hints);
+ XChangeProperty(m_display, m_window, WMHintsAtom, WMHintsAtom, 32, PropModeReplace, ptr, 5);
+ }
+
+ // This is a hack to force some windows managers to disable resizing
+ if (!(style & Style::Resize))
+ {
+ XSizeHints* sizeHints = XAllocSizeHints();
+ sizeHints->flags = PMinSize | PMaxSize;
+ sizeHints->min_width = sizeHints->max_width = width;
+ sizeHints->min_height = sizeHints->max_height = height;
+ XSetWMNormalHints(m_display, m_window, sizeHints);
+ XFree(sizeHints);
+ }
+ }
+
+ // Set the window's WM class (this can be used by window managers)
+ char windowClass[512];
+ findExecutableName(windowClass, sizeof(windowClass));
+ XClassHint* classHint = XAllocClassHint();
+ classHint->res_name = windowClass;
+ classHint->res_class = windowClass;
+ XSetClassHint(m_display, m_window, classHint);
+ XFree(classHint);
+
+ // Do some common initializations
+ initialize();
+
+ // In fullscreen mode, we must grab keyboard and mouse inputs
+ if (fullscreen)
+ {
+ XGrabPointer(m_display, m_window, true, 0, GrabModeAsync, GrabModeAsync, m_window, None, CurrentTime);
+ XGrabKeyboard(m_display, m_window, true, GrabModeAsync, GrabModeAsync, CurrentTime);
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+WindowImplX11::~WindowImplX11()
+{
+ // Cleanup graphical resources
+ cleanup();
+
+ // Destroy the cursor
+ if (m_hiddenCursor)
+ XFreeCursor(m_display, m_hiddenCursor);
+
+ // Destroy the input context
+ if (m_inputContext)
+ XDestroyIC(m_inputContext);
+
+ // Destroy the window
+ if (m_window && !m_isExternal)
+ {
+ XDestroyWindow(m_display, m_window);
+ XFlush(m_display);
+ }
+
+ // Close the input method
+ if (m_inputMethod)
+ XCloseIM(m_inputMethod);
+
+ // Close the connection with the X server
+ CloseDisplay(m_display);
+}
+
+
+////////////////////////////////////////////////////////////
+WindowHandle WindowImplX11::getSystemHandle() const
+{
+ return m_window;
+}
+
+
+////////////////////////////////////////////////////////////
+void WindowImplX11::processEvents()
+{
+ XEvent event;
+ while (XCheckIfEvent(m_display, &event, &checkEvent, reinterpret_cast<XPointer>(m_window)))
+ {
+ processEvent(event);
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+Vector2i WindowImplX11::getPosition() const
+{
+ ::Window root, child;
+ int localX, localY, x, y;
+ unsigned int width, height, border, depth;
+
+ XGetGeometry(m_display, m_window, &root, &localX, &localY, &width, &height, &border, &depth);
+ XTranslateCoordinates(m_display, m_window, root, localX, localY, &x, &y, &child);
+
+ return Vector2i(x, y);
+}
+
+
+////////////////////////////////////////////////////////////
+void WindowImplX11::setPosition(const Vector2i& position)
+{
+ XMoveWindow(m_display, m_window, position.x, position.y);
+ XFlush(m_display);
+}
+
+
+////////////////////////////////////////////////////////////
+Vector2u WindowImplX11::getSize() const
+{
+ XWindowAttributes attributes;
+ XGetWindowAttributes(m_display, m_window, &attributes);
+ return Vector2u(attributes.width, attributes.height);
+}
+
+
+////////////////////////////////////////////////////////////
+void WindowImplX11::setSize(const Vector2u& size)
+{
+ XResizeWindow(m_display, m_window, size.x, size.y);
+ XFlush(m_display);
+}
+
+
+////////////////////////////////////////////////////////////
+void WindowImplX11::setTitle(const String& title)
+{
+ // Bare X11 has no Unicode window title support.
+ // There is however an option to tell the window manager your unicode title via hints.
+
+ // Convert to UTF-8 encoding.
+ std::basic_string<Uint8> utf8Title;
+ Utf32::toUtf8(title.begin(), title.end(), std::back_inserter(utf8Title));
+
+ // Set the _NET_WM_NAME atom, which specifies a UTF-8 encoded window title.
+ Atom wmName = XInternAtom(m_display, "_NET_WM_NAME", False);
+ Atom useUtf8 = XInternAtom(m_display, "UTF8_STRING", False);
+ XChangeProperty(m_display, m_window, wmName, useUtf8, 8,
+ PropModeReplace, utf8Title.c_str(), utf8Title.size());
+
+ // Set the non-Unicode title as a fallback for window managers who don't support _NET_WM_NAME.
+ XStoreName(m_display, m_window, title.toAnsiString().c_str());
+}
+
+
+////////////////////////////////////////////////////////////
+void WindowImplX11::setIcon(unsigned int width, unsigned int height, const Uint8* pixels)
+{
+ // X11 wants BGRA pixels : swap red and blue channels
+ // Note: this memory will be freed by XDestroyImage
+ Uint8* iconPixels = static_cast<Uint8*>(std::malloc(width * height * 4));
+ for (std::size_t i = 0; i < width * height; ++i)
+ {
+ iconPixels[i * 4 + 0] = pixels[i * 4 + 2];
+ iconPixels[i * 4 + 1] = pixels[i * 4 + 1];
+ iconPixels[i * 4 + 2] = pixels[i * 4 + 0];
+ iconPixels[i * 4 + 3] = pixels[i * 4 + 3];
+ }
+
+ // Create the icon pixmap
+ Visual* defVisual = DefaultVisual(m_display, m_screen);
+ unsigned int defDepth = DefaultDepth(m_display, m_screen);
+ XImage* iconImage = XCreateImage(m_display, defVisual, defDepth, ZPixmap, 0, (char*)iconPixels, width, height, 32, 0);
+ if (!iconImage)
+ {
+ err() << "Failed to set the window's icon" << std::endl;
+ return;
+ }
+ Pixmap iconPixmap = XCreatePixmap(m_display, RootWindow(m_display, m_screen), width, height, defDepth);
+ XGCValues values;
+ GC iconGC = XCreateGC(m_display, iconPixmap, 0, &values);
+ XPutImage(m_display, iconPixmap, iconGC, iconImage, 0, 0, 0, 0, width, height);
+ XFreeGC(m_display, iconGC);
+ XDestroyImage(iconImage);
+
+ // Create the mask pixmap (must have 1 bit depth)
+ std::size_t pitch = (width + 7) / 8;
+ static std::vector<Uint8> maskPixels(pitch * height, 0);
+ for (std::size_t j = 0; j < height; ++j)
+ {
+ for (std::size_t i = 0; i < pitch; ++i)
+ {
+ for (std::size_t k = 0; k < 8; ++k)
+ {
+ if (i * 8 + k < width)
+ {
+ Uint8 opacity = (pixels[(i * 8 + k + j * width) * 4 + 3] > 0) ? 1 : 0;
+ maskPixels[i + j * pitch] |= (opacity << k);
+ }
+ }
+ }
+ }
+ Pixmap maskPixmap = XCreatePixmapFromBitmapData(m_display, m_window, (char*)&maskPixels[0], width, height, 1, 0, 1);
+
+ // Send our new icon to the window through the WMHints
+ XWMHints* hints = XAllocWMHints();
+ hints->flags = IconPixmapHint | IconMaskHint;
+ hints->icon_pixmap = iconPixmap;
+ hints->icon_mask = maskPixmap;
+ XSetWMHints(m_display, m_window, hints);
+ XFree(hints);
+
+ XFlush(m_display);
+}
+
+
+////////////////////////////////////////////////////////////
+void WindowImplX11::setVisible(bool visible)
+{
+ if (visible)
+ XMapWindow(m_display, m_window);
+ else
+ XUnmapWindow(m_display, m_window);
+
+ XFlush(m_display);
+}
+
+
+////////////////////////////////////////////////////////////
+void WindowImplX11::setMouseCursorVisible(bool visible)
+{
+ XDefineCursor(m_display, m_window, visible ? None : m_hiddenCursor);
+ XFlush(m_display);
+}
+
+
+////////////////////////////////////////////////////////////
+void WindowImplX11::setKeyRepeatEnabled(bool enabled)
+{
+ m_keyRepeat = enabled;
+}
+
+
+////////////////////////////////////////////////////////////
+void WindowImplX11::switchToFullscreen(const VideoMode& mode)
+{
+ // Check if the XRandR extension is present
+ int version;
+ if (XQueryExtension(m_display, "RANDR", &version, &version, &version))
+ {
+ // Get the current configuration
+ XRRScreenConfiguration* config = XRRGetScreenInfo(m_display, RootWindow(m_display, m_screen));
+ if (config)
+ {
+ // Get the current rotation
+ Rotation currentRotation;
+ m_oldVideoMode = XRRConfigCurrentConfiguration(config, &currentRotation);
+
+ // Get the available screen sizes
+ int nbSizes;
+ XRRScreenSize* sizes = XRRConfigSizes(config, &nbSizes);
+ if (sizes && (nbSizes > 0))
+ {
+ // Search a matching size
+ for (int i = 0; i < nbSizes; ++i)
+ {
+ if ((sizes[i].width == static_cast<int>(mode.width)) && (sizes[i].height == static_cast<int>(mode.height)))
+ {
+ // Switch to fullscreen mode
+ XRRSetScreenConfig(m_display, config, RootWindow(m_display, m_screen), i, currentRotation, CurrentTime);
+
+ // Set "this" as the current fullscreen window
+ fullscreenWindow = this;
+ break;
+ }
+ }
+ }
+
+ // Free the configuration instance
+ XRRFreeScreenConfigInfo(config);
+ }
+ else
+ {
+ // Failed to get the screen configuration
+ err() << "Failed to get the current screen configuration for fullscreen mode, switching to window mode" << std::endl;
+ }
+ }
+ else
+ {
+ // XRandr extension is not supported : we cannot use fullscreen mode
+ err() << "Fullscreen is not supported, switching to window mode" << std::endl;
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void WindowImplX11::initialize()
+{
+ // Get the atom defining the close event
+ m_atomClose = XInternAtom(m_display, "WM_DELETE_WINDOW", false);
+ XSetWMProtocols(m_display, m_window, &m_atomClose, 1);
+
+ // Create the input context
+ m_inputMethod = XOpenIM(m_display, NULL, NULL, NULL);
+ if (m_inputMethod)
+ {
+ m_inputContext = XCreateIC(m_inputMethod,
+ XNClientWindow, m_window,
+ XNFocusWindow, m_window,
+ XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
+ (void*)NULL);
+ }
+ else
+ {
+ m_inputContext = NULL;
+ }
+ if (!m_inputContext)
+ err() << "Failed to create input context for window -- TextEntered event won't be able to return unicode" << std::endl;
+
+ // Show the window
+ XMapWindow(m_display, m_window);
+ XFlush(m_display);
+
+ // Create the hiden cursor
+ createHiddenCursor();
+
+ // Flush the commands queue
+ XFlush(m_display);
+}
+
+
+////////////////////////////////////////////////////////////
+void WindowImplX11::createHiddenCursor()
+{
+ // Create the cursor's pixmap (1x1 pixels)
+ Pixmap cursorPixmap = XCreatePixmap(m_display, m_window, 1, 1, 1);
+ GC graphicsContext = XCreateGC(m_display, cursorPixmap, 0, NULL);
+ XDrawPoint(m_display, cursorPixmap, graphicsContext, 0, 0);
+ XFreeGC(m_display, graphicsContext);
+
+ // Create the cursor, using the pixmap as both the shape and the mask of the cursor
+ XColor color;
+ color.flags = DoRed | DoGreen | DoBlue;
+ color.red = color.blue = color.green = 0;
+ m_hiddenCursor = XCreatePixmapCursor(m_display, cursorPixmap, cursorPixmap, &color, &color, 0, 0);
+
+ // We don't need the pixmap any longer, free it
+ XFreePixmap(m_display, cursorPixmap);
+}
+
+
+////////////////////////////////////////////////////////////
+void WindowImplX11::cleanup()
+{
+ // Restore the previous video mode (in case we were running in fullscreen)
+ if (fullscreenWindow == this)
+ {
+ // Get current screen info
+ XRRScreenConfiguration* config = XRRGetScreenInfo(m_display, RootWindow(m_display, m_screen));
+ if (config)
+ {
+ // Get the current rotation
+ Rotation currentRotation;
+ XRRConfigCurrentConfiguration(config, &currentRotation);
+
+ // Reset the video mode
+ XRRSetScreenConfig(m_display, config, RootWindow(m_display, m_screen), m_oldVideoMode, currentRotation, CurrentTime);
+
+ // Free the configuration instance
+ XRRFreeScreenConfigInfo(config);
+ }
+
+ // Reset the fullscreen window
+ fullscreenWindow = NULL;
+ }
+
+ // Unhide the mouse cursor (in case it was hidden)
+ setMouseCursorVisible(true);
+}
+
+
+////////////////////////////////////////////////////////////
+bool WindowImplX11::processEvent(XEvent windowEvent)
+{
+ // This function implements a workaround to properly discard
+ // repeated key events when necessary. The problem is that the
+ // system's key events policy doesn't match SFML's one: X server will generate
+ // both repeated KeyPress and KeyRelease events when maintaining a key down, while
+ // SFML only wants repeated KeyPress events. Thus, we have to:
+ // - Discard duplicated KeyRelease events when KeyRepeatEnabled is true
+ // - Discard both duplicated KeyPress and KeyRelease events when KeyRepeatEnabled is false
+
+ // Detect repeated key events
+ // (code shamelessly taken from SDL)
+ if (windowEvent.type == KeyRelease)
+ {
+ // Check if there's a matching KeyPress event in the queue
+ XEvent nextEvent;
+ if (XPending(m_display))
+ {
+ // Grab it but don't remove it from the queue, it still needs to be processed :)
+ XPeekEvent(m_display, &nextEvent);
+ if (nextEvent.type == KeyPress)
+ {
+ // Check if it is a duplicated event (same timestamp as the KeyRelease event)
+ if ((nextEvent.xkey.keycode == windowEvent.xkey.keycode) &&
+ (nextEvent.xkey.time - windowEvent.xkey.time < 2))
+ {
+ // If we don't want repeated events, remove the next KeyPress from the queue
+ if (!m_keyRepeat)
+ XNextEvent(m_display, &nextEvent);
+
+ // This KeyRelease is a repeated event and we don't want it
+ return false;
+ }
+ }
+ }
+ }
+
+ // Convert the X11 event to a sf::Event
+ switch (windowEvent.type)
+ {
+ // Destroy event
+ case DestroyNotify :
+ {
+ // The window is about to be destroyed : we must cleanup resources
+ cleanup();
+ break;
+ }
+
+ // Gain focus event
+ case FocusIn :
+ {
+ // Update the input context
+ if (m_inputContext)
+ XSetICFocus(m_inputContext);
+
+ Event event;
+ event.type = Event::GainedFocus;
+ pushEvent(event);
+ break;
+ }
+
+ // Lost focus event
+ case FocusOut :
+ {
+ // Update the input context
+ if (m_inputContext)
+ XUnsetICFocus(m_inputContext);
+
+ Event event;
+ event.type = Event::LostFocus;
+ pushEvent(event);
+ break;
+ }
+
+ // Resize event
+ case ConfigureNotify :
+ {
+ // ConfigureNotify can be triggered for other reasons, check if the size has acutally changed
+ if ((windowEvent.xconfigure.width != m_previousSize.x) || (windowEvent.xconfigure.height != m_previousSize.y))
+ {
+ Event event;
+ event.type = Event::Resized;
+ event.size.width = windowEvent.xconfigure.width;
+ event.size.height = windowEvent.xconfigure.height;
+ pushEvent(event);
+
+ m_previousSize.x = windowEvent.xconfigure.width;
+ m_previousSize.y = windowEvent.xconfigure.height;
+ }
+ break;
+ }
+
+ // Close event
+ case ClientMessage :
+ {
+ if ((windowEvent.xclient.format == 32) && (windowEvent.xclient.data.l[0]) == static_cast<long>(m_atomClose))
+ {
+ Event event;
+ event.type = Event::Closed;
+ pushEvent(event);
+ }
+ break;
+ }
+
+ // Key down event
+ case KeyPress :
+ {
+ // Get the keysym of the key that has been pressed
+ static XComposeStatus keyboard;
+ char buffer[32];
+ KeySym symbol;
+ XLookupString(&windowEvent.xkey, buffer, sizeof(buffer), &symbol, &keyboard);
+
+ // Fill the event parameters
+ // TODO: if modifiers are wrong, use XGetModifierMapping to retrieve the actual modifiers mapping
+ Event event;
+ event.type = Event::KeyPressed;
+ event.key.code = keysymToSF(symbol);
+ event.key.alt = windowEvent.xkey.state & Mod1Mask;
+ event.key.control = windowEvent.xkey.state & ControlMask;
+ event.key.shift = windowEvent.xkey.state & ShiftMask;
+ event.key.system = windowEvent.xkey.state & Mod4Mask;
+ pushEvent(event);
+
+ // Generate a TextEntered event
+ if (!XFilterEvent(&windowEvent, None))
+ {
+ #ifdef X_HAVE_UTF8_STRING
+ if (m_inputContext)
+ {
+ Status status;
+ Uint8 keyBuffer[16];
+ int length = Xutf8LookupString(m_inputContext, &windowEvent.xkey, reinterpret_cast<char*>(keyBuffer), sizeof(keyBuffer), NULL, &status);
+ if (length > 0)
+ {
+ Uint32 unicode = 0;
+ Utf8::decode(keyBuffer, keyBuffer + length, unicode, 0);
+ if (unicode != 0)
+ {
+ Event textEvent;
+ textEvent.type = Event::TextEntered;
+ textEvent.text.unicode = unicode;
+ pushEvent(textEvent);
+ }
+ }
+ }
+ else
+ #endif
+ {
+ static XComposeStatus status;
+ char keyBuffer[16];
+ if (XLookupString(&windowEvent.xkey, keyBuffer, sizeof(keyBuffer), NULL, &status))
+ {
+ Event textEvent;
+ textEvent.type = Event::TextEntered;
+ textEvent.text.unicode = static_cast<Uint32>(keyBuffer[0]);
+ pushEvent(textEvent);
+ }
+ }
+ }
+
+ break;
+ }
+
+ // Key up event
+ case KeyRelease :
+ {
+ // Get the keysym of the key that has been pressed
+ char buffer[32];
+ KeySym symbol;
+ XLookupString(&windowEvent.xkey, buffer, 32, &symbol, NULL);
+
+ // Fill the event parameters
+ Event event;
+ event.type = Event::KeyReleased;
+ event.key.code = keysymToSF(symbol);
+ event.key.alt = windowEvent.xkey.state & Mod1Mask;
+ event.key.control = windowEvent.xkey.state & ControlMask;
+ event.key.shift = windowEvent.xkey.state & ShiftMask;
+ event.key.system = windowEvent.xkey.state & Mod4Mask;
+ pushEvent(event);
+
+ break;
+ }
+
+ // Mouse button pressed
+ case ButtonPress :
+ {
+ unsigned int button = windowEvent.xbutton.button;
+ if ((button == Button1) || (button == Button2) || (button == Button3) || (button == 8) || (button == 9))
+ {
+ Event event;
+ event.type = Event::MouseButtonPressed;
+ event.mouseButton.x = windowEvent.xbutton.x;
+ event.mouseButton.y = windowEvent.xbutton.y;
+ switch (button)
+ {
+ case Button1 : event.mouseButton.button = Mouse::Left; break;
+ case Button2 : event.mouseButton.button = Mouse::Middle; break;
+ case Button3 : event.mouseButton.button = Mouse::Right; break;
+ case 8 : event.mouseButton.button = Mouse::XButton1; break;
+ case 9 : event.mouseButton.button = Mouse::XButton2; break;
+ }
+ pushEvent(event);
+ }
+ break;
+ }
+
+ // Mouse button released
+ case ButtonRelease :
+ {
+ unsigned int button = windowEvent.xbutton.button;
+ if ((button == Button1) || (button == Button2) || (button == Button3) || (button == 8) || (button == 9))
+ {
+ Event event;
+ event.type = Event::MouseButtonReleased;
+ event.mouseButton.x = windowEvent.xbutton.x;
+ event.mouseButton.y = windowEvent.xbutton.y;
+ switch (button)
+ {
+ case Button1 : event.mouseButton.button = Mouse::Left; break;
+ case Button2 : event.mouseButton.button = Mouse::Middle; break;
+ case Button3 : event.mouseButton.button = Mouse::Right; break;
+ case 8 : event.mouseButton.button = Mouse::XButton1; break;
+ case 9 : event.mouseButton.button = Mouse::XButton2; break;
+ }
+ pushEvent(event);
+ }
+ else if ((button == Button4) || (button == Button5))
+ {
+ Event event;
+ event.type = Event::MouseWheelMoved;
+ event.mouseWheel.delta = windowEvent.xbutton.button == Button4 ? 1 : -1;
+ event.mouseWheel.x = windowEvent.xbutton.x;
+ event.mouseWheel.y = windowEvent.xbutton.y;
+ pushEvent(event);
+ }
+ break;
+ }
+
+ // Mouse moved
+ case MotionNotify :
+ {
+ Event event;
+ event.type = Event::MouseMoved;
+ event.mouseMove.x = windowEvent.xmotion.x;
+ event.mouseMove.y = windowEvent.xmotion.y;
+ pushEvent(event);
+ break;
+ }
+
+ // Mouse entered
+ case EnterNotify :
+ {
+ if (windowEvent.xcrossing.mode == NotifyNormal)
+ {
+ Event event;
+ event.type = Event::MouseEntered;
+ pushEvent(event);
+ }
+ break;
+ }
+
+ // Mouse left
+ case LeaveNotify :
+ {
+ if (windowEvent.xcrossing.mode == NotifyNormal)
+ {
+ Event event;
+ event.type = Event::MouseLeft;
+ pushEvent(event);
+ }
+ break;
+ }
+ }
+
+ return true;
+}
+
+
+////////////////////////////////////////////////////////////
+Keyboard::Key WindowImplX11::keysymToSF(KeySym symbol)
+{
+ // First convert to uppercase (to avoid dealing with two different keysyms for the same key)
+ KeySym lower, key;
+ XConvertCase(symbol, &lower, &key);
+
+ switch (key)
+ {
+ case XK_Shift_L : return Keyboard::LShift;
+ case XK_Shift_R : return Keyboard::RShift;
+ case XK_Control_L : return Keyboard::LControl;
+ case XK_Control_R : return Keyboard::RControl;
+ case XK_Alt_L : return Keyboard::LAlt;
+ case XK_Alt_R : return Keyboard::RAlt;
+ case XK_Super_L : return Keyboard::LSystem;
+ case XK_Super_R : return Keyboard::RSystem;
+ case XK_Menu : return Keyboard::Menu;
+ case XK_Escape : return Keyboard::Escape;
+ case XK_semicolon : return Keyboard::SemiColon;
+ case XK_slash : return Keyboard::Slash;
+ case XK_equal : return Keyboard::Equal;
+ case XK_minus : return Keyboard::Dash;
+ case XK_bracketleft : return Keyboard::LBracket;
+ case XK_bracketright : return Keyboard::RBracket;
+ case XK_comma : return Keyboard::Comma;
+ case XK_period : return Keyboard::Period;
+ case XK_dead_acute : return Keyboard::Quote;
+ case XK_backslash : return Keyboard::BackSlash;
+ case XK_dead_grave : return Keyboard::Tilde;
+ case XK_space : return Keyboard::Space;
+ case XK_Return : return Keyboard::Return;
+ case XK_KP_Enter : return Keyboard::Return;
+ case XK_BackSpace : return Keyboard::BackSpace;
+ case XK_Tab : return Keyboard::Tab;
+ case XK_Prior : return Keyboard::PageUp;
+ case XK_Next : return Keyboard::PageDown;
+ case XK_End : return Keyboard::End;
+ case XK_Home : return Keyboard::Home;
+ case XK_Insert : return Keyboard::Insert;
+ case XK_Delete : return Keyboard::Delete;
+ case XK_KP_Add : return Keyboard::Add;
+ case XK_KP_Subtract : return Keyboard::Subtract;
+ case XK_KP_Multiply : return Keyboard::Multiply;
+ case XK_KP_Divide : return Keyboard::Divide;
+ case XK_Pause : return Keyboard::Pause;
+ case XK_F1 : return Keyboard::F1;
+ case XK_F2 : return Keyboard::F2;
+ case XK_F3 : return Keyboard::F3;
+ case XK_F4 : return Keyboard::F4;
+ case XK_F5 : return Keyboard::F5;
+ case XK_F6 : return Keyboard::F6;
+ case XK_F7 : return Keyboard::F7;
+ case XK_F8 : return Keyboard::F8;
+ case XK_F9 : return Keyboard::F9;
+ case XK_F10 : return Keyboard::F10;
+ case XK_F11 : return Keyboard::F11;
+ case XK_F12 : return Keyboard::F12;
+ case XK_F13 : return Keyboard::F13;
+ case XK_F14 : return Keyboard::F14;
+ case XK_F15 : return Keyboard::F15;
+ case XK_Left : return Keyboard::Left;
+ case XK_Right : return Keyboard::Right;
+ case XK_Up : return Keyboard::Up;
+ case XK_Down : return Keyboard::Down;
+ case XK_KP_0 : return Keyboard::Numpad0;
+ case XK_KP_1 : return Keyboard::Numpad1;
+ case XK_KP_2 : return Keyboard::Numpad2;
+ case XK_KP_3 : return Keyboard::Numpad3;
+ case XK_KP_4 : return Keyboard::Numpad4;
+ case XK_KP_5 : return Keyboard::Numpad5;
+ case XK_KP_6 : return Keyboard::Numpad6;
+ case XK_KP_7 : return Keyboard::Numpad7;
+ case XK_KP_8 : return Keyboard::Numpad8;
+ case XK_KP_9 : return Keyboard::Numpad9;
+ case XK_A : return Keyboard::A;
+ case XK_Z : return Keyboard::Z;
+ case XK_E : return Keyboard::E;
+ case XK_R : return Keyboard::R;
+ case XK_T : return Keyboard::T;
+ case XK_Y : return Keyboard::Y;
+ case XK_U : return Keyboard::U;
+ case XK_I : return Keyboard::I;
+ case XK_O : return Keyboard::O;
+ case XK_P : return Keyboard::P;
+ case XK_Q : return Keyboard::Q;
+ case XK_S : return Keyboard::S;
+ case XK_D : return Keyboard::D;
+ case XK_F : return Keyboard::F;
+ case XK_G : return Keyboard::G;
+ case XK_H : return Keyboard::H;
+ case XK_J : return Keyboard::J;
+ case XK_K : return Keyboard::K;
+ case XK_L : return Keyboard::L;
+ case XK_M : return Keyboard::M;
+ case XK_W : return Keyboard::W;
+ case XK_X : return Keyboard::X;
+ case XK_C : return Keyboard::C;
+ case XK_V : return Keyboard::V;
+ case XK_B : return Keyboard::B;
+ case XK_N : return Keyboard::N;
+ case XK_0 : return Keyboard::Num0;
+ case XK_1 : return Keyboard::Num1;
+ case XK_2 : return Keyboard::Num2;
+ case XK_3 : return Keyboard::Num3;
+ case XK_4 : return Keyboard::Num4;
+ case XK_5 : return Keyboard::Num5;
+ case XK_6 : return Keyboard::Num6;
+ case XK_7 : return Keyboard::Num7;
+ case XK_8 : return Keyboard::Num8;
+ case XK_9 : return Keyboard::Num9;
+ }
+
+ return Keyboard::Unknown;
+}
+
+} // namespace priv
+
+} // namespace sf
diff --git a/src/SFML/Window/Linux/WindowImplX11.hpp b/src/SFML/Window/Linux/WindowImplX11.hpp
index 9fd4e0e..613fa7b 100755..100644
--- a/src/SFML/Window/Linux/WindowImplX11.hpp
+++ b/src/SFML/Window/Linux/WindowImplX11.hpp
@@ -1,266 +1,234 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-#ifndef SFML_WINDOWIMPLX11_HPP
-#define SFML_WINDOWIMPLX11_HPP
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Window/Event.hpp>
-#include <SFML/Window/WindowImpl.hpp>
-#include <X11/Xlib.h>
-#include <GL/glx.h>
-#include <set>
-#include <string>
-
-
-namespace sf
-{
-namespace priv
-{
-class VideoModeSupport;
-
-////////////////////////////////////////////////////////////
-/// WindowImplX11 is the Linux (X11) implementation of WindowImpl
-////////////////////////////////////////////////////////////
-class WindowImplX11 : public WindowImpl
-{
-public :
-
- ////////////////////////////////////////////////////////////
- /// Default constructor
- /// (creates a dummy window to provide a valid OpenGL context)
- ///
- ////////////////////////////////////////////////////////////
- WindowImplX11();
-
- ////////////////////////////////////////////////////////////
- /// Construct the window implementation from an existing control
- ///
- /// \param Handle : Platform-specific handle of the control
- /// \param Params : Creation settings
- ///
- ////////////////////////////////////////////////////////////
- WindowImplX11(WindowHandle Handle, WindowSettings& Params);
-
- ////////////////////////////////////////////////////////////
- /// Create the window implementation
- ///
- /// \param Mode : Video mode to use
- /// \param Title : Title of the window
- /// \param WindowStyle : Window style (resizable, fixed, or fullscren)
- /// \param Params : Creation settings
- ///
- ////////////////////////////////////////////////////////////
- WindowImplX11(VideoMode Mode, const std::string& Title, unsigned long WindowStyle, WindowSettings& Params);
-
- ////////////////////////////////////////////////////////////
- /// Destructor
- ///
- ////////////////////////////////////////////////////////////
- ~WindowImplX11();
-
- ////////////////////////////////////////////////////////////
- /// Check if there's an active context on the current thread
- ///
- /// \return True if there's a context bound to the current thread
- ///
- ////////////////////////////////////////////////////////////
- static bool IsContextActive();
-
-private :
-
- friend class VideoModeSupport;
-
- ////////////////////////////////////////////////////////////
- /// /see WindowImpl::Display
- ///
- ////////////////////////////////////////////////////////////
- virtual void Display();
-
- ////////////////////////////////////////////////////////////
- /// /see WindowImpl::ProcessEvents
- ///
- ////////////////////////////////////////////////////////////
- virtual void ProcessEvents();
-
- ////////////////////////////////////////////////////////////
- /// /see WindowImpl::SetActive
- ///
- ////////////////////////////////////////////////////////////
- virtual void SetActive(bool Active = true) const;
-
- ////////////////////////////////////////////////////////////
- /// /see WindowImpl::UseVerticalSync
- ///
- ////////////////////////////////////////////////////////////
- virtual void UseVerticalSync(bool Enabled);
-
- ////////////////////////////////////////////////////////////
- /// /see WindowImpl::ShowMouseCursor
- ///
- ////////////////////////////////////////////////////////////
- virtual void ShowMouseCursor(bool Show);
-
- ////////////////////////////////////////////////////////////
- /// /see sfWindowImpl::SetCursorPosition
- ///
- ////////////////////////////////////////////////////////////
- virtual void SetCursorPosition(unsigned int Left, unsigned int Top);
-
- ////////////////////////////////////////////////////////////
- /// /see sfWindowImpl::SetPosition
- ///
- ////////////////////////////////////////////////////////////
- virtual void SetPosition(int Left, int Top);
-
- ////////////////////////////////////////////////////////////
- /// /see WindowImpl::SetSize
- ///
- ////////////////////////////////////////////////////////////
- virtual void SetSize(unsigned int Width, unsigned int Height);
-
- ////////////////////////////////////////////////////////////
- /// /see sfWindowImpl::Show
- ///
- ////////////////////////////////////////////////////////////
- virtual void Show(bool State);
-
- ////////////////////////////////////////////////////////////
- /// /see sfWindowImpl::EnableKeyRepeat
- ///
- ////////////////////////////////////////////////////////////
- virtual void EnableKeyRepeat(bool Enabled);
-
- ////////////////////////////////////////////////////////////
- /// /see WindowImpl::SetIcon
- ///
- ////////////////////////////////////////////////////////////
- virtual void SetIcon(unsigned int Width, unsigned int Height, const Uint8* Pixels);
-
- ////////////////////////////////////////////////////////////
- /// Switch to fullscreen mode
- ///
- /// \param Mode : video mode to switch to
- ///
- ////////////////////////////////////////////////////////////
- void SwitchToFullscreen(const VideoMode& Mode);
-
- ////////////////////////////////////////////////////////////
- /// Create the OpenGL rendering context
- ///
- /// \param Mode : Video mode to use
- /// \param ChosenVisual : Visual that has been chosen for creating the contexte
- /// \param Params : Creation parameters
- /// \param Template : Visual infos to match
- /// \param Mask : Visual attributes to check in Template
- ///
- /// \return True on success, false on error
- ///
- ////////////////////////////////////////////////////////////
- bool CreateContext(const VideoMode& Mode, XVisualInfo& ChosenVisual, WindowSettings& Params, XVisualInfo Template = XVisualInfo(), unsigned long Mask = 0);
-
- ////////////////////////////////////////////////////////////
- /// Do some common initializations after the window has been created
- ///
- ////////////////////////////////////////////////////////////
- void Initialize();
-
- ////////////////////////////////////////////////////////////
- /// Create a transparent mouse cursor
- ///
- ////////////////////////////////////////////////////////////
- void CreateHiddenCursor();
-
- ////////////////////////////////////////////////////////////
- /// Cleanup graphical resources attached to the window
- ///
- ////////////////////////////////////////////////////////////
- void CleanUp();
-
- ////////////////////////////////////////////////////////////
- /// Process an incoming event from the window
- ///
- /// \param WinEvent : Event which has been received
- ///
- ////////////////////////////////////////////////////////////
- void ProcessEvent(XEvent WinEvent);
-
- ////////////////////////////////////////////////////////////
- /// Convert a X11 keysym to SFML key code
- ///
- /// \param Sym : keysym to convert
- ///
- /// \return Corrsponding SFML key code
- ///
- ////////////////////////////////////////////////////////////
- static Key::Code KeysymToSF(KeySym Sym);
-
- ////////////////////////////////////////////////////////////
- /// Open the display (if not already done)
- ///
- /// \param AddWindow : Tell whether or not we must increase the windows count
- ///
- /// \return True if the display is properly opened
- ///
- ////////////////////////////////////////////////////////////
- static bool OpenDisplay(bool AddWindow = true);
-
- ////////////////////////////////////////////////////////////
- /// Close the display
- ///
- ////////////////////////////////////////////////////////////
- static void CloseDisplay();
-
- ////////////////////////////////////////////////////////////
- // Static member data
- ////////////////////////////////////////////////////////////
- static ::Display* ourDisplay; ///< Current opened display
- static int ourScreen; ///< Default screen on the opened display
- static WindowImplX11* ourFullscreenWindow; ///< Keep track of the active fullscreen window
- static unsigned int ourWindowsCount; ///< Number of windows created
- static unsigned long ourEventMask; ///< Mask defining the events that will be caught by our windows
- static XIM ourInputMethod; ///< Input object used to get unicode characters from keypress messages
-
- ////////////////////////////////////////////////////////////
- // Member data
- ////////////////////////////////////////////////////////////
- ::Window myWindow; ///< X11 structure defining our window
- bool myIsExternal; ///< Tell whether the window has been created externally or by SFML
- GLXContext myGLContext; ///< OpenGL context attached to the window
- Atom myAtomClose; ///< Atom used to identify the close event
- int myOldVideoMode; ///< Video mode in use before we switch to fullscreen
- Cursor myHiddenCursor; ///< As X11 doesn't provide cursor hidding, we must create a transparent one
- XIC myInputContext; ///< Input context used to get unicode input in our window
- bool myKeyRepeat; ///< Is the KeyRepeat feature enabled ?
- XEvent myLastKeyReleaseEvent; ///< Last key release event we received (needed for discarding repeated key events)
-};
-
-} // namespace priv
-
-} // namespace sf
-
-
-#endif // SFML_WINDOWIMPLX11_HPP
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_WINDOWIMPLX11_HPP
+#define SFML_WINDOWIMPLX11_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/Event.hpp>
+#include <SFML/Window/WindowImpl.hpp>
+#include <SFML/System/String.hpp>
+#include <X11/Xlib.h>
+#include <set>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief Linux (X11) implementation of WindowImpl
+///
+////////////////////////////////////////////////////////////
+class WindowImplX11 : public WindowImpl
+{
+public :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Construct the window implementation from an existing control
+ ///
+ /// \param handle Platform-specific handle of the control
+ ///
+ ////////////////////////////////////////////////////////////
+ WindowImplX11(WindowHandle handle);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Create the window implementation
+ ///
+ /// \param mode Video mode to use
+ /// \param title Title of the window
+ /// \param style Window style (resizable, fixed, or fullscren)
+ /// \param settings Additional settings for the underlying OpenGL context
+ ///
+ ////////////////////////////////////////////////////////////
+ WindowImplX11(VideoMode mode, const String& title, unsigned long style, const ContextSettings& settings);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Destructor
+ ///
+ ////////////////////////////////////////////////////////////
+ ~WindowImplX11();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Get the OS-specific handle of the window
+ ///
+ /// \return Handle of the window
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual WindowHandle getSystemHandle() const;
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Get the position of the window
+ ///
+ /// \return Position of the window, in pixels
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual Vector2i getPosition() const;
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Change the position of the window on screen
+ ///
+ /// \param position New position of the window, in pixels
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual void setPosition(const Vector2i& position);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Get the client size of the window
+ ///
+ /// \return Size of the window, in pixels
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual Vector2u getSize() const;
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Change the size of the rendering region of the window
+ ///
+ /// \param size New size, in pixels
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual void setSize(const Vector2u& size);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Change the title of the window
+ ///
+ /// \param title New title
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual void setTitle(const String& title);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Change the window's icon
+ ///
+ /// \param width Icon's width, in pixels
+ /// \param height Icon's height, in pixels
+ /// \param pixels Pointer to the pixels in memory, format must be RGBA 32 bits
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual void setIcon(unsigned int width, unsigned int height, const Uint8* pixels);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Show or hide the window
+ ///
+ /// \param visible True to show, false to hide
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual void setVisible(bool visible);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Show or hide the mouse cursor
+ ///
+ /// \param visible True to show, false to hide
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual void setMouseCursorVisible(bool visible);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Enable or disable automatic key-repeat
+ ///
+ /// \param enabled True to enable, false to disable
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual void setKeyRepeatEnabled(bool enabled);
+
+protected :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Process incoming events from the operating system
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual void processEvents();
+
+private :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Switch to fullscreen mode
+ ///
+ /// \param Mode video mode to switch to
+ ///
+ ////////////////////////////////////////////////////////////
+ void switchToFullscreen(const VideoMode& mode);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Do some common initializations after the window has been created
+ ///
+ ////////////////////////////////////////////////////////////
+ void initialize();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Create a transparent mouse cursor
+ ///
+ ////////////////////////////////////////////////////////////
+ void createHiddenCursor();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Cleanup graphical resources attached to the window
+ ///
+ ////////////////////////////////////////////////////////////
+ void cleanup();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Process an incoming event from the window
+ ///
+ /// \param windowEvent Event which has been received
+ ///
+ /// \return True if the event was processed, false if it was discarded
+ ///
+ ////////////////////////////////////////////////////////////
+ bool processEvent(XEvent windowEvent);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Convert a X11 keysym to SFML key code
+ ///
+ /// \param symbol Key symbol to convert
+ ///
+ /// \return Corrsponding SFML key code
+ ///
+ ////////////////////////////////////////////////////////////
+ static Keyboard::Key keysymToSF(KeySym symbol);
+
+ ////////////////////////////////////////////////////////////
+ // Member data
+ ////////////////////////////////////////////////////////////
+ ::Window m_window; ///< X11 structure defining our window
+ ::Display* m_display; ///< Pointer to the display
+ int m_screen; ///< Screen identifier
+ XIM m_inputMethod; ///< Input method linked to the X display
+ XIC m_inputContext; ///< Input context used to get unicode input in our window
+ bool m_isExternal; ///< Tell whether the window has been created externally or by SFML
+ Atom m_atomClose; ///< Atom used to identify the close event
+ int m_oldVideoMode; ///< Video mode in use before we switch to fullscreen
+ Cursor m_hiddenCursor; ///< As X11 doesn't provide cursor hidding, we must create a transparent one
+ bool m_keyRepeat; ///< Is the KeyRepeat feature enabled ?
+ Vector2i m_previousSize; ///< Previous size of the window, to find if a ConfigureNotify event is a resize event (could be a move event only)
+};
+
+} // namespace priv
+
+} // namespace sf
+
+
+#endif // SFML_WINDOWIMPLX11_HPP
diff --git a/src/SFML/Window/Makefile b/src/SFML/Window/Makefile
deleted file mode 100755
index 0dd689c..0000000
--- a/src/SFML/Window/Makefile
+++ /dev/null
@@ -1,35 +0,0 @@
-SRC = $(wildcard *.cpp ./Linux/*.cpp)
-OBJ = $(SRC:.cpp=.o)
-OBJGLEW = $(SRCGLEW:.c=.o)
-
-ifeq ($(STATIC), yes)
- LIB = libsfml-window-s.a
- LIBNAME = $(LIBPATH)/$(LIB)
- INSTALL =
-else
- LIB = libsfml-window.so
- LIBNAME = $(LIBPATH)/$(LIB).$(VERSION)
- INSTALL = && $(LN) $(LNFLAGS) $(LIB).$(VERSION) $(DESTLIBDIR)/$(LIB)
-endif
-
-all: $(LIB)
-
-libsfml-window-s.a: $(OBJ)
- $(AR) $(ARFLAGS) $(LIBNAME) $(OBJ)
-
-libsfml-window.so: $(OBJ)
- $(CPP) $(LDFLAGS) -Wl,-soname,$(LIB).$(VERSION) -o $(LIBNAME) $(OBJ) $(OBJGLEW) -lX11 -lXrandr -lGL
-
-$(OBJ): %.o: %.cpp
- $(CPP) -o $@ -c $< $(CFLAGS)
-
-.PHONY: clean mrproper
-
-clean:
- @rm -rf $(OBJ)
-
-mrproper: clean
- @rm -rf $(LIBNAME)
-
-install:
- @($(CP) $(LIBNAME) $(DESTLIBDIR) $(INSTALL))
diff --git a/src/SFML/System/Win32/Mutex.cpp b/src/SFML/Window/Mouse.cpp
index 717062c..e8b6b0c 100755..100644
--- a/src/SFML/System/Win32/Mutex.cpp
+++ b/src/SFML/Window/Mouse.cpp
@@ -1,68 +1,69 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/System/Win32/Mutex.hpp>
-
-
-namespace sf
-{
-////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
-Mutex::Mutex()
-{
- InitializeCriticalSection(&myHandle);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Destructor
-////////////////////////////////////////////////////////////
-Mutex::~Mutex()
-{
- DeleteCriticalSection(&myHandle);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Lock the mutex
-////////////////////////////////////////////////////////////
-void Mutex::Lock()
-{
- EnterCriticalSection(&myHandle);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Unlock the mutex
-////////////////////////////////////////////////////////////
-void Mutex::Unlock()
-{
- LeaveCriticalSection(&myHandle);
-}
-
-} // namespace sf
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/Mouse.hpp>
+#include <SFML/Window/InputImpl.hpp>
+#include <SFML/Window/Window.hpp>
+
+
+namespace sf
+{
+////////////////////////////////////////////////////////////
+bool Mouse::isButtonPressed(Button button)
+{
+ return priv::InputImpl::isMouseButtonPressed(button);
+}
+
+
+////////////////////////////////////////////////////////////
+Vector2i Mouse::getPosition()
+{
+ return priv::InputImpl::getMousePosition();
+}
+
+
+////////////////////////////////////////////////////////////
+Vector2i Mouse::getPosition(const Window& relativeTo)
+{
+ return priv::InputImpl::getMousePosition(relativeTo);
+}
+
+
+////////////////////////////////////////////////////////////
+void Mouse::setPosition(const Vector2i& position)
+{
+ priv::InputImpl::setMousePosition(position);
+}
+
+
+////////////////////////////////////////////////////////////
+void Mouse::setPosition(const Vector2i& position, const Window& relativeTo)
+{
+ priv::InputImpl::setMousePosition(position, relativeTo);
+}
+
+} // namespace sf
diff --git a/src/SFML/Window/OSX/AutoreleasePoolWrapper.h b/src/SFML/Window/OSX/AutoreleasePoolWrapper.h
new file mode 100644
index 0000000..f357e23
--- /dev/null
+++ b/src/SFML/Window/OSX/AutoreleasePoolWrapper.h
@@ -0,0 +1,51 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2012 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+/// \brief Ensure at least one autorelease pool is available on this thread.
+///
+/// Increment a retain count.
+/// See SPECIAL CONSIDERATION in implementation file.
+///
+////////////////////////////////////////////////////////////
+void retainPool(void);
+
+////////////////////////////////////////////////////////////
+/// \brief Release the pool.
+///
+/// Drain the pool if it is no more needed (retain count is zero).
+/// See SPECIAL CONSIDERATION in implementation file.
+///
+////////////////////////////////////////////////////////////
+void releasePool(void);
+
+////////////////////////////////////////////////////////////
+/// \brief Drain the pool.
+///
+/// releasePool must be called at least once before drainPool.
+///
+////////////////////////////////////////////////////////////
+void drainPool();
+
diff --git a/src/SFML/Window/OSX/AutoreleasePoolWrapper.mm b/src/SFML/Window/OSX/AutoreleasePoolWrapper.mm
new file mode 100644
index 0000000..68c709b
--- /dev/null
+++ b/src/SFML/Window/OSX/AutoreleasePoolWrapper.mm
@@ -0,0 +1,239 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2012 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/System/ThreadLocalPtr.hpp>
+#include <SFML/System/NonCopyable.hpp>
+#include <SFML/System/Err.hpp>
+
+#import <Foundation/Foundation.h>
+#import <SFML/Window/OSX/AutoreleasePoolWrapper.h>
+
+
+////////////////////////////////////////////////////////////
+/// Here we manage one and only one pool by thread. This prevents draining one
+/// pool and making other pools invalid which can lead to a crash on 10.5 and an
+/// annoying message on 10.6 (*** attempt to pop an unknown autorelease pool).
+///
+/// Because NSAutoreleasePool cannot be retain we have to do it ourself.
+/// We use an sf::ThreadLocalPtr to have one PoolWrapper in each thread.
+///
+/// SPECIAL CONSIDERATION :
+/// =======================
+/// This implies that if retainPool is called X times in a thread Y then
+/// releasePool must be called X times too in the same thread Y.
+///
+////////////////////////////////////////////////////////////
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief C++ Wrapper of Obj-C Autorelease Pool.
+///
+////////////////////////////////////////////////////////////
+class PoolWrapper : NonCopyable {
+public :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Default constructor
+ ///
+ ////////////////////////////////////////////////////////////
+ PoolWrapper();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Default destructor
+ ///
+ ////////////////////////////////////////////////////////////
+ ~PoolWrapper();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Increment retain count and allocate memory if needed
+ ///
+ ////////////////////////////////////////////////////////////
+ void retain();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Decrement retain count and releasing memory if needed
+ ///
+ ////////////////////////////////////////////////////////////
+ void release();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Drain the pool
+ ///
+ ////////////////////////////////////////////////////////////
+ void Drain();
+
+private:
+
+ ////////////////////////////////////////////////////////////
+ // Member data
+ ////////////////////////////////////////////////////////////
+ int m_count; ///< How many times was the pool retained ?
+ NSAutoreleasePool* m_pool; ///< Our dedicated pool
+};
+
+
+////////////////////////////////////////////////////////////
+PoolWrapper::PoolWrapper()
+: m_count(0)
+, m_pool(0)
+{
+ /* Nothing else */
+}
+
+
+////////////////////////////////////////////////////////////
+PoolWrapper::~PoolWrapper()
+{
+#ifdef SFML_DEBUG
+ if (m_count < 0) {
+ sf::err() << "~PoolWrapper : m_count is less than zero! "
+ "You called releasePool from a thread too many times."
+ << std::endl;
+ } else if (m_count > 0) {
+ sf::err() << "~PoolWrapper : m_count is greater than zero! "
+ "You called releasePool from a thread to few times."
+ << std::endl;
+ } else { // m_count == 0
+ sf::err() << "~PoolWrapper is HAPPY!" << std::endl;
+ }
+#endif
+}
+
+
+////////////////////////////////////////////////////////////
+void PoolWrapper::retain()
+{
+ // Increase counter.
+ ++m_count;
+
+ // Allocate pool if required.
+ if (m_pool == 0) {
+ m_pool = [[NSAutoreleasePool alloc] init];
+ }
+
+#ifdef SFML_DEBUG
+ if (m_count <= 0) {
+ sf::err() << "PoolWrapper::retain : m_count <= 0! " << std::endl;
+ }
+#endif
+}
+
+
+////////////////////////////////////////////////////////////
+void PoolWrapper::release()
+{
+ // Decrease counter.
+ --m_count;
+
+ // Drain pool if required.
+ if (m_count == 0) {
+ Drain();
+ }
+
+#ifdef SFML_DEBUG
+ if (m_count < 0) {
+ sf::err() << "PoolWrapper::release : m_count < 0! " << std::endl;
+ }
+#endif
+}
+
+void PoolWrapper::Drain()
+{
+ [m_pool drain];
+ m_pool = 0;
+
+ if (m_count != 0) {
+ m_pool = [[NSAutoreleasePool alloc] init];
+ }
+}
+
+
+} // namespace priv
+
+} // namespace sf
+
+////////////////////////////////////////////////////////////
+// Private data
+////////////////////////////////////////////////////////////
+namespace
+{
+ // This per-thread variable holds the current autorelease pool for each thread
+ sf::ThreadLocalPtr<sf::priv::PoolWrapper> localPool;
+}
+
+
+////////////////////////////////////////////////////////////
+void retainPool(void)
+{
+ // First, Check that we have a valid PoolWrapper object in our local pool.
+ if (localPool == NULL) {
+ localPool = new sf::priv::PoolWrapper();
+ }
+
+ // Then retains!
+ localPool->retain();
+}
+
+
+////////////////////////////////////////////////////////////
+void releasePool(void)
+{
+#ifdef SFML_DEBUG
+ if (localPool == NULL) {
+ sf::err() << "releasePool : You must call retainPool at least once "
+ "in this thread before calling releasePool."
+ << std::endl;
+ } else {
+#endif
+
+ // Releases, that's all.
+ localPool->release();
+
+#ifdef SFML_DEBUG
+ }
+#endif
+}
+
+
+////////////////////////////////////////////////////////////
+void drainPool()
+{
+ if (localPool != NULL) {
+ localPool->Drain();
+ }
+#ifdef SFML_DEBUG
+ else {
+ sf::err() << "releasePool must be called at least one before drainPool"
+ << std::endl;
+ }
+#endif
+}
+
diff --git a/src/SFML/Window/OSX/HIDInputManager.hpp b/src/SFML/Window/OSX/HIDInputManager.hpp
new file mode 100644
index 0000000..e6f7229
--- /dev/null
+++ b/src/SFML/Window/OSX/HIDInputManager.hpp
@@ -0,0 +1,264 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_HIDINPUTMANAGER_HPP
+#define SFML_HIDINPUTMANAGER_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/System/NonCopyable.hpp>
+#include <SFML/Window/JoystickImpl.hpp>
+#include <SFML/Window/Keyboard.hpp>
+#include <SFML/Window/Mouse.hpp>
+#include <Carbon/Carbon.h>
+#include <IOKit/hid/IOHIDManager.h>
+#include <IOKit/hid/IOHIDDevice.h>
+#include <vector>
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief This class manage as a singleton instance the
+/// keyboard and mouse states. It's only purpose is
+/// to help sf::priv::InputImpl class.
+///
+////////////////////////////////////////////////////////////
+class HIDInputManager : NonCopyable
+{
+public :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Get the unique instance of the class
+ ///
+ /// \note Private use only
+ ///
+ /// \return Reference to the HIDInputManager instance
+ ///
+ ////////////////////////////////////////////////////////////
+ static HIDInputManager& getInstance();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Check if a key is pressed
+ ///
+ /// \param key Key to check
+ ///
+ /// \return True if the key is pressed, false otherwise
+ ///
+ ////////////////////////////////////////////////////////////
+ bool isKeyPressed(Keyboard::Key key);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Check if a mouse button is pressed
+ ///
+ /// \param button Button to check
+ ///
+ /// \return True if the button is pressed, false otherwise
+ ///
+ ////////////////////////////////////////////////////////////
+ bool isMouseButtonPressed(Mouse::Button button);
+
+public :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Get the usb location ID of a given device
+ ///
+ /// This location ID is unique and can be used a usb port identifier
+ ///
+ /// \param device HID device to query
+ /// \return the device's location ID or 0 if something went wrong
+ ///
+ ////////////////////////////////////////////////////////////
+ static long getLocationID(IOHIDDeviceRef device);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Create a mask (dictionary) for an IOHIDManager
+ ///
+ /// \param page HID page
+ /// \param usage HID usage page
+ /// \return a retained CFDictionaryRef
+ ///
+ ////////////////////////////////////////////////////////////
+ static CFDictionaryRef copyDevicesMask(UInt32 page, UInt32 usage);
+
+ ////////////////////////////////////////////////////////////
+ /// Try to convert a character into a SFML key code.
+ ///
+ /// Return sf::Keyboard::Unknown if it doesn't match any 'localized' keys.
+ ///
+ /// By 'localized' I mean keys that depend on the keyboard layout
+ /// and might not be the same as the US keycode in some country
+ /// (e.g. the keys 'Y' and 'Z' are switched on QWERTZ keyboard and
+ /// US keyboard layouts.)
+ ///
+ ////////////////////////////////////////////////////////////
+ static Keyboard::Key localizedKeys(UniChar ch);
+
+ ////////////////////////////////////////////////////////////
+ /// Try to convert a virtual keycode into a SFML key code.
+ ///
+ /// Return sf::Keyboard::Unknown if the keycode is unknown.
+ ///
+ ////////////////////////////////////////////////////////////
+ static Keyboard::Key nonLocalizedKeys(UniChar virtualKeycode);
+
+private :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Default constructor
+ ///
+ ////////////////////////////////////////////////////////////
+ HIDInputManager();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Destructor
+ ///
+ ////////////////////////////////////////////////////////////
+ ~HIDInputManager();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Initialize the keyboard part of this class
+ ///
+ /// If something went wrong freeUp is called
+ ///
+ ////////////////////////////////////////////////////////////
+ void initializeKeyboard();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Initialize the mouse part of this class
+ ///
+ /// If something went wrong freeUp is called
+ ///
+ ////////////////////////////////////////////////////////////
+ void initializeMouse();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Load the given keyboard into m_keys
+ ///
+ /// If the given keyboard has no key this function simply
+ /// returns. freeUp is _not_ called because this is not fatal.
+ ///
+ /// \param keyboard Keyboard to load
+ ///
+ ////////////////////////////////////////////////////////////
+ void loadKeyboard(IOHIDDeviceRef keyboard);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Load the given mouse into m_buttons
+ ///
+ /// If the given mouse has no button this function simply
+ /// returns. freeUp is _not_ called because this is not fatal.
+ ///
+ /// \param mouse Mouse to load
+ ///
+ ////////////////////////////////////////////////////////////
+ void loadMouse(IOHIDDeviceRef mouse);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Load the given key into m_keys
+ ///
+ /// freeUp is _not_ called by this function.
+ ///
+ /// \param key Key to load
+ ///
+ ////////////////////////////////////////////////////////////
+ void loadKey(IOHIDElementRef key);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Load the given button into m_buttons
+ ///
+ /// freeUp is _not_ called by this function.
+ ///
+ /// \param button Button to load
+ ///
+ ////////////////////////////////////////////////////////////
+ void loadButton(IOHIDElementRef button);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Release all resources
+ ///
+ /// Close all connections to any devices, if required
+ /// Set m_isValid to false
+ ///
+ ////////////////////////////////////////////////////////////
+ void freeUp();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Filter the devices and return them.
+ ///
+ /// freeUp is _not_ called by this function.
+ ///
+ /// \param page HID page like kHIDPage_GenericDesktop
+ /// \param usage HID usage page like kHIDUsage_GD_Keyboard or kHIDUsage_GD_Mouse
+ /// \return a retained CFSetRef of IOHIDDeviceRef or NULL
+ ///
+ ////////////////////////////////////////////////////////////
+ CFSetRef copyDevices(UInt32 page, UInt32 usage);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Convert a HID key usage to its corresponding virtual code
+ ///
+ /// See IOHIDUsageTables.h
+ ///
+ /// \param usage Any kHIDUsage_Keyboard* usage
+ /// \return the virtual code associate with the given HID key usage
+ /// or 0xff if it is associate with no virtual code
+ ///
+ ////////////////////////////////////////////////////////////
+ static UInt8 usageToVirtualCode(UInt32 usage);
+
+private :
+
+ ////////////////////////////////////////////////////////////
+ // Member data
+ ////////////////////////////////////////////////////////////
+ bool m_isValid; ///< If any error occurs this variable is false
+ CFDataRef m_layoutData; ///< CFData containing the layout
+ UCKeyboardLayout* m_layout; ///< Current Keyboard Layout
+ IOHIDManagerRef m_manager; ///< HID Manager
+
+ typedef std::vector<IOHIDElementRef> IOHIDElements;
+ IOHIDElements m_keys[Keyboard::KeyCount]; ///< All the keys on any connected keyboard
+ IOHIDElements m_buttons[Mouse::ButtonCount];///< All the buttons on any connected mouse
+
+ ////////////////////////////////////////////////////////////
+ /// m_keys' index corresponds to sf::Keyboard::Key enum.
+ /// if no key is assigned with key XYZ then m_keys[XYZ].size() == 0.
+ /// if there are several keyboards connected and several HID keys associate
+ /// with the same sf::Keyboard::Key then m_keys[XYZ] contains all these
+ /// HID keys.
+ ///
+ /// m_buttons works the same way.
+ ///
+ ////////////////////////////////////////////////////////////
+};
+
+} // namespace priv
+
+} // namespace sf
+
+#endif
diff --git a/src/SFML/Window/OSX/HIDInputManager.mm b/src/SFML/Window/OSX/HIDInputManager.mm
new file mode 100644
index 0000000..9f5b2d2
--- /dev/null
+++ b/src/SFML/Window/OSX/HIDInputManager.mm
@@ -0,0 +1,1027 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2012 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/OSX/HIDInputManager.hpp>
+#include <SFML/System/Err.hpp>
+#include <AppKit/AppKit.h>
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+HIDInputManager& HIDInputManager::getInstance()
+{
+ static HIDInputManager instance;
+ return instance;
+}
+
+
+////////////////////////////////////////////////////////////
+bool HIDInputManager::isKeyPressed(Keyboard::Key key)
+{
+ if (!m_isValid) {
+ sf::err() << "HIDInputManager is invalid." << std::endl;
+ return false;
+ }
+
+ // state = true if at least one corresponding HID key is pressed
+ bool state = false;
+
+ for (IOHIDElements::iterator it = m_keys[key].begin(); it != m_keys[key].end(); ++it) {
+
+ IOHIDValueRef value = 0;
+
+ IOHIDDeviceRef device = IOHIDElementGetDevice(*it);
+ IOHIDDeviceGetValue(device, *it, &value);
+
+ if (!value) {
+
+ // This means some kind of error / deconnection so we remove this
+ // element from our keys
+
+ CFRelease(*it);
+ it = m_keys[key].erase(it);
+
+ } else if (IOHIDValueGetIntegerValue(value) == 1) {
+
+ // This means the key is pressed
+ state = true;
+ break; // Stop here
+
+ } else {
+
+ // This means the key is released
+ }
+
+ }
+
+ return state;
+}
+
+////////////////////////////////////////////////////////////
+bool HIDInputManager::isMouseButtonPressed(Mouse::Button button)
+{
+ if (!m_isValid) {
+ sf::err() << "HIDInputManager is invalid." << std::endl;
+ return false;
+ }
+
+ // state = true if at least one corresponding HID button is pressed
+ bool state = false;
+
+ for (IOHIDElements::iterator it = m_buttons[button].begin(); it != m_buttons[button].end(); ++it) {
+
+ IOHIDValueRef value = 0;
+
+ IOHIDDeviceRef device = IOHIDElementGetDevice(*it);
+ IOHIDDeviceGetValue(device, *it, &value);
+
+ if (!value) {
+
+ // This means some kind of error / deconnection so we remove this
+ // element from our buttons
+
+ CFRelease(*it);
+ it = m_buttons[button].erase(it);
+
+ } else if (IOHIDValueGetIntegerValue(value) == 1) {
+
+ // This means the button is pressed
+ state = true;
+ break; // Stop here
+
+ } else {
+
+ // This means the button is released
+ }
+
+ }
+
+ return state;
+}
+
+
+////////////////////////////////////////////////////////////
+long HIDInputManager::getLocationID(IOHIDDeviceRef device)
+{
+ long loc = 0;
+
+ // Get a unique ID : its usb location ID
+ CFTypeRef typeRef = IOHIDDeviceGetProperty(device,
+ CFSTR(kIOHIDLocationIDKey));
+ if (!typeRef || CFGetTypeID(typeRef) != CFNumberGetTypeID()) {
+ return 0;
+ }
+
+ CFNumberRef locRef = (CFNumberRef)typeRef;
+
+ if (!CFNumberGetValue(locRef, kCFNumberLongType, &loc)) {
+ return 0;
+ }
+
+ return loc;
+}
+
+
+////////////////////////////////////////////////////////////
+CFDictionaryRef HIDInputManager::copyDevicesMask(UInt32 page, UInt32 usage)
+{
+ // Create the dictionary.
+ CFMutableDictionaryRef dict = CFDictionaryCreateMutable(kCFAllocatorDefault, 2,
+ &kCFTypeDictionaryKeyCallBacks,
+ &kCFTypeDictionaryValueCallBacks);
+
+ // Add the page value.
+ CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &page);
+ CFDictionarySetValue(dict, CFSTR(kIOHIDDeviceUsagePageKey), value);
+ CFRelease(value);
+
+ // Add the usage value (which is only valid if page value exists).
+ value = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &usage);
+ CFDictionarySetValue(dict, CFSTR(kIOHIDDeviceUsageKey), value);
+ CFRelease(value);
+
+ return dict;
+}
+
+
+////////////////////////////////////////////////////////////
+HIDInputManager::HIDInputManager()
+: m_isValid(true)
+, m_layoutData(0)
+, m_layout(0)
+, m_manager(0)
+{
+ // Get the current keyboard layout
+ TISInputSourceRef tis = TISCopyCurrentKeyboardLayoutInputSource();
+ m_layoutData = (CFDataRef)TISGetInputSourceProperty(tis,
+ kTISPropertyUnicodeKeyLayoutData);
+
+ if (m_layoutData == 0) {
+ sf::err() << "Cannot get the keyboard layout" << std::endl;
+ freeUp();
+ return;
+ }
+
+ // Keep a reference for ourself
+ CFRetain(m_layoutData);
+ m_layout = (UCKeyboardLayout *)CFDataGetBytePtr(m_layoutData);
+
+ // The TIS is no more needed
+ CFRelease(tis);
+
+ // Create an HID Manager reference
+ m_manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
+
+ // Open the HID Manager reference
+ IOReturn openStatus = IOHIDManagerOpen(m_manager, kIOHIDOptionsTypeNone);
+
+ if (openStatus != kIOReturnSuccess) {
+ sf::err() << "Error when opening the HID manager" << std::endl;
+
+ freeUp();
+ return;
+ }
+
+ // Initialize the keyboard
+ initializeKeyboard();
+
+ if (!m_isValid) {
+ return; // Something went wrong
+ }
+
+ // Initialize the mouse
+ initializeMouse();
+
+ if (!m_isValid) {
+ return; // Something went wrong
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+HIDInputManager::~HIDInputManager()
+{
+ freeUp();
+}
+
+
+void HIDInputManager::initializeKeyboard()
+{
+ ////////////////////////////////////////////////////////////
+ // The purpose of this function is to initalize m_keys so we can get
+ // the associate IOHIDElementRef with a sf::Keyboard::Key in ~constant~ time.
+
+ // Get only keyboards
+ CFSetRef keyboards = copyDevices(kHIDPage_GenericDesktop, kHIDUsage_GD_Keyboard);
+ if (keyboards == NULL) {
+ freeUp();
+ return;
+ }
+
+ CFIndex keyboardCount = CFSetGetCount(keyboards); // >= 1 (asserted by copyDevices)
+
+ // Get an iterable array
+ CFTypeRef devicesArray[keyboardCount];
+ CFSetGetValues(keyboards, devicesArray);
+
+ for (CFIndex i = 0; i < keyboardCount; ++i) {
+
+ IOHIDDeviceRef keyboard = (IOHIDDeviceRef)devicesArray[i];
+
+ loadKeyboard(keyboard);
+ }
+
+ // Release unused stuff
+ CFRelease(keyboards);
+
+ ////////////////////////////////////////////////////////////
+ // At this point m_keys is filled with as many IOHIDElementRef as possible
+}
+
+
+////////////////////////////////////////////////////////////
+void HIDInputManager::initializeMouse()
+{
+ ////////////////////////////////////////////////////////////
+ // The purpose of this function is to initalize m_buttons so we can get
+ // the associate IOHIDElementRef with a sf::Mouse::Button in ~constant~ time.
+
+ // Get only mouses
+ CFSetRef mouses = copyDevices(kHIDPage_GenericDesktop, kHIDUsage_GD_Mouse);
+ if (mouses == NULL) {
+ freeUp();
+ return;
+ }
+
+ CFIndex mouseCount = CFSetGetCount(mouses); // >= 1 (asserted by copyDevices)
+
+ // Get an iterable array
+ CFTypeRef devicesArray[mouseCount];
+ CFSetGetValues(mouses, devicesArray);
+
+ for (CFIndex i = 0; i < mouseCount; ++i) {
+
+ IOHIDDeviceRef mouse = (IOHIDDeviceRef)devicesArray[i];
+
+ loadMouse(mouse);
+ }
+
+ // Release unused stuff
+ CFRelease(mouses);
+
+ ////////////////////////////////////////////////////////////
+ // At this point m_buttons is filled with as many IOHIDElementRef as possible
+}
+
+
+////////////////////////////////////////////////////////////
+void HIDInputManager::loadKeyboard(IOHIDDeviceRef keyboard)
+{
+ CFArrayRef keys = IOHIDDeviceCopyMatchingElements(keyboard,
+ NULL,
+ kIOHIDOptionsTypeNone);
+ if (keys == NULL) {
+ sf::err() << "We got a keyboard without any keys (1)" << std::endl;
+ return;
+ }
+
+ // How many elements are there ?
+ CFIndex keysCount = CFArrayGetCount(keys);
+
+ if (keysCount == 0) {
+ sf::err() << "We got a keyboard without any keys (2)" << std::endl;
+ CFRelease(keys);
+ return;
+ }
+
+ // Go through all connected elements.
+ for (CFIndex i = 0; i < keysCount; ++i) {
+
+ IOHIDElementRef aKey = (IOHIDElementRef) CFArrayGetValueAtIndex(keys, i);
+
+ // Skip non-matching keys elements
+ if (IOHIDElementGetUsagePage(aKey) != kHIDPage_KeyboardOrKeypad) {
+ continue;
+ }
+
+ loadKey(aKey);
+
+ }
+
+ // Release unused stuff
+ CFRelease(keys);
+}
+
+
+////////////////////////////////////////////////////////////
+void HIDInputManager::loadMouse(IOHIDDeviceRef mouse)
+{
+ CFArrayRef buttons = IOHIDDeviceCopyMatchingElements(mouse,
+ NULL,
+ kIOHIDOptionsTypeNone);
+ if (buttons == NULL) {
+ sf::err() << "We got a mouse without any buttons (1)" << std::endl;
+ return;
+ }
+
+ // How many elements are there ?
+ CFIndex buttonCount = CFArrayGetCount(buttons);
+
+ if (buttonCount == 0) {
+ sf::err() << "We got a mouse without any buttons (2)" << std::endl;
+ CFRelease(buttons);
+ return;
+ }
+
+ // Go through all connected elements.
+ for (CFIndex i = 0; i < buttonCount; ++i) {
+
+ IOHIDElementRef aButton = (IOHIDElementRef) CFArrayGetValueAtIndex(buttons, i);
+
+ // Skip non-matching keys elements
+ if (IOHIDElementGetUsagePage(aButton) != kHIDPage_Button) {
+ continue;
+ }
+
+ loadButton(aButton);
+ }
+
+ // Release unused stuff
+ CFRelease(buttons);
+}
+
+
+////////////////////////////////////////////////////////////
+void HIDInputManager::loadKey(IOHIDElementRef key)
+{
+ // Get its virtual code
+ UInt32 usageCode = IOHIDElementGetUsage(key);
+ UInt8 virtualCode = usageToVirtualCode(usageCode);
+
+ if (virtualCode == 0xff) {
+ return; // no corresponding virtual code -> skip
+ }
+
+ // Now translate the virtual code to unicode according to
+ // the current keyboard layout
+
+ UInt32 deadKeyState = 0;
+ // Unicode string length is usually less or equal to 4
+ UniCharCount maxStringLength = 4;
+ UniCharCount actualStringLength = 0;
+ UniChar unicodeString[maxStringLength];
+
+ OSStatus error;
+
+ error = UCKeyTranslate(m_layout, // current layout
+ virtualCode, // our key
+ kUCKeyActionDown, // or kUCKeyActionUp ?
+ 0x100, // no modifiers
+ LMGetKbdType(), // keyboard's type
+ kUCKeyTranslateNoDeadKeysBit,// some sort of option
+ &deadKeyState, // unused stuff
+ maxStringLength, // our memory limit
+ &actualStringLength, // length of what we get
+ unicodeString); // what we get
+
+ if (error == noErr) {
+ // Translation went fine
+
+ // The corresponding SFML key code
+ Keyboard::Key code = Keyboard::Unknown; // KeyCound means 'none'
+
+ // First we look if the key down is from a list of characters
+ // that depend on keyboard localization
+ if (actualStringLength > 0) {
+ code = localizedKeys(unicodeString[0]);
+ }
+
+ // The key is not a localized one so we try to find a
+ // corresponding code through virtual key code
+ if (code == Keyboard::Unknown) {
+ code = nonLocalizedKeys(virtualCode);
+ }
+
+ // A code was found, wonderful!
+ if (code != Keyboard::Unknown) {
+
+ // Ok, everything went fine. Now we have a unique
+ // corresponding sf::Keyboard::Key to one IOHIDElementRef
+
+ m_keys[code].push_back(key);
+
+ // And don't forget to keep the reference alive for our usage
+ CFRetain(m_keys[code].back());
+
+ }
+
+ ////////////////////////////////////////////////////////////
+ // These are known to be unbound :
+ // Supposed Virtual | HID | Supposed Key
+ // ===============================================
+ // 0x1b | 0x2d | Hyphen
+ // 0x39 | 0x39 | CapsLock
+ // 0x47 | 0x53 | NumLock
+ // 0x6e | 0x65 | Application
+ // 0x4c | 0x77 | Select
+
+ //if (code == Keyboard::Unknown) { // The key is unknown.
+ // sf::err() << "This is an unknow key. Virtual key code is 0x"
+ // << std::hex
+ // << (UInt32)virtualCode
+ // << " and HID usage code is 0x"
+ // << usageCode
+ // << std::dec
+ // << "."
+ // << std::endl;
+ //}
+
+ } /* if (error == noErr) */
+ else {
+
+ sf::err() << "Cannot translate the virtual key code, error : "
+ << error
+ << std::endl;
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void HIDInputManager::loadButton(IOHIDElementRef button)
+{
+ // Identify the button
+ UInt32 usage = IOHIDElementGetUsage(button);
+ Mouse::Button dest = Mouse::ButtonCount;
+
+ // Extends kHIDUsage_Button_* enum with :
+#define kHIDUsage_Button_5 0x05
+
+ switch (usage) {
+ case kHIDUsage_Button_1: dest = Mouse::Left; break;
+ case kHIDUsage_Button_2: dest = Mouse::Right; break;
+ case kHIDUsage_Button_3: dest = Mouse::Middle; break;
+ case kHIDUsage_Button_4: dest = Mouse::XButton1; break;
+ case kHIDUsage_Button_5: dest = Mouse::XButton2; break;
+ default: dest = Mouse::ButtonCount; break;
+ }
+
+ if (dest != Mouse::ButtonCount) {
+ // We know what kind of button it is!
+
+ m_buttons[dest].push_back(button);
+
+ // And don't forget to keep the reference alive for our usage
+ CFRetain(m_buttons[dest].back());
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void HIDInputManager::freeUp()
+{
+ m_isValid = false;
+
+ if (m_layoutData != 0) CFRelease(m_layoutData);
+ // Do not release m_layout ! It is owned by m_layoutData.
+ if (m_manager != 0) CFRelease(m_manager);
+
+ for (unsigned int i = 0; i < Keyboard::KeyCount; ++i) {
+ for (IOHIDElements::iterator it = m_keys[i].begin(); it != m_keys[i].end(); ++it) {
+ CFRelease(*it);
+ }
+ m_keys[i].clear();
+ }
+
+ for (unsigned int i = 0; i < Mouse::ButtonCount; ++i) {
+ for (IOHIDElements::iterator it = m_buttons[i].begin(); it != m_buttons[i].end(); ++it) {
+ CFRelease(*it);
+ }
+ m_buttons[i].clear();
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+CFSetRef HIDInputManager::copyDevices(UInt32 page, UInt32 usage)
+{
+ // Filter and keep only the requested devices
+ CFDictionaryRef mask = copyDevicesMask(page, usage);
+
+ IOHIDManagerSetDeviceMatching(m_manager, mask);
+
+ CFRelease(mask);
+ mask = 0;
+
+ CFSetRef devices = IOHIDManagerCopyDevices(m_manager);
+ if (devices == NULL) {
+ return NULL;
+ }
+
+ // Is there at least one device ?
+ CFIndex deviceCount = CFSetGetCount(devices);
+ if (deviceCount < 1) {
+ CFRelease(devices);
+ return NULL;
+ }
+
+ return devices;
+}
+
+
+////////////////////////////////////////////////////////////
+UInt8 HIDInputManager::usageToVirtualCode(UInt32 usage)
+{
+ // Some usage key doesn't have any corresponding virtual
+ // code or it was not found (return 0xff).
+ switch (usage) {
+ case kHIDUsage_KeyboardErrorRollOver: return 0xff;
+ case kHIDUsage_KeyboardPOSTFail: return 0xff;
+ case kHIDUsage_KeyboardErrorUndefined: return 0xff;
+
+ case kHIDUsage_KeyboardA: return 0x00;
+ case kHIDUsage_KeyboardB: return 0x0b;
+ case kHIDUsage_KeyboardC: return 0x08;
+ case kHIDUsage_KeyboardD: return 0x02;
+ case kHIDUsage_KeyboardE: return 0x0e;
+ case kHIDUsage_KeyboardF: return 0x03;
+ case kHIDUsage_KeyboardG: return 0x05;
+ case kHIDUsage_KeyboardH: return 0x04;
+ case kHIDUsage_KeyboardI: return 0x22;
+ case kHIDUsage_KeyboardJ: return 0x26;
+ case kHIDUsage_KeyboardK: return 0x28;
+ case kHIDUsage_KeyboardL: return 0x25;
+ case kHIDUsage_KeyboardM: return 0x2e;
+ case kHIDUsage_KeyboardN: return 0x2d;
+ case kHIDUsage_KeyboardO: return 0x1f;
+ case kHIDUsage_KeyboardP: return 0x23;
+ case kHIDUsage_KeyboardQ: return 0x0c;
+ case kHIDUsage_KeyboardR: return 0x0f;
+ case kHIDUsage_KeyboardS: return 0x01;
+ case kHIDUsage_KeyboardT: return 0x11;
+ case kHIDUsage_KeyboardU: return 0x20;
+ case kHIDUsage_KeyboardV: return 0x09;
+ case kHIDUsage_KeyboardW: return 0x0d;
+ case kHIDUsage_KeyboardX: return 0x07;
+ case kHIDUsage_KeyboardY: return 0x10;
+ case kHIDUsage_KeyboardZ: return 0x06;
+
+ case kHIDUsage_Keyboard1: return 0x12;
+ case kHIDUsage_Keyboard2: return 0x13;
+ case kHIDUsage_Keyboard3: return 0x14;
+ case kHIDUsage_Keyboard4: return 0x15;
+ case kHIDUsage_Keyboard5: return 0x17;
+ case kHIDUsage_Keyboard6: return 0x16;
+ case kHIDUsage_Keyboard7: return 0x1a;
+ case kHIDUsage_Keyboard8: return 0x1c;
+ case kHIDUsage_Keyboard9: return 0x19;
+ case kHIDUsage_Keyboard0: return 0x1d;
+
+ case kHIDUsage_KeyboardReturnOrEnter: return 0x24;
+ case kHIDUsage_KeyboardEscape: return 0x35;
+ case kHIDUsage_KeyboardDeleteOrBackspace: return 0x33;
+ case kHIDUsage_KeyboardTab: return 0x30;
+ case kHIDUsage_KeyboardSpacebar: return 0x31;
+ case kHIDUsage_KeyboardHyphen: return 0x1b;
+ case kHIDUsage_KeyboardEqualSign: return 0x18;
+ case kHIDUsage_KeyboardOpenBracket: return 0x21;
+ case kHIDUsage_KeyboardCloseBracket: return 0x1e;
+ case kHIDUsage_KeyboardBackslash: return 0x2a;
+ case kHIDUsage_KeyboardNonUSPound: return 0xff;
+ case kHIDUsage_KeyboardSemicolon: return 0x29;
+ case kHIDUsage_KeyboardQuote: return 0x27;
+ case kHIDUsage_KeyboardGraveAccentAndTilde: return 0x32;
+ case kHIDUsage_KeyboardComma: return 0x2b;
+ case kHIDUsage_KeyboardPeriod: return 0x2F;
+ case kHIDUsage_KeyboardSlash: return 0x2c;
+ case kHIDUsage_KeyboardCapsLock: return 0x39;
+
+ case kHIDUsage_KeyboardF1: return 0x7a;
+ case kHIDUsage_KeyboardF2: return 0x78;
+ case kHIDUsage_KeyboardF3: return 0x63;
+ case kHIDUsage_KeyboardF4: return 0x76;
+ case kHIDUsage_KeyboardF5: return 0x60;
+ case kHIDUsage_KeyboardF6: return 0x61;
+ case kHIDUsage_KeyboardF7: return 0x62;
+ case kHIDUsage_KeyboardF8: return 0x64;
+ case kHIDUsage_KeyboardF9: return 0x65;
+ case kHIDUsage_KeyboardF10: return 0x6d;
+ case kHIDUsage_KeyboardF11: return 0x67;
+ case kHIDUsage_KeyboardF12: return 0x6f;
+
+ case kHIDUsage_KeyboardPrintScreen: return 0xff;
+ case kHIDUsage_KeyboardScrollLock: return 0xff;
+ case kHIDUsage_KeyboardPause: return 0xff;
+ case kHIDUsage_KeyboardInsert: return 0x72;
+ case kHIDUsage_KeyboardHome: return 0x73;
+ case kHIDUsage_KeyboardPageUp: return 0x74;
+ case kHIDUsage_KeyboardDeleteForward: return 0x75;
+ case kHIDUsage_KeyboardEnd: return 0x77;
+ case kHIDUsage_KeyboardPageDown: return 0x79;
+
+ case kHIDUsage_KeyboardRightArrow: return 0x7c;
+ case kHIDUsage_KeyboardLeftArrow: return 0x7b;
+ case kHIDUsage_KeyboardDownArrow: return 0x7d;
+ case kHIDUsage_KeyboardUpArrow: return 0x7e;
+
+ case kHIDUsage_KeypadNumLock: return 0x47;
+ case kHIDUsage_KeypadSlash: return 0x4b;
+ case kHIDUsage_KeypadAsterisk: return 0x43;
+ case kHIDUsage_KeypadHyphen: return 0x4e;
+ case kHIDUsage_KeypadPlus: return 0x45;
+ case kHIDUsage_KeypadEnter: return 0x4c;
+
+ case kHIDUsage_Keypad1: return 0x53;
+ case kHIDUsage_Keypad2: return 0x54;
+ case kHIDUsage_Keypad3: return 0x55;
+ case kHIDUsage_Keypad4: return 0x56;
+ case kHIDUsage_Keypad5: return 0x57;
+ case kHIDUsage_Keypad6: return 0x58;
+ case kHIDUsage_Keypad7: return 0x59;
+ case kHIDUsage_Keypad8: return 0x5b;
+ case kHIDUsage_Keypad9: return 0x5c;
+ case kHIDUsage_Keypad0: return 0x52;
+
+ case kHIDUsage_KeypadPeriod: return 0x41;
+ case kHIDUsage_KeyboardNonUSBackslash: return 0xff;
+ case kHIDUsage_KeyboardApplication: return 0x6e;
+ case kHIDUsage_KeyboardPower: return 0xff;
+ case kHIDUsage_KeypadEqualSign: return 0x51;
+
+ case kHIDUsage_KeyboardF13: return 0x69;
+ case kHIDUsage_KeyboardF14: return 0x6b;
+ case kHIDUsage_KeyboardF15: return 0x71;
+ case kHIDUsage_KeyboardF16: return 0xff;
+ case kHIDUsage_KeyboardF17: return 0xff;
+ case kHIDUsage_KeyboardF18: return 0xff;
+ case kHIDUsage_KeyboardF19: return 0xff;
+ case kHIDUsage_KeyboardF20: return 0xff;
+ case kHIDUsage_KeyboardF21: return 0xff;
+ case kHIDUsage_KeyboardF22: return 0xff;
+ case kHIDUsage_KeyboardF23: return 0xff;
+ case kHIDUsage_KeyboardF24: return 0xff;
+
+ case kHIDUsage_KeyboardExecute: return 0xff;
+ case kHIDUsage_KeyboardHelp: return 0xff;
+ case kHIDUsage_KeyboardMenu: return 0x7F;
+ case kHIDUsage_KeyboardSelect: return 0x4c;
+ case kHIDUsage_KeyboardStop: return 0xff;
+ case kHIDUsage_KeyboardAgain: return 0xff;
+ case kHIDUsage_KeyboardUndo: return 0xff;
+ case kHIDUsage_KeyboardCut: return 0xff;
+ case kHIDUsage_KeyboardCopy: return 0xff;
+ case kHIDUsage_KeyboardPaste: return 0xff;
+ case kHIDUsage_KeyboardFind: return 0xff;
+
+ case kHIDUsage_KeyboardMute: return 0xff;
+ case kHIDUsage_KeyboardVolumeUp: return 0xff;
+ case kHIDUsage_KeyboardVolumeDown: return 0xff;
+
+ case kHIDUsage_KeyboardLockingCapsLock: return 0xff;
+ case kHIDUsage_KeyboardLockingNumLock: return 0xff;
+ case kHIDUsage_KeyboardLockingScrollLock: return 0xff;
+
+ case kHIDUsage_KeypadComma: return 0xff;
+ case kHIDUsage_KeypadEqualSignAS400: return 0xff;
+ case kHIDUsage_KeyboardInternational1: return 0xff;
+ case kHIDUsage_KeyboardInternational2: return 0xff;
+ case kHIDUsage_KeyboardInternational3: return 0xff;
+ case kHIDUsage_KeyboardInternational4: return 0xff;
+ case kHIDUsage_KeyboardInternational5: return 0xff;
+ case kHIDUsage_KeyboardInternational6: return 0xff;
+ case kHIDUsage_KeyboardInternational7: return 0xff;
+ case kHIDUsage_KeyboardInternational8: return 0xff;
+ case kHIDUsage_KeyboardInternational9: return 0xff;
+
+ case kHIDUsage_KeyboardLANG1: return 0xff;
+ case kHIDUsage_KeyboardLANG2: return 0xff;
+ case kHIDUsage_KeyboardLANG3: return 0xff;
+ case kHIDUsage_KeyboardLANG4: return 0xff;
+ case kHIDUsage_KeyboardLANG5: return 0xff;
+ case kHIDUsage_KeyboardLANG6: return 0xff;
+ case kHIDUsage_KeyboardLANG7: return 0xff;
+ case kHIDUsage_KeyboardLANG8: return 0xff;
+ case kHIDUsage_KeyboardLANG9: return 0xff;
+
+ case kHIDUsage_KeyboardAlternateErase: return 0xff;
+ case kHIDUsage_KeyboardSysReqOrAttention: return 0xff;
+ case kHIDUsage_KeyboardCancel: return 0xff;
+ case kHIDUsage_KeyboardClear: return 0xff;
+ case kHIDUsage_KeyboardPrior: return 0xff;
+ case kHIDUsage_KeyboardReturn: return 0xff;
+ case kHIDUsage_KeyboardSeparator: return 0xff;
+ case kHIDUsage_KeyboardOut: return 0xff;
+ case kHIDUsage_KeyboardOper: return 0xff;
+ case kHIDUsage_KeyboardClearOrAgain: return 0xff;
+ case kHIDUsage_KeyboardCrSelOrProps: return 0xff;
+ case kHIDUsage_KeyboardExSel: return 0xff;
+
+ /* 0xa5-0xdf Reserved */
+
+ case kHIDUsage_KeyboardLeftControl: return 0x3b;
+ case kHIDUsage_KeyboardLeftShift: return 0x38;
+ case kHIDUsage_KeyboardLeftAlt: return 0x3a;
+ case kHIDUsage_KeyboardLeftGUI: return 0x37;
+ case kHIDUsage_KeyboardRightControl: return 0x3e;
+ case kHIDUsage_KeyboardRightShift: return 0x3c;
+ case kHIDUsage_KeyboardRightAlt: return 0x3d;
+ case kHIDUsage_KeyboardRightGUI: return 0x36;
+
+ /* 0xe8-0xffff Reserved */
+
+ case kHIDUsage_Keyboard_Reserved: return 0xff;
+ default: return 0xff;
+ }
+}
+
+
+////////////////////////////////////////////////////////
+Keyboard::Key HIDInputManager::localizedKeys(UniChar ch)
+{
+ switch (ch) {
+ case 'a':
+ case 'A': return sf::Keyboard::A;
+
+ case 'b':
+ case 'B': return sf::Keyboard::B;
+
+ case 'c':
+ case 'C': return sf::Keyboard::C;
+
+ case 'd':
+ case 'D': return sf::Keyboard::D;
+
+ case 'e':
+ case 'E': return sf::Keyboard::E;
+
+ case 'f':
+ case 'F': return sf::Keyboard::F;
+
+ case 'g':
+ case 'G': return sf::Keyboard::G;
+
+ case 'h':
+ case 'H': return sf::Keyboard::H;
+
+ case 'i':
+ case 'I': return sf::Keyboard::I;
+
+ case 'j':
+ case 'J': return sf::Keyboard::J;
+
+ case 'k':
+ case 'K': return sf::Keyboard::K;
+
+ case 'l':
+ case 'L': return sf::Keyboard::L;
+
+ case 'm':
+ case 'M': return sf::Keyboard::M;
+
+ case 'n':
+ case 'N': return sf::Keyboard::N;
+
+ case 'o':
+ case 'O': return sf::Keyboard::O;
+
+ case 'p':
+ case 'P': return sf::Keyboard::P;
+
+ case 'q':
+ case 'Q': return sf::Keyboard::Q;
+
+ case 'r':
+ case 'R': return sf::Keyboard::R;
+
+ case 's':
+ case 'S': return sf::Keyboard::S;
+
+ case 't':
+ case 'T': return sf::Keyboard::T;
+
+ case 'u':
+ case 'U': return sf::Keyboard::U;
+
+ case 'v':
+ case 'V': return sf::Keyboard::V;
+
+ case 'w':
+ case 'W': return sf::Keyboard::W;
+
+ case 'x':
+ case 'X': return sf::Keyboard::X;
+
+ case 'y':
+ case 'Y': return sf::Keyboard::Y;
+
+ case 'z':
+ case 'Z': return sf::Keyboard::Z;
+
+ // The key is not 'localized'.
+ default: return sf::Keyboard::Unknown;
+ }
+}
+
+
+////////////////////////////////////////////////////////
+Keyboard::Key HIDInputManager::nonLocalizedKeys(UniChar virtualKeycode)
+{
+ // (Some) 0x code based on http://forums.macrumors.com/showthread.php?t=780577
+ // Some sf::Keyboard::Key are present twice.
+ switch (virtualKeycode) {
+ // These cases should not be used but anyway...
+ case 0x00: return sf::Keyboard::A;
+ case 0x0b: return sf::Keyboard::B;
+ case 0x08: return sf::Keyboard::C;
+ case 0x02: return sf::Keyboard::D;
+ case 0x0e: return sf::Keyboard::E;
+ case 0x03: return sf::Keyboard::F;
+ case 0x05: return sf::Keyboard::G;
+ case 0x04: return sf::Keyboard::H;
+ case 0x22: return sf::Keyboard::I;
+ case 0x26: return sf::Keyboard::J;
+ case 0x28: return sf::Keyboard::K;
+ case 0x25: return sf::Keyboard::L;
+ case 0x2e: return sf::Keyboard::M;
+ case 0x2d: return sf::Keyboard::N;
+ case 0x1f: return sf::Keyboard::O;
+ case 0x23: return sf::Keyboard::P;
+ case 0x0c: return sf::Keyboard::Q;
+ case 0x0f: return sf::Keyboard::R;
+ case 0x01: return sf::Keyboard::S;
+ case 0x11: return sf::Keyboard::T;
+ case 0x20: return sf::Keyboard::U;
+ case 0x09: return sf::Keyboard::V;
+ case 0x0d: return sf::Keyboard::W;
+ case 0x07: return sf::Keyboard::X;
+ case 0x10: return sf::Keyboard::Y;
+ case 0x06: return sf::Keyboard::Z;
+
+ // These cases should not be used but anyway...
+ case 0x1d: return sf::Keyboard::Num0;
+ case 0x12: return sf::Keyboard::Num1;
+ case 0x13: return sf::Keyboard::Num2;
+ case 0x14: return sf::Keyboard::Num3;
+ case 0x15: return sf::Keyboard::Num4;
+ case 0x17: return sf::Keyboard::Num5;
+ case 0x16: return sf::Keyboard::Num6;
+ case 0x1a: return sf::Keyboard::Num7;
+ case 0x1c: return sf::Keyboard::Num8;
+ case 0x19: return sf::Keyboard::Num9;
+
+ case 0x35: return sf::Keyboard::Escape;
+
+ // Modifier keys : never happen with keyDown/keyUp methods (?)
+ case 0x3b: return sf::Keyboard::LControl;
+ case 0x38: return sf::Keyboard::LShift;
+ case 0x3a: return sf::Keyboard::LAlt;
+ case 0x37: return sf::Keyboard::LSystem;
+ case 0x3e: return sf::Keyboard::RControl;
+ case 0x3c: return sf::Keyboard::RShift;
+ case 0x3d: return sf::Keyboard::RAlt;
+ case 0x36: return sf::Keyboard::RSystem;
+
+ case 0x7f: return sf::Keyboard::Menu;
+ case NSMenuFunctionKey: return sf::Keyboard::Menu;
+
+ case 0x21: return sf::Keyboard::LBracket;
+ case 0x1e: return sf::Keyboard::RBracket;
+ case 0x29: return sf::Keyboard::SemiColon;
+ case 0x2b: return sf::Keyboard::Comma;
+ case 0x41: /* keypad */ return sf::Keyboard::Period;
+ case 0x2f: /* keyboard */ return sf::Keyboard::Period;
+ case 0x27: return sf::Keyboard::Quote;
+ case 0x2c: return sf::Keyboard::Slash;
+ case 0x2a: return sf::Keyboard::BackSlash;
+
+#warning sf::Keyboard::Tilde might be in conflict with some other key.
+ // 0x0a is for "Non-US Backslash" according to HID Calibrator,
+ // a sample provided by Apple.
+ case 0x0a: return sf::Keyboard::Tilde;
+
+ case 0x51: /* keypad */ return sf::Keyboard::Equal;
+ case 0x18: /* keyboard */ return sf::Keyboard::Equal;
+ case 0x32: return sf::Keyboard::Dash;
+ case 0x31: return sf::Keyboard::Space;
+ case 0x4c: /* keypad */ return sf::Keyboard::Return;
+ case 0x24: /* keyboard */ return sf::Keyboard::Return;
+ case 0x33: return sf::Keyboard::BackSpace;
+ case 0x30: return sf::Keyboard::Tab;
+
+ // Duplicates (see next §).
+ case 0x74: return sf::Keyboard::PageUp;
+ case 0x79: return sf::Keyboard::PageDown;
+ case 0x77: return sf::Keyboard::End;
+ case 0x73: return sf::Keyboard::Home;
+
+ case NSPageUpFunctionKey: return sf::Keyboard::PageUp;
+ case NSPageDownFunctionKey: return sf::Keyboard::PageDown;
+ case NSEndFunctionKey: return sf::Keyboard::End;
+ case NSHomeFunctionKey: return sf::Keyboard::Home;
+
+ case 0x72: return sf::Keyboard::Insert;
+ case NSInsertFunctionKey: return sf::Keyboard::Insert;
+ case 0x75: return sf::Keyboard::Delete;
+ case NSDeleteFunctionKey: return sf::Keyboard::Delete;
+
+ case 0x45: return sf::Keyboard::Add;
+ case 0x4e: return sf::Keyboard::Subtract;
+ case 0x43: return sf::Keyboard::Multiply;
+ case 0x4b: return sf::Keyboard::Divide;
+
+ // Duplicates (see next §).
+ case 0x7b: return sf::Keyboard::Left;
+ case 0x7c: return sf::Keyboard::Right;
+ case 0x7e: return sf::Keyboard::Up;
+ case 0x7d: return sf::Keyboard::Down;
+
+ case NSLeftArrowFunctionKey: return sf::Keyboard::Left;
+ case NSRightArrowFunctionKey: return sf::Keyboard::Right;
+ case NSUpArrowFunctionKey: return sf::Keyboard::Up;
+ case NSDownArrowFunctionKey: return sf::Keyboard::Down;
+
+ case 0x52: return sf::Keyboard::Numpad0;
+ case 0x53: return sf::Keyboard::Numpad1;
+ case 0x54: return sf::Keyboard::Numpad2;
+ case 0x55: return sf::Keyboard::Numpad3;
+ case 0x56: return sf::Keyboard::Numpad4;
+ case 0x57: return sf::Keyboard::Numpad5;
+ case 0x58: return sf::Keyboard::Numpad6;
+ case 0x59: return sf::Keyboard::Numpad7;
+ case 0x5b: return sf::Keyboard::Numpad8;
+ case 0x5c: return sf::Keyboard::Numpad9;
+
+ // Duplicates (see next §).
+ case 0x7a: return sf::Keyboard::F1;
+ case 0x78: return sf::Keyboard::F2;
+ case 0x63: return sf::Keyboard::F3;
+ case 0x76: return sf::Keyboard::F4;
+ case 0x60: return sf::Keyboard::F5;
+ case 0x61: return sf::Keyboard::F6;
+ case 0x62: return sf::Keyboard::F7;
+ case 0x64: return sf::Keyboard::F8;
+ case 0x65: return sf::Keyboard::F9;
+ case 0x6d: return sf::Keyboard::F10;
+ case 0x67: return sf::Keyboard::F11;
+ case 0x6f: return sf::Keyboard::F12;
+ case 0x69: return sf::Keyboard::F13;
+ case 0x6b: return sf::Keyboard::F14;
+ case 0x71: return sf::Keyboard::F15;
+
+ case NSF1FunctionKey: return sf::Keyboard::F1;
+ case NSF2FunctionKey: return sf::Keyboard::F2;
+ case NSF3FunctionKey: return sf::Keyboard::F3;
+ case NSF4FunctionKey: return sf::Keyboard::F4;
+ case NSF5FunctionKey: return sf::Keyboard::F5;
+ case NSF6FunctionKey: return sf::Keyboard::F6;
+ case NSF7FunctionKey: return sf::Keyboard::F7;
+ case NSF8FunctionKey: return sf::Keyboard::F8;
+ case NSF9FunctionKey: return sf::Keyboard::F9;
+ case NSF10FunctionKey: return sf::Keyboard::F10;
+ case NSF11FunctionKey: return sf::Keyboard::F11;
+ case NSF12FunctionKey: return sf::Keyboard::F12;
+ case NSF13FunctionKey: return sf::Keyboard::F13;
+ case NSF14FunctionKey: return sf::Keyboard::F14;
+ case NSF15FunctionKey: return sf::Keyboard::F15;
+
+ case NSPauseFunctionKey: return sf::Keyboard::Pause;
+
+#warning keycode 0x1b is not bound to any key.
+ // This key is ' on CH-FR, ) on FR and - on US layouts.
+
+ // An unknown key.
+ default: return sf::Keyboard::Unknown;
+ }
+}
+
+
+} // namespace priv
+
+} // namespace sf
+
diff --git a/src/SFML/Window/OSX/HIDJoystickManager.cpp b/src/SFML/Window/OSX/HIDJoystickManager.cpp
new file mode 100644
index 0000000..b2897a6
--- /dev/null
+++ b/src/SFML/Window/OSX/HIDJoystickManager.cpp
@@ -0,0 +1,151 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/OSX/HIDJoystickManager.hpp>
+#include <SFML/Window/OSX/HIDInputManager.hpp>
+
+////////////////////////////////////////////////////////////
+// Private data
+////////////////////////////////////////////////////////////
+namespace
+{
+ // Using a custom run loop mode solve some issues that appears when SFML
+ // is used with Cocoa.
+ CFStringRef const RunLoopMode = CFSTR("SFML_RUN_LOOP_MODE");
+}
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+HIDJoystickManager& HIDJoystickManager::getInstance()
+{
+ static HIDJoystickManager manager;
+ return manager;
+}
+
+
+////////////////////////////////////////////////////////////
+unsigned int HIDJoystickManager::getJoystickCount()
+{
+ update();
+ return m_joystickCount;
+}
+
+
+////////////////////////////////////////////////////////////
+CFSetRef HIDJoystickManager::copyJoysticks()
+{
+ CFSetRef devices = IOHIDManagerCopyDevices(m_manager);
+ return devices;
+}
+
+
+////////////////////////////////////////////////////////////
+HIDJoystickManager::HIDJoystickManager()
+: m_manager(0)
+, m_joystickCount(0)
+{
+ m_manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
+
+ CFDictionaryRef mask0 = HIDInputManager::copyDevicesMask(kHIDPage_GenericDesktop,
+ kHIDUsage_GD_Joystick);
+
+ CFDictionaryRef mask1 = HIDInputManager::copyDevicesMask(kHIDPage_GenericDesktop,
+ kHIDUsage_GD_GamePad);
+
+ CFDictionaryRef maskArray[2];
+ maskArray[0] = mask0;
+ maskArray[1] = mask1;
+
+ CFArrayRef mask = CFArrayCreate(NULL, (const void**)maskArray, 2, NULL);
+
+ IOHIDManagerSetDeviceMatchingMultiple(m_manager, mask);
+ CFRelease(mask);
+ CFRelease(mask1);
+ CFRelease(mask0);
+
+
+ IOHIDManagerRegisterDeviceMatchingCallback(m_manager, pluggedIn, this);
+ IOHIDManagerRegisterDeviceRemovalCallback(m_manager, pluggedOut, this);
+
+ IOHIDManagerScheduleWithRunLoop(m_manager,
+ CFRunLoopGetCurrent(),
+ RunLoopMode);
+
+ IOHIDManagerOpen(m_manager, kIOHIDOptionsTypeNone);
+}
+
+
+////////////////////////////////////////////////////////////
+HIDJoystickManager::~HIDJoystickManager()
+{
+ IOHIDManagerUnscheduleFromRunLoop(m_manager,
+ CFRunLoopGetCurrent(),
+ RunLoopMode);
+
+ IOHIDManagerRegisterDeviceMatchingCallback(m_manager, NULL, 0);
+ IOHIDManagerRegisterDeviceRemovalCallback(m_manager, NULL, 0);
+
+ IOHIDManagerClose(m_manager, kIOHIDOptionsTypeNone);
+}
+
+
+////////////////////////////////////////////////////////////
+void HIDJoystickManager::update()
+{
+ SInt32 status = kCFRunLoopRunHandledSource;
+
+ while (status == kCFRunLoopRunHandledSource) {
+ status = CFRunLoopRunInMode(RunLoopMode, 0, true);
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void HIDJoystickManager::pluggedIn(void * context, IOReturn, void *, IOHIDDeviceRef)
+{
+ HIDJoystickManager* manager = (HIDJoystickManager*)context;
+ manager->m_joystickCount++;
+}
+
+
+////////////////////////////////////////////////////////////
+void HIDJoystickManager::pluggedOut(void * context, IOReturn, void *, IOHIDDeviceRef)
+{
+ HIDJoystickManager* manager = (HIDJoystickManager*)context;
+ manager->m_joystickCount--;
+}
+
+
+} // namespace priv
+
+} // namespace sf
+
diff --git a/src/SFML/Window/OSX/HIDJoystickManager.hpp b/src/SFML/Window/OSX/HIDJoystickManager.hpp
new file mode 100644
index 0000000..1577157
--- /dev/null
+++ b/src/SFML/Window/OSX/HIDJoystickManager.hpp
@@ -0,0 +1,128 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_HIDJOYSTICKMANAGER_HPP
+#define SFML_HIDJOYSTICKMANAGER_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/System/NonCopyable.hpp>
+#include <IOKit/hid/IOHIDManager.h>
+#include <IOKit/hid/IOHIDDevice.h>
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief This class manage as a singleton instance the
+/// joysticks. It's only purpose is
+/// to help sf::priv::JoystickImpl class.
+///
+////////////////////////////////////////////////////////////
+class HIDJoystickManager : NonCopyable
+{
+public :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Get the unique instance of the class
+ ///
+ /// \note Private use only
+ ///
+ /// \return Reference to the HIDJoystickManager instance
+ ///
+ ////////////////////////////////////////////////////////////
+ static HIDJoystickManager& getInstance();
+
+public :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Get the number of currently connected joystick
+ ///
+ ////////////////////////////////////////////////////////////
+ unsigned int getJoystickCount();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Copy the devices assosiated with this HID manager
+ ///
+ /// \return a retained CFSetRef of IOHIDDeviceRef or NULL
+ ///
+ ////////////////////////////////////////////////////////////
+ CFSetRef copyJoysticks();
+
+private :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Default constructor
+ ///
+ ////////////////////////////////////////////////////////////
+ HIDJoystickManager();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Destructor
+ ///
+ ////////////////////////////////////////////////////////////
+ ~HIDJoystickManager();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Make sur all event have been processed in the run loop
+ ///
+ ////////////////////////////////////////////////////////////
+ void update();
+
+private :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Private "plug-in" callback
+ /// \note Only 'context' parametre is used.
+ /// \see IOHIDDeviceCallback
+ ///
+ ////////////////////////////////////////////////////////////
+ static void pluggedIn(void * context, IOReturn, void *, IOHIDDeviceRef);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Private "plug-out" callback
+ /// \note Only 'context' parametre is used.
+ /// \see IOHIDDeviceCallback
+ ///
+ ////////////////////////////////////////////////////////////
+ static void pluggedOut(void * context, IOReturn, void *, IOHIDDeviceRef);
+
+private :
+
+ ////////////////////////////////////////////////////////////
+ // Member data
+ ////////////////////////////////////////////////////////////
+ IOHIDManagerRef m_manager; ///< HID Manager
+ unsigned int m_joystickCount;///< Number of joysticks currently connected
+};
+
+
+} // namespace priv
+
+} // namespace sf
+
+#endif
diff --git a/src/SFML/Window/OSX/InputImpl.hpp b/src/SFML/Window/OSX/InputImpl.hpp
new file mode 100644
index 0000000..c3700ce
--- /dev/null
+++ b/src/SFML/Window/OSX/InputImpl.hpp
@@ -0,0 +1,124 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_INPUTIMPLOSX_HPP
+#define SFML_INPUTIMPLOSX_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/Keyboard.hpp>
+#include <SFML/Window/Mouse.hpp>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief Mac OS X implementation of inputs (keyboard + mouse)
+///
+////////////////////////////////////////////////////////////
+class InputImpl
+{
+public :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Check if a key is pressed
+ ///
+ /// \param key Key to check
+ ///
+ /// \return True if the key is pressed, false otherwise
+ ///
+ ////////////////////////////////////////////////////////////
+ static bool isKeyPressed(Keyboard::Key key);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Check if a mouse button is pressed
+ ///
+ /// \param button Button to check
+ ///
+ /// \return True if the button is pressed, false otherwise
+ ///
+ ////////////////////////////////////////////////////////////
+ static bool isMouseButtonPressed(Mouse::Button button);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Get the current position of the mouse in desktop coordinates
+ ///
+ /// This function returns the current position of the mouse
+ /// cursor, in global (desktop) coordinates.
+ ///
+ /// \return Current position of the mouse
+ ///
+ ////////////////////////////////////////////////////////////
+ static Vector2i getMousePosition();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Get the current position of the mouse in window coordinates
+ ///
+ /// This function returns the current position of the mouse
+ /// cursor, relative to the given window.
+ /// If no window is used, it returns desktop coordinates.
+ ///
+ /// \param relativeTo Reference window
+ ///
+ /// \return Current position of the mouse
+ ///
+ ////////////////////////////////////////////////////////////
+ static Vector2i getMousePosition(const Window& relativeTo);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Set the current position of the mouse in desktop coordinates
+ ///
+ /// This function sets the current position of the mouse
+ /// cursor in global (desktop) coordinates.
+ /// If no window is used, it sets the position in desktop coordinates.
+ ///
+ /// \param position New position of the mouse
+ ///
+ ////////////////////////////////////////////////////////////
+ static void setMousePosition(const Vector2i& position);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Set the current position of the mouse in window coordinates
+ ///
+ /// This function sets the current position of the mouse
+ /// cursor, relative to the given window.
+ /// If no window is used, it sets the position in desktop coordinates.
+ ///
+ /// \param position New position of the mouse
+ /// \param relativeTo Reference window
+ ///
+ ////////////////////////////////////////////////////////////
+ static void setMousePosition(const Vector2i& position, const Window& relativeTo);
+};
+
+} // namespace priv
+
+} // namespace sf
+
+
+#endif // SFML_INPUTIMPLOSX_HPP
diff --git a/src/SFML/Window/OSX/InputImpl.mm b/src/SFML/Window/OSX/InputImpl.mm
new file mode 100644
index 0000000..37b5faf
--- /dev/null
+++ b/src/SFML/Window/OSX/InputImpl.mm
@@ -0,0 +1,183 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2012 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/OSX/InputImpl.hpp>
+#include <SFML/Window/VideoMode.hpp>
+#include <SFML/Window/Window.hpp>
+#include <SFML/System/Err.hpp>
+#include <SFML/Window/OSX/HIDInputManager.hpp>
+
+#import <AppKit/AppKit.h>
+#import <SFML/Window/OSX/SFOpenGLView.h>
+
+////////////////////////////////////////////////////////////
+/// In order to keep track of the keyboard's state and mouse buttons' state
+/// we use the HID manager. Mouse position is handled differently.
+///
+/// NB : we probably could use
+/// NSEvent +addGlobalMonitorForEventsMatchingMask:handler: for mouse only.
+///
+////////////////////////////////////////////////////////////
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief Extract the dedicated SFOpenGLView from the SFML window
+///
+/// \param window a SFML window
+/// \return nil if something went wrong or a SFOpenGLView*.
+///
+////////////////////////////////////////////////////////////
+SFOpenGLView* getSFOpenGLViewFromSFMLWindow(const Window& window)
+{
+ id nsHandle = (id)window.getSystemHandle();
+
+ // Get our SFOpenGLView from ...
+ SFOpenGLView* view = nil;
+
+ if ([nsHandle isKindOfClass:[NSWindow class]]) {
+ // If system handle is a window then from its content view.
+ view = [nsHandle contentView];
+
+ // Subview doesn't match ?
+ if (![view isKindOfClass:[SFOpenGLView class]]) {
+ sf::err() << "The content view is not a valid SFOpenGLView"
+ << std::endl;
+ view = nil;
+ }
+
+ } else if ([nsHandle isKindOfClass:[NSView class]]) {
+ // If system handle is a view then from a subview of kind SFOpenGLView.
+ NSArray* subviews = [nsHandle subviews];
+ for (NSView* subview in subviews) {
+ if ([subview isKindOfClass:[SFOpenGLView class]]) {
+ view = (SFOpenGLView *)subview;
+ break;
+ }
+ }
+
+ // No matching subview ?
+ if (view == nil) {
+ sf::err() << "Cannot find a valid SFOpenGLView subview." << std::endl;
+
+ }
+
+ } else {
+ if (nsHandle != 0) {
+ sf::err() << "The system handle is neither a <NSWindow*> nor <NSView*>"
+ << "object. This shouldn't happen."
+ << std::endl;
+ } else {
+ // This probably means the SFML window was previously closed.
+ }
+
+ }
+
+ return view;
+}
+
+////////////////////////////////////////////////////////////
+bool InputImpl::isKeyPressed(Keyboard::Key key)
+{
+ return HIDInputManager::getInstance().isKeyPressed(key);
+}
+
+
+////////////////////////////////////////////////////////////
+bool InputImpl::isMouseButtonPressed(Mouse::Button button)
+{
+ return HIDInputManager::getInstance().isMouseButtonPressed(button);
+}
+
+
+////////////////////////////////////////////////////////////
+Vector2i InputImpl::getMousePosition()
+{
+ // Reverse Y axis to match SFML coord.
+ NSPoint pos = [NSEvent mouseLocation];
+ pos.y = sf::VideoMode::getDesktopMode().height - pos.y;
+
+ return Vector2i(pos.x, pos.y);
+}
+
+
+////////////////////////////////////////////////////////////
+Vector2i InputImpl::getMousePosition(const Window& relativeTo)
+{
+ SFOpenGLView* view = getSFOpenGLViewFromSFMLWindow(relativeTo);
+
+ // No view ?
+ if (view == nil) {
+ return Vector2i();
+ }
+
+ // Use -cursorPositionFromEvent: with nil.
+ NSPoint pos = [view cursorPositionFromEvent:nil];
+
+ return Vector2i(pos.x, pos.y);
+}
+
+
+////////////////////////////////////////////////////////////
+void InputImpl::setMousePosition(const Vector2i& position)
+{
+ // Here we don't need to reverse the coordinates.
+ CGPoint pos = CGPointMake(position.x, position.y);
+
+ // Place the cursor.
+ CGEventRef event = CGEventCreateMouseEvent(NULL,
+ kCGEventMouseMoved,
+ pos,
+ /*we don't care about this : */0);
+ CGEventPost(kCGHIDEventTap, event);
+ CFRelease(event);
+ // This is a workaround to deprecated CGSetLocalEventsSuppressionInterval.
+}
+
+
+////////////////////////////////////////////////////////////
+void InputImpl::setMousePosition(const Vector2i& position, const Window& relativeTo)
+{
+ SFOpenGLView* view = getSFOpenGLViewFromSFMLWindow(relativeTo);
+
+ // No view ?
+ if (view == nil) {
+ return;
+ }
+
+ // Let SFOpenGLView compute the position in global coordinate
+ NSPoint p = NSMakePoint(position.x, position.y);
+ p = [view computeGlobalPositionOfRelativePoint:p];
+ setMousePosition(sf::Vector2i(p.x, p.y));
+}
+
+} // namespace priv
+
+} // namespace sf
diff --git a/src/SFML/Window/OSX/JoystickImpl.cpp b/src/SFML/Window/OSX/JoystickImpl.cpp
new file mode 100644
index 0000000..235ab4d
--- /dev/null
+++ b/src/SFML/Window/OSX/JoystickImpl.cpp
@@ -0,0 +1,402 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/JoystickImpl.hpp>
+#include <SFML/Window/OSX/HIDInputManager.hpp>
+#include <SFML/Window/OSX/HIDJoystickManager.hpp>
+
+
+namespace
+{
+ bool JoystickButtonSortPredicate(IOHIDElementRef b1, IOHIDElementRef b2)
+ {
+ return IOHIDElementGetUsage(b1) < IOHIDElementGetUsage(b2);
+ }
+}
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+JoystickImpl::Location JoystickImpl::m_locationIDs[sf::Joystick::Count] = { 0 };
+
+
+////////////////////////////////////////////////////////////
+void JoystickImpl::initialize()
+{
+ // Nothing to do
+}
+
+
+////////////////////////////////////////////////////////////
+void JoystickImpl::cleanup()
+{
+ // Nothing to do
+}
+
+
+////////////////////////////////////////////////////////////
+bool JoystickImpl::isConnected(unsigned int index)
+{
+ bool state = false; // Is the index-th joystick connected ?
+
+ // First, let's check if the device was previously detected :
+
+ if (m_locationIDs[index] != 0) {
+ state = true;
+ }
+
+ // Otherwise, let's check if it is now connected :
+ else { // i.e., m_locationIDs[index] == 0
+
+ // if there is more connected joystick to the HID manager than
+ // opened joystick devices then we find the new one.
+
+ unsigned int openedCount = 0;
+ for (unsigned int i(0); i < sf::Joystick::Count; ++i) {
+ if (m_locationIDs[i] != 0) openedCount++;
+ }
+
+ unsigned int connectedCount = HIDJoystickManager::getInstance().getJoystickCount();
+
+ if (connectedCount > openedCount) {
+
+ // Get all devices
+ CFSetRef devices = HIDJoystickManager::getInstance().copyJoysticks();
+
+ if (devices != NULL) {
+
+ CFIndex size = CFSetGetCount(devices);
+
+ if (size > 0) {
+
+ CFTypeRef array[size]; // array of IOHIDDeviceRef
+ CFSetGetValues(devices, array);
+
+ // If there exists a device d s.t. there is no j s.t.
+ // m_locationIDs[j] == d's location then we have a new device.
+
+ for (CFIndex didx(0); didx < size; ++didx) {
+ IOHIDDeviceRef d = (IOHIDDeviceRef)array[didx];
+ Location dloc = HIDInputManager::getLocationID(d);
+
+ bool foundJ = false;
+ for (unsigned int j(0); j < Joystick::Count; ++j) {
+ if (m_locationIDs[j] == dloc) {
+ foundJ = true;
+ break; // no need to loop again
+ }
+ }
+
+ if (foundJ) {
+ // This is a known device
+ // Nothing else to do
+ } else {
+ // This is a new device
+ // We set it up for Open(..)
+ m_locationIDs[index] = dloc;
+ state = true;
+ break; // We stop looking for a new device
+ }
+ }
+
+ }
+
+ CFRelease(devices);
+ }
+ }
+ }
+
+ return state;
+}
+
+
+////////////////////////////////////////////////////////////
+bool JoystickImpl::open(unsigned int index)
+{
+ m_index = index;
+ Location deviceLoc = m_locationIDs[index]; // The device we need to load
+
+ // Get all devices
+ CFSetRef devices = HIDJoystickManager::getInstance().copyJoysticks();
+ if (devices == NULL) {
+ return false;
+ }
+
+ // Get a usable copy of the joysticks devices.
+ CFIndex joysticksCount = CFSetGetCount(devices);
+ CFTypeRef devicesArray[joysticksCount];
+ CFSetGetValues(devices, devicesArray);
+
+ // Get the desired joystick.
+ IOHIDDeviceRef self = 0;
+ for (CFIndex i(0); i < joysticksCount; ++i) {
+ IOHIDDeviceRef d = (IOHIDDeviceRef)devicesArray[i];
+ if (deviceLoc == HIDInputManager::getLocationID(d)) {
+ self = d;
+ break; // We found it so we stop looping.
+ }
+ }
+
+ if (self == 0) {
+ // This shouldn't happen!
+ CFRelease(devices);
+ return false;
+ }
+
+ // Get a list of all elements attached to the device.
+ CFArrayRef elements = IOHIDDeviceCopyMatchingElements(self,
+ NULL,
+ kIOHIDOptionsTypeNone);
+
+ if (elements == NULL) {
+ CFRelease(devices);
+ return false;
+ }
+
+ // How many elements are there ?
+ CFIndex elementsCount = CFArrayGetCount(elements);
+
+ if (elementsCount == 0) {
+ // What is a joystick with no element ?
+ CFRelease(elements);
+ CFRelease(devices);
+ return false;
+ }
+
+ // Go through all connected elements.
+ for (int i = 0; i < elementsCount; ++i) {
+ IOHIDElementRef element = (IOHIDElementRef) CFArrayGetValueAtIndex(elements, i);
+
+ switch (IOHIDElementGetType(element)) {
+
+ case kIOHIDElementTypeInput_Misc:
+ switch (IOHIDElementGetUsage(element)) {
+
+ case kHIDUsage_GD_X:
+ m_axis[Joystick::X] = element;
+ break;
+
+ case kHIDUsage_GD_Y:
+ m_axis[Joystick::Y] = element;
+ break;
+
+ case kHIDUsage_GD_Z:
+ m_axis[Joystick::Z] = element;
+ break;
+
+ case kHIDUsage_GD_Rx:
+ m_axis[Joystick::U] = element;
+ break;
+
+ case kHIDUsage_GD_Ry:
+ m_axis[Joystick::V] = element;
+ break;
+
+ case kHIDUsage_GD_Rz:
+ m_axis[Joystick::R] = element;
+ break;
+
+ // kHIDUsage_GD_Vx, kHIDUsage_GD_Vy, kHIDUsage_GD_Vz are ignored.
+ }
+ break;
+
+ case kIOHIDElementTypeInput_Button:
+ if (m_buttons.size() < Joystick::ButtonCount) { // If we have free slot...
+ m_buttons.push_back(element); // ...we add this element to the list
+ } else {
+ // Too many buttons. We ignore this one.
+ }
+ break;
+
+ default: // Make compiler happy
+ break;
+ }
+ }
+
+ // Ensure that the buttons will be indexed in the same order as their
+ // HID Usage (assigned by manufacturer and/or a driver).
+ std::sort(m_buttons.begin(), m_buttons.end(), JoystickButtonSortPredicate);
+
+ // Note : Joy::AxisPovX/Y are not supported (yet).
+ // Maybe kIOHIDElementTypeInput_Axis is the corresponding type but I can't test.
+
+ // Retain all these objets for personal use
+ for (ButtonsVector::iterator it(m_buttons.begin()); it != m_buttons.end(); ++it) {
+ CFRetain(*it);
+ }
+ for (AxisMap::iterator it(m_axis.begin()); it != m_axis.end(); ++it) {
+ CFRetain(it->second);
+ }
+
+ // Note : we didn't retain element in the switch because we might have multiple
+ // Axis X (for example) and we want to keep only the last one. So to prevent
+ // leaking we retain objects 'only' now.
+
+ CFRelease(devices);
+ CFRelease(elements);
+
+ return true;
+}
+
+
+////////////////////////////////////////////////////////////
+void JoystickImpl::close()
+{
+ for (ButtonsVector::iterator it(m_buttons.begin()); it != m_buttons.end(); ++it) {
+ CFRelease(*it);
+ }
+ m_buttons.clear();
+
+ for (AxisMap::iterator it(m_axis.begin()); it != m_axis.end(); ++it) {
+ CFRelease(it->second);
+ }
+ m_axis.clear();
+
+ // And we unregister this joystick
+ m_locationIDs[m_index] = 0;
+}
+
+
+////////////////////////////////////////////////////////////
+JoystickCaps JoystickImpl::getCapabilities() const
+{
+ JoystickCaps caps;
+
+ // Buttons :
+ caps.buttonCount = m_buttons.size();
+
+ // Axis :
+ for (AxisMap::const_iterator it(m_axis.begin()); it != m_axis.end(); ++it) {
+ caps.axes[it->first] = true;
+ }
+
+ return caps;
+}
+
+
+////////////////////////////////////////////////////////////
+JoystickState JoystickImpl::update()
+{
+ static const JoystickState disconnectedState; // return this if joystick was disconnected
+ JoystickState state; // otherwise return that
+ state.connected = true;
+
+ // Note : free up is done in close() which is called, if required,
+ // by the joystick manager. So we don't release buttons nor axes here.
+
+ // First, let's determine if the joystick is still connected
+ Location selfLoc = m_locationIDs[m_index];
+
+ // Get all devices
+ CFSetRef devices = HIDJoystickManager::getInstance().copyJoysticks();
+ if (devices == NULL) {
+ return disconnectedState;
+ }
+
+ // Get a usable copy of the joysticks devices.
+ CFIndex joysticksCount = CFSetGetCount(devices);
+ CFTypeRef devicesArray[joysticksCount];
+ CFSetGetValues(devices, devicesArray);
+
+ // Search for it
+ bool found = false;
+ for (CFIndex i(0); i < joysticksCount; ++i) {
+ IOHIDDeviceRef d = (IOHIDDeviceRef)devicesArray[i];
+ if (selfLoc == HIDInputManager::getLocationID(d)) {
+ found = true;
+ break; // Stop looping
+ }
+ }
+
+ // Release unused stuff
+ CFRelease(devices);
+
+ // Was it found ?
+ if (found) {
+ // Yes, so we can continue.
+ } else {
+ // No, so we stop here
+ return disconnectedState;
+ }
+
+ // Update buttons' state
+ unsigned int i = 0;
+ for (ButtonsVector::iterator it(m_buttons.begin()); it != m_buttons.end(); ++it, ++i) {
+ IOHIDValueRef value = 0;
+ IOHIDDeviceGetValue(IOHIDElementGetDevice(*it), *it, &value);
+
+ // Check for plug out.
+ if (!value) {
+ // No value ? Hum... Seems like the joystick is gone
+ return disconnectedState;
+ }
+
+ // 1 means pressed, others mean released
+ state.buttons[i] = IOHIDValueGetIntegerValue(value) == 1;
+ }
+
+ // Update axes' state
+ for (AxisMap::iterator it = m_axis.begin(); it != m_axis.end(); ++it) {
+ IOHIDValueRef value = 0;
+ IOHIDDeviceGetValue(IOHIDElementGetDevice(it->second), it->second, &value);
+
+ // Check for plug out.
+ if (!value) {
+ // No value ? Hum... Seems like the joystick is gone
+ return disconnectedState;
+ }
+
+ // We want to bind [physicalMin,physicalMax] to [-100=min,100=max].
+ //
+ // General formula to bind [a,b] to [c,d] with a linear progression :
+ //
+ // f : [a, b] -> [c, d]
+ // x |-> (x-a)(d-c)/(b-a)+c
+ //
+ // This method might not be very accurate (the "0 position" can be
+ // slightly shift with some device) but we don't care because most
+ // of devices are so sensitive that this is not relevant.
+ double physicalMax = IOHIDElementGetPhysicalMax(it->second);
+ double physicalMin = IOHIDElementGetPhysicalMin(it->second);
+ double scaledMin = -100;
+ double scaledMax = 100;
+ double physicalValue = IOHIDValueGetScaledValue(value, kIOHIDValueScaleTypePhysical);
+ float scaledValue = ((physicalValue - physicalMin) * (scaledMax - scaledMin) / (physicalMax - physicalMin)) + scaledMin;
+ state.axes[it->first] = scaledValue;
+ }
+
+
+ return state;
+}
+
+} // namespace priv
+
+} // namespace sf
diff --git a/src/SFML/Window/OSX/JoystickImpl.hpp b/src/SFML/Window/OSX/JoystickImpl.hpp
new file mode 100644
index 0000000..fe1a8fa
--- /dev/null
+++ b/src/SFML/Window/OSX/JoystickImpl.hpp
@@ -0,0 +1,126 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_JOYSTICKIMPLOSX_HPP
+#define SFML_JOYSTICKIMPLOSX_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/JoystickImpl.hpp>
+#include <IOKit/hid/IOHIDDevice.h>
+#include <map>
+#include <vector>
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief Mac OS X implementation of joysticks
+///
+////////////////////////////////////////////////////////////
+class JoystickImpl
+{
+public :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Perform the global initialization of the joystick module
+ ///
+ ////////////////////////////////////////////////////////////
+ static void initialize();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Perform the global cleanup of the joystick module
+ ///
+ ////////////////////////////////////////////////////////////
+ static void cleanup();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Check if a joystick is currently connected
+ ///
+ /// \param index Index of the joystick to check
+ ///
+ /// \return True if the joystick is connected, false otherwise
+ ///
+ ////////////////////////////////////////////////////////////
+ static bool isConnected(unsigned int index);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Open the joystick
+ ///
+ /// \param index Index assigned to the joystick
+ ///
+ /// \return True on success, false on failure
+ ///
+ ////////////////////////////////////////////////////////////
+ bool open(unsigned int index);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Close the joystick
+ ///
+ ////////////////////////////////////////////////////////////
+ void close();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Get the joystick capabilities
+ ///
+ /// \return Joystick capabilities
+ ///
+ ////////////////////////////////////////////////////////////
+ JoystickCaps getCapabilities() const;
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Update the joystick and get its new state
+ ///
+ /// \return Joystick state
+ ///
+ ////////////////////////////////////////////////////////////
+ JoystickState update();
+
+private :
+
+ ////////////////////////////////////////////////////////////
+ // Member data
+ ////////////////////////////////////////////////////////////
+ typedef long Location;
+ typedef std::map<sf::Joystick::Axis, IOHIDElementRef> AxisMap;
+ typedef std::vector<IOHIDElementRef> ButtonsVector;
+
+ AxisMap m_axis; ///< Axis (IOHIDElementRef) connected to the joystick
+ ButtonsVector m_buttons; ///< Buttons (IOHIDElementRef) connected to the joystick
+ unsigned int m_index; ///< SFML index
+
+ static Location m_locationIDs[sf::Joystick::Count]; ///< Global Joystick register
+ /// For a corresponding SFML index, m_locationIDs is either some usb
+ /// location or 0 if there isn't currently a connected joystick device
+};
+
+} // namespace priv
+
+} // namespace sf
+
+
+#endif // SFML_JOYSTICKIMPLOSX_HPP
diff --git a/src/SFML/Audio/AudioResource.cpp b/src/SFML/Window/OSX/SFApplication.h
index a1a352c..2abbca2 100755..100644
--- a/src/SFML/Audio/AudioResource.cpp
+++ b/src/SFML/Window/OSX/SFApplication.h
@@ -1,60 +1,55 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Audio/AudioResource.hpp>
-#include <SFML/Audio/AudioDevice.hpp>
-
-
-namespace sf
-{
-////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
-AudioResource::AudioResource()
-{
- priv::AudioDevice::AddReference();
-}
-
-
-////////////////////////////////////////////////////////////
-/// Copy constructor
-////////////////////////////////////////////////////////////
-AudioResource::AudioResource(const AudioResource&)
-{
- priv::AudioDevice::AddReference();
-}
-
-
-////////////////////////////////////////////////////////////
-/// Destructor
-////////////////////////////////////////////////////////////
-AudioResource::~AudioResource()
-{
- priv::AudioDevice::RemoveReference();
-}
-
-} // namespace sf
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2012 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#import <Foundation/Foundation.h>
+#import <AppKit/AppKit.h>
+
+////////////////////////////////////////////////////////////
+/// \brief Event processing
+///
+////////////////////////////////////////////////////////////
+@interface SFApplication : NSApplication
+
+
+////////////////////////////////////////////////////////////
+/// \brief Event processing
+///
+////////////////////////////////////////////////////////////
++(void)processEvent;
+
+
+////////////////////////////////////////////////////////////
+/// \brief Dispatch events
+///
+/// This overload of -[NSApplication sendEvent:] is used to
+/// fix KeyRelease events when the command key is down.
+////////////////////////////////////////////////////////////
+-(void)sendEvent:(NSEvent *)anEvent;
+
+
+@end
diff --git a/src/SFML/Window/OSX/SFApplication.m b/src/SFML/Window/OSX/SFApplication.m
new file mode 100644
index 0000000..a8bd3e4
--- /dev/null
+++ b/src/SFML/Window/OSX/SFApplication.m
@@ -0,0 +1,64 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2012 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#import <SFML/Window/OSX/SFApplication.h>
+
+
+////////////////////////////////////////////////////////////
+@implementation SFApplication
+
+
+////////////////////////////////////////////////////////////
++(void)processEvent
+{
+ [SFApplication sharedApplication]; // Make sure NSApp exists
+ NSEvent* event = nil;
+
+ while ((event = [NSApp nextEventMatchingMask:NSAnyEventMask
+ untilDate:[NSDate distantPast]
+ inMode:NSDefaultRunLoopMode
+ dequeue:YES])) // Remove the event from the dequeue
+ {
+ [NSApp sendEvent:event];
+ }
+}
+
+- (void)sendEvent:(NSEvent *)anEvent
+{
+ if ([anEvent type] == NSKeyUp) {
+ [[[self mainWindow] firstResponder] tryToPerform:@selector(keyUp:)
+ with:anEvent];
+ } else {
+ [super sendEvent:anEvent];
+ }
+}
+
+
+@end
+
+
diff --git a/src/SFML/Window/OSX/SFContext.hpp b/src/SFML/Window/OSX/SFContext.hpp
new file mode 100644
index 0000000..dbab403
--- /dev/null
+++ b/src/SFML/Window/OSX/SFContext.hpp
@@ -0,0 +1,161 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_SFCONTEXT_HPP
+#define SFML_SFCONTEXT_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/GlContext.hpp>
+
+////////////////////////////////////////////////////////////
+/// Predefine OBJC classes
+////////////////////////////////////////////////////////////
+#ifdef __OBJC__
+
+@class NSOpenGLContext;
+typedef NSOpenGLContext* NSOpenGLContextRef;
+
+@class NSOpenGLView;
+typedef NSOpenGLView* NSOpenGLViewRef;
+
+@class NSWindow;
+typedef NSWindow* NSWindowRef;
+
+#else // If C++
+
+typedef void* NSOpenGLContextRef;
+typedef void* NSOpenGLViewRef;
+typedef void* NSWindowRef;
+
+#endif
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief OSX (Cocoa) implementation of OpenGL contexts
+///
+////////////////////////////////////////////////////////////
+class SFContext : public GlContext
+{
+public:
+ ////////////////////////////////////////////////////////////
+ /// \brief Create a new context, not associated to a window
+ ///
+ /// \param shared Context to share the new one with (can be NULL)
+ ///
+ ////////////////////////////////////////////////////////////
+ SFContext(SFContext* shared);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Create a new context attached to a window
+ ///
+ /// \param shared Context to share the new one with
+ /// \param settings Creation parameters
+ /// \param owner Pointer to the owner window
+ /// \param bitsPerPixel Pixel depth, in bits per pixel
+ ///
+ ////////////////////////////////////////////////////////////
+ SFContext(SFContext* shared, const ContextSettings& settings,
+ const WindowImpl* owner, unsigned int bitsPerPixel);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Create a new context that embeds its own rendering target
+ ///
+ /// \param shared Context to share the new one with
+ /// \param settings Creation parameters
+ /// \param width Back buffer width, in pixels
+ /// \param height Back buffer height, in pixels
+ ///
+ ////////////////////////////////////////////////////////////
+ SFContext(SFContext* shared, const ContextSettings& settings,
+ unsigned int width, unsigned int height);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Destructor
+ ///
+ ////////////////////////////////////////////////////////////
+ ~SFContext();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Display what has been rendered to the context so far
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual void display();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Enable or disable vertical synchronization
+ ///
+ /// Activating vertical synchronization will limit the number
+ /// of frames displayed to the refresh rate of the monitor.
+ /// This can avoid some visual artifacts, and limit the framerate
+ /// to a good value (but not constant across different computers).
+ ///
+ /// \param enabled : True to enable v-sync, false to deactivate
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual void setVerticalSyncEnabled(bool enabled);
+
+protected:
+ ////////////////////////////////////////////////////////////
+ /// \brief Activate the context as the current target
+ /// for rendering
+ ///
+ /// \return True on success, false if any error happened
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual bool makeCurrent();
+
+private:
+ ////////////////////////////////////////////////////////////
+ /// \brief Create the context
+ /// \note Must only be called from Ctor.
+ ///
+ /// \param shared Context to share the new one with (can be NULL)
+ /// \param bitsPerPixel bpp
+ /// \param settings Creation parameters
+ ///
+ ////////////////////////////////////////////////////////////
+ void createContext(SFContext* shared,
+ unsigned int bitsPerPixel,
+ const ContextSettings& settings);
+
+ ////////////////////////////////////////////////////////////
+ // Member data
+ ////////////////////////////////////////////////////////////
+ NSOpenGLContextRef m_context; ///< OpenGL context.
+ NSOpenGLViewRef m_view; ///< Only for offscreen context.
+ NSWindowRef m_window; ///< Only for offscreen context.
+};
+
+} // namespace priv
+
+} // namespace sf
+
+#endif // SFML_SFCONTEXT_HPP
diff --git a/src/SFML/Window/OSX/SFContext.mm b/src/SFML/Window/OSX/SFContext.mm
new file mode 100644
index 0000000..876e065
--- /dev/null
+++ b/src/SFML/Window/OSX/SFContext.mm
@@ -0,0 +1,223 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2012 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/OSX/SFContext.hpp>
+#include <SFML/Window/OSX/WindowImplCocoa.hpp>
+#include <SFML/System/Err.hpp>
+
+#import <SFML/Window/OSX/AutoreleasePoolWrapper.h>
+
+namespace sf
+{
+namespace priv
+{
+
+
+////////////////////////////////////////////////////////////
+SFContext::SFContext(SFContext* shared)
+: m_view(0), m_window(0)
+{
+ // Ask for a pool.
+ retainPool();
+
+ // Create the context
+ createContext(shared,
+ VideoMode::getDesktopMode().bitsPerPixel,
+ ContextSettings(0, 0, 0));
+}
+
+
+////////////////////////////////////////////////////////////
+SFContext::SFContext(SFContext* shared, const ContextSettings& settings,
+ const WindowImpl* owner, unsigned int bitsPerPixel)
+: m_view(0), m_window(0)
+{
+ // Ask for a pool.
+ retainPool();
+
+ // Create the context.
+ createContext(shared, bitsPerPixel, settings);
+
+ // Apply context.
+ WindowImplCocoa const * ownerCocoa = static_cast<WindowImplCocoa const *>(owner);
+ ownerCocoa->applyContext(m_context);
+}
+
+
+////////////////////////////////////////////////////////////
+SFContext::SFContext(SFContext* shared, const ContextSettings& settings,
+ unsigned int width, unsigned int height)
+: m_view(0), m_window(0)
+{
+ // Ensure the process is setup in order to create a valid window.
+ WindowImplCocoa::setUpProcess();
+
+ // Ask for a pool.
+ retainPool();
+
+ // Create the context.
+ createContext(shared, VideoMode::getDesktopMode().bitsPerPixel, settings);
+
+ // Create a dummy window/view pair (hidden) and asign it our context.
+ m_window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, width, height)
+ styleMask:NSBorderlessWindowMask
+ backing:NSBackingStoreBuffered
+ defer:NO]; // Don't defer it!
+ m_view = [[NSOpenGLView alloc] initWithFrame:NSMakeRect(0, 0, width, height)];
+ [m_window setContentView:m_view];
+ [m_view setOpenGLContext:m_context];
+ [m_context setView:m_view];
+}
+
+
+////////////////////////////////////////////////////////////
+SFContext::~SFContext()
+{
+ [m_context clearDrawable];
+ [m_context release];
+
+ [m_view release]; // Might be nil but we don't care.
+ [m_window release]; // Idem.
+
+ releasePool();
+}
+
+
+////////////////////////////////////////////////////////////
+bool SFContext::makeCurrent()
+{
+ [m_context makeCurrentContext];
+ return m_context == [NSOpenGLContext currentContext]; // Should be true.
+}
+
+
+////////////////////////////////////////////////////////////
+void SFContext::display()
+{
+ [m_context flushBuffer];
+}
+
+
+////////////////////////////////////////////////////////////
+void SFContext::setVerticalSyncEnabled(bool enabled)
+{
+ // Make compiler happy
+#if MAC_OS_X_VERSION_MAX_ALLOWED < 1060
+ typedef int GLint;
+#endif
+
+ GLint swapInterval = enabled ? 1 : 0;
+
+ [m_context setValues:&swapInterval forParameter:NSOpenGLCPSwapInterval];
+}
+
+
+////////////////////////////////////////////////////////////
+void SFContext::createContext(SFContext* shared,
+ unsigned int bitsPerPixel,
+ const ContextSettings& settings)
+{
+ // Choose the attributs of OGL context.
+ std::vector<NSOpenGLPixelFormatAttribute> attrs;
+ attrs.reserve(20); // max attributs (estimation).
+
+ // These casts are safe. C++ is much more strict than Obj-C.
+
+ attrs.push_back(NSOpenGLPFAClosestPolicy);
+ attrs.push_back(NSOpenGLPFADoubleBuffer);
+
+ if (bitsPerPixel > 24) {
+ attrs.push_back(NSOpenGLPFAAlphaSize);
+ attrs.push_back((NSOpenGLPixelFormatAttribute)8);
+ }
+
+ attrs.push_back(NSOpenGLPFADepthSize);
+ attrs.push_back((NSOpenGLPixelFormatAttribute)settings.depthBits);
+
+ attrs.push_back(NSOpenGLPFAStencilSize);
+ attrs.push_back((NSOpenGLPixelFormatAttribute)settings.stencilBits);
+
+ if (settings.antialiasingLevel > 0) {
+ /*
+ * Antialiasing techniques are described in the
+ * "OpenGL Programming Guide for Mac OS X" document.
+ *
+ * According to this document, the specification currently allows
+ * only one multisample buffer.
+ *
+ * The document also states that software renderers should be avoided
+ * because antialisaing techniques are very slow with them.
+ */
+
+ // Prefer multisampling over supersampling
+ attrs.push_back(NSOpenGLPFAMultisample);
+
+ // Only one buffer is currently available
+ attrs.push_back(NSOpenGLPFASampleBuffers);
+ attrs.push_back((NSOpenGLPixelFormatAttribute)1);
+
+ // Antialiasing level
+ attrs.push_back(NSOpenGLPFASamples);
+ attrs.push_back((NSOpenGLPixelFormatAttribute)settings.antialiasingLevel);
+
+ // No software renderer - only hardware renderer
+ attrs.push_back(NSOpenGLPFAAccelerated);
+ }
+
+ attrs.push_back((NSOpenGLPixelFormatAttribute)0); // end of array
+
+ // Create the pixel pormat.
+ NSOpenGLPixelFormat* pixFmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:&attrs[0]];
+
+ if (pixFmt == nil) {
+ sf::err() << "Error. Unable to find a suitable pixel format." << std::endl;
+ return;
+ }
+
+ // Use the shared context if one is given.
+ NSOpenGLContext* sharedContext = shared != NULL ? shared->m_context : nil;
+
+ // Create the context.
+ m_context = [[NSOpenGLContext alloc] initWithFormat:pixFmt
+ shareContext:sharedContext];
+
+ if (m_context == nil) {
+ sf::err() << "Error. Unable to create the context." << std::endl;
+ }
+
+ // Free up.
+ [pixFmt release];
+
+ // Save the settings. (OpenGL version is updated elsewhere.)
+ m_settings = settings;
+}
+
+} // namespace priv
+
+} // namespace sf
+
diff --git a/src/SFML/Window/OSX/SFKeyboardModifiersHelper.h b/src/SFML/Window/OSX/SFKeyboardModifiersHelper.h
new file mode 100644
index 0000000..2020673
--- /dev/null
+++ b/src/SFML/Window/OSX/SFKeyboardModifiersHelper.h
@@ -0,0 +1,61 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2012 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#import <AppKit/AppKit.h>
+
+namespace sf {
+ namespace priv {
+ class WindowImplCocoa;
+ }
+}
+
+////////////////////////////////////////////////////////////
+/// Keyboard Modifiers Helper
+///
+/// Handle left & right modifiers (cmd, ctrl, alt, shift)
+/// events and send them back to the requester.
+///
+////////////////////////////////////////////////////////////
+
+
+////////////////////////////////////////////////////////////
+/// Set up a SFML key event based on the given modifiers
+/// flags and key code.
+///
+////////////////////////////////////////////////////////////
+sf::Event::KeyEvent keyEventWithModifiers(NSUInteger modifiers, sf::Keyboard::Key key);
+
+
+////////////////////////////////////////////////////////////
+/// Handle the state of modifiers keys and send key
+/// release & pressed events to the requester.
+///
+////////////////////////////////////////////////////////////
+void handleModifiersChanged(NSUInteger modifiers, sf::priv::WindowImplCocoa& requester);
+
+
diff --git a/src/SFML/Window/OSX/SFKeyboardModifiersHelper.mm b/src/SFML/Window/OSX/SFKeyboardModifiersHelper.mm
new file mode 100644
index 0000000..d023079
--- /dev/null
+++ b/src/SFML/Window/OSX/SFKeyboardModifiersHelper.mm
@@ -0,0 +1,247 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2012 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/OSX/WindowImplCocoa.hpp>
+
+#import <SFML/Window/OSX/SFKeyboardModifiersHelper.h>
+
+
+////////////////////////////////////////////////////////////
+/// Here are define the mask value for the 'modifiers'
+/// keys (cmd, ctrl, alt, shift)
+///
+////////////////////////////////////////////////////////////
+#define NSRightShiftKeyMask 0x020004
+#define NSLeftShiftKeyMask 0x020002
+#define NSRightCommandKeyMask 0x100010
+#define NSLeftCommandKeyMask 0x100008
+#define NSRightAlternateKeyMask 0x080040
+#define NSLeftAlternateKeyMask 0x080020
+#define NSRightControlKeyMask 0x042000
+#define NSLeftControlKeyMask 0x040001
+
+
+////////////////////////////////////////////////////////////
+// Local Data Structures
+////////////////////////////////////////////////////////////
+
+/// Modifiers states
+struct ModifiersState
+{
+ BOOL rightShiftWasDown;
+ BOOL leftShiftWasDown;
+ BOOL rightCommandWasDown;
+ BOOL leftCommandWasDown;
+ BOOL rightAlternateWasDown;
+ BOOL leftAlternateWasDown;
+ BOOL leftControlWasDown;
+ BOOL rightControlWasDown;
+};
+
+
+////////////////////////////////////////////////////////////
+// Global Variables
+////////////////////////////////////////////////////////////
+
+/// Share 'modifiers' state with all windows to correctly fire pressed/released events
+static ModifiersState state;
+static BOOL isStateInitialized = NO;
+
+
+////////////////////////////////////////////////////////////
+// Local & Private Functions
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+/// Carefully observe if the key mask is on in the modifiers
+///
+////////////////////////////////////////////////////////////
+BOOL isKeyMaskActive(NSUInteger modifiers, NSUInteger mask);
+
+
+////////////////////////////////////////////////////////
+/// Init the global state only if needed
+///
+////////////////////////////////////////////////////////////
+void ensureModifiersStateIsInitilized();
+
+
+////////////////////////////////////////////////////////////
+/// Handle one modifier key mask, update the key state and
+/// send events to the requester
+///
+////////////////////////////////////////////////////////////
+void processOneModifier(NSUInteger modifiers, NSUInteger mask,
+ BOOL& wasDown, sf::Keyboard::Key key,
+ sf::priv::WindowImplCocoa& requester);
+
+
+////////////////////////////////////////////////////////////
+/// Handle left & right modifier keys, update the keys state and
+/// send events to the requester
+///
+////////////////////////////////////////////////////////////
+void processLeftRightModifiers(NSUInteger modifiers,
+ NSUInteger leftMask, NSUInteger rightMask,
+ BOOL& leftWasDown, BOOL& rightWasDown,
+ sf::Keyboard::Key leftKey, sf::Keyboard::Key rightKey,
+ sf::priv::WindowImplCocoa& requester);
+
+
+
+////////////////////////////////////////////////////////////
+// Implementations
+////////////////////////////////////////////////////////////
+
+
+////////////////////////////////////////////////////////
+sf::Event::KeyEvent keyEventWithModifiers(NSUInteger modifiers, sf::Keyboard::Key key)
+{
+ sf::Event::KeyEvent event;
+ event.code = key;
+ event.alt = modifiers & NSAlternateKeyMask;
+ event.control = modifiers & NSControlKeyMask;
+ event.shift = modifiers & NSShiftKeyMask;
+ event.system = modifiers & NSCommandKeyMask;
+
+ return event;
+}
+
+
+////////////////////////////////////////////////////////
+void handleModifiersChanged(NSUInteger modifiers, sf::priv::WindowImplCocoa& requester)
+{
+ // Handle shift
+ processLeftRightModifiers(
+ modifiers,
+ NSLeftShiftKeyMask, NSRightShiftKeyMask,
+ state.leftShiftWasDown, state.rightShiftWasDown,
+ sf::Keyboard::LShift, sf::Keyboard::RShift,
+ requester
+ );
+
+ // Handle command
+ processLeftRightModifiers(
+ modifiers,
+ NSLeftCommandKeyMask, NSRightCommandKeyMask,
+ state.leftCommandWasDown, state.rightCommandWasDown,
+ sf::Keyboard::LSystem, sf::Keyboard::RSystem,
+ requester
+ );
+
+ // Handle option (alt)
+ processLeftRightModifiers(
+ modifiers,
+ NSLeftAlternateKeyMask, NSRightAlternateKeyMask,
+ state.leftAlternateWasDown, state.rightAlternateWasDown,
+ sf::Keyboard::LAlt, sf::Keyboard::RAlt,
+ requester
+ );
+
+ // Handle control
+ processLeftRightModifiers(
+ modifiers,
+ NSLeftControlKeyMask, NSRightControlKeyMask,
+ state.leftControlWasDown, state.rightControlWasDown,
+ sf::Keyboard::LControl, sf::Keyboard::RControl,
+ requester
+ );
+}
+
+
+////////////////////////////////////////////////////////
+BOOL isKeyMaskActive(NSUInteger modifiers, NSUInteger mask)
+{
+ // Here we need to make sure it's exactly the mask since some masks
+ // share some bits such that the & operation would result in a non zero
+ // value without corresponding to the processed key.
+ return (modifiers & mask) == mask;
+}
+
+
+////////////////////////////////////////////////////////
+void ensureModifiersStateIsInitilized()
+{
+ if (isStateInitialized) return;
+
+ NSUInteger modifiers = [[NSApp currentEvent] modifierFlags];
+
+ // Load current keyboard state
+ state.leftShiftWasDown = isKeyMaskActive(modifiers, NSLeftShiftKeyMask);
+ state.rightShiftWasDown = isKeyMaskActive(modifiers, NSRightShiftKeyMask);
+ state.leftCommandWasDown = isKeyMaskActive(modifiers, NSLeftCommandKeyMask);
+ state.rightCommandWasDown = isKeyMaskActive(modifiers, NSRightCommandKeyMask);
+ state.leftAlternateWasDown = isKeyMaskActive(modifiers, NSLeftAlternateKeyMask);
+ state.rightAlternateWasDown = isKeyMaskActive(modifiers, NSRightAlternateKeyMask);
+ state.leftControlWasDown = isKeyMaskActive(modifiers, NSLeftControlKeyMask);
+ state.rightControlWasDown = isKeyMaskActive(modifiers, NSRightControlKeyMask);
+
+ isStateInitialized = YES;
+}
+
+
+////////////////////////////////////////////////////////
+void processOneModifier(NSUInteger modifiers, NSUInteger mask,
+ BOOL& wasDown, sf::Keyboard::Key key,
+ sf::priv::WindowImplCocoa& requester)
+{
+ ensureModifiersStateIsInitilized();
+
+ // Setup a potential event key.
+ sf::Event::KeyEvent event = keyEventWithModifiers(modifiers, key);
+
+ // State
+ BOOL isDown = isKeyMaskActive(modifiers, mask);
+
+ // Check for key pressed event
+ if (isDown && !wasDown) {
+ requester.keyDown(event);
+ }
+ // And check for key released event
+ else if (!isDown && wasDown) {
+ requester.keyUp(event);
+ }
+ // else isDown == wasDown, so no change
+
+ // Update state
+ wasDown = isDown;
+}
+
+
+////////////////////////////////////////////////////////
+void processLeftRightModifiers(NSUInteger modifiers,
+ NSUInteger leftMask, NSUInteger rightMask,
+ BOOL& leftWasDown, BOOL& rightWasDown,
+ sf::Keyboard::Key leftKey, sf::Keyboard::Key rightKey,
+ sf::priv::WindowImplCocoa& requester)
+{
+ processOneModifier(modifiers, leftMask, leftWasDown, leftKey, requester);
+ processOneModifier(modifiers, rightMask, rightWasDown, rightKey, requester);
+}
+
+
diff --git a/src/SFML/Window/OSX/SFOpenGLView.h b/src/SFML/Window/OSX/SFOpenGLView.h
new file mode 100644
index 0000000..50373cd
--- /dev/null
+++ b/src/SFML/Window/OSX/SFOpenGLView.h
@@ -0,0 +1,120 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2012 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#import <AppKit/AppKit.h>
+
+namespace sf {
+ namespace priv {
+ class WindowImplCocoa;
+ }
+}
+
+@class SFSilentResponder;
+
+////////////////////////////////////////////////////////////
+/// \brief Specialized NSOpenGLView
+///
+/// Handle event and send them back to the requester.
+///
+/// NSTrackingArea is used to keep track of mouse events. We also
+/// need to be able to ignore mouse event when exiting fullscreen.
+/// The SFWindowController should call -[SFOpenGLView exitFullscreen]
+/// and -[SFOpenGLView enterFullscreen] when appropriate.
+///
+/// In order to send correct mouse coordonate to the requester when
+/// the window is in fullscreen we use m_realSize to represent the
+/// back buffer size (see SFWindowController). If 'm_realSize' is
+/// bound to its default value we don't recompute the mouse position
+/// and assume it's correct.
+///
+/// Modifiers keys (cmd, ctrl, alt, shift) are handled by this class
+/// but the actual logic is done in SFKeyboardModifiersHelper.(h|mm).
+///
+////////////////////////////////////////////////////////////
+@interface SFOpenGLView : NSOpenGLView {
+ sf::priv::WindowImplCocoa* m_requester;
+ BOOL m_useKeyRepeat;
+ BOOL m_mouseIsIn;
+ NSTrackingArea* m_trackingArea;
+ NSSize m_realSize;
+
+ // Hidden text view used to convert key event to actual chars.
+ // We use a silent responder to prevent sound alerts.
+ SFSilentResponder* m_silentResponder;
+ NSTextView* m_hiddenTextView;
+}
+
+////////////////////////////////////////////////////////////
+/// Create the SFML opengl view to fit the given area.
+///
+////////////////////////////////////////////////////////////
+-(id)initWithFrame:(NSRect)frameRect;
+
+////////////////////////////////////////////////////////////
+/// Handle going in and out of fullscreen mode.
+///
+////////////////////////////////////////////////////////////
+-(void)enterFullscreen;
+-(void)exitFullscreen;
+
+////////////////////////////////////////////////////////////
+/// Apply the given resquester to the view.
+///
+////////////////////////////////////////////////////////////
+-(void)setRequesterTo:(sf::priv::WindowImplCocoa *)requester;
+
+////////////////////////////////////////////////////////////
+/// Set the real size of view (it should be the back buffer size).
+/// If not set, or set to its default value NSZeroSize, the view
+/// won't recompute the mouse coordinates before sending them
+/// to the requester.
+///
+////////////////////////////////////////////////////////////
+-(void)setRealSize:(NSSize)newSize;
+
+////////////////////////////////////////////////////////////
+/// Compute the position in global coordinate
+/// of the given point in SFML coordinate.
+///
+////////////////////////////////////////////////////////////
+-(NSPoint)computeGlobalPositionOfRelativePoint:(NSPoint)point;
+
+////////////////////////////////////////////////////////////
+/// Adjust key repeat configuration.
+///
+////////////////////////////////////////////////////////////
+-(void)enableKeyRepeat;
+-(void)disableKeyRepeat;
+
+////////////////////////////////////////////////////////////
+/// Compute the position of the cursor.
+///
+////////////////////////////////////////////////////////////
+-(NSPoint)cursorPositionFromEvent:(NSEvent *)eventOrNil;
+
+@end
diff --git a/src/SFML/Window/OSX/SFOpenGLView.mm b/src/SFML/Window/OSX/SFOpenGLView.mm
new file mode 100644
index 0000000..b787e48
--- /dev/null
+++ b/src/SFML/Window/OSX/SFOpenGLView.mm
@@ -0,0 +1,695 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2012 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/OSX/WindowImplCocoa.hpp>
+#include <SFML/Window/OSX/HIDInputManager.hpp> // For localizedKeys and nonLocalizedKeys
+#include <SFML/System/Err.hpp>
+
+#import <SFML/Window/OSX/SFOpenGLView.h>
+#import <SFML/Window/OSX/SFSilentResponder.h>
+#import <SFML/Window/OSX/SFKeyboardModifiersHelper.h>
+
+
+////////////////////////////////////////////////////////////
+/// Returns true if `event` represents a representable character.
+///
+/// The event is assumed to be a key down event.
+/// False is returned if the event is either escape or a non text unicode.
+///
+////////////////////////////////////////////////////////////
+BOOL isValidTextUnicode(NSEvent* event);
+
+
+////////////////////////////////////////////////////////////
+/// SFOpenGLView class : Privates Methods Declaration
+///
+////////////////////////////////////////////////////////////
+@interface SFOpenGLView ()
+
+////////////////////////////////////////////////////////////
+/// Handle view resized event.
+///
+////////////////////////////////////////////////////////////
+-(void)frameDidChange:(NSNotification *)notification;
+
+////////////////////////////////////////////////////////////
+/// Establish if the mouse is inside or outside the OpenGL view.
+///
+////////////////////////////////////////////////////////////
+-(BOOL)isMouseInside;
+
+////////////////////////////////////////////////////////////
+/// Update the mouse state (in or out) and fire an event
+/// if its state has changed.
+///
+////////////////////////////////////////////////////////////
+-(void)updateMouseState;
+
+////////////////////////////////////////////////////////////
+/// Convert the NSEvent mouse button type to SFML type.
+///
+/// Returns ButtonCount if the button is unknown
+///
+////////////////////////////////////////////////////////////
+-(sf::Mouse::Button)mouseButtonFromEvent:(NSEvent *)event;
+
+////////////////////////////////////////////////////////////
+/// Convert a key down/up NSEvent into an SFML key event.
+/// Based on localizedKeys and nonLocalizedKeys function.
+///
+/// Return sf::Keyboard::Unknown as Code if the key is unknown.
+///
+////////////////////////////////////////////////////////////
++(sf::Event::KeyEvent)convertNSKeyEventToSFMLEvent:(NSEvent *)anEvent;
+
+@end
+
+@implementation SFOpenGLView
+
+#pragma mark
+#pragma mark SFOpenGLView's methods
+
+////////////////////////////////////////////////////////
+-(id)initWithFrame:(NSRect)frameRect
+{
+ if ((self = [super initWithFrame:frameRect])) {
+ [self setRequesterTo:0];
+ [self enableKeyRepeat];
+ m_realSize = NSZeroSize;
+
+ // Register for mouse move event
+ m_mouseIsIn = [self isMouseInside];
+ NSUInteger opts = (NSTrackingActiveAlways | NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingEnabledDuringMouseDrag);
+ m_trackingArea = [[NSTrackingArea alloc] initWithRect:[self bounds]
+ options:opts
+ owner:self
+ userInfo:nil];
+ [self addTrackingArea:m_trackingArea];
+
+ // Register for resize event
+ NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
+ [center addObserver:self
+ selector:@selector(frameDidChange:)
+ name:NSViewFrameDidChangeNotification
+ object:self];
+
+ // Create a hidden text view for parsing key down event properly
+ m_silentResponder = [[SFSilentResponder alloc] init];
+ m_hiddenTextView = [[NSTextView alloc] initWithFrame:NSZeroRect];
+ [m_hiddenTextView setNextResponder:m_silentResponder];
+ }
+
+ return self;
+}
+
+
+////////////////////////////////////////////////////////
+-(void)enterFullscreen
+{
+ // Remove the tracking area first,
+ // just to be sure we don't add it twice!
+ [self removeTrackingArea:m_trackingArea];
+ [self addTrackingArea:m_trackingArea];
+
+ // Fire an mouse entered event if needed
+ if (!m_mouseIsIn && m_requester != 0) {
+ m_requester->mouseMovedIn();
+ }
+
+ // Update status
+ m_mouseIsIn = YES;
+}
+
+
+////////////////////////////////////////////////////////
+-(void)exitFullscreen
+{
+ [self removeTrackingArea:m_trackingArea];
+
+ // Fire an mouse left event if needed
+ if (m_mouseIsIn && m_requester != 0) {
+ m_requester->mouseMovedOut();
+ }
+
+ // Update status
+ m_mouseIsIn = NO;
+}
+
+
+////////////////////////////////////////////////////////
+-(void)setRequesterTo:(sf::priv::WindowImplCocoa *)requester
+{
+ m_requester = requester;
+}
+
+
+////////////////////////////////////////////////////////
+-(void)setRealSize:(NSSize)newSize
+{
+ m_realSize = newSize;
+}
+
+
+////////////////////////////////////////////////////////
+-(NSPoint)computeGlobalPositionOfRelativePoint:(NSPoint)point
+{
+ // Recompute the mouse pos if required.
+ if (!NSEqualSizes(m_realSize, NSZeroSize)) {
+ point.x = point.x / m_realSize.width * [self frame].size.width;
+ point.y = point.y / m_realSize.height * [self frame].size.height;
+ }
+
+ // Note : -[NSWindow convertBaseToScreen:] is deprecated on 10.7
+ // but the recommended -[NSWindow convertRectToScreen] is not
+ // available until 10.7.
+ //
+ // So we stick with the old one for now.
+
+
+ // Flip SFML coordinates to match window coordinates
+ point.y = [self frame].size.height - point.y;
+
+ // Get the position of (x, y) in the coordinate system of the window.
+ point = [self convertPoint:point toView:self];
+ point = [self convertPoint:point toView:nil]; // nil means window
+
+ // Convert it to screen coordinates
+ point = [[self window] convertBaseToScreen:point];
+
+ // Flip screen coodinates to match CGDisplayMoveCursorToPoint referential.
+ float const screenHeight = [[[self window] screen] frame].size.height;
+ point.y = screenHeight - point.y;
+
+ return point;
+}
+
+
+////////////////////////////////////////////////////////
+-(void)enableKeyRepeat
+{
+ m_useKeyRepeat = YES;
+}
+
+
+////////////////////////////////////////////////////////
+-(void)disableKeyRepeat
+{
+ m_useKeyRepeat = NO;
+}
+
+
+////////////////////////////////////////////////////////
+-(void)frameDidChange:(NSNotification *)notification
+{
+ // Update mouse internal state.
+ [self updateMouseState];
+
+ // Update the OGL view to fit the new size.
+ [self update];
+
+ // Send an event
+ if (m_requester == 0) return;
+
+ // The new size
+ NSSize newSize = [self frame].size;
+ m_requester->windowResized(newSize.width, newSize.height);
+}
+
+
+////////////////////////////////////////////////////////
+-(BOOL)isMouseInside
+{
+ NSPoint relativeToWindow = [[self window] mouseLocationOutsideOfEventStream];
+ NSPoint relativeToView = [self convertPoint:relativeToWindow fromView:nil];
+
+ if (NSPointInRect(relativeToView, [self frame])) {
+ return YES;
+ }
+
+ return NO;
+}
+
+
+////////////////////////////////////////////////////////
+-(void)updateMouseState
+{
+ BOOL mouseWasIn = m_mouseIsIn;
+ m_mouseIsIn = [self isMouseInside];
+
+ // Send event if needed.
+ if (mouseWasIn && !m_mouseIsIn) {
+ [self mouseExited:nil];
+ } else if (!mouseWasIn && m_mouseIsIn) {
+ [self mouseEntered:nil];
+ }
+}
+
+
+#pragma mark
+#pragma mark Subclassing methods
+
+
+////////////////////////////////////////////////////////
+-(void)dealloc
+{
+ // Unregister
+ [[NSNotificationCenter defaultCenter] removeObserver:self];
+ [self removeTrackingArea:m_trackingArea];
+
+ // Release attributes
+ [m_hiddenTextView release];
+ [m_silentResponder release];
+ [m_trackingArea release];
+
+ [self setRequesterTo:0];
+
+ [super dealloc];
+}
+
+
+////////////////////////////////////////////////////////
+-(BOOL)acceptsFirstResponder
+{
+ // Accepts key event.
+ return YES;
+}
+
+
+////////////////////////////////////////////////////////
+-(BOOL)canBecomeKeyView
+{
+ // Accepts key event.
+ return YES;
+}
+
+
+#pragma mark
+#pragma mark Mouse-event methods
+
+
+////////////////////////////////////////////////////////
+-(void)mouseDown:(NSEvent *)theEvent
+{
+ // Forward to...
+ [self otherMouseDown:theEvent];
+
+ // Transmit to non-SFML responder
+ [[self nextResponder] mouseDown:theEvent];
+}
+
+
+////////////////////////////////////////////////////////
+-(void)mouseUp:(NSEvent *)theEvent
+{
+ // Forward to...
+ [self otherMouseUp:theEvent];
+
+ // Transmit to non-SFML responder
+ [[self nextResponder] mouseUp:theEvent];
+}
+
+
+////////////////////////////////////////////////////////
+-(void)mouseMoved:(NSEvent *)theEvent
+{
+ // Forward to...
+ [self otherMouseDragged:theEvent];
+
+ // Transmit to non-SFML responder
+ [[self nextResponder] mouseMoved:theEvent];
+}
+
+
+////////////////////////////////////////////////////////
+-(void)scrollWheel:(NSEvent *)theEvent
+{
+ if (m_requester != 0) {
+ NSPoint loc = [self cursorPositionFromEvent:theEvent];
+
+ m_requester->mouseWheelScrolledAt([theEvent deltaY], loc.x, loc.y);
+ }
+
+ // Transmit to non-SFML responder
+ [[self nextResponder] scrollWheel:theEvent];
+}
+
+
+////////////////////////////////////////////////////////
+-(void)mouseEntered:(NSEvent *)theEvent
+{
+ // There are two cases when we need to fire an event:
+ // a) the event is nil, meaning that the method was
+ // called from our code (e.g. updateMouseState)
+ // b) the mouse was outside the view.
+ BOOL shouldFire = (theEvent == nil || m_mouseIsIn == NO);
+
+ // Update status
+ m_mouseIsIn = YES;
+
+ if (m_requester == 0) return;
+
+ // Fire (or not) an event
+ if (shouldFire) {
+ m_requester->mouseMovedIn();
+ }
+}
+
+
+////////////////////////////////////////////////////////
+-(void)mouseExited:(NSEvent *)theEvent
+{
+ // Similarly to mouseEntered:
+ BOOL shouldFire = (theEvent == nil || m_mouseIsIn == YES);
+
+ // Update status
+ m_mouseIsIn = NO;
+
+ if (m_requester == 0) return;
+
+ // Fire (or not) an event
+ if (shouldFire) {
+ m_requester->mouseMovedOut();
+ }
+}
+
+
+////////////////////////////////////////////////////////
+-(void)rightMouseDown:(NSEvent *)theEvent
+{
+ // Forward to...
+ [self otherMouseDown:theEvent];
+
+ // Transmit to non-SFML responder
+ [[self nextResponder] rightMouseDown:theEvent];
+}
+
+
+////////////////////////////////////////////////////////
+-(void)rightMouseUp:(NSEvent *)theEvent
+{
+ // Forward to...
+ [self otherMouseUp:theEvent];
+
+ // Transmit to non-SFML responder
+ [[self nextResponder] rightMouseUp:theEvent];
+}
+
+
+////////////////////////////////////////////////////////
+-(void)otherMouseDown:(NSEvent *)theEvent
+{
+ sf::Mouse::Button button = [self mouseButtonFromEvent:theEvent];
+
+ if (m_requester != 0) {
+ NSPoint loc = [self cursorPositionFromEvent:theEvent];
+
+ if (button != sf::Mouse::ButtonCount) {
+ m_requester->mouseDownAt(button, loc.x, loc.y);
+ }
+ }
+
+ // If the event is not forwarded by mouseDown or rightMouseDown...
+ if (button != sf::Mouse::Left && button != sf::Mouse::Right) {
+ // ... transmit to non-SFML responder
+ [[self nextResponder] otherMouseDown:theEvent];
+ }
+}
+
+
+////////////////////////////////////////////////////////
+-(void)otherMouseUp:(NSEvent *)theEvent
+{
+ sf::Mouse::Button button = [self mouseButtonFromEvent:theEvent];
+
+ if (m_requester != 0) {
+ NSPoint loc = [self cursorPositionFromEvent:theEvent];
+
+ if (button != sf::Mouse::ButtonCount) {
+ m_requester->mouseUpAt(button, loc.x, loc.y);
+ }
+ }
+
+ // If the event is not forwarded by mouseUp or rightMouseUp...
+ if (button != sf::Mouse::Left && button != sf::Mouse::Right) {
+ // ... transmit to non-SFML responder
+ [[self nextResponder] otherMouseUp:theEvent];
+ }
+}
+
+
+////////////////////////////////////////////////////////
+-(void)rightMouseDragged:(NSEvent *)theEvent
+{
+ // Forward to...
+ [self otherMouseDragged:theEvent];
+
+ // Transmit to non-SFML responder
+ [[self nextResponder] rightMouseDragged:theEvent];
+}
+
+
+////////////////////////////////////////////////////////
+-(void)mouseDragged:(NSEvent *)theEvent
+{
+ // Forward to...
+ [self otherMouseDragged:theEvent];
+
+ // Transmit to non-SFML responder
+ [[self nextResponder] mouseDragged:theEvent];
+}
+
+
+////////////////////////////////////////////////////////
+-(void)otherMouseDragged:(NSEvent *)theEvent
+{
+ if (m_requester != 0) {
+ NSPoint loc = [self cursorPositionFromEvent:theEvent];
+
+ // Make sure the point is inside the view.
+ // (mouseEntered: and mouseExited: are not immediately called
+ // when the mouse is dragged. That would be too easy!)
+ [self updateMouseState];
+ if (m_mouseIsIn) {
+ m_requester->mouseMovedAt(loc.x, loc.y);
+ }
+ }
+
+ // If the event is not forwarded by mouseDragged or rightMouseDragged...
+ sf::Mouse::Button button = [self mouseButtonFromEvent:theEvent];
+ if (button != sf::Mouse::Left && button != sf::Mouse::Right) {
+ // ... transmit to non-SFML responder
+ [[self nextResponder] otherMouseUp:theEvent];
+ }
+}
+
+
+////////////////////////////////////////////////////////
+-(NSPoint)cursorPositionFromEvent:(NSEvent *)eventOrNil
+{
+ NSPoint loc;
+ // If no event given then get current mouse pos.
+ if (eventOrNil == nil) {
+ NSPoint rawPos = [[self window] mouseLocationOutsideOfEventStream];
+ loc = [self convertPoint:rawPos fromView:nil];
+ } else {
+ loc = [self convertPoint:[eventOrNil locationInWindow] fromView:nil];
+ }
+
+ // Don't forget to change to SFML coord system.
+ float h = [self frame].size.height;
+ loc.y = h - loc.y;
+
+ // Recompute the mouse pos if required.
+ if (!NSEqualSizes(m_realSize, NSZeroSize)) {
+ loc.x = loc.x * m_realSize.width / [self frame].size.width;
+ loc.y = loc.y * m_realSize.height / [self frame].size.height;
+ }
+
+ return loc;
+}
+
+
+////////////////////////////////////////////////////////
+-(sf::Mouse::Button)mouseButtonFromEvent:(NSEvent *)event
+{
+ switch ([event buttonNumber]) {
+ case 0: return sf::Mouse::Left;
+ case 1: return sf::Mouse::Right;
+ case 2: return sf::Mouse::Middle;
+ case 3: return sf::Mouse::XButton1;
+ case 4: return sf::Mouse::XButton2;
+ default: return sf::Mouse::ButtonCount; // Never happens! (hopefully)
+ }
+}
+
+
+#pragma mark
+#pragma mark Key-event methods
+
+
+////////////////////////////////////////////////////////
+-(void)keyDown:(NSEvent *)theEvent
+{
+ // Transmit to non-SFML responder
+ [[self nextResponder] keyDown:theEvent];
+
+ if (m_requester == 0) return;
+
+ // Handle key down event
+ if (m_useKeyRepeat || ![theEvent isARepeat]) {
+ sf::Event::KeyEvent key = [SFOpenGLView convertNSKeyEventToSFMLEvent:theEvent];
+
+ if (key.code != sf::Keyboard::Unknown) { // The key is recognized.
+ m_requester->keyDown(key);
+ }
+ }
+
+
+ // Handle text entred event:
+ // Ignore event if we don't want repeated keystrokes
+ if (m_useKeyRepeat || ![theEvent isARepeat]) {
+ // Ignore escape key and other non text keycode (See NSEvent.h)
+ // because they produce a sound alert.
+ if (isValidTextUnicode(theEvent)) {
+ // Send the event to the hidden text view for processing
+ [m_hiddenTextView interpretKeyEvents:[NSArray arrayWithObject:theEvent]];
+ }
+
+ // Carefully handle backspace and delete..
+ // Note: the event is intentionally sent to the hidden view
+ // even if we do something more specific below. This way
+ // key combination are correctly interpreted.
+
+ unsigned short keycode = [theEvent keyCode];
+
+ // Backspace
+ if (keycode == 0x33) {
+ // Send the correct unicode value (i.e. 8) instead of 127 (which is 'delete')
+ m_requester->textEntered(8);
+ }
+
+ // Delete
+ else if (keycode == 0x75 || keycode == NSDeleteFunctionKey) {
+ // Instead of the value 63272 we send 127.
+ m_requester->textEntered(127);
+ }
+
+ // Otherwise, let's see what our hidden field has computed
+ else {
+ NSString* string = [m_hiddenTextView string];
+
+ // Send each character to SFML event requester
+ for (NSUInteger index = 0; index < [string length]; ++index) {
+ m_requester->textEntered([string characterAtIndex:index]);
+ }
+
+ // Empty our hidden cache
+ [m_hiddenTextView setString:@""];
+ }
+ }
+}
+
+
+////////////////////////////////////////////////////////
+-(void)keyUp:(NSEvent *)theEvent
+{
+ // Transmit to non-SFML responder
+ [[self nextResponder] keyUp:theEvent];
+
+ if (m_requester == 0) return;
+
+ sf::Event::KeyEvent key = [SFOpenGLView convertNSKeyEventToSFMLEvent:theEvent];
+
+ if (key.code != sf::Keyboard::Unknown) { // The key is recognized.
+ m_requester->keyUp(key);
+ }
+}
+
+
+////////////////////////////////////////////////////////
+-(void)flagsChanged:(NSEvent *)theEvent
+{
+ // Transmit to non-SFML responder
+ [[self nextResponder] flagsChanged:theEvent];
+
+ if (m_requester == 0) return;
+
+ NSUInteger modifiers = [theEvent modifierFlags];
+ handleModifiersChanged(modifiers, *m_requester);
+}
+
+
+////////////////////////////////////////////////////////
++(sf::Event::KeyEvent)convertNSKeyEventToSFMLEvent:(NSEvent *)anEvent
+{
+ // Key code
+ sf::Keyboard::Key key = sf::Keyboard::Unknown;
+
+ // First we look if the key down is from a list of characters
+ // that depend on keyboard localization.
+ NSString* string = [anEvent charactersIgnoringModifiers];
+ if ([string length] > 0) {
+ key = sf::priv::HIDInputManager::localizedKeys([string characterAtIndex:0]);
+ }
+
+ // If the key is not a localized one, we try to find a corresponding code
+ // through virtual key code.
+ if (key == sf::Keyboard::Unknown) {
+ key = sf::priv::HIDInputManager::nonLocalizedKeys([anEvent keyCode]);
+ }
+
+//#ifdef SFML_DEBUG // Don't bother the final customers with annoying messages.
+// if (key.code == sf::Keyboard::Unknown) { // The key is unknown.
+// sf::err() << "This is an unknow key. Virtual key code is 0x"
+// << std::hex
+// << [anEvent keyCode]
+// << "."
+// << std::endl;
+// }
+//#endif
+
+ return keyEventWithModifiers([anEvent modifierFlags], key);
+}
+
+@end
+
+
+#pragma mark - C-like functions
+
+BOOL isValidTextUnicode(NSEvent* event)
+{
+ if ([event keyCode] == 0x35) { // Escape
+ return false;
+ } else if ([[event characters] length] > 0) {
+ unichar code = [[event characters] characterAtIndex:0];
+ return code < 0xF700 || code > 0xF8FF;
+ } else {
+ return true;
+ }
+}
+
diff --git a/src/SFML/Window/OSX/SFSilentResponder.h b/src/SFML/Window/OSX/SFSilentResponder.h
new file mode 100644
index 0000000..0890c92
--- /dev/null
+++ b/src/SFML/Window/OSX/SFSilentResponder.h
@@ -0,0 +1,41 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2012 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#import <AppKit/AppKit.h>
+
+////////////////////////////////////////////////////////////
+/// \brief Silent Responder used to prevent sound alert with key event
+///
+/// Mainly used by SFOpenGLView and its hidden text view.
+////////////////////////////////////////////////////////////
+@interface SFSilentResponder : NSResponder
+
+-(void)doCommandBySelector:(SEL)sel;
+
+@end
+
diff --git a/src/SFML/Window/OSX/SFSilentResponder.m b/src/SFML/Window/OSX/SFSilentResponder.m
new file mode 100644
index 0000000..0fb49f6
--- /dev/null
+++ b/src/SFML/Window/OSX/SFSilentResponder.m
@@ -0,0 +1,39 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2012 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#import <SFML/Window/OSX/SFSilentResponder.h>
+
+@implementation SFSilentResponder
+
+-(void)doCommandBySelector:(SEL)sel
+{
+ // Just do nothing, to prevent sound alerts
+}
+
+@end
+
diff --git a/src/SFML/Window/OSX/SFViewController.h b/src/SFML/Window/OSX/SFViewController.h
new file mode 100644
index 0000000..1a75327
--- /dev/null
+++ b/src/SFML/Window/OSX/SFViewController.h
@@ -0,0 +1,49 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2012 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#import <SFML/Window/OSX/WindowImplDelegateProtocol.h>
+
+////////////////////////////////////////////////////////////
+/// Predefine some classes
+////////////////////////////////////////////////////////////
+@class SFOpenGLView;
+
+////////////////////////////////////////////////////////////
+/// Implementation of WindowImplDelegateProtocol for view managment.
+///
+////////////////////////////////////////////////////////////
+
+@interface SFViewController : NSObject <WindowImplDelegateProtocol> {
+ NSView* m_view;
+ SFOpenGLView* m_oglView;
+ sf::priv::WindowImplCocoa* m_requester;
+}
+
+-(id)initWithView:(NSView *)view;
+
+@end
diff --git a/src/SFML/Window/OSX/SFViewController.mm b/src/SFML/Window/OSX/SFViewController.mm
new file mode 100644
index 0000000..d9cc4c7
--- /dev/null
+++ b/src/SFML/Window/OSX/SFViewController.mm
@@ -0,0 +1,241 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2012 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#import <SFML/Window/OSX/SFViewController.h>
+#import <SFML/Window/OSX/SFOpenGLView.h>
+#import <SFML/Window/OSX/SFApplication.h>
+#include <SFML/System/Err.hpp>
+#include <SFML/Window/OSX/WindowImplCocoa.hpp>
+
+@implementation SFViewController
+
+
+////////////////////////////////////////////////////////
+-(id)initWithView:(NSView *)view
+{
+ if ((self = [super init])) {
+ m_requester = 0;
+
+ // Retain the view for our own use.
+ m_view = [view retain];
+
+ if (m_view == nil) {
+
+ sf::err()
+ << "No view was given to initWithWindow:."
+ << std::endl;
+
+ return self;
+ }
+
+ // Create the view.
+ NSRect frame = [m_view frame];
+ frame.origin.x = 0;
+ frame.origin.y = 0;
+ m_oglView = [[SFOpenGLView alloc] initWithFrame:frame];
+
+ if (m_oglView == nil) {
+
+ sf::err()
+ << "Could not create an instance of NSOpenGLView "
+ << "in (SFViewController -initWithView:)."
+ << std::endl;
+
+ return self;
+ }
+
+ // Set the (OGL) view to the view as its "content" view.
+ [m_view addSubview:m_oglView];
+
+ [m_oglView setAutoresizingMask:[m_view autoresizingMask]];
+ }
+
+ return self;
+}
+
+
+////////////////////////////////////////////////////////
+-(void)dealloc
+{
+ [self closeWindow];
+
+ [m_view release];
+ [m_oglView release];
+
+ [super dealloc];
+}
+
+
+////////////////////////////////////////////////////////
+-(void)setRequesterTo:(sf::priv::WindowImplCocoa *)requester
+{
+ // Forward to the view.
+ [m_oglView setRequesterTo:requester];
+ m_requester = requester;
+}
+
+
+////////////////////////////////////////////////////////
+-(sf::WindowHandle)getSystemHandle
+{
+ return m_view;
+}
+
+
+////////////////////////////////////////////////////////
+-(void)hideMouseCursor
+{
+ [NSCursor hide];
+}
+
+
+////////////////////////////////////////////////////////
+-(void)showMouseCursor
+{
+ [NSCursor unhide];
+}
+
+
+////////////////////////////////////////////////////////////
+-(NSPoint)position
+{
+ // Origin is bottom-left corner of the window
+ return [m_view convertPoint:NSMakePoint(0, 0) toView:nil]; // nil means window
+}
+
+
+////////////////////////////////////////////////////////.
+-(void)setWindowPositionToX:(int)x Y:(int)y
+{
+ sf::err() << "Cannot move SFML area when SFML is integrated in a NSView. Use the view hanlder directly instead." << std::endl;
+}
+
+
+////////////////////////////////////////////////////////////
+-(NSSize)size
+{
+ return [m_oglView frame].size;
+}
+
+
+////////////////////////////////////////////////////////
+-(void)resizeTo:(unsigned int)width by:(unsigned int)height
+{
+ NSRect frame = NSMakeRect([m_view frame].origin.x,
+ [m_view frame].origin.y,
+ width,
+ height);
+
+ [m_view setFrame:frame];
+ [m_oglView setFrame:frame];
+}
+
+
+////////////////////////////////////////////////////////
+-(void)changeTitle:(NSString *)title
+{
+ sf::err() << "Cannot change the title of the SFML area when SFML is integrated in a NSView." << std::endl;
+}
+
+
+////////////////////////////////////////////////////////
+-(void)hideWindow
+{
+ [m_view setHidden:YES];
+}
+
+
+////////////////////////////////////////////////////////
+-(void)showWindow
+{
+ [m_view setHidden:NO];
+}
+
+
+////////////////////////////////////////////////////////
+-(void)closeWindow
+{
+ sf::err() << "Cannot close SFML area when SFML is integrated in a NSView." << std::endl;
+}
+
+
+////////////////////////////////////////////////////////
+-(void)enableKeyRepeat
+{
+ [m_oglView enableKeyRepeat];
+}
+
+
+////////////////////////////////////////////////////////
+-(void)disableKeyRepeat
+{
+ [m_oglView disableKeyRepeat];
+}
+
+
+////////////////////////////////////////////////////////
+-(void)setIconTo:(unsigned int)width
+ by:(unsigned int)height
+ with:(sf::Uint8 const *)pixels
+{
+ sf::err() << "Cannot set an icon when SFML is integrated in a NSView." << std::endl;
+}
+
+
+////////////////////////////////////////////////////////
+-(void)processEvent
+{
+ // If we are not on the main thread we stop here and advice the user.
+ if ([NSThread currentThread] != [NSThread mainThread]) {
+ /*
+ * See http://lists.apple.com/archives/cocoa-dev/2011/Feb/msg00460.html
+ * for more information.
+ */
+ sf::err()
+ << "Cannot fetch event from a worker thread. (OS X restriction)"
+ << std::endl;
+
+ return;
+ }
+
+ // If we don't have a requester we don't fetch event.
+ if (m_requester != 0) {
+ [SFApplication processEvent];
+ }
+}
+
+
+////////////////////////////////////////////////////////
+-(void)applyContext:(NSOpenGLContext *)context
+{
+ [m_oglView setOpenGLContext:context];
+ [context setView:m_oglView];
+}
+
+
+@end
diff --git a/src/SFML/Window/OSX/SFWindow.h b/src/SFML/Window/OSX/SFWindow.h
new file mode 100644
index 0000000..ad823a8
--- /dev/null
+++ b/src/SFML/Window/OSX/SFWindow.h
@@ -0,0 +1,48 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2012 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#import <AppKit/AppKit.h>
+
+////////////////////////////////////////////////////////////
+/// \brief Here we redefine some methods to allow grabing fullscreen events.
+///
+////////////////////////////////////////////////////////////
+@interface SFWindow : NSWindow {
+
+}
+
+////////////////////////////////////////////////////////////
+/// These two methods must return YES to grab fullscreen events.
+/// See http://stackoverflow.com/questions/999464/fullscreen-key-down-actions
+/// for more informations
+///
+////////////////////////////////////////////////////////////
+-(BOOL)acceptsFirstResponder;
+-(BOOL)canBecomeKeyWindow;
+
+@end
diff --git a/src/SFML/Window/OSX/SFWindow.m b/src/SFML/Window/OSX/SFWindow.m
new file mode 100644
index 0000000..5f5de20
--- /dev/null
+++ b/src/SFML/Window/OSX/SFWindow.m
@@ -0,0 +1,59 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2012 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#import "SFWindow.h"
+
+
+@implementation SFWindow
+
+////////////////////////////////////////////////////////
+-(BOOL)acceptsFirstResponder
+{
+ return YES;
+}
+
+
+////////////////////////////////////////////////////////
+-(BOOL)canBecomeKeyWindow
+{
+ return YES;
+}
+
+////////////////////////////////////////////////////////
+-(void)keyDown:(NSEvent *)theEvent
+{
+ // Do nothing except preventing a system alert each time a key is pressed
+ //
+ // Special Consideration :
+ // -----------------------
+ // Consider overriding NSResponder -keyDown: message in a Cocoa view/window
+ // that contains a SFML rendering area. Doing so will prevent a system
+ // alert to be thrown everytime the user presses a key.
+}
+
+@end
diff --git a/src/SFML/Window/OSX/SFWindowController.h b/src/SFML/Window/OSX/SFWindowController.h
new file mode 100644
index 0000000..e96ba95
--- /dev/null
+++ b/src/SFML/Window/OSX/SFWindowController.h
@@ -0,0 +1,79 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2012 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#import <SFML/Window/OSX/WindowImplDelegateProtocol.h>
+#include <SFML/Window/VideoMode.hpp>
+
+////////////////////////////////////////////////////////////
+/// Predefine some classes
+////////////////////////////////////////////////////////////
+namespace sf {
+ namespace priv {
+ class WindowImplCocoa;
+ }
+}
+
+@class SFOpenGLView;
+
+////////////////////////////////////////////////////////////
+/// Implementation of WindowImplDelegateProtocol for window managment.
+///
+/// Key and mouse events are delegated to its view.
+/// Window events are managed by this class.
+///
+/// Used when SFML handle everything and when a NSWindow* is given
+/// as handle to WindowImpl.
+///
+/// m_fullscreenMode is bind to default video mode if we don't need to change screen size.
+///
+////////////////////////////////////////////////////////////
+
+#if MAC_OS_X_VERSION_MAX_ALLOWED < 1060 // NSWindowDelegate is only define since 10.6
+@interface SFWindowController : NSResponder <WindowImplDelegateProtocol> {
+#else
+@interface SFWindowController : NSResponder <WindowImplDelegateProtocol, NSWindowDelegate> {
+#endif
+ NSWindow* m_window;
+ SFOpenGLView* m_oglView;
+ sf::priv::WindowImplCocoa* m_requester;
+ sf::VideoMode* m_fullscreenMode; // Note : C++ ctor/dtor are not called for Obj-C fields.
+}
+
+////////////////////////////////////////////////////////////
+/// Create the SFML window with an external Cocoa window.
+///
+////////////////////////////////////////////////////////////
+-(id)initWithWindow:(NSWindow *)window;
+
+////////////////////////////////////////////////////////////
+/// Create the SFML window "from scratch" (full SFML handling).
+///
+////////////////////////////////////////////////////////////
+-(id)initWithMode:(sf::VideoMode const &)mode andStyle:(unsigned long)style;
+
+@end
diff --git a/src/SFML/Window/OSX/SFWindowController.mm b/src/SFML/Window/OSX/SFWindowController.mm
new file mode 100644
index 0000000..4f68c13
--- /dev/null
+++ b/src/SFML/Window/OSX/SFWindowController.mm
@@ -0,0 +1,546 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2012 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/OSX/WindowImplCocoa.hpp>
+#include <SFML/Window/VideoMode.hpp>
+#include <SFML/Window/WindowHandle.hpp>
+#include <SFML/Window/WindowStyle.hpp>
+#include <SFML/System/Err.hpp>
+#include <ApplicationServices/ApplicationServices.h>
+
+#import <SFML/Window/OSX/SFWindowController.h>
+#import <SFML/Window/OSX/SFApplication.h>
+#import <SFML/Window/OSX/SFOpenGLView.h>
+#import <SFML/Window/OSX/SFWindow.h>
+#import <OpenGL/OpenGL.h>
+
+////////////////////////////////////////////////////////////
+/// SFWindowController class : Privates Methods Declaration
+///
+////////////////////////////////////////////////////////////
+@interface SFWindowController ()
+
+////////////////////////////////////////////////////////////
+/// Retrieves the screen height.
+///
+////////////////////////////////////////////////////////////
+-(float)screenHeight;
+
+////////////////////////////////////////////////////////////
+/// Retrives the title bar height.
+///
+////////////////////////////////////////////////////////////
+-(float)titlebarHeight;
+
+@end
+
+@implementation SFWindowController
+
+#pragma mark
+#pragma mark SFWindowController's methods
+
+////////////////////////////////////////////////////////
+-(id)initWithWindow:(NSWindow *)window
+{
+ if ((self = [super init])) {
+ m_requester = 0;
+ m_fullscreenMode = new sf::VideoMode();
+
+ // Retain the window for our own use.
+ m_window = [window retain];
+
+ if (m_window == nil) {
+
+ sf::err()
+ << "No window was given to initWithWindow:."
+ << std::endl;
+
+ return self;
+ }
+
+ // Create the view.
+ m_oglView = [[SFOpenGLView alloc] initWithFrame:[[m_window contentView] frame]];
+
+ if (m_oglView == nil) {
+
+ sf::err()
+ << "Could not create an instance of NSOpenGLView "
+ << "in (SFWindowController -initWithWindow:)."
+ << std::endl;
+
+ return self;
+ }
+
+ // Set the view to the window as its content view.
+ [m_window setContentView:m_oglView];
+ }
+
+ return self;
+}
+
+
+////////////////////////////////////////////////////////
+-(id)initWithMode:(sf::VideoMode const &)mode andStyle:(unsigned long)style
+{
+ // If we are not on the main thread we stop here and advice the user.
+ if ([NSThread currentThread] != [NSThread mainThread]) {
+ /*
+ * See http://lists.apple.com/archives/cocoa-dev/2011/Feb/msg00460.html
+ * for more information.
+ */
+ sf::err()
+ << "Cannot create a window from a worker thread. (OS X limitation)"
+ << std::endl;
+
+ return nil;
+ }
+
+ if ((self = [super init])) {
+ m_requester = 0;
+ m_fullscreenMode = new sf::VideoMode();
+
+ // Create our window size.
+ NSRect rect = NSZeroRect;
+ if (style & sf::Style::Fullscreen && mode != sf::VideoMode::getDesktopMode()) {
+ // We use desktop mode to size the window
+ // but we set the back buffer size to 'mode' in applyContext method.
+
+ *m_fullscreenMode = mode;
+
+ sf::VideoMode dm = sf::VideoMode::getDesktopMode();
+ rect = NSMakeRect(0, 0, dm.width, dm.height);
+
+ } else { // no fullscreen requested.
+ rect = NSMakeRect(0, 0, mode.width, mode.height);
+ }
+
+ // Convert the SFML window style to Cocoa window style.
+ unsigned int nsStyle = NSBorderlessWindowMask;
+ if (!(style & sf::Style::Fullscreen)) { // if fullscrean we keep our NSBorderlessWindowMask.
+
+ if (style & sf::Style::Titlebar) nsStyle |= NSTitledWindowMask | NSMiniaturizableWindowMask;
+
+ if (style & sf::Style::Resize) nsStyle |= NSResizableWindowMask;
+
+ if (style & sf::Style::Close) nsStyle |= NSClosableWindowMask;
+
+ }
+
+ // Create the window.
+ m_window = [[SFWindow alloc] initWithContentRect:rect
+ styleMask:nsStyle
+ backing:NSBackingStoreBuffered
+ defer:NO]; // Don't defer it!
+ /*
+ "YES" produces some "invalid drawable".
+ See http://www.cocoabuilder.com/archive/cocoa/152482-nsviews-and-nsopenglcontext-invalid-drawable-error.html
+
+ [...]
+ As best as I can figure, this is happening because the NSWindow (and
+ hence my view) are not visible onscreen yet, and the system doesn't like that.
+ [...]
+ */
+
+ if (m_window == nil) {
+ sf::err()
+ << "Could not create an instance of NSWindow "
+ << "in (SFWindowController -initWithMode:andStyle:)."
+ << std::endl;
+
+ return self;
+ }
+
+ // Apply special feature for fullscreen window.
+ if (style & sf::Style::Fullscreen) {
+ // We place the window above everything else.
+ [m_window setOpaque:YES];
+ [m_window setHidesOnDeactivate:YES];
+ [m_window setLevel:NSMainMenuWindowLevel+1];
+
+ // And hide the menu bar
+ [NSMenu setMenuBarVisible:NO];
+
+ /* ---------------------------
+ * | Note for future version |
+ * ---------------------------
+ *
+ * starting with OS 10.6 NSView provides
+ * a new method -enterFullScreenMode:withOptions:
+ * which could be a good alternative.
+ */
+ }
+
+ // Center the window to be cool =)
+ [m_window center];
+
+ // Create the view.
+ m_oglView = [[SFOpenGLView alloc] initWithFrame:[[m_window contentView] frame]];
+
+ if (m_oglView == nil) {
+ sf::err()
+ << "Could not create an instance of NSOpenGLView "
+ << "in (SFWindowController -initWithMode:andStyle:)."
+ << std::endl;
+
+ return self;
+ }
+
+ // If a fullscreen window was requested...
+ if (style & sf::Style::Fullscreen) {
+ /// ... we tell the OpenGL view
+ [m_oglView enterFullscreen];
+
+ // ... and if the resolution is not the default one...
+ if (mode != sf::VideoMode::getDesktopMode()) {
+ // ... we set the "real size" of the view (that is the back buffer size).
+ [m_oglView setRealSize:NSMakeSize(m_fullscreenMode->width, m_fullscreenMode->height)];
+ }
+ }
+
+ // Set the view to the window as its content view.
+ [m_window setContentView:m_oglView];
+
+ // Register for event.
+ [m_window setDelegate:self];
+ [m_window setAcceptsMouseMovedEvents:YES];
+ [m_window setIgnoresMouseEvents:NO];
+
+ // And some other things...
+ [m_window setAutodisplay:YES];
+ [m_window setReleasedWhenClosed:NO];
+ } // if super init ok
+
+ return self;
+}
+
+////////////////////////////////////////////////////////
+-(void)dealloc
+{
+ [self closeWindow];
+ [NSMenu setMenuBarVisible:YES];
+
+ [m_window release];
+ [m_oglView release];
+
+ delete m_fullscreenMode;
+
+ [super dealloc];
+}
+
+
+#pragma mark
+#pragma mark WindowImplDelegateProtocol's methods
+
+
+////////////////////////////////////////////////////////
+-(void)setRequesterTo:(sf::priv::WindowImplCocoa *)requester
+{
+ // Forward to the view.
+ [m_oglView setRequesterTo:requester];
+ m_requester = requester;
+}
+
+
+////////////////////////////////////////////////////////
+-(sf::WindowHandle)getSystemHandle
+{
+ return m_window;
+}
+
+
+////////////////////////////////////////////////////////
+-(void)hideMouseCursor
+{
+ [NSCursor hide];
+}
+
+
+////////////////////////////////////////////////////////
+-(void)showMouseCursor
+{
+ [NSCursor unhide];
+}
+
+
+////////////////////////////////////////////////////////////
+-(NSPoint)position
+{
+ // First, get the top left corner of the view in its own base system
+ NSPoint const origin = [m_oglView frame].origin;
+ NSSize const size = [m_oglView frame].size;
+ NSPoint const topLeftCornerOfView = NSMakePoint(origin.x, origin.y + size.height);
+ NSPoint const positionInView = [m_oglView convertPointToBase:topLeftCornerOfView];
+
+ // Then, convert it to window base system
+ NSPoint const positionInWindow = [m_oglView convertPoint:positionInView toView:nil];
+ // here nil denotes the window containing the view
+
+ // Next, convert it to the screen base system
+ NSPoint const positionInScreen = [[m_oglView window] convertBaseToScreen:positionInWindow];
+
+ // Finally, flip for SFML window coordinate system
+ // Don't forget to discard the title bar !
+ NSPoint const positionInSFML = NSMakePoint(positionInScreen.x,
+ ([self screenHeight] - [self titlebarHeight]) - positionInScreen.y);
+
+ return positionInSFML;
+}
+
+
+////////////////////////////////////////////////////////.
+-(void)setWindowPositionToX:(int)x Y:(int)y
+{
+ NSPoint point = NSMakePoint(x, y);
+
+ // Flip for SFML window coordinate system.
+ point.y = [self screenHeight] - point.y;
+
+ // Place the window.
+ [m_window setFrameTopLeftPoint:point];
+}
+
+
+////////////////////////////////////////////////////////
+-(NSSize)size
+{
+ if (*m_fullscreenMode == sf::VideoMode()) {
+ return [m_oglView frame].size;
+ } else {
+ return NSMakeSize(m_fullscreenMode->width, m_fullscreenMode->height);
+ }
+}
+
+
+////////////////////////////////////////////////////////
+-(void)resizeTo:(unsigned int)width by:(unsigned int)height
+{
+ // Add titlebar height.
+ NSRect frame = NSMakeRect([m_window frame].origin.x,
+ [m_window frame].origin.y,
+ width,
+ height + [self titlebarHeight]);
+
+ [m_window setFrame:frame display:YES];
+}
+
+
+////////////////////////////////////////////////////////
+-(void)changeTitle:(NSString *)title
+{
+ [m_window setTitle:title];
+}
+
+
+////////////////////////////////////////////////////////
+-(void)hideWindow
+{
+ [m_window orderOut:nil];
+}
+
+
+////////////////////////////////////////////////////////
+-(void)showWindow
+{
+ [m_window makeKeyAndOrderFront:nil];
+}
+
+
+////////////////////////////////////////////////////////
+-(void)closeWindow
+{
+ [m_window close];
+ [m_window setDelegate:nil];
+ [self setRequesterTo:0];
+}
+
+
+////////////////////////////////////////////////////////
+-(void)enableKeyRepeat
+{
+ [m_oglView enableKeyRepeat];
+}
+
+
+////////////////////////////////////////////////////////
+-(void)disableKeyRepeat
+{
+ [m_oglView disableKeyRepeat];
+}
+
+
+////////////////////////////////////////////////////////
+-(void)setIconTo:(unsigned int)width
+ by:(unsigned int)height
+ with:(sf::Uint8 const *)pixels
+{
+ // Create an empty image representation.
+ NSBitmapImageRep* bitmap =
+ [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:0 // if 0 : only allocate memory
+ pixelsWide:width
+ pixelsHigh:height
+ bitsPerSample:8 // The number of bits used to specify
+ // one pixel in a single component of the data.
+ samplesPerPixel:4 // 3 if no alpha, 4 with it
+ hasAlpha:YES
+ isPlanar:NO // I don't know what it is but it works
+ colorSpaceName:NSCalibratedRGBColorSpace
+ bytesPerRow:0 // 0 == determine automatically
+ bitsPerPixel:0]; // 0 == determine automatically
+
+ // Load data pixels.
+#if MAC_OS_X_VERSION_MAX_ALLOWED < 1050 // We may need to define NSUInteger.
+#define NSUInteger unsigned int
+#endif
+ for (unsigned int y = 0; y < height; ++y) {
+ for (unsigned int x = 0; x < width; ++x, pixels+=4) {
+ NSUInteger pixel[4] = { pixels[0], pixels[1], pixels[2], pixels[3] };
+ [bitmap setPixel:pixel
+ atX:x
+ y:y];
+ }
+ }
+
+ // Create an image from the representation.
+ NSImage* icon = [[NSImage alloc] initWithSize:NSMakeSize(width, height)];
+ [icon addRepresentation:bitmap];
+
+ // Set app icon.
+ [[SFApplication sharedApplication] setApplicationIconImage:icon];
+
+ // Free up.
+ [icon release];
+ [bitmap release];
+}
+
+
+////////////////////////////////////////////////////////
+-(void)processEvent
+{
+ // If we are not on the main thread we stop here and advice the user.
+ if ([NSThread currentThread] != [NSThread mainThread]) {
+ /*
+ * See http://lists.apple.com/archives/cocoa-dev/2011/Feb/msg00460.html
+ * for more information.
+ */
+ sf::err()
+ << "Cannot fetch event from a worker thread. (OS X restriction)"
+ << std::endl;
+
+ return;
+ }
+
+ // If we don't have a requester we don't fetch event.
+ if (m_requester != 0) {
+ [SFApplication processEvent];
+ }
+}
+
+
+////////////////////////////////////////////////////////
+-(void)applyContext:(NSOpenGLContext *)context
+{
+ [m_oglView setOpenGLContext:context];
+ [context setView:m_oglView];
+
+ // If fullscreen was requested and the mode used to create the window
+ // was not the desktop mode, we change the back buffer size of the
+ // context.
+ if (*m_fullscreenMode != sf::VideoMode()) {
+ CGLContextObj cgcontext = (CGLContextObj)[context CGLContextObj];
+
+ GLint dim[2] = {m_fullscreenMode->width, m_fullscreenMode->height};
+
+ CGLSetParameter(cgcontext, kCGLCPSurfaceBackingSize, dim);
+ CGLEnable(cgcontext, kCGLCESurfaceBackingSize);
+ }
+}
+
+
+#pragma mark
+#pragma mark NSWindowDelegate's methods
+
+
+////////////////////////////////////////////////////////
+-(BOOL)windowShouldClose:(id)sender
+{
+ if (m_requester == 0) return YES;
+
+ m_requester->windowClosed();
+ return NO;
+}
+
+
+////////////////////////////////////////////////////////
+-(void)windowDidBecomeKey:(NSNotification *)notification
+{
+ // Send event.
+ if (m_requester == 0) return;
+
+ m_requester->windowGainedFocus();
+
+ if (*m_fullscreenMode != sf::VideoMode()) {
+ [m_oglView enterFullscreen];
+ }
+}
+
+
+////////////////////////////////////////////////////////
+-(void)windowDidResignKey:(NSNotification *)notification
+{
+ // Send event.
+ if (m_requester == 0) return;
+
+ m_requester->windowLostFocus();
+
+ if (*m_fullscreenMode != sf::VideoMode()) {
+ [m_oglView exitFullscreen];
+ }
+}
+
+
+#pragma mark
+#pragma mark Other methods
+
+////////////////////////////////////////////////////////
+-(float)screenHeight
+{
+ NSDictionary *deviceDescription = [[m_window screen] deviceDescription];
+ NSNumber *screenNumber = [deviceDescription valueForKey:@"NSScreenNumber"];
+ CGDirectDisplayID screenID = (CGDirectDisplayID)[screenNumber intValue];
+ CGFloat height = CGDisplayPixelsHigh(screenID);
+ return height;
+}
+
+
+////////////////////////////////////////////////////////
+-(float)titlebarHeight
+{
+ return NSHeight([m_window frame]) - NSHeight([[m_window contentView] frame]);
+}
+
+@end
diff --git a/src/SFML/Window/OSX/VideoModeImpl.cpp b/src/SFML/Window/OSX/VideoModeImpl.cpp
new file mode 100644
index 0000000..1d7b0df
--- /dev/null
+++ b/src/SFML/Window/OSX/VideoModeImpl.cpp
@@ -0,0 +1,118 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/VideoModeImpl.hpp>
+#include <SFML/Window/OSX/cg_sf_conversion.hpp>
+#include <SFML/System/Err.hpp>
+#include <algorithm>
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// Note :
+/// Starting with 10.6, CGDisplayModeRef and CGDisplayCopyAllDisplayModes
+/// should be used instead of CFDictionaryRef and CGDisplayAvailableModes.
+///
+////////////////////////////////////////////////////////////
+std::vector<VideoMode> VideoModeImpl::getFullscreenModes()
+{
+#if MAC_OS_X_VERSION_MAX_ALLOWED < 1060
+
+ std::vector<VideoMode> modes;
+
+ // Retrieve array of dictionaries representing display modes.
+ CFArrayRef displayModes = CGDisplayAvailableModes(CGMainDisplayID());
+
+ if (displayModes == NULL) {
+ sf::err() << "Couldn't get VideoMode for main display.";
+ return modes;
+ }
+
+ // Loop on each mode and convert it into a sf::VideoMode object.
+ CFIndex const modesCount = CFArrayGetCount(displayModes);
+ for (CFIndex i = 0; i < modesCount; i++) {
+ CFDictionaryRef dictionary = (CFDictionaryRef)CFArrayGetValueAtIndex(displayModes, i);
+
+ VideoMode mode = convertCGModeToSFMode(dictionary);
+
+ // If not yet listed we add it to our modes array.
+ if (std::find(modes.begin(), modes.end(), mode) == modes.end()) {
+ modes.push_back(mode);
+ }
+ }
+
+ return modes;
+
+#else // MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
+
+ std::vector<VideoMode> modes;
+
+ // Retrieve all modes available for main screen only.
+ CFArrayRef cgmodes = CGDisplayCopyAllDisplayModes(CGMainDisplayID(), NULL);
+
+ if (cgmodes == NULL) {
+ sf::err() << "Couldn't get VideoMode for main display.";
+ return modes;
+ }
+
+ // Loop on each mode and convert it into a sf::VideoMode object.
+ CFIndex const modesCount = CFArrayGetCount(cgmodes);
+ for (CFIndex i = 0; i < modesCount; i++) {
+ CGDisplayModeRef cgmode = (CGDisplayModeRef)CFArrayGetValueAtIndex(cgmodes, i);
+
+ VideoMode mode = convertCGModeToSFMode(cgmode);
+
+ // If not yet listed we add it to our modes array.
+ if (std::find(modes.begin(), modes.end(), mode) == modes.end()) {
+ modes.push_back(mode);
+ }
+ }
+
+ // Clean up memory.
+ CFRelease(cgmodes);
+
+ return modes;
+
+#endif
+}
+
+
+////////////////////////////////////////////////////////////
+VideoMode VideoModeImpl::getDesktopMode()
+{
+ CGDirectDisplayID display = CGMainDisplayID();
+ return VideoMode(CGDisplayPixelsWide(display),
+ CGDisplayPixelsHigh(display),
+ displayBitsPerPixel(display));
+}
+
+} // namespace priv
+
+} // namespace sf
diff --git a/src/SFML/Window/OSX/WindowImplCocoa.hpp b/src/SFML/Window/OSX/WindowImplCocoa.hpp
new file mode 100644
index 0000000..c0c29c3
--- /dev/null
+++ b/src/SFML/Window/OSX/WindowImplCocoa.hpp
@@ -0,0 +1,343 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_WINDOWIMPLCOCOA_HPP
+#define SFML_WINDOWIMPLCOCOA_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/Event.hpp>
+#include <SFML/Window/WindowImpl.hpp>
+#include <SFML/System/String.hpp>
+
+////////////////////////////////////////////////////////////
+/// Predefine OBJC classes
+////////////////////////////////////////////////////////////
+#ifdef __OBJC__
+
+#import <SFML/Window/OSX/WindowImplDelegateProtocol.h>
+typedef id<WindowImplDelegateProtocol,NSObject> WindowImplDelegateRef;
+
+@class NSOpenGLContext;
+typedef NSOpenGLContext* NSOpenGLContextRef;
+
+#else // If C++
+
+typedef unsigned short unichar; // See NSString.h
+
+typedef void* WindowImplDelegateRef;
+typedef void* NSOpenGLContextRef;
+
+#endif
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief Mac OS X (Cocoa) implementation of WindowImpl
+///
+////////////////////////////////////////////////////////////
+class WindowImplCocoa : public WindowImpl
+{
+public :
+ ////////////////////////////////////////////////////////////
+ /// \brief Construct the window implementation from an existing control
+ ///
+ /// \param handle Platform-specific handle of the control
+ ///
+ ////////////////////////////////////////////////////////////
+ WindowImplCocoa(WindowHandle handle);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Create the window implementation
+ ///
+ /// \param mode Video mode to use
+ /// \param title Title of the window
+ /// \param style Window style (resizable, fixed, or fullscren)
+ /// \param settings Additional settings for the underlying OpenGL context
+ ///
+ ////////////////////////////////////////////////////////////
+ WindowImplCocoa(VideoMode mode, const String& title, unsigned long style, const ContextSettings& settings);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Destructor
+ ///
+ ////////////////////////////////////////////////////////////
+ ~WindowImplCocoa();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Window Closed Event – called by the cocoa window object.
+ ///
+ /// Send the event to SFML WindowImpl class.
+ ///
+ ////////////////////////////////////////////////////////////
+ void windowClosed(void);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Window Resized Event – called by the cocoa window object.
+ ///
+ /// Send the event to SFML WindowImpl class.
+ ///
+ /// \param width
+ /// \param height
+ ///
+ ////////////////////////////////////////////////////////////
+ void windowResized(unsigned int width, unsigned int height);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Window Lost Focus Event – called by the cocoa window object.
+ ///
+ /// Send the event to SFML WindowImpl class.
+ ///
+ ////////////////////////////////////////////////////////////
+ void windowLostFocus(void);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Window Get Focus Event – called by the cocoa window object.
+ ///
+ /// Send the event to SFML WindowImpl class.
+ ///
+ ////////////////////////////////////////////////////////////
+ void windowGainedFocus(void);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Mouse Down Event – called by the cocoa view object.
+ ///
+ /// Send the event to SFML WindowImpl class.
+ ///
+ /// \param button
+ /// \param x
+ /// \param y
+ ///
+ ////////////////////////////////////////////////////////////
+ void mouseDownAt(Mouse::Button button, int x, int y);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Mouse Up Event – called by the cocoa view object.
+ ///
+ /// Send the event to SFML WindowImpl class.
+ ///
+ /// \param button
+ /// \param x
+ /// \param y
+ ///
+ ////////////////////////////////////////////////////////////
+ void mouseUpAt(Mouse::Button button, int x, int y);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Mouse Moved Event – called by the cocoa view object.
+ ///
+ /// Send the event to SFML WindowImpl class.
+ ///
+ /// \param x
+ /// \param y
+ ///
+ ////////////////////////////////////////////////////////////
+ void mouseMovedAt(int x, int y);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Mouse Wheel Scrolled Event – called by the cocoa view object.
+ ///
+ /// Send the event to SFML WindowImpl class.
+ ///
+ /// \param delta
+ /// \param x
+ /// \param y
+ ///
+ ////////////////////////////////////////////////////////////
+ void mouseWheelScrolledAt(float delta, int x, int y);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Mouse In Event – called by the cocoa view object.
+ ///
+ /// Send the event to SFML WindowImpl class.
+ ///
+ ////////////////////////////////////////////////////////////
+ void mouseMovedIn(void);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Mouse Out Event – called by the cocoa view object.
+ ///
+ /// Send the event to SFML WindowImpl class.
+ ///
+ ////////////////////////////////////////////////////////////
+ void mouseMovedOut(void);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Key Down Event – called by the cocoa view object.
+ ///
+ /// Send the event to SFML WindowImpl class.
+ ///
+ /// \param key
+ ///
+ ////////////////////////////////////////////////////////////
+ void keyDown(Event::KeyEvent key);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Key Up Event – called by the cocoa view object.
+ ///
+ /// Send the event to SFML WindowImpl class.
+ ///
+ /// \param key
+ ///
+ ////////////////////////////////////////////////////////////
+ void keyUp(Event::KeyEvent key);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Text Entred Event – called by the cocoa view object.
+ ///
+ /// Send the event to SFML WindowImpl class.
+ ///
+ /// \param charcode Input unicode
+ ///
+ ////////////////////////////////////////////////////////////
+ void textEntered(unichar charcode);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Apply the context to the view.
+ ///
+ /// Called by the SFML context object to finalize its creation.
+ ///
+ /// \param context The context to bind to the window
+ ///
+ ////////////////////////////////////////////////////////////
+ void applyContext(NSOpenGLContextRef context) const;
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Change the type of the current process to become a full GUI app.
+ /// Also ensure NSApp is constructed.
+ ///
+ ////////////////////////////////////////////////////////////
+ static void setUpProcess(void);
+
+public :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Get the OS-specific handle of the window
+ ///
+ /// \return Handle of the window
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual WindowHandle getSystemHandle() const;
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Get the position of the window
+ ///
+ /// \return Position of the window, in pixels
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual Vector2i getPosition() const;
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Change the position of the window on screen
+ ///
+ /// \param position New position of the window, in pixels
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual void setPosition(const Vector2i& position);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Get the client size of the window
+ ///
+ /// \return Size of the window, in pixels
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual Vector2u getSize() const;
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Change the size of the rendering region of the window
+ ///
+ /// \param size New size, in pixels
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual void setSize(const Vector2u& size);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Change the title of the window
+ ///
+ /// \param title New title
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual void setTitle(const String& title);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Change the window's icon
+ ///
+ /// \param width Icon's width, in pixels
+ /// \param height Icon's height, in pixels
+ /// \param pixels Pointer to the pixels in memory, format must be RGBA 32 bits
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual void setIcon(unsigned int width, unsigned int height, const Uint8* pixels);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Show or hide the window
+ ///
+ /// \param visible True to show, false to hide
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual void setVisible(bool visible);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Show or hide the mouse cursor
+ ///
+ /// \param visible True to show, false to hide
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual void setMouseCursorVisible(bool visible);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Enable or disable automatic key-repeat
+ ///
+ /// \param enabled True to enable, false to disable
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual void setKeyRepeatEnabled(bool enabled);
+
+protected :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Process incoming events from the operating system
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual void processEvents();
+
+private :
+
+ ////////////////////////////////////////////////////////////
+ // Member data
+ ////////////////////////////////////////////////////////////
+ WindowImplDelegateRef m_delegate; ///< Implementation in Obj-C.
+ bool m_showCursor; ///< Is the cursor displayed or hidden ?
+};
+
+} // namespace priv
+
+} // namespace sf
+
+
+#endif // SFML_WINDOWIMPLCOCOA_HPP
diff --git a/src/SFML/Window/OSX/WindowImplCocoa.mm b/src/SFML/Window/OSX/WindowImplCocoa.mm
new file mode 100644
index 0000000..a3bea49
--- /dev/null
+++ b/src/SFML/Window/OSX/WindowImplCocoa.mm
@@ -0,0 +1,418 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2012 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/OSX/WindowImplCocoa.hpp>
+#include <SFML/System/Err.hpp>
+#include <SFML/System/String.hpp>
+
+#import <SFML/Window/OSX/SFWindowController.h>
+#import <SFML/Window/OSX/SFViewController.h>
+#import <SFML/Window/OSX/cpp_objc_conversion.h>
+#import <SFML/Window/OSX/AutoreleasePoolWrapper.h>
+#import <SFML/Window/OSX/SFApplication.h>
+
+namespace sf
+{
+namespace priv
+{
+
+#pragma mark
+#pragma mark WindowImplCocoa's ctor/dtor
+
+////////////////////////////////////////////////////////////
+WindowImplCocoa::WindowImplCocoa(WindowHandle handle)
+: m_showCursor(true)
+{
+ // Ask for a pool.
+ retainPool();
+
+ // Treat the handle as it real type
+ id nsHandle = (id)handle;
+ if ([nsHandle isKindOfClass:[NSWindow class]]) {
+
+ // We have a window.
+ m_delegate = [[SFWindowController alloc] initWithWindow:nsHandle];
+
+ } else if ([nsHandle isKindOfClass:[NSView class]]) {
+
+ // We have a view.
+ m_delegate = [[SFViewController alloc] initWithView:nsHandle];
+
+ } else {
+
+ sf::err()
+ << "Cannot import this Window Handle because it is neither "
+ << "a <NSWindow*> nor <NSView*> object "
+ << "(or any of their subclasses). You gave a <"
+ << [[nsHandle className] UTF8String]
+ << "> object."
+ << std::endl;
+ return;
+
+ }
+
+ [m_delegate setRequesterTo:this];
+}
+
+
+////////////////////////////////////////////////////////////
+WindowImplCocoa::WindowImplCocoa(VideoMode mode,
+ const String& title,
+ unsigned long style,
+ const ContextSettings& /*settings*/)
+: m_showCursor(true)
+{
+ // Transform the app process.
+ setUpProcess();
+
+ // Ask for a pool.
+ retainPool();
+
+ m_delegate = [[SFWindowController alloc] initWithMode:mode andStyle:style];
+ [m_delegate changeTitle:sfStringToNSString(title)];
+ [m_delegate setRequesterTo:this];
+}
+
+
+////////////////////////////////////////////////////////////
+WindowImplCocoa::~WindowImplCocoa()
+{
+ [m_delegate closeWindow];
+
+ [m_delegate release];
+
+ releasePool();
+
+ drainPool(); // Make sure everything was freed
+ // This solve some issue when sf::Window::Create is called for the
+ // second time (nothing was render until the function was called again)
+}
+
+
+////////////////////////////////////////////////////////////
+void WindowImplCocoa::applyContext(NSOpenGLContextRef context) const
+{
+ [m_delegate applyContext:context];
+}
+
+
+////////////////////////////////////////////////////////////
+void WindowImplCocoa::setUpProcess(void)
+{
+ static bool isTheProcessSetAsApplication = false;
+
+ if (!isTheProcessSetAsApplication) {
+ // Do it only once !
+ isTheProcessSetAsApplication = true;
+
+ // Set the process as a normal application so it can get focus.
+ ProcessSerialNumber psn;
+ if (!GetCurrentProcess(&psn)) {
+ TransformProcessType(&psn, kProcessTransformToForegroundApplication);
+ SetFrontProcess(&psn);
+ }
+
+ // Tell the application to stop bouncing in the Dock.
+ [[SFApplication sharedApplication] finishLaunching];
+ // NOTE : This last call won't harm anything even if SFML window was
+ // created with an external handle.
+ }
+}
+
+
+#pragma mark
+#pragma mark WindowImplCocoa's window-event methods
+
+
+////////////////////////////////////////////////////////////
+void WindowImplCocoa::windowClosed(void)
+{
+ Event event;
+ event.type = Event::Closed;
+
+ pushEvent(event);
+}
+
+
+////////////////////////////////////////////////////////////
+void WindowImplCocoa::windowResized(unsigned int width, unsigned int height)
+{
+ Event event;
+ event.type = Event::Resized;
+ event.size.width = width;
+ event.size.height = height;
+
+ pushEvent(event);
+}
+
+
+////////////////////////////////////////////////////////////
+void WindowImplCocoa::windowLostFocus(void)
+{
+ if (!m_showCursor) {
+ [m_delegate showMouseCursor]; // Make sur the cursor is visible
+ }
+
+ Event event;
+ event.type = Event::LostFocus;
+
+ pushEvent(event);
+}
+
+
+////////////////////////////////////////////////////////////
+void WindowImplCocoa::windowGainedFocus(void)
+{
+ if (!m_showCursor) {
+ [m_delegate hideMouseCursor]; // Restore user's setting
+ }
+
+ Event event;
+ event.type = Event::GainedFocus;
+
+ pushEvent(event);
+}
+
+#pragma mark
+#pragma mark WindowImplCocoa's mouse-event methods
+
+
+////////////////////////////////////////////////////////////
+void WindowImplCocoa::mouseDownAt(Mouse::Button button, int x, int y)
+{
+ Event event;
+ event.type = Event::MouseButtonPressed;
+ event.mouseButton.button = button;
+ event.mouseButton.x = x;
+ event.mouseButton.y = y;
+
+ pushEvent(event);
+}
+
+
+////////////////////////////////////////////////////////////
+void WindowImplCocoa::mouseUpAt(Mouse::Button button, int x, int y)
+{
+ Event event;
+ event.type = Event::MouseButtonReleased;
+ event.mouseButton.button = button;
+ event.mouseButton.x = x;
+ event.mouseButton.y = y;
+
+ pushEvent(event);
+}
+
+
+////////////////////////////////////////////////////////////
+void WindowImplCocoa::mouseMovedAt(int x, int y)
+{
+ Event event;
+ event.type = Event::MouseMoved;
+ event.mouseMove.x = x;
+ event.mouseMove.y = y;
+
+ pushEvent(event);
+}
+
+////////////////////////////////////////////////////////////
+void WindowImplCocoa::mouseWheelScrolledAt(float delta, int x, int y)
+{
+ Event event;
+ event.type = Event::MouseWheelMoved;
+ event.mouseWheel.delta = delta;
+ event.mouseWheel.x = x;
+ event.mouseWheel.y = y;
+
+ pushEvent(event);
+}
+
+////////////////////////////////////////////////////////////
+void WindowImplCocoa::mouseMovedIn(void)
+{
+ if (!m_showCursor) {
+ [m_delegate hideMouseCursor]; // Restore user's setting
+ }
+
+ Event event;
+ event.type = Event::MouseEntered;
+
+ pushEvent(event);
+}
+
+////////////////////////////////////////////////////////////
+void WindowImplCocoa::mouseMovedOut(void)
+{
+ if (!m_showCursor) {
+ [m_delegate showMouseCursor]; // Make sur the cursor is visible
+ }
+
+ Event event;
+ event.type = Event::MouseLeft;
+
+ pushEvent(event);
+}
+
+
+#pragma mark
+#pragma mark WindowImplCocoa's key-event methods
+
+
+////////////////////////////////////////////////////////////
+void WindowImplCocoa::keyDown(Event::KeyEvent key)
+{
+ Event event;
+ event.type = Event::KeyPressed;
+ event.key = key;
+
+ pushEvent(event);
+}
+
+
+////////////////////////////////////////////////////////////
+void WindowImplCocoa::keyUp(Event::KeyEvent key)
+{
+ Event event;
+ event.type = Event::KeyReleased;
+ event.key = key;
+
+ pushEvent(event);
+}
+
+
+////////////////////////////////////////////////////////////
+void WindowImplCocoa::textEntered(unichar charcode)
+{
+ Event event;
+ event.type = Event::TextEntered;
+ event.text.unicode = charcode;
+
+ pushEvent(event);
+}
+
+
+#pragma mark
+#pragma mark WindowImplCocoa's event-related methods
+
+////////////////////////////////////////////////////////////
+void WindowImplCocoa::processEvents()
+{
+ [m_delegate processEvent];
+}
+
+#pragma mark
+#pragma mark WindowImplCocoa's private methods
+
+////////////////////////////////////////////////////////////
+WindowHandle WindowImplCocoa::getSystemHandle() const
+{
+ return [m_delegate getSystemHandle];
+}
+
+
+////////////////////////////////////////////////////////////
+Vector2i WindowImplCocoa::getPosition() const
+{
+ NSPoint pos = [m_delegate position];
+ return Vector2i(pos.x, pos.y);
+}
+
+
+////////////////////////////////////////////////////////////
+void WindowImplCocoa::setPosition(const Vector2i& position)
+{
+ [m_delegate setWindowPositionToX:position.x Y:position.y];
+}
+
+
+////////////////////////////////////////////////////////////
+Vector2u WindowImplCocoa::getSize() const
+{
+ NSSize size = [m_delegate size];
+ return Vector2u(size.width, size.height);
+}
+
+
+////////////////////////////////////////////////////////////
+void WindowImplCocoa::setSize(const Vector2u& size)
+{
+ [m_delegate resizeTo:size.x by:size.y];
+}
+
+
+////////////////////////////////////////////////////////////
+void WindowImplCocoa::setTitle(const String& title)
+{
+ [m_delegate changeTitle:sfStringToNSString(title)];
+}
+
+
+////////////////////////////////////////////////////////////
+void WindowImplCocoa::setIcon(unsigned int width, unsigned int height, const Uint8* pixels)
+{
+ [m_delegate setIconTo:width by:height with:pixels];
+}
+
+
+////////////////////////////////////////////////////////////
+void WindowImplCocoa::setVisible(bool visible)
+{
+ if (visible) {
+ [m_delegate showWindow];
+ } else {
+ [m_delegate hideWindow];
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void WindowImplCocoa::setMouseCursorVisible(bool visible)
+{
+ m_showCursor = visible;
+
+ if (m_showCursor) {
+ [m_delegate showMouseCursor];
+ } else {
+ [m_delegate hideMouseCursor];
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void WindowImplCocoa::setKeyRepeatEnabled(bool enabled)
+{
+ if (enabled) {
+ [m_delegate enableKeyRepeat];
+ } else {
+ [m_delegate disableKeyRepeat];
+ }
+}
+
+
+} // namespace priv
+
+} // namespace sf
diff --git a/src/SFML/Window/OSX/WindowImplDelegateProtocol.h b/src/SFML/Window/OSX/WindowImplDelegateProtocol.h
new file mode 100644
index 0000000..7e4bbbf
--- /dev/null
+++ b/src/SFML/Window/OSX/WindowImplDelegateProtocol.h
@@ -0,0 +1,159 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2012 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/WindowHandle.hpp>
+#include <SFML/Config.hpp> // for sf::Uint8
+
+#import <AppKit/AppKit.h>
+
+namespace sf {
+ namespace priv {
+ class WindowImplCocoa;
+ }
+}
+
+////////////////////////////////////////////////////////////
+/// This protocol defines the interface of the delegate of
+/// the window implementation.
+///
+/// We don't create an interface here because Obj-C doesn't allow
+/// multiple inheritance (SFViewController and SFWindowController
+/// don't have the same parent classes). Unfortunately this means
+/// we have to duplicate some code.
+///
+/// Everything is done via a class that implement this protocol.
+/// There are two of these classes :
+///
+/// SFViewController and SFWindowController
+///
+/// The requester is a WindowImplCocoa. It's used to send back
+/// event via these functions :
+///
+/// windowClosed, windowResized, windowLostFocus, windowGainedFocus
+///
+/// mouseDownAt, mouseUpAt, mouseMovedAt, mouseWheelScrolledAt,
+/// mouseMovedIn, mouseMovedOut
+///
+/// keyDown, keyUp, textEntered
+///
+/// Note : Joysticks are not bound to a view or window
+/// thus they're not managed by a class implementing this protocol.
+///
+////////////////////////////////////////////////////////////
+@protocol WindowImplDelegateProtocol
+
+////////////////////////////////////////////////////////////
+/// Set the WindowImpl who requested this delegate
+/// (This would be a ctor in C++ or Java where we can prohibit the
+/// construction of an object.)
+///
+////////////////////////////////////////////////////////////
+-(void)setRequesterTo:(sf::priv::WindowImplCocoa *)requester;
+
+////////////////////////////////////////////////////////////
+/// Return the main view or window.
+///
+////////////////////////////////////////////////////////////
+-(sf::WindowHandle)getSystemHandle;
+
+////////////////////////////////////////////////////////////
+/// Hide or show the mouse cursor.
+///
+////////////////////////////////////////////////////////////
+-(void)hideMouseCursor;
+-(void)showMouseCursor;
+
+////////////////////////////////////////////////////////////
+/// Get window's position.
+///
+////////////////////////////////////////////////////////////
+-(NSPoint)position;
+
+////////////////////////////////////////////////////////////
+/// Move the window (not the view if we handle not a window) (SFML Coordinates).
+///
+////////////////////////////////////////////////////////////
+-(void)setWindowPositionToX:(int)x Y:(int)y;
+
+////////////////////////////////////////////////////////////
+/// Get window's size.
+///
+////////////////////////////////////////////////////////////
+-(NSSize)size;
+
+////////////////////////////////////////////////////////////
+/// Resize the window/view.
+///
+////////////////////////////////////////////////////////////
+-(void)resizeTo:(unsigned int)width by:(unsigned int)height;
+
+////////////////////////////////////////////////////////////
+/// Set the title (does nothing if we manage a view).
+///
+////////////////////////////////////////////////////////////
+-(void)changeTitle:(NSString *)title;
+
+////////////////////////////////////////////////////////////
+/// Hide or show the window (does nothing if we manage a view).
+///
+////////////////////////////////////////////////////////////
+-(void)hideWindow;
+-(void)showWindow;
+
+////////////////////////////////////////////////////////////
+/// Close the window (does nothing if we manage a view).
+///
+////////////////////////////////////////////////////////////
+-(void)closeWindow;
+
+////////////////////////////////////////////////////////////
+/// Enable or disable key repeat.
+///
+////////////////////////////////////////////////////////////
+-(void)enableKeyRepeat;
+-(void)disableKeyRepeat;
+
+////////////////////////////////////////////////////////////
+/// Set an icon to the application.
+///
+////////////////////////////////////////////////////////////
+-(void)setIconTo:(unsigned int)width by:(unsigned int)height with:(sf::Uint8 const*)pixels;
+
+////////////////////////////////////////////////////////////
+/// Fetch new event
+///
+////////////////////////////////////////////////////////////
+-(void)processEvent;
+
+////////////////////////////////////////////////////////////
+/// Apply a given context to an OpenGL view.
+///
+////////////////////////////////////////////////////////////
+-(void)applyContext:(NSOpenGLContext *)context;
+
+@end
diff --git a/src/SFML/Window/OSX/cg_sf_conversion.cpp b/src/SFML/Window/OSX/cg_sf_conversion.cpp
new file mode 100644
index 0000000..3481cce
--- /dev/null
+++ b/src/SFML/Window/OSX/cg_sf_conversion.cpp
@@ -0,0 +1,181 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/OSX/cg_sf_conversion.hpp>
+#include <SFML/System/Err.hpp>
+
+namespace sf
+{
+namespace priv
+{
+
+////////////////////////////////////////////////////////////
+#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
+size_t modeBitsPerPixel(CGDisplayModeRef mode)
+{
+ size_t bpp = 0; // no match
+
+ // Compare encoding.
+ CFStringRef pixEnc = CGDisplayModeCopyPixelEncoding(mode);
+ if(CFStringCompare(pixEnc, CFSTR(IO32BitDirectPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo) {
+
+ bpp = 32;
+
+ } else if(CFStringCompare(pixEnc, CFSTR(IO16BitDirectPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo) {
+
+ bpp = 16;
+
+ } else if(CFStringCompare(pixEnc, CFSTR(IO8BitIndexedPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo) {
+
+ bpp = 8;
+
+ }
+
+ // Clean up memory.
+ CFRelease(pixEnc);
+
+ return bpp;
+}
+#endif
+
+
+
+////////////////////////////////////////////////////////////
+size_t displayBitsPerPixel(CGDirectDisplayID displayId)
+{
+#if MAC_OS_X_VERSION_MAX_ALLOWED < 1060
+
+ return CGDisplayBitsPerPixel(displayId);
+
+#else // MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
+
+ // Get the display mode.
+ CGDisplayModeRef mode = CGDisplayCopyDisplayMode(displayId);
+
+ // Get bpp for the mode.
+ size_t const bpp = modeBitsPerPixel(mode);
+
+ // Clean up Memory.
+ CGDisplayModeRelease(mode);
+
+ return bpp;
+
+#endif
+}
+
+
+////////////////////////////////////////////////////////////
+#if MAC_OS_X_VERSION_MAX_ALLOWED < 1060
+
+VideoMode convertCGModeToSFMode(CFDictionaryRef dictionary)
+{
+ VideoMode sfmode;
+
+ CFNumberRef cfnumber = (CFNumberRef)CFDictionaryGetValue(dictionary, kCGDisplayWidth);
+ CFNumberGetValue(cfnumber, kCFNumberIntType, &(sfmode.width));
+
+ cfnumber = (CFNumberRef)CFDictionaryGetValue(dictionary, kCGDisplayHeight);
+ CFNumberGetValue(cfnumber, kCFNumberIntType, &(sfmode.height));
+
+ cfnumber = (CFNumberRef)CFDictionaryGetValue(dictionary, kCGDisplayBitsPerPixel);
+ CFNumberGetValue(cfnumber, kCFNumberIntType, &(sfmode.bitsPerPixel));
+
+ return sfmode;
+}
+
+#else // MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
+
+VideoMode convertCGModeToSFMode(CGDisplayModeRef cgmode)
+{
+ return VideoMode(CGDisplayModeGetWidth(cgmode),
+ CGDisplayModeGetHeight(cgmode),
+ modeBitsPerPixel(cgmode));
+}
+
+#endif
+
+////////////////////////////////////////////////////////////
+#if MAC_OS_X_VERSION_MAX_ALLOWED < 1060
+
+CFDictionaryRef convertSFModeToCGMode(VideoMode sfmode)
+{
+ // If sfmode is in VideoMode::GetFullscreenModes
+ // then this should be an exact match (see NULL parameter doc).
+ return CGDisplayBestModeForParameters(CGMainDisplayID(),
+ sfmode.bitsPerPixel,
+ sfmode.width,
+ sfmode.height,
+ NULL);
+}
+
+#else // MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
+
+CGDisplayModeRef convertSFModeToCGMode(VideoMode sfmode)
+{
+ // Starting with 10.6 we should query the display all the modes and
+ // search for the best one.
+
+ // Will return NULL if sfmode is not in VideoMode::GetFullscreenModes.
+ CGDisplayModeRef cgbestMode = NULL;
+
+ // Retrieve all modes available for main screen only.
+ CFArrayRef cgmodes = CGDisplayCopyAllDisplayModes(CGMainDisplayID(), NULL);
+
+ if (cgmodes == NULL) { // Should not happen but anyway...
+ sf::err() << "Couldn't get VideoMode for main display.";
+ return NULL;
+ }
+
+ // Loop on each mode and convert it into a sf::VideoMode object.
+ CFIndex const modesCount = CFArrayGetCount(cgmodes);
+ for (CFIndex i = 0; i < modesCount; i++) {
+ CGDisplayModeRef cgmode = (CGDisplayModeRef)CFArrayGetValueAtIndex(cgmodes, i);
+
+ VideoMode mode = convertCGModeToSFMode(cgmode);
+
+ if (mode == sfmode) {
+ cgbestMode = cgmode;
+ }
+ }
+
+ // Clean up memory.
+ CFRelease(cgmodes);
+
+ if (cgbestMode == NULL) {
+ sf::err()
+ << "Couldn't convert the given sf:VideoMode into a CGDisplayMode."
+ << std::endl;
+ }
+
+ return cgbestMode;
+}
+
+#endif
+
+} // namespace priv
+} // namespace sf
diff --git a/src/SFML/Window/OSX/cg_sf_conversion.hpp b/src/SFML/Window/OSX/cg_sf_conversion.hpp
new file mode 100644
index 0000000..150e7b5
--- /dev/null
+++ b/src/SFML/Window/OSX/cg_sf_conversion.hpp
@@ -0,0 +1,82 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_CG_SF_CONVERSION_HPP
+#define SFML_CG_SF_CONVERSION_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/VideoMode.hpp>
+#include <ApplicationServices/ApplicationServices.h>
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief Get bpp of a video mode for OS 10.6 or later.
+///
+/// With OS 10.6 and later, Quartz doesn't use anymore dictionaries
+/// to represent video mode. Instead it uses a CGDisplayMode opaque type.
+///
+////////////////////////////////////////////////////////////
+#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
+size_t modeBitsPerPixel(CGDisplayModeRef mode);
+#endif
+
+////////////////////////////////////////////////////////////
+/// \brief Get bpp for all OS X version.
+///
+/// This function use only non-deprecated way to get the
+/// display bits per pixel information for a given display id.
+///
+////////////////////////////////////////////////////////////
+size_t displayBitsPerPixel(CGDirectDisplayID displayId);
+
+////////////////////////////////////////////////////////////
+/// \brief Convert a Quartz video mode into a sf::VideoMode object.
+///
+////////////////////////////////////////////////////////////
+#if MAC_OS_X_VERSION_MAX_ALLOWED < 1060
+VideoMode convertCGModeToSFMode(CFDictionaryRef dictionary);
+#else // MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
+VideoMode convertCGModeToSFMode(CGDisplayModeRef cgmode);
+#endif
+
+////////////////////////////////////////////////////////////
+/// \brief Convert a sf::VideoMode object into a Quartz video mode.
+///
+////////////////////////////////////////////////////////////
+#if MAC_OS_X_VERSION_MAX_ALLOWED < 1060
+CFDictionaryRef convertSFModeToCGMode(VideoMode sfmode);
+#else // MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
+CGDisplayModeRef convertSFModeToCGMode(VideoMode sfmode);
+#endif
+
+} // namespace priv
+} // namespace sf
+
+#endif
diff --git a/src/SFML/Window/OSX/cpp_objc_conversion.h b/src/SFML/Window/OSX/cpp_objc_conversion.h
new file mode 100644
index 0000000..75095b3
--- /dev/null
+++ b/src/SFML/Window/OSX/cpp_objc_conversion.h
@@ -0,0 +1,39 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2012 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <string>
+#include <SFML/System/String.hpp>
+
+#import <Foundation/Foundation.h>
+
+////////////////////////////////////////////////////////////
+/// \brief Returns a NSString construct with +stringWithCString:encoding:.
+///
+////////////////////////////////////////////////////////////
+NSString* stringToNSString(std::string const& string);
+NSString* sfStringToNSString(sf::String const& string);
diff --git a/src/SFML/Window/OSX/cpp_objc_conversion.mm b/src/SFML/Window/OSX/cpp_objc_conversion.mm
new file mode 100644
index 0000000..4b619a5
--- /dev/null
+++ b/src/SFML/Window/OSX/cpp_objc_conversion.mm
@@ -0,0 +1,58 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2012 Marco Antognini (antognini.marco@gmail.com),
+// Laurent Gomila (laurent.gom@gmail.com),
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/System/Utf.hpp>
+
+#import <Foundation/Foundation.h>
+#import <SFML/Window/OSX/cpp_objc_conversion.h>
+
+////////////////////////////////////////////////////////////
+NSString* stringToNSString(std::string const& string)
+{
+ std::string utf8; utf8.reserve(string.size() + 1);
+ sf::Utf8::fromAnsi(string.begin(), string.end(), std::back_inserter(utf8));
+ NSString* str = [NSString stringWithCString:utf8.c_str() encoding:NSUTF8StringEncoding];
+
+ return str;
+}
+
+////////////////////////////////////////////////////////////
+NSString* sfStringToNSString(sf::String const& string)
+{
+ sf::Uint32 length = string.getSize() * sizeof(sf::Uint32);
+ const void* data = reinterpret_cast<const void*>(string.getData());
+
+ NSStringEncoding encoding;
+ if (NSHostByteOrder() == NS_LittleEndian)
+ encoding = NSUTF32LittleEndianStringEncoding;
+ else
+ encoding = NSUTF32BigEndianStringEncoding;
+
+ NSString* str = [[NSString alloc] initWithBytes:data length:length encoding:encoding];
+ return str;
+}
diff --git a/src/SFML/Window/Template for new ports/VideoModeSupport.hpp b/src/SFML/Window/Template for new ports/VideoModeSupport.hpp
deleted file mode 100755
index 9d46f78..0000000
--- a/src/SFML/Window/Template for new ports/VideoModeSupport.hpp
+++ /dev/null
@@ -1,69 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-#ifndef SFML_VIDEOMODESUPPORTXXX_HPP
-#define SFML_VIDEOMODESUPPORTXXX_HPP
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Window/VideoMode.hpp>
-#include <vector>
-
-
-namespace sf
-{
-namespace priv
-{
-////////////////////////////////////////////////////////////
-/// XXX implementation of VideoModeSupport
-/// Give access to video mode related OS-specific functions
-////////////////////////////////////////////////////////////
-class VideoModeSupport
-{
-public :
-
- ////////////////////////////////////////////////////////////
- /// Get supported video modes
- ///
- /// \param Modes : Array to fill with available video modes
- ///
- ////////////////////////////////////////////////////////////
- static void GetSupportedVideoModes(std::vector<VideoMode>& Modes);
-
- ////////////////////////////////////////////////////////////
- /// Get current desktop video mode
- ///
- /// \return Current desktop video mode
- ///
- ////////////////////////////////////////////////////////////
- static VideoMode GetDesktopVideoMode();
-};
-
-} // namespace priv
-
-} // namespace sf
-
-
-#endif // SFML_VIDEOMODESUPPORTXXX_HPP
diff --git a/src/SFML/Window/Template for new ports/WindowImplXXX.cpp b/src/SFML/Window/Template for new ports/WindowImplXXX.cpp
deleted file mode 100755
index 46f5d2d..0000000
--- a/src/SFML/Window/Template for new ports/WindowImplXXX.cpp
+++ /dev/null
@@ -1,231 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Window/XXX/WindowImplXXX.hpp>
-#include <SFML/Window/WindowStyle.hpp>
-#include <GL/gl.h>
-
-
-namespace sf
-{
-namespace priv
-{
-////////////////////////////////////////////////////////////
-/// Default constructor
-/// (creates a dummy window to provide a valid OpenGL context)
-////////////////////////////////////////////////////////////
-WindowImplXXX::WindowImplXXX()
-{
- // Create a dummy window (with the fewest attributes -- it's just to have a valid support for an OpenGL context)
-
- // Initialize myWidth and myHeight members from base class with the window size
-
- // Create an OpenGL context in this window and DO NOT make it active
-}
-
-
-////////////////////////////////////////////////////////////
-/// Create the window implementation from an existing control
-////////////////////////////////////////////////////////////
-WindowImplXXX::WindowImplXXX(WindowHandle Handle, WindowSettings& Params)
-{
- // Make sure we'll be able to catch all the events of the given window
-
- // Initialize myWidth and myHeight members from base class with the window size
-
- // Create an OpenGL context in this window and make it active
-}
-
-
-////////////////////////////////////////////////////////////
-/// Create the window implementation
-////////////////////////////////////////////////////////////
-WindowImplXXX::WindowImplXXX(VideoMode Mode, const std::string& Title, unsigned long WindowStyle, WindowSettings& Params) :
-{
- // Create a new window with given size, title and style
-
- // Initialize myWidth and myHeight members from base class with the window size
-
- // Create an OpenGL context in this window and make it active
-}
-
-
-////////////////////////////////////////////////////////////
-/// Destructor
-////////////////////////////////////////////////////////////
-WindowImplXXX::~WindowImplXXX()
-{
- // Destroy the OpenGL context, the window and every resource allocated by this class
-}
-
-
-////////////////////////////////////////////////////////////
-/// Check if there's an active context on the current thread
-////////////////////////////////////////////////////////////
-bool WindowImplXXX::IsContextActive()
-{
- // Should return whether xxxGetCurrentContext() is NULL or not;
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see WindowImpl::Display
-////////////////////////////////////////////////////////////
-void WindowImplXXX::Display()
-{
- // Swap OpenGL buffers (should be a call to xxxSwapBuffers)
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see WindowImpl::ProcessEvents
-////////////////////////////////////////////////////////////
-void WindowImplXXX::ProcessEvents()
-{
- // Process every event for this window
-
- // Generate a sf::Event and call SendEvent(Evt) for each event
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see WindowImpl::SetActive
-////////////////////////////////////////////////////////////
-void WindowImplXXX::SetActive(bool Active) const
-{
- // Bind / unbind OpenGL context (should be a call to xxxMakeCurrent)
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see WindowImpl::UseVerticalSync
-////////////////////////////////////////////////////////////
-void WindowImplXXX::UseVerticalSync(bool Enabled)
-{
- // Activate / deactivate vertical synchronization
- // usually using an OpenGL extension (should be a call to xxxSwapInterval)
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see WindowImpl::ShowMouseCursor
-////////////////////////////////////////////////////////////
-void WindowImplXXX::ShowMouseCursor(bool Show)
-{
- // Show or hide the system cursor in this window
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see WindowImpl::SetCursorPosition
-////////////////////////////////////////////////////////////
-void WindowImplXXX::SetCursorPosition(unsigned int Left, unsigned int Top)
-{
- // Change the cursor position (Left and Top are relative to this window)
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see WindowImpl::SetPosition
-////////////////////////////////////////////////////////////
-void WindowImplXXX::SetPosition(int Left, int Top)
-{
- // Change the window position
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see WindowImpl::SetSize
-////////////////////////////////////////////////////////////
-void WindowImplWin32::SetSize(unsigned int Width, unsigned int Height)
-{
- // Change the window size
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see WindowImpl::Show
-////////////////////////////////////////////////////////////
-void WindowImplXXX::Show(bool State)
-{
- // Show or hide the window
-}
-
-////////////////////////////////////////////////////////////
-/// /see WindowImpl::EnableKeyRepeat
-////////////////////////////////////////////////////////////
-void WindowImplXXX::EnableKeyRepeat(bool Enabled)
-{
- // Enable or disable automatic key-repeat for keydown events
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see WindowImpl::SetIcon
-////////////////////////////////////////////////////////////
-void WindowImplXXX::SetIcon(unsigned int Width, unsigned int Height, const Uint8* Pixels)
-{
- // Change all the necessary icons of the window (titlebar, task bar, ...) with the
- // provided array of 32 bits RGBA pixels
-}
-
-
-/*===========================================================
- STRATEGY FOR OPENGL CONTEXT CREATION
-
-- If the requested level of anti-aliasing is not supported and is greater than 2, try with 2
- --> if level 2 fails, disable anti-aliasing
- --> it's important not to generate an error if anti-aliasing is not supported
-
-- Use a matching pixel mode, or the best of all available pixel modes if no perfect match ;
- You should use the function EvaluateConfig to get a score for a given configuration
-
-- Don't forget to fill Params (see constructors) back with the actual parameters we got from the chosen pixel format
-
-- IMPORTANT : all OpenGL contexts must be shared (usually a call to xxxShareLists)
-
-===========================================================*/
-
-
-/*===========================================================
- STRATEGY FOR EVENT HANDLING
-
-- Process any event matching with the ones in sf::Event::EventType
- --> Create a sf::Event, fill the members corresponding to the event type
- --> No need to handle joystick events, they are handled by WindowImpl::ProcessJoystickEvents
- --> Event::TextEntered must provide UTF-16 characters
- (see http://www.unicode.org/Public/PROGRAMS/CVTUTF/ for unicode conversions)
- --> Don't forget to process any destroy-like event (ie. when the window is destroyed externally)
-
-- Use SendEvent function from base class to propagate the created events
-
-===========================================================*/
-
-
-} // namespace priv
-
-} // namespace sf
diff --git a/src/SFML/Window/Template for new ports/WindowImplXXX.hpp b/src/SFML/Window/Template for new ports/WindowImplXXX.hpp
deleted file mode 100755
index e5dee89..0000000
--- a/src/SFML/Window/Template for new ports/WindowImplXXX.hpp
+++ /dev/null
@@ -1,167 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-#ifndef SFML_WINDOWIMPLXXX_HPP
-#define SFML_WINDOWIMPLXXX_HPP
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Window/Event.hpp>
-#include <SFML/Window/WindowImpl.hpp>
-#include <string>
-
-
-namespace sf
-{
-namespace priv
-{
-////////////////////////////////////////////////////////////
-/// WindowImplXXX is the XXX implementation of WindowImpl
-////////////////////////////////////////////////////////////
-class WindowImplXXX : public WindowImpl
-{
-public :
-
- ////////////////////////////////////////////////////////////
- /// Default constructor
- /// (creates a dummy window to provide a valid OpenGL context)
- ///
- ////////////////////////////////////////////////////////////
- WindowImplXXX();
-
- ////////////////////////////////////////////////////////////
- /// Construct the window implementation from an existing control
- ///
- /// \param Handle : Platform-specific handle of the control
- /// \param Params : Creation parameters
- ///
- ////////////////////////////////////////////////////////////
- WindowImplXXX(WindowHandle Handle, WindowSettings& Params);
-
- ////////////////////////////////////////////////////////////
- /// Create the window implementation
- ///
- /// \param Mode : Video mode to use
- /// \param Title : Title of the window
- /// \param WindowStyle : Window style
- /// \param Params : Creation parameters
- ///
- ////////////////////////////////////////////////////////////
- WindowImplXXX(VideoMode Mode, const std::string& Title, unsigned long WindowStyle, WindowSettings& Params);
-
- ////////////////////////////////////////////////////////////
- /// Destructor
- ///
- ////////////////////////////////////////////////////////////
- ~WindowImplXXX();
-
- ////////////////////////////////////////////////////////////
- /// Check if there's an active context on the current thread
- ///
- /// \return True if there's a context bound to the current thread
- ///
- ////////////////////////////////////////////////////////////
- static bool IsContextActive();
-
-private :
-
- ////////////////////////////////////////////////////////////
- /// /see WindowImpl::Display
- ///
- ////////////////////////////////////////////////////////////
- virtual void Display();
-
- ////////////////////////////////////////////////////////////
- /// /see WindowImpl::ProcessEvents
- ///
- ////////////////////////////////////////////////////////////
- virtual void ProcessEvents();
-
- ////////////////////////////////////////////////////////////
- /// /see WindowImpl::SetActive
- ///
- ////////////////////////////////////////////////////////////
- virtual void SetActive(bool Active = true) const;
-
- ////////////////////////////////////////////////////////////
- /// /see WindowImpl::IsActive
- ///
- ////////////////////////////////////////////////////////////
- virtual bool IsActive() const;
-
- ////////////////////////////////////////////////////////////
- /// /see WindowImpl::UseVerticalSync
- ///
- ////////////////////////////////////////////////////////////
- virtual void UseVerticalSync(bool Enabled);
-
- ////////////////////////////////////////////////////////////
- /// /see WindowImpl::ShowMouseCursor
- ///
- ////////////////////////////////////////////////////////////
- virtual void ShowMouseCursor(bool Show);
-
- ////////////////////////////////////////////////////////////
- /// /see WindowImpl::SetCursorPosition
- ///
- ////////////////////////////////////////////////////////////
- virtual void SetCursorPosition(unsigned int Left, unsigned int Top);
-
- ////////////////////////////////////////////////////////////
- /// /see WindowImpl::SetPosition
- ///
- ////////////////////////////////////////////////////////////
- virtual void SetPosition(int Left, int Top);
-
- ////////////////////////////////////////////////////////////
- /// /see WindowImpl::SetSize
- ///
- ////////////////////////////////////////////////////////////
- virtual void SetSize(unsigned int Width, unsigned int Height);
-
- ////////////////////////////////////////////////////////////
- /// /see WindowImpl::Show
- ///
- ////////////////////////////////////////////////////////////
- virtual void Show(bool State);
-
- ////////////////////////////////////////////////////////////
- /// /see WindowImpl::EnableKeyRepeat
- ///
- ////////////////////////////////////////////////////////////
- virtual void EnableKeyRepeat(bool Enabled);
-
- ////////////////////////////////////////////////////////////
- /// /see WindowImpl::SetIcon
- ///
- ////////////////////////////////////////////////////////////
- virtual void SetIcon(unsigned int Width, unsigned int Height, const Uint8* Pixels);
-};
-
-} // namespace priv
-
-} // namespace sf
-
-#endif // SFML_WINDOWIMPLXXX_HPP
diff --git a/src/SFML/Window/VideoMode.cpp b/src/SFML/Window/VideoMode.cpp
index 3ed77bc..1a4b141 100755..100644
--- a/src/SFML/Window/VideoMode.cpp
+++ b/src/SFML/Window/VideoMode.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -26,145 +26,121 @@
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Window/VideoMode.hpp>
-#include <SFML/Window/VideoModeSupport.hpp>
+#include <SFML/Window/VideoModeImpl.hpp>
#include <algorithm>
-#include <vector>
-
-
-////////////////////////////////////////////////////////////
-/// Internal data
-////////////////////////////////////////////////////////////
-namespace
-{
- // Global array of supported video modes
- std::vector<sf::VideoMode> SupportedModes;
-
- // Functor for sorting modes from highest to lowest
- struct CompareModes
- {
- bool operator ()(const sf::VideoMode& v1, const sf::VideoMode& v2) const
- {
- if (v1.BitsPerPixel > v2.BitsPerPixel)
- return true;
- else if (v1.BitsPerPixel < v2.BitsPerPixel)
- return false;
- else if (v1.Width > v2.Width)
- return true;
- else if (v1.Width < v2.Width)
- return false;
- else
- return (v1.Height > v2.Height);
- }
- };
-}
+#include <functional>
namespace sf
{
////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
VideoMode::VideoMode() :
-Width (0),
-Height (0),
-BitsPerPixel(0)
+width (0),
+height (0),
+bitsPerPixel(0)
{
}
////////////////////////////////////////////////////////////
-/// Construct the video mode with its attributes
-////////////////////////////////////////////////////////////
-VideoMode::VideoMode(unsigned int ModeWidth, unsigned int ModeHeight, unsigned int ModeBpp) :
-Width (ModeWidth),
-Height (ModeHeight),
-BitsPerPixel(ModeBpp)
+VideoMode::VideoMode(unsigned int modeWidth, unsigned int modeHeight, unsigned int modeBitsPerPixel) :
+width (modeWidth),
+height (modeHeight),
+bitsPerPixel(modeBitsPerPixel)
{
}
////////////////////////////////////////////////////////////
-/// Get the current desktop video mode
-////////////////////////////////////////////////////////////
-VideoMode VideoMode::GetDesktopMode()
+VideoMode VideoMode::getDesktopMode()
{
- // Directly forward to the video mode support
- return priv::VideoModeSupport::GetDesktopVideoMode();
+ // Directly forward to the OS-specific implementation
+ return priv::VideoModeImpl::getDesktopMode();
}
////////////////////////////////////////////////////////////
-/// Get a valid video mode
-/// Index must be in range [0, GetModesCount()[
-////////////////////////////////////////////////////////////
-VideoMode VideoMode::GetMode(std::size_t Index)
+const std::vector<VideoMode>& VideoMode::getFullscreenModes()
{
- if (SupportedModes.empty())
- InitializeModes();
+ static std::vector<VideoMode> modes;
- if (Index < GetModesCount())
- return SupportedModes[Index];
- else
- return VideoMode();
+ // Populate the array on first call
+ if (modes.empty())
+ {
+ modes = priv::VideoModeImpl::getFullscreenModes();
+ std::sort(modes.begin(), modes.end(), std::greater<VideoMode>());
+ }
+
+ return modes;
}
////////////////////////////////////////////////////////////
-/// Get valid video modes count
-////////////////////////////////////////////////////////////
-std::size_t VideoMode::GetModesCount()
+bool VideoMode::isValid() const
{
- if (SupportedModes.empty())
- InitializeModes();
+ const std::vector<VideoMode>& modes = getFullscreenModes();
- return SupportedModes.size();
+ return std::find(modes.begin(), modes.end(), *this) != modes.end();
}
////////////////////////////////////////////////////////////
-/// Tell whether or not the video mode is supported
-////////////////////////////////////////////////////////////
-bool VideoMode::IsValid() const
+bool operator ==(const VideoMode& left, const VideoMode& right)
{
- if (SupportedModes.empty())
- InitializeModes();
-
- return std::find(SupportedModes.begin(), SupportedModes.end(), *this) != SupportedModes.end();
+ return (left.width == right.width) &&
+ (left.height == right.height) &&
+ (left.bitsPerPixel == right.bitsPerPixel);
}
////////////////////////////////////////////////////////////
-/// Comparison operator overload -- tell if two video modes are equal
-////////////////////////////////////////////////////////////
-bool VideoMode::operator ==(const VideoMode& Other) const
+bool operator !=(const VideoMode& left, const VideoMode& right)
{
- return (Width == Other.Width) &&
- (Height == Other.Height) &&
- (BitsPerPixel == Other.BitsPerPixel);
+ return !(left == right);
}
////////////////////////////////////////////////////////////
-/// Comparison operator overload -- tell if two video modes are different
-////////////////////////////////////////////////////////////
-bool VideoMode::operator !=(const VideoMode& Other) const
+bool operator <(const VideoMode& left, const VideoMode& right)
{
- return !(*this == Other);
+ if (left.bitsPerPixel == right.bitsPerPixel)
+ {
+ if (left.width == right.width)
+ {
+ return left.height < right.height;
+ }
+ else
+ {
+ return left.width < right.width;
+ }
+ }
+ else
+ {
+ return left.bitsPerPixel < right.bitsPerPixel;
+ }
}
////////////////////////////////////////////////////////////
-/// Get and sort valid video modes
+bool operator >(const VideoMode& left, const VideoMode& right)
+{
+ return right < left;
+}
+
+
////////////////////////////////////////////////////////////
-void VideoMode::InitializeModes()
+bool operator <=(const VideoMode& left, const VideoMode& right)
{
- // We request the array of valid modes
- priv::VideoModeSupport::GetSupportedVideoModes(SupportedModes);
+ return !(right < left);
+}
+
- // And we sort them from highest to lowest (so that number 0 is the best)
- std::sort(SupportedModes.begin(), SupportedModes.end(), CompareModes());
+////////////////////////////////////////////////////////////
+bool operator >=(const VideoMode& left, const VideoMode& right)
+{
+ return !(left < right);
}
} // namespace sf
diff --git a/src/SFML/Window/Cocoa/VideoModeSupport.hpp b/src/SFML/Window/VideoModeImpl.hpp
index 4892fe5..7908c20 100755..100644
--- a/src/SFML/Window/Cocoa/VideoModeSupport.hpp
+++ b/src/SFML/Window/VideoModeImpl.hpp
@@ -1,69 +1,68 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-#ifndef SFML_VIDEOMODESUPPORTCOCOA_HPP
-#define SFML_VIDEOMODESUPPORTCOCOA_HPP
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Window/VideoMode.hpp>
-#include <vector>
-
-
-namespace sf
-{
-namespace priv
-{
-////////////////////////////////////////////////////////////
-/// Cocoa implementation of VideoModeSupport
-/// Give access to video mode related OS-specific functions
-////////////////////////////////////////////////////////////
-class VideoModeSupport
-{
-public :
-
- ////////////////////////////////////////////////////////////
- /// Get supported video modes
- ///
- /// \param Modes : Array to fill with available video modes
- ///
- ////////////////////////////////////////////////////////////
- static void GetSupportedVideoModes(std::vector<VideoMode>& Modes);
-
- ////////////////////////////////////////////////////////////
- /// Get current desktop video mode
- ///
- /// \return Current desktop video mode
- ///
- ////////////////////////////////////////////////////////////
- static VideoMode GetDesktopVideoMode();
-};
-
-} // namespace priv
-
-} // namespace sf
-
-
-#endif // SFML_VIDEOMODESUPPORTCOCOA_HPP
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_VIDEOMODEIMPL_HPP
+#define SFML_VIDEOMODEIMPL_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/VideoMode.hpp>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief OS-specific implementation of video modes functions
+///
+////////////////////////////////////////////////////////////
+class VideoModeImpl
+{
+public :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Get the list of all the supported fullscreen video modes
+ ///
+ /// \return Array filled with the fullscreen video modes
+ ///
+ ////////////////////////////////////////////////////////////
+ static std::vector<VideoMode> getFullscreenModes();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Get the current desktop video mode
+ ///
+ /// \return Current desktop video mode
+ ///
+ ////////////////////////////////////////////////////////////
+ static VideoMode getDesktopMode();
+};
+
+} // namespace priv
+
+} // namespace sf
+
+
+#endif // SFML_VIDEOMODEIMPL_HPP
diff --git a/src/SFML/Window/Win32/InputImpl.cpp b/src/SFML/Window/Win32/InputImpl.cpp
new file mode 100644
index 0000000..0ad303b
--- /dev/null
+++ b/src/SFML/Window/Win32/InputImpl.cpp
@@ -0,0 +1,225 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#ifdef _WIN32_WINDOWS
+ #undef _WIN32_WINDOWS
+#endif
+#ifdef _WIN32_WINNT
+ #undef _WIN32_WINNT
+#endif
+#define _WIN32_WINDOWS 0x0501
+#define _WIN32_WINNT 0x0501
+#include <SFML/Window/Window.hpp>
+#include <SFML/Window/Win32/InputImpl.hpp>
+#include <windows.h>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+bool InputImpl::isKeyPressed(Keyboard::Key key)
+{
+ int vkey = 0;
+ switch (key)
+ {
+ default: vkey = 0; break;
+ case Keyboard::A: vkey = 'A'; break;
+ case Keyboard::B: vkey = 'B'; break;
+ case Keyboard::C: vkey = 'C'; break;
+ case Keyboard::D: vkey = 'D'; break;
+ case Keyboard::E: vkey = 'E'; break;
+ case Keyboard::F: vkey = 'F'; break;
+ case Keyboard::G: vkey = 'G'; break;
+ case Keyboard::H: vkey = 'H'; break;
+ case Keyboard::I: vkey = 'I'; break;
+ case Keyboard::J: vkey = 'J'; break;
+ case Keyboard::K: vkey = 'K'; break;
+ case Keyboard::L: vkey = 'L'; break;
+ case Keyboard::M: vkey = 'M'; break;
+ case Keyboard::N: vkey = 'N'; break;
+ case Keyboard::O: vkey = 'O'; break;
+ case Keyboard::P: vkey = 'P'; break;
+ case Keyboard::Q: vkey = 'Q'; break;
+ case Keyboard::R: vkey = 'R'; break;
+ case Keyboard::S: vkey = 'S'; break;
+ case Keyboard::T: vkey = 'T'; break;
+ case Keyboard::U: vkey = 'U'; break;
+ case Keyboard::V: vkey = 'V'; break;
+ case Keyboard::W: vkey = 'W'; break;
+ case Keyboard::X: vkey = 'X'; break;
+ case Keyboard::Y: vkey = 'Y'; break;
+ case Keyboard::Z: vkey = 'Z'; break;
+ case Keyboard::Num0: vkey = '0'; break;
+ case Keyboard::Num1: vkey = '1'; break;
+ case Keyboard::Num2: vkey = '2'; break;
+ case Keyboard::Num3: vkey = '3'; break;
+ case Keyboard::Num4: vkey = '4'; break;
+ case Keyboard::Num5: vkey = '5'; break;
+ case Keyboard::Num6: vkey = '6'; break;
+ case Keyboard::Num7: vkey = '7'; break;
+ case Keyboard::Num8: vkey = '8'; break;
+ case Keyboard::Num9: vkey = '9'; break;
+ case Keyboard::Escape: vkey = VK_ESCAPE; break;
+ case Keyboard::LControl: vkey = VK_LCONTROL; break;
+ case Keyboard::LShift: vkey = VK_LSHIFT; break;
+ case Keyboard::LAlt: vkey = VK_LMENU; break;
+ case Keyboard::LSystem: vkey = VK_LWIN; break;
+ case Keyboard::RControl: vkey = VK_RCONTROL; break;
+ case Keyboard::RShift: vkey = VK_RSHIFT; break;
+ case Keyboard::RAlt: vkey = VK_RMENU; break;
+ case Keyboard::RSystem: vkey = VK_RWIN; break;
+ case Keyboard::Menu: vkey = VK_APPS; break;
+ case Keyboard::LBracket: vkey = VK_OEM_4; break;
+ case Keyboard::RBracket: vkey = VK_OEM_6; break;
+ case Keyboard::SemiColon: vkey = VK_OEM_1; break;
+ case Keyboard::Comma: vkey = VK_OEM_COMMA; break;
+ case Keyboard::Period: vkey = VK_OEM_PERIOD; break;
+ case Keyboard::Quote: vkey = VK_OEM_7; break;
+ case Keyboard::Slash: vkey = VK_OEM_2; break;
+ case Keyboard::BackSlash: vkey = VK_OEM_5; break;
+ case Keyboard::Tilde: vkey = VK_OEM_3; break;
+ case Keyboard::Equal: vkey = VK_OEM_PLUS; break;
+ case Keyboard::Dash: vkey = VK_OEM_MINUS; break;
+ case Keyboard::Space: vkey = VK_SPACE; break;
+ case Keyboard::Return: vkey = VK_RETURN; break;
+ case Keyboard::BackSpace: vkey = VK_BACK; break;
+ case Keyboard::Tab: vkey = VK_TAB; break;
+ case Keyboard::PageUp: vkey = VK_PRIOR; break;
+ case Keyboard::PageDown: vkey = VK_NEXT; break;
+ case Keyboard::End: vkey = VK_END; break;
+ case Keyboard::Home: vkey = VK_HOME; break;
+ case Keyboard::Insert: vkey = VK_INSERT; break;
+ case Keyboard::Delete: vkey = VK_DELETE; break;
+ case Keyboard::Add: vkey = VK_ADD; break;
+ case Keyboard::Subtract: vkey = VK_SUBTRACT; break;
+ case Keyboard::Multiply: vkey = VK_MULTIPLY; break;
+ case Keyboard::Divide: vkey = VK_DIVIDE; break;
+ case Keyboard::Left: vkey = VK_LEFT; break;
+ case Keyboard::Right: vkey = VK_RIGHT; break;
+ case Keyboard::Up: vkey = VK_UP; break;
+ case Keyboard::Down: vkey = VK_DOWN; break;
+ case Keyboard::Numpad0: vkey = VK_NUMPAD0; break;
+ case Keyboard::Numpad1: vkey = VK_NUMPAD1; break;
+ case Keyboard::Numpad2: vkey = VK_NUMPAD2; break;
+ case Keyboard::Numpad3: vkey = VK_NUMPAD3; break;
+ case Keyboard::Numpad4: vkey = VK_NUMPAD4; break;
+ case Keyboard::Numpad5: vkey = VK_NUMPAD5; break;
+ case Keyboard::Numpad6: vkey = VK_NUMPAD6; break;
+ case Keyboard::Numpad7: vkey = VK_NUMPAD7; break;
+ case Keyboard::Numpad8: vkey = VK_NUMPAD8; break;
+ case Keyboard::Numpad9: vkey = VK_NUMPAD9; break;
+ case Keyboard::F1: vkey = VK_F1; break;
+ case Keyboard::F2: vkey = VK_F2; break;
+ case Keyboard::F3: vkey = VK_F3; break;
+ case Keyboard::F4: vkey = VK_F4; break;
+ case Keyboard::F5: vkey = VK_F5; break;
+ case Keyboard::F6: vkey = VK_F6; break;
+ case Keyboard::F7: vkey = VK_F7; break;
+ case Keyboard::F8: vkey = VK_F8; break;
+ case Keyboard::F9: vkey = VK_F9; break;
+ case Keyboard::F10: vkey = VK_F10; break;
+ case Keyboard::F11: vkey = VK_F11; break;
+ case Keyboard::F12: vkey = VK_F12; break;
+ case Keyboard::F13: vkey = VK_F13; break;
+ case Keyboard::F14: vkey = VK_F14; break;
+ case Keyboard::F15: vkey = VK_F16; break;
+ case Keyboard::Pause: vkey = VK_PAUSE; break;
+ }
+
+ return (GetAsyncKeyState(vkey) & 0x8000) != 0;
+}
+
+
+////////////////////////////////////////////////////////////
+bool InputImpl::isMouseButtonPressed(Mouse::Button button)
+{
+ int vkey = 0;
+ switch (button)
+ {
+ case Mouse::Left: vkey = GetSystemMetrics(SM_SWAPBUTTON) ? VK_RBUTTON : VK_LBUTTON; break;
+ case Mouse::Right: vkey = GetSystemMetrics(SM_SWAPBUTTON) ? VK_LBUTTON : VK_RBUTTON; break;
+ case Mouse::Middle: vkey = VK_MBUTTON; break;
+ case Mouse::XButton1: vkey = VK_XBUTTON1; break;
+ case Mouse::XButton2: vkey = VK_XBUTTON2; break;
+ default: vkey = 0; break;
+ }
+
+ return (GetAsyncKeyState(vkey) & 0x8000) != 0;
+}
+
+
+////////////////////////////////////////////////////////////
+Vector2i InputImpl::getMousePosition()
+{
+ POINT point;
+ GetCursorPos(&point);
+ return Vector2i(point.x, point.y);
+}
+
+
+////////////////////////////////////////////////////////////
+Vector2i InputImpl::getMousePosition(const Window& relativeTo)
+{
+ WindowHandle handle = relativeTo.getSystemHandle();
+ if (handle)
+ {
+ POINT point;
+ GetCursorPos(&point);
+ ScreenToClient(handle, &point);
+ return Vector2i(point.x, point.y);
+ }
+ else
+ {
+ return Vector2i();
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void InputImpl::setMousePosition(const Vector2i& position)
+{
+ SetCursorPos(position.x, position.y);
+}
+
+
+////////////////////////////////////////////////////////////
+void InputImpl::setMousePosition(const Vector2i& position, const Window& relativeTo)
+{
+ WindowHandle handle = relativeTo.getSystemHandle();
+ if (handle)
+ {
+ POINT point = {position.x, position.y};
+ ClientToScreen(handle, &point);
+ SetCursorPos(point.x, point.y);
+ }
+}
+
+} // namespace priv
+
+} // namespace sf
diff --git a/src/SFML/Window/Win32/InputImpl.hpp b/src/SFML/Window/Win32/InputImpl.hpp
new file mode 100644
index 0000000..0669b4a
--- /dev/null
+++ b/src/SFML/Window/Win32/InputImpl.hpp
@@ -0,0 +1,123 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_INPUTIMPLWIN32_HPP
+#define SFML_INPUTIMPLWIN32_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/Keyboard.hpp>
+#include <SFML/Window/Mouse.hpp>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief Windows implementation of inputs (keyboard + mouse)
+///
+////////////////////////////////////////////////////////////
+class InputImpl
+{
+public :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Check if a key is pressed
+ ///
+ /// \param key Key to check
+ ///
+ /// \return True if the key is pressed, false otherwise
+ ///
+ ////////////////////////////////////////////////////////////
+ static bool isKeyPressed(Keyboard::Key key);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Check if a mouse button is pressed
+ ///
+ /// \param button Button to check
+ ///
+ /// \return True if the button is pressed, false otherwise
+ ///
+ ////////////////////////////////////////////////////////////
+ static bool isMouseButtonPressed(Mouse::Button button);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Get the current position of the mouse in desktop coordinates
+ ///
+ /// This function returns the current position of the mouse
+ /// cursor, in global (desktop) coordinates.
+ ///
+ /// \return Current position of the mouse
+ ///
+ ////////////////////////////////////////////////////////////
+ static Vector2i getMousePosition();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Get the current position of the mouse in window coordinates
+ ///
+ /// This function returns the current position of the mouse
+ /// cursor, relative to the given window.
+ /// If no window is used, it returns desktop coordinates.
+ ///
+ /// \param relativeTo Reference window
+ ///
+ /// \return Current position of the mouse
+ ///
+ ////////////////////////////////////////////////////////////
+ static Vector2i getMousePosition(const Window& relativeTo);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Set the current position of the mouse in desktop coordinates
+ ///
+ /// This function sets the current position of the mouse
+ /// cursor in global (desktop) coordinates.
+ /// If no window is used, it sets the position in desktop coordinates.
+ ///
+ /// \param position New position of the mouse
+ ///
+ ////////////////////////////////////////////////////////////
+ static void setMousePosition(const Vector2i& position);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Set the current position of the mouse in window coordinates
+ ///
+ /// This function sets the current position of the mouse
+ /// cursor, relative to the given window.
+ /// If no window is used, it sets the position in desktop coordinates.
+ ///
+ /// \param position New position of the mouse
+ /// \param relativeTo Reference window
+ ///
+ ////////////////////////////////////////////////////////////
+ static void setMousePosition(const Vector2i& position, const Window& relativeTo);
+};
+
+} // namespace priv
+
+} // namespace sf
+
+
+#endif // SFML_INPUTIMPLWIN32_HPP
diff --git a/src/SFML/Window/Win32/Joystick.cpp b/src/SFML/Window/Win32/Joystick.cpp
deleted file mode 100755
index e5e16a9..0000000
--- a/src/SFML/Window/Win32/Joystick.cpp
+++ /dev/null
@@ -1,157 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#define _WIN32_WINDOWS 0x0501
-#define _WIN32_WINNT 0x0501
-#include <SFML/Window/Joystick.hpp>
-#include <windows.h>
-#include <mmsystem.h>
-
-
-namespace sf
-{
-namespace priv
-{
-////////////////////////////////////////////////////////////
-/// Initialize the instance and bind it to a physical joystick
-////////////////////////////////////////////////////////////
-void Joystick::Initialize(unsigned int Index)
-{
- // Reset state
- myIndex = JOYSTICKID1;
- myNbButtons = 0;
- myIsConnected = false;
- myHasContinuousPOV = false;
- for (int i = 0; i < Joy::AxisCount; ++i)
- myAxes[i] = false;
-
- // Get the Index-th connected joystick
- MMRESULT Error;
- JOYINFOEX JoyInfo;
- JoyInfo.dwSize = sizeof(JoyInfo);
- JoyInfo.dwFlags = JOY_RETURNALL;
- for (unsigned int NbFound = 0; (Error = joyGetPosEx(myIndex, &JoyInfo)) != JOYERR_PARMS; myIndex++)
- {
- // Check if the current joystick is connected
- if (Error == JOYERR_NOERROR)
- {
- // Check if it's the required index
- if (NbFound == Index)
- {
- // Ok : store its parameters and return
- myIsConnected = true;
- JOYCAPS Caps;
- joyGetDevCaps(myIndex, &Caps, sizeof(Caps));
- myNbButtons = Caps.wNumButtons;
- if (myNbButtons > Joy::ButtonCount)
- myNbButtons = Joy::ButtonCount;
-
- myAxes[Joy::AxisX] = true;
- myAxes[Joy::AxisY] = true;
- myAxes[Joy::AxisZ] = (Caps.wCaps & JOYCAPS_HASZ) != 0;
- myAxes[Joy::AxisR] = (Caps.wCaps & JOYCAPS_HASR) != 0;
- myAxes[Joy::AxisU] = (Caps.wCaps & JOYCAPS_HASU) != 0;
- myAxes[Joy::AxisV] = (Caps.wCaps & JOYCAPS_HASV) != 0;
- myAxes[Joy::AxisPOV] = (Caps.wCaps & JOYCAPS_HASPOV) != 0;
- myHasContinuousPOV = (Caps.wCaps & JOYCAPS_POVCTS) != 0;
-
- return;
- }
-
- // Go to the next valid joystick
- ++NbFound;
- }
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Update the current joystick and return its new state
-////////////////////////////////////////////////////////////
-JoystickState Joystick::UpdateState()
-{
- JoystickState State;
-
- if (myIsConnected)
- {
- // Get the joystick caps (for range conversions)
- JOYCAPS Caps;
- if (joyGetDevCaps(myIndex, &Caps, sizeof(Caps)) == JOYERR_NOERROR)
- {
- // Get the current joystick state
- JOYINFOEX Pos;
- Pos.dwFlags = JOY_RETURNX | JOY_RETURNY | JOY_RETURNZ | JOY_RETURNR | JOY_RETURNU | JOY_RETURNV | JOY_RETURNBUTTONS;
- Pos.dwFlags |= myHasContinuousPOV ? JOY_RETURNPOVCTS : JOY_RETURNPOV;
- Pos.dwSize = sizeof(JOYINFOEX);
- if (joyGetPosEx(myIndex, &Pos) == JOYERR_NOERROR)
- {
- // Axes
- State.Axis[Joy::AxisX] = (Pos.dwXpos - (Caps.wXmax + Caps.wXmin) / 2.f) * 200.f / (Caps.wXmax - Caps.wXmin);
- State.Axis[Joy::AxisY] = (Pos.dwYpos - (Caps.wYmax + Caps.wYmin) / 2.f) * 200.f / (Caps.wYmax - Caps.wYmin);
- State.Axis[Joy::AxisZ] = (Pos.dwZpos - (Caps.wZmax + Caps.wZmin) / 2.f) * 200.f / (Caps.wZmax - Caps.wZmin);
- State.Axis[Joy::AxisR] = (Pos.dwRpos - (Caps.wRmax + Caps.wRmin) / 2.f) * 200.f / (Caps.wRmax - Caps.wRmin);
- State.Axis[Joy::AxisU] = (Pos.dwUpos - (Caps.wUmax + Caps.wUmin) / 2.f) * 200.f / (Caps.wUmax - Caps.wUmin);
- State.Axis[Joy::AxisV] = (Pos.dwVpos - (Caps.wVmax + Caps.wVmin) / 2.f) * 200.f / (Caps.wVmax - Caps.wVmin);
-
- // POV
- if (Pos.dwPOV != 0xFFFF)
- State.Axis[Joy::AxisPOV] = Pos.dwPOV / 100.f;
- else
- State.Axis[Joy::AxisPOV] = -1.f;
-
- // Buttons
- for (unsigned int i = 0; i < GetButtonsCount(); ++i)
- State.Buttons[i] = (Pos.dwButtons & (1 << i)) != 0;
- }
- }
- }
-
- return State;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Check if the joystick supports the given axis
-////////////////////////////////////////////////////////////
-bool Joystick::HasAxis(Joy::Axis Axis) const
-{
- return myAxes[Axis];
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the number of buttons supported by the joystick
-////////////////////////////////////////////////////////////
-unsigned int Joystick::GetButtonsCount() const
-{
- return myNbButtons;
-}
-
-
-} // namespace priv
-
-} // namespace sf
diff --git a/src/SFML/Window/Win32/JoystickImpl.cpp b/src/SFML/Window/Win32/JoystickImpl.cpp
new file mode 100644
index 0000000..c2645e8
--- /dev/null
+++ b/src/SFML/Window/Win32/JoystickImpl.cpp
@@ -0,0 +1,189 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/JoystickImpl.hpp>
+#include <SFML/System/Clock.hpp>
+#include <windows.h>
+#include <cmath>
+
+
+namespace
+{
+ struct ConnectionCache
+ {
+ ConnectionCache() : connected(false) {}
+ bool connected;
+ sf::Clock timer;
+ };
+
+ const sf::Time connectionRefreshDelay = sf::milliseconds(500);
+ ConnectionCache connectionCache[sf::Joystick::Count];
+}
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+void JoystickImpl::initialize()
+{
+ // Perform the initial scan and populate the connection cache
+ for (unsigned int i = 0; i < Joystick::Count; ++i)
+ {
+ ConnectionCache& cache = connectionCache[i];
+
+ // Check if the joystick is connected
+ JOYINFOEX joyInfo;
+ joyInfo.dwSize = sizeof(joyInfo);
+ joyInfo.dwFlags = 0;
+ cache.connected = joyGetPosEx(JOYSTICKID1 + i, &joyInfo) == JOYERR_NOERROR;
+
+ // start the timeout
+ cache.timer.restart();
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+void JoystickImpl::cleanup()
+{
+ // Nothing to do
+}
+
+
+////////////////////////////////////////////////////////////
+bool JoystickImpl::isConnected(unsigned int index)
+{
+ // We check the connection state of joysticks only every N milliseconds,
+ // because of a strange (buggy?) behaviour of joyGetPosEx when joysticks
+ // are just plugged/unplugged -- it takes really long and kills the app performances
+ ConnectionCache& cache = connectionCache[index];
+ if (cache.timer.getElapsedTime() > connectionRefreshDelay)
+ {
+ cache.timer.restart();
+
+ JOYINFOEX joyInfo;
+ joyInfo.dwSize = sizeof(joyInfo);
+ joyInfo.dwFlags = 0;
+
+ cache.connected = joyGetPosEx(JOYSTICKID1 + index, &joyInfo) == JOYERR_NOERROR;
+ return cache.connected;
+ }
+ else
+ {
+ return cache.connected;
+ }
+}
+
+
+////////////////////////////////////////////////////////////
+bool JoystickImpl::open(unsigned int index)
+{
+ // No explicit "open" action is required
+ m_index = JOYSTICKID1 + index;
+
+ // Store the joystick capabilities
+ return joyGetDevCaps(m_index, &m_caps, sizeof(m_caps)) == JOYERR_NOERROR;
+}
+
+
+////////////////////////////////////////////////////////////
+void JoystickImpl::close()
+{
+ // Nothing to do
+}
+
+
+////////////////////////////////////////////////////////////
+JoystickCaps JoystickImpl::getCapabilities() const
+{
+ JoystickCaps caps;
+
+ caps.buttonCount = m_caps.wNumButtons;
+ if (caps.buttonCount > Joystick::ButtonCount)
+ caps.buttonCount = Joystick::ButtonCount;
+
+ caps.axes[Joystick::X] = true;
+ caps.axes[Joystick::Y] = true;
+ caps.axes[Joystick::Z] = (m_caps.wCaps & JOYCAPS_HASZ) != 0;
+ caps.axes[Joystick::R] = (m_caps.wCaps & JOYCAPS_HASR) != 0;
+ caps.axes[Joystick::U] = (m_caps.wCaps & JOYCAPS_HASU) != 0;
+ caps.axes[Joystick::V] = (m_caps.wCaps & JOYCAPS_HASV) != 0;
+ caps.axes[Joystick::PovX] = (m_caps.wCaps & JOYCAPS_HASPOV) != 0;
+ caps.axes[Joystick::PovY] = (m_caps.wCaps & JOYCAPS_HASPOV) != 0;
+
+ return caps;
+}
+
+
+////////////////////////////////////////////////////////////
+JoystickState JoystickImpl::update()
+{
+ JoystickState state;
+
+ // Get the current joystick state
+ JOYINFOEX pos;
+ pos.dwFlags = JOY_RETURNX | JOY_RETURNY | JOY_RETURNZ | JOY_RETURNR | JOY_RETURNU | JOY_RETURNV | JOY_RETURNBUTTONS;
+ pos.dwFlags |= (m_caps.wCaps & JOYCAPS_POVCTS) ? JOY_RETURNPOVCTS : JOY_RETURNPOV;
+ pos.dwSize = sizeof(JOYINFOEX);
+ if (joyGetPosEx(m_index, &pos) == JOYERR_NOERROR)
+ {
+ // The joystick is connected
+ state.connected = true;
+
+ // Axes
+ state.axes[Joystick::X] = (pos.dwXpos - (m_caps.wXmax + m_caps.wXmin) / 2.f) * 200.f / (m_caps.wXmax - m_caps.wXmin);
+ state.axes[Joystick::Y] = (pos.dwYpos - (m_caps.wYmax + m_caps.wYmin) / 2.f) * 200.f / (m_caps.wYmax - m_caps.wYmin);
+ state.axes[Joystick::Z] = (pos.dwZpos - (m_caps.wZmax + m_caps.wZmin) / 2.f) * 200.f / (m_caps.wZmax - m_caps.wZmin);
+ state.axes[Joystick::R] = (pos.dwRpos - (m_caps.wRmax + m_caps.wRmin) / 2.f) * 200.f / (m_caps.wRmax - m_caps.wRmin);
+ state.axes[Joystick::U] = (pos.dwUpos - (m_caps.wUmax + m_caps.wUmin) / 2.f) * 200.f / (m_caps.wUmax - m_caps.wUmin);
+ state.axes[Joystick::V] = (pos.dwVpos - (m_caps.wVmax + m_caps.wVmin) / 2.f) * 200.f / (m_caps.wVmax - m_caps.wVmin);
+
+ // Special case for POV, it is given as an angle
+ if (pos.dwPOV != 0xFFFF)
+ {
+ float angle = pos.dwPOV / 18000.f * 3.141592654f;
+ state.axes[Joystick::PovX] = std::cos(angle) * 100;
+ state.axes[Joystick::PovY] = std::sin(angle) * 100;
+ }
+ else
+ {
+ state.axes[Joystick::PovX] = 0;
+ state.axes[Joystick::PovY] = 0;
+ }
+
+ // Buttons
+ for (unsigned int i = 0; i < Joystick::ButtonCount; ++i)
+ state.buttons[i] = (pos.dwButtons & (1 << i)) != 0;
+ }
+
+ return state;
+}
+
+} // namespace priv
+
+} // namespace sf
diff --git a/src/SFML/Window/Win32/JoystickImpl.hpp b/src/SFML/Window/Win32/JoystickImpl.hpp
new file mode 100644
index 0000000..1630f99
--- /dev/null
+++ b/src/SFML/Window/Win32/JoystickImpl.hpp
@@ -0,0 +1,125 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_JOYSTICKIMPLWIN32_HPP
+#define SFML_JOYSTICKIMPLWIN32_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#ifdef _WIN32_WINDOWS
+ #undef _WIN32_WINDOWS
+#endif
+#ifdef _WIN32_WINNT
+ #undef _WIN32_WINNT
+#endif
+#define _WIN32_WINDOWS 0x0501
+#define _WIN32_WINNT 0x0501
+#include <SFML/Window/JoystickImpl.hpp>
+#include <windows.h>
+#include <mmsystem.h>
+#include <cmath>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief Windows implementation of joysticks
+///
+////////////////////////////////////////////////////////////
+class JoystickImpl
+{
+public :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Perform the global initialization of the joystick module
+ ///
+ ////////////////////////////////////////////////////////////
+ static void initialize();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Perform the global cleanup of the joystick module
+ ///
+ ////////////////////////////////////////////////////////////
+ static void cleanup();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Check if a joystick is currently connected
+ ///
+ /// \param index Index of the joystick to check
+ ///
+ /// \return True if the joystick is connected, false otherwise
+ ///
+ ////////////////////////////////////////////////////////////
+ static bool isConnected(unsigned int index);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Open the joystick
+ ///
+ /// \param index Index assigned to the joystick
+ ///
+ /// \return True on success, false on failure
+ ///
+ ////////////////////////////////////////////////////////////
+ bool open(unsigned int index);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Close the joystick
+ ///
+ ////////////////////////////////////////////////////////////
+ void close();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Get the joystick capabilities
+ ///
+ /// \return Joystick capabilities
+ ///
+ ////////////////////////////////////////////////////////////
+ JoystickCaps getCapabilities() const;
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Update the joystick and get its new state
+ ///
+ /// \return Joystick state
+ ///
+ ////////////////////////////////////////////////////////////
+ JoystickState update();
+
+private :
+
+ ////////////////////////////////////////////////////////////
+ // Member data
+ ////////////////////////////////////////////////////////////
+ unsigned int m_index; ///< Index of the joystick
+ JOYCAPS m_caps; ///< Joystick capabilities
+};
+
+} // namespace priv
+
+} // namespace sf
+
+
+#endif // SFML_JOYSTICKIMPLWIN32_HPP
diff --git a/src/SFML/Window/Joystick.hpp b/src/SFML/Window/Win32/VideoModeImpl.cpp
index 6dd1b6e..11f04ab 100755..100644
--- a/src/SFML/Window/Joystick.hpp
+++ b/src/SFML/Window/Win32/VideoModeImpl.cpp
@@ -1,80 +1,71 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-#ifndef SFML_JOYSTICK_HPP
-#define SFML_JOYSTICK_HPP
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Config.hpp>
-#include <SFML/Window/Event.hpp>
-
-
-namespace sf
-{
-namespace priv
-{
-////////////////////////////////////////////////////////////
-/// Structure holding the joystick state's parameters
-////////////////////////////////////////////////////////////
-struct JoystickState
-{
- JoystickState()
- {
- // Default value for axes
- for (int i = 0; i < Joy::AxisCount; ++i)
- Axis[i] = 0.f;
- Axis[Joy::AxisPOV] = -1.f;
-
- // Default value for buttons
- for (int i = 0; i < Joy::ButtonCount; ++i)
- Buttons[i] = false;
- }
-
- float Axis[Joy::AxisCount]; ///< Position on each axis in range [-100, 100] (except POV which is [0, 360])
- bool Buttons[Joy::ButtonCount]; ///< Status of each button (true = pressed)
-};
-
-} // namespace priv
-
-} // namespace sf
-
-
-#if defined(SFML_SYSTEM_WINDOWS)
-
- #include <SFML/Window/Win32/Joystick.hpp>
-
-#elif defined(SFML_SYSTEM_LINUX) || defined(SFML_SYSTEM_FREEBSD)
-
- #include <SFML/Window/Linux/Joystick.hpp>
-
-#elif defined(SFML_SYSTEM_MACOS)
-
- #include <SFML/Window/Cocoa/Joystick.hpp>
-
-#endif
-
-
-#endif // SFML_JOYSTICK_HPP
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/VideoModeImpl.hpp>
+#include <windows.h>
+#include <algorithm>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+std::vector<VideoMode> VideoModeImpl::getFullscreenModes()
+{
+ std::vector<VideoMode> modes;
+
+ // Enumerate all available video modes for the primary display adapter
+ DEVMODE win32Mode;
+ win32Mode.dmSize = sizeof(win32Mode);
+ for (int count = 0; EnumDisplaySettings(NULL, count, &win32Mode); ++count)
+ {
+ // Convert to sf::VideoMode
+ VideoMode mode(win32Mode.dmPelsWidth, win32Mode.dmPelsHeight, win32Mode.dmBitsPerPel);
+
+ // Add it only if it is not already in the array
+ if (std::find(modes.begin(), modes.end(), mode) == modes.end())
+ modes.push_back(mode);
+ }
+
+ return modes;
+}
+
+
+////////////////////////////////////////////////////////////
+VideoMode VideoModeImpl::getDesktopMode()
+{
+ DEVMODE win32Mode;
+ win32Mode.dmSize = sizeof(win32Mode);
+ EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &win32Mode);
+
+ return VideoMode(win32Mode.dmPelsWidth, win32Mode.dmPelsHeight, win32Mode.dmBitsPerPel);
+}
+
+} // namespace priv
+
+} // namespace sf
diff --git a/src/SFML/Window/Win32/VideoModeSupport.hpp b/src/SFML/Window/Win32/VideoModeSupport.hpp
deleted file mode 100755
index f00d474..0000000
--- a/src/SFML/Window/Win32/VideoModeSupport.hpp
+++ /dev/null
@@ -1,69 +0,0 @@
-////////////////////////////////////////////////////////////
-//
-// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2008 Laurent Gomila (laurent.gom@gmail.com)
-//
-// This software is provided 'as-is', without any express or implied warranty.
-// In no event will the authors be held liable for any damages arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it freely,
-// subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented;
-// you must not claim that you wrote the original software.
-// If you use this software in a product, an acknowledgment
-// in the product documentation would be appreciated but is not required.
-//
-// 2. Altered source versions must be plainly marked as such,
-// and must not be misrepresented as being the original software.
-//
-// 3. This notice may not be removed or altered from any source distribution.
-//
-////////////////////////////////////////////////////////////
-
-#ifndef SFML_VIDEOMODESUPPORTWIN32_HPP
-#define SFML_VIDEOMODESUPPORTWIN32_HPP
-
-////////////////////////////////////////////////////////////
-// Headers
-////////////////////////////////////////////////////////////
-#include <SFML/Window/VideoMode.hpp>
-#include <vector>
-
-
-namespace sf
-{
-namespace priv
-{
-////////////////////////////////////////////////////////////
-/// Win32 implementation of VideoModeSupport
-/// Give access to video mode related OS-specific functions
-////////////////////////////////////////////////////////////
-class VideoModeSupport
-{
-public :
-
- ////////////////////////////////////////////////////////////
- /// Get supported video modes
- ///
- /// \param Modes : Array to fill with available video modes
- ///
- ////////////////////////////////////////////////////////////
- static void GetSupportedVideoModes(std::vector<VideoMode>& Modes);
-
- ////////////////////////////////////////////////////////////
- /// Get current desktop video mode
- ///
- /// \return Current desktop video mode
- ///
- ////////////////////////////////////////////////////////////
- static VideoMode GetDesktopVideoMode();
-};
-
-} // namespace priv
-
-} // namespace sf
-
-
-#endif // SFML_VIDEOMODESUPPORTWIN32_HPP
diff --git a/src/SFML/Window/Win32/WglContext.cpp b/src/SFML/Window/Win32/WglContext.cpp
new file mode 100644
index 0000000..7d9cc43
--- /dev/null
+++ b/src/SFML/Window/Win32/WglContext.cpp
@@ -0,0 +1,325 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/WindowImpl.hpp> // included first to avoid a warning about macro redefinition
+#include <SFML/Window/Win32/WglContext.hpp>
+#include <SFML/Window/glext/wglext.h>
+#include <SFML/System/Lock.hpp>
+#include <SFML/System/Mutex.hpp>
+#include <SFML/System/Err.hpp>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+WglContext::WglContext(WglContext* shared) :
+m_window (NULL),
+m_deviceContext(NULL),
+m_context (NULL),
+m_ownsWindow (true)
+{
+ // Creating a dummy window is mandatory: we could create a memory DC but then
+ // its pixel format wouldn't match the regular contexts' format, and thus
+ // wglShareLists would always fail. Too bad...
+
+ // Create a dummy window (disabled and hidden)
+ m_window = CreateWindowA("STATIC", "", WS_POPUP | WS_DISABLED, 0, 0, 1, 1, NULL, NULL, GetModuleHandle(NULL), NULL);
+ ShowWindow(m_window, SW_HIDE);
+ m_deviceContext = GetDC(m_window);
+
+ // Create the context
+ if (m_deviceContext)
+ createContext(shared, VideoMode::getDesktopMode().bitsPerPixel, ContextSettings());
+}
+
+
+////////////////////////////////////////////////////////////
+WglContext::WglContext(WglContext* shared, const ContextSettings& settings, const WindowImpl* owner, unsigned int bitsPerPixel) :
+m_window (NULL),
+m_deviceContext(NULL),
+m_context (NULL),
+m_ownsWindow (false)
+{
+ // Get the owner window and its device context
+ m_window = owner->getSystemHandle();
+ m_deviceContext = GetDC(m_window);
+
+ // Create the context
+ if (m_deviceContext)
+ createContext(shared, bitsPerPixel, settings);
+}
+
+
+////////////////////////////////////////////////////////////
+WglContext::WglContext(WglContext* shared, const ContextSettings& settings, unsigned int width, unsigned int height) :
+m_window (NULL),
+m_deviceContext(NULL),
+m_context (NULL),
+m_ownsWindow (true)
+{
+ // The target of the context is a hidden window.
+ // We can't create a memory DC (the resulting context wouldn't be compatible
+ // with other contexts), and we don't add the extra complexity of P-Buffers;
+ // we can still support them in the future if this solution is not good enough.
+
+ // Create the hidden window
+ m_window = CreateWindowA("STATIC", "", WS_POPUP | WS_DISABLED, 0, 0, width, height, NULL, NULL, GetModuleHandle(NULL), NULL);
+ ShowWindow(m_window, SW_HIDE);
+ m_deviceContext = GetDC(m_window);
+
+ // Create the context
+ if (m_deviceContext)
+ createContext(shared, VideoMode::getDesktopMode().bitsPerPixel, settings);
+}
+
+
+////////////////////////////////////////////////////////////
+WglContext::~WglContext()
+{
+ // Destroy the OpenGL context
+ if (m_context)
+ {
+ if (wglGetCurrentContext() == m_context)
+ wglMakeCurrent(NULL, NULL);
+ wglDeleteContext(m_context);
+ }
+
+ // Destroy the device context
+ if (m_deviceContext)
+ ReleaseDC(m_window, m_deviceContext);
+
+ // Destroy the window if we own it
+ if (m_window && m_ownsWindow)
+ DestroyWindow(m_window);
+}
+
+
+////////////////////////////////////////////////////////////
+bool WglContext::makeCurrent()
+{
+ return m_deviceContext && m_context && wglMakeCurrent(m_deviceContext, m_context);
+}
+
+
+////////////////////////////////////////////////////////////
+void WglContext::display()
+{
+ if (m_deviceContext && m_context)
+ SwapBuffers(m_deviceContext);
+}
+
+
+////////////////////////////////////////////////////////////
+void WglContext::setVerticalSyncEnabled(bool enabled)
+{
+ PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = reinterpret_cast<PFNWGLSWAPINTERVALEXTPROC>(wglGetProcAddress("wglSwapIntervalEXT"));
+ if (wglSwapIntervalEXT)
+ wglSwapIntervalEXT(enabled ? 1 : 0);
+}
+
+
+////////////////////////////////////////////////////////////
+void WglContext::createContext(WglContext* shared, unsigned int bitsPerPixel, const ContextSettings& settings)
+{
+ // Save the creation settings
+ m_settings = settings;
+
+ // Let's find a suitable pixel format -- first try with antialiasing
+ int bestFormat = 0;
+ if (m_settings.antialiasingLevel > 0)
+ {
+ // Get the wglChoosePixelFormatARB function (it is an extension)
+ PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = reinterpret_cast<PFNWGLCHOOSEPIXELFORMATARBPROC>(wglGetProcAddress("wglChoosePixelFormatARB"));
+ if (wglChoosePixelFormatARB)
+ {
+ // Define the basic attributes we want for our window
+ int intAttributes[] =
+ {
+ WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
+ WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
+ WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
+ WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
+ WGL_SAMPLE_BUFFERS_ARB, (m_settings.antialiasingLevel ? GL_TRUE : GL_FALSE),
+ WGL_SAMPLES_ARB, static_cast<int>(m_settings.antialiasingLevel),
+ 0, 0
+ };
+
+ // Let's check how many formats are supporting our requirements
+ int formats[128];
+ UINT nbFormats;
+ float floatAttributes[] = {0, 0};
+ bool isValid = wglChoosePixelFormatARB(m_deviceContext, intAttributes, floatAttributes, sizeof(formats) / sizeof(*formats), formats, &nbFormats) != 0;
+ while ((!isValid || (nbFormats == 0)) && m_settings.antialiasingLevel > 0)
+ {
+ // Decrease the antialiasing level until we find a valid one
+ m_settings.antialiasingLevel--;
+ intAttributes[11] = m_settings.antialiasingLevel;
+ isValid = wglChoosePixelFormatARB(m_deviceContext, intAttributes, floatAttributes, sizeof(formats) / sizeof(*formats), formats, &nbFormats) != 0;
+ }
+
+ // Get the best format among the returned ones
+ if (isValid && (nbFormats > 0))
+ {
+ int bestScore = 0xFFFF;
+ for (UINT i = 0; i < nbFormats; ++i)
+ {
+ // Get the current format's attributes
+ PIXELFORMATDESCRIPTOR attributes;
+ attributes.nSize = sizeof(attributes);
+ attributes.nVersion = 1;
+ DescribePixelFormat(m_deviceContext, formats[i], sizeof(attributes), &attributes);
+
+ // Evaluate the current configuration
+ int color = attributes.cRedBits + attributes.cGreenBits + attributes.cBlueBits + attributes.cAlphaBits;
+ int score = evaluateFormat(bitsPerPixel, m_settings, color, attributes.cDepthBits, attributes.cStencilBits, m_settings.antialiasingLevel);
+
+ // Keep it if it's better than the current best
+ if (score < bestScore)
+ {
+ bestScore = score;
+ bestFormat = formats[i];
+ }
+ }
+ }
+ }
+ else
+ {
+ // wglChoosePixelFormatARB not supported ; disabling antialiasing
+ err() << "Antialiasing is not supported ; it will be disabled" << std::endl;
+ m_settings.antialiasingLevel = 0;
+ }
+ }
+
+ // Find a pixel format with no antialiasing, if not needed or not supported
+ if (bestFormat == 0)
+ {
+ // Setup a pixel format descriptor from the rendering settings
+ PIXELFORMATDESCRIPTOR descriptor;
+ ZeroMemory(&descriptor, sizeof(descriptor));
+ descriptor.nSize = sizeof(descriptor);
+ descriptor.nVersion = 1;
+ descriptor.iLayerType = PFD_MAIN_PLANE;
+ descriptor.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
+ descriptor.iPixelType = PFD_TYPE_RGBA;
+ descriptor.cColorBits = static_cast<BYTE>(bitsPerPixel);
+ descriptor.cDepthBits = static_cast<BYTE>(m_settings.depthBits);
+ descriptor.cStencilBits = static_cast<BYTE>(m_settings.stencilBits);
+ descriptor.cAlphaBits = bitsPerPixel == 32 ? 8 : 0;
+
+ // Get the pixel format that best matches our requirements
+ bestFormat = ChoosePixelFormat(m_deviceContext, &descriptor);
+ if (bestFormat == 0)
+ {
+ err() << "Failed to find a suitable pixel format for device context -- cannot create OpenGL context" << std::endl;
+ return;
+ }
+ }
+
+ // Extract the depth and stencil bits from the chosen format
+ PIXELFORMATDESCRIPTOR actualFormat;
+ actualFormat.nSize = sizeof(actualFormat);
+ actualFormat.nVersion = 1;
+ DescribePixelFormat(m_deviceContext, bestFormat, sizeof(actualFormat), &actualFormat);
+ m_settings.depthBits = actualFormat.cDepthBits;
+ m_settings.stencilBits = actualFormat.cStencilBits;
+
+ // Set the chosen pixel format
+ if (!SetPixelFormat(m_deviceContext, bestFormat, &actualFormat))
+ {
+ err() << "Failed to set pixel format for device context -- cannot create OpenGL context" << std::endl;
+ return;
+ }
+
+ // Get the context to share display lists with
+ HGLRC sharedContext = shared ? shared->m_context : NULL;
+
+ // Create the OpenGL context -- first try context versions >= 3.0 if it is requested (they require special code)
+ while (!m_context && (m_settings.majorVersion >= 3))
+ {
+ PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = reinterpret_cast<PFNWGLCREATECONTEXTATTRIBSARBPROC>(wglGetProcAddress("wglCreateContextAttribsARB"));
+ if (wglCreateContextAttribsARB)
+ {
+ int attributes[] =
+ {
+ WGL_CONTEXT_MAJOR_VERSION_ARB, static_cast<int>(m_settings.majorVersion),
+ WGL_CONTEXT_MINOR_VERSION_ARB, static_cast<int>(m_settings.minorVersion),
+ WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB,
+ 0, 0
+ };
+ m_context = wglCreateContextAttribsARB(m_deviceContext, sharedContext, attributes);
+ }
+
+ // If we couldn't create the context, lower the version number and try again -- stop at 3.0
+ // Invalid version numbers will be generated by this algorithm (like 3.9), but we really don't care
+ if (!m_context)
+ {
+ if (m_settings.minorVersion > 0)
+ {
+ // If the minor version is not 0, we decrease it and try again
+ m_settings.minorVersion--;
+ }
+ else
+ {
+ // If the minor version is 0, we decrease the major version
+ m_settings.majorVersion--;
+ m_settings.minorVersion = 9;
+ }
+ }
+ }
+
+ // If the OpenGL >= 3.0 context failed or if we don't want one, create a regular OpenGL 1.x/2.x context
+ if (!m_context)
+ {
+ // set the context version to 2.0 (arbitrary)
+ m_settings.majorVersion = 2;
+ m_settings.minorVersion = 0;
+
+ m_context = wglCreateContext(m_deviceContext);
+ if (!m_context)
+ {
+ err() << "Failed to create an OpenGL context for this window" << std::endl;
+ return;
+ }
+
+ // Share this context with others
+ if (sharedContext)
+ {
+ // wglShareLists doesn't seem to be thread-safe
+ static Mutex mutex;
+ Lock lock(mutex);
+
+ if (!wglShareLists(sharedContext, m_context))
+ err() << "Failed to share the OpenGL context" << std::endl;
+ }
+ }
+}
+
+} // namespace priv
+
+} // namespace sf
diff --git a/src/SFML/Window/Win32/WglContext.hpp b/src/SFML/Window/Win32/WglContext.hpp
new file mode 100644
index 0000000..3fa1c3a
--- /dev/null
+++ b/src/SFML/Window/Win32/WglContext.hpp
@@ -0,0 +1,136 @@
+////////////////////////////////////////////////////////////
+//
+// SFML - Simple and Fast Multimedia Library
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
+//
+// This software is provided 'as-is', without any express or implied warranty.
+// In no event will the authors be held liable for any damages arising from the use of this software.
+//
+// Permission is granted to anyone to use this software for any purpose,
+// including commercial applications, and to alter it and redistribute it freely,
+// subject to the following restrictions:
+//
+// 1. The origin of this software must not be misrepresented;
+// you must not claim that you wrote the original software.
+// If you use this software in a product, an acknowledgment
+// in the product documentation would be appreciated but is not required.
+//
+// 2. Altered source versions must be plainly marked as such,
+// and must not be misrepresented as being the original software.
+//
+// 3. This notice may not be removed or altered from any source distribution.
+//
+////////////////////////////////////////////////////////////
+
+#ifndef SFML_WGLCONTEXT_HPP
+#define SFML_WGLCONTEXT_HPP
+
+////////////////////////////////////////////////////////////
+// Headers
+////////////////////////////////////////////////////////////
+#include <SFML/Window/GlContext.hpp>
+#include <SFML/OpenGL.hpp>
+#include <windows.h>
+
+
+namespace sf
+{
+namespace priv
+{
+////////////////////////////////////////////////////////////
+/// \brief Windows (WGL) implementation of OpenGL contexts
+///
+////////////////////////////////////////////////////////////
+class WglContext : public GlContext
+{
+public :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Create a new default context
+ ///
+ /// \param shared Context to share the new one with (can be NULL)
+ ///
+ ////////////////////////////////////////////////////////////
+ WglContext(WglContext* shared);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Create a new context attached to a window
+ ///
+ /// \param shared Context to share the new one with
+ /// \param settings Creation parameters
+ /// \param owner Pointer to the owner window
+ /// \param bitsPerPixel Pixel depth, in bits per pixel
+ ///
+ ////////////////////////////////////////////////////////////
+ WglContext(WglContext* shared, const ContextSettings& settings, const WindowImpl* owner, unsigned int bitsPerPixel);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Create a new context that embeds its own rendering target
+ ///
+ /// \param shared Context to share the new one with
+ /// \param settings Creation parameters
+ /// \param width Back buffer width, in pixels
+ /// \param height Back buffer height, in pixels
+ ///
+ ////////////////////////////////////////////////////////////
+ WglContext(WglContext* shared, const ContextSettings& settings, unsigned int width, unsigned int height);
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Destructor
+ ///
+ ////////////////////////////////////////////////////////////
+ ~WglContext();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Activate the context as the current target for rendering
+ ///
+ /// \return True on success, false if any error happened
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual bool makeCurrent();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Display what has been rendered to the context so far
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual void display();
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Enable or disable vertical synchronization
+ ///
+ /// Activating vertical synchronization will limit the number
+ /// of frames displayed to the refresh rate of the monitor.
+ /// This can avoid some visual artifacts, and limit the framerate
+ /// to a good value (but not constant across different computers).
+ ///
+ /// \param enabled : True to enable v-sync, false to deactivate
+ ///
+ ////////////////////////////////////////////////////////////
+ virtual void setVerticalSyncEnabled(bool enabled);
+
+private :
+
+ ////////////////////////////////////////////////////////////
+ /// \brief Create the context
+ ///
+ /// \param shared Context to share the new one with (can be NULL)
+ /// \param bitsPerPixel Pixel depth, in bits per pixel
+ /// \param settings Creation parameters
+ ///
+ ////////////////////////////////////////////////////////////
+ void createContext(WglContext* shared, unsigned int bitsPerPixel, const ContextSettings& settings);
+
+ ////////////////////////////////////////////////////////////
+ // Member data
+ ////////////////////////////////////////////////////////////
+ HWND m_window; ///< Window to which the context is attached
+ HDC m_deviceContext; ///< Device context associated to the context
+ HGLRC m_context; ///< OpenGL context
+ bool m_ownsWindow; ///< Do we own the target window?
+};
+
+} // namespace priv
+
+} // namespace sf
+
+#endif // SFML_WGLCONTEXT_HPP
diff --git a/src/SFML/Window/Win32/WindowImplWin32.cpp b/src/SFML/Window/Win32/WindowImplWin32.cpp
index 506cb73..4c83cae 100755..100644
--- a/src/SFML/Window/Win32/WindowImplWin32.cpp
+++ b/src/SFML/Window/Win32/WindowImplWin32.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -25,15 +25,19 @@
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
+#ifdef _WIN32_WINDOWS
+ #undef _WIN32_WINDOWS
+#endif
+#ifdef _WIN32_WINNT
+ #undef _WIN32_WINNT
+#endif
#define _WIN32_WINDOWS 0x0501
#define _WIN32_WINNT 0x0501
#include <SFML/Window/Win32/WindowImplWin32.hpp>
-#include <SFML/Window/WindowSettings.hpp>
#include <SFML/Window/WindowStyle.hpp>
#include <GL/gl.h>
-#include <SFML/Window/glext/wglext.h>
-#include <SFML/Window/glext/glext.h>
-#include <iostream>
+#include <SFML/System/Err.hpp>
+#include <SFML/System/Utf.hpp>
#include <vector>
// MinGW lacks the definition of some Win32 constants
@@ -48,653 +52,376 @@
#endif
+namespace
+{
+ unsigned int windowCount = 0;
+ const char* classNameA = "SFML_Window";
+ const wchar_t* classNameW = L"SFML_Window";
+ sf::priv::WindowImplWin32* fullscreenWindow = NULL;
+}
+
namespace sf
{
namespace priv
{
////////////////////////////////////////////////////////////
-// Static member data
-////////////////////////////////////////////////////////////
-unsigned int WindowImplWin32::ourWindowCount = 0;
-const char* WindowImplWin32::ourClassNameA = "SFML_Window";
-const wchar_t* WindowImplWin32::ourClassNameW = L"SFML_Window";
-WindowImplWin32* WindowImplWin32::ourFullscreenWindow = NULL;
-
-
-////////////////////////////////////////////////////////////
-/// Default constructor
-/// (creates a dummy window to provide a valid OpenGL context)
-////////////////////////////////////////////////////////////
-WindowImplWin32::WindowImplWin32() :
-myHandle (NULL),
-myCallback (0),
-myCursor (NULL),
-myIcon (NULL),
-myKeyRepeatEnabled(true),
-myIsCursorIn (false)
-{
- // Register the window class at first call
- if (ourWindowCount == 0)
- RegisterWindowClass();
-
- // Use small dimensions
- myWidth = 1;
- myHeight = 1;
-
- // Create a dummy window (disabled and hidden)
- if (HasUnicodeSupport())
- {
- myHandle = CreateWindowW(ourClassNameW, L"", WS_POPUP | WS_DISABLED, 0, 0, myWidth, myHeight, NULL, NULL, GetModuleHandle(NULL), NULL);
- }
- else
- {
- myHandle = CreateWindowA(ourClassNameA, "", WS_POPUP | WS_DISABLED, 0, 0, myWidth, myHeight, NULL, NULL, GetModuleHandle(NULL), NULL);
- }
- ShowWindow(myHandle, SW_HIDE);
-
- // Create the rendering context
- if (myHandle)
- {
- WindowSettings Params(0, 0, 0);
- CreateContext(VideoMode(myWidth, myHeight, 32), Params);
-
- // Don't activate by default
- SetActive(false);
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Create the window implementation from an existing control
-////////////////////////////////////////////////////////////
-WindowImplWin32::WindowImplWin32(WindowHandle Handle, WindowSettings& Params) :
-myHandle (NULL),
-myCallback (0),
-myCursor (NULL),
-myIcon (NULL),
-myKeyRepeatEnabled(true),
-myIsCursorIn (false)
+WindowImplWin32::WindowImplWin32(WindowHandle handle) :
+m_handle (handle),
+m_callback (0),
+m_cursor (NULL),
+m_icon (NULL),
+m_keyRepeatEnabled(true),
+m_lastSize (0, 0),
+m_resizing (false),
+m_surrogate (0)
{
- // Save window handle
- myHandle = static_cast<HWND>(Handle);
-
- if (myHandle)
+ if (m_handle)
{
- // Get window client size
- RECT Rect;
- GetClientRect(myHandle, &Rect);
- myWidth = Rect.right - Rect.left;
- myHeight = Rect.bottom - Rect.top;
-
- // Create the rendering context
- VideoMode Mode(myWidth, myHeight, VideoMode::GetDesktopMode().BitsPerPixel);
- CreateContext(Mode, Params);
-
// We change the event procedure of the control (it is important to save the old one)
- SetWindowLongPtr(myHandle, GWLP_USERDATA, reinterpret_cast<long>(this));
- myCallback = SetWindowLongPtr(myHandle, GWLP_WNDPROC, reinterpret_cast<long>(&WindowImplWin32::GlobalOnEvent));
+ SetWindowLongPtr(m_handle, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this));
+ m_callback = SetWindowLongPtr(m_handle, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(&WindowImplWin32::globalOnEvent));
}
}
////////////////////////////////////////////////////////////
-/// Create the window implementation
-////////////////////////////////////////////////////////////
-WindowImplWin32::WindowImplWin32(VideoMode Mode, const std::string& Title, unsigned long WindowStyle, WindowSettings& Params) :
-myHandle (NULL),
-myCallback (0),
-myCursor (NULL),
-myIcon (NULL),
-myKeyRepeatEnabled(true),
-myIsCursorIn (false)
+WindowImplWin32::WindowImplWin32(VideoMode mode, const String& title, Uint32 style, const ContextSettings& /*settings*/) :
+m_handle (NULL),
+m_callback (0),
+m_cursor (NULL),
+m_icon (NULL),
+m_keyRepeatEnabled(true),
+m_lastSize (mode.width, mode.height),
+m_resizing (false),
+m_surrogate (0)
{
// Register the window class at first call
- if (ourWindowCount == 0)
- RegisterWindowClass();
+ if (windowCount == 0)
+ registerWindowClass();
// Compute position and size
- HDC ScreenDC = GetDC(NULL);
- int Left = (GetDeviceCaps(ScreenDC, HORZRES) - Mode.Width) / 2;
- int Top = (GetDeviceCaps(ScreenDC, VERTRES) - Mode.Height) / 2;
- int Width = myWidth = Mode.Width;
- int Height = myHeight = Mode.Height;
- ReleaseDC(NULL, ScreenDC);
+ HDC screenDC = GetDC(NULL);
+ int left = (GetDeviceCaps(screenDC, HORZRES) - static_cast<int>(mode.width)) / 2;
+ int top = (GetDeviceCaps(screenDC, VERTRES) - static_cast<int>(mode.height)) / 2;
+ int width = mode.width;
+ int height = mode.height;
+ ReleaseDC(NULL, screenDC);
// Choose the window style according to the Style parameter
- DWORD Win32Style = WS_VISIBLE;
- if (WindowStyle == Style::None)
+ DWORD win32Style = WS_VISIBLE;
+ if (style == Style::None)
{
- Win32Style |= WS_POPUP;
+ win32Style |= WS_POPUP;
}
else
{
- if (WindowStyle & Style::Titlebar) Win32Style |= WS_CAPTION | WS_MINIMIZEBOX;
- if (WindowStyle & Style::Resize) Win32Style |= WS_THICKFRAME | WS_MAXIMIZEBOX;
- if (WindowStyle & Style::Close) Win32Style |= WS_SYSMENU;
+ if (style & Style::Titlebar) win32Style |= WS_CAPTION | WS_MINIMIZEBOX;
+ if (style & Style::Resize) win32Style |= WS_THICKFRAME | WS_MAXIMIZEBOX;
+ if (style & Style::Close) win32Style |= WS_SYSMENU;
}
// In windowed mode, adjust width and height so that window will have the requested client area
- bool Fullscreen = (WindowStyle & Style::Fullscreen) != 0;
- if (!Fullscreen)
+ bool fullscreen = (style & Style::Fullscreen) != 0;
+ if (!fullscreen)
{
- RECT Rect = {0, 0, Width, Height};
- AdjustWindowRect(&Rect, Win32Style, false);
- Width = Rect.right - Rect.left;
- Height = Rect.bottom - Rect.top;
+ RECT rectangle = {0, 0, width, height};
+ AdjustWindowRect(&rectangle, win32Style, false);
+ width = rectangle.right - rectangle.left;
+ height = rectangle.bottom - rectangle.top;
}
// Create the window
- if (HasUnicodeSupport())
+ if (hasUnicodeSupport())
{
- wchar_t WTitle[256];
- int NbChars = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, Title.c_str(), static_cast<int>(Title.size()), WTitle, sizeof(WTitle) / sizeof(*WTitle));
- WTitle[NbChars] = L'\0';
- myHandle = CreateWindowW(ourClassNameW, WTitle, Win32Style, Left, Top, Width, Height, NULL, NULL, GetModuleHandle(NULL), this);
+ m_handle = CreateWindowW(classNameW, title.toWideString().c_str(), win32Style, left, top, width, height, NULL, NULL, GetModuleHandle(NULL), this);
}
else
{
- myHandle = CreateWindowA(ourClassNameA, Title.c_str(), Win32Style, Left, Top, Width, Height, NULL, NULL, GetModuleHandle(NULL), this);
+ m_handle = CreateWindowA(classNameA, title.toAnsiString().c_str(), win32Style, left, top, width, height, NULL, NULL, GetModuleHandle(NULL), this);
}
- // Switch to fullscreen if requested
- if (Fullscreen)
- SwitchToFullscreen(Mode);
+ // By default, the OS limits the size of the window the the desktop size,
+ // we have to resize it after creation to apply the real size
+ setSize(Vector2u(mode.width, mode.height));
- // Create the rendering context
- if (myHandle)
- CreateContext(Mode, Params);
+ // Switch to fullscreen if requested
+ if (fullscreen)
+ switchToFullscreen(mode);
// Increment window count
- ourWindowCount++;
-
- // Get the actual size of the window, which can be smaller even after the call to AdjustWindowRect
- // This happens when the window is bigger than the desktop
- RECT ActualRect;
- GetClientRect(myHandle, &ActualRect);
- myWidth = ActualRect.right - ActualRect.left;
- myHeight = ActualRect.bottom - ActualRect.top;
+ windowCount++;
}
////////////////////////////////////////////////////////////
-/// Destructor
-////////////////////////////////////////////////////////////
WindowImplWin32::~WindowImplWin32()
{
// Destroy the custom icon, if any
- if (myIcon)
- DestroyIcon(myIcon);
+ if (m_icon)
+ DestroyIcon(m_icon);
- if (!myCallback)
+ if (!m_callback)
{
// Destroy the window
- if (myHandle)
- DestroyWindow(myHandle);
+ if (m_handle)
+ DestroyWindow(m_handle);
// Decrement the window count
- ourWindowCount--;
+ windowCount--;
// Unregister window class if we were the last window
- if (ourWindowCount == 0)
+ if (windowCount == 0)
{
- if (HasUnicodeSupport())
+ if (hasUnicodeSupport())
{
- UnregisterClassW(ourClassNameW, GetModuleHandle(NULL));
+ UnregisterClassW(classNameW, GetModuleHandle(NULL));
}
else
{
- UnregisterClassA(ourClassNameA, GetModuleHandle(NULL));
+ UnregisterClassA(classNameA, GetModuleHandle(NULL));
}
}
}
else
{
// The window is external : remove the hook on its message callback
- SetWindowLongPtr(myHandle, GWLP_WNDPROC, myCallback);
+ SetWindowLongPtr(m_handle, GWLP_WNDPROC, m_callback);
}
}
////////////////////////////////////////////////////////////
-/// Check if there's an active context on the current thread
-////////////////////////////////////////////////////////////
-bool WindowImplWin32::IsContextActive()
+WindowHandle WindowImplWin32::getSystemHandle() const
{
- return wglGetCurrentContext() != NULL;
+ return m_handle;
}
////////////////////////////////////////////////////////////
-/// /see WindowImpl::ProcessEvents
-////////////////////////////////////////////////////////////
-void WindowImplWin32::ProcessEvents()
+void WindowImplWin32::processEvents()
{
- // We update the window only if we own it
- if (!myCallback)
+ // We process the window events only if we own it
+ if (!m_callback)
{
- MSG Message;
- while (PeekMessage(&Message, NULL, 0, 0, PM_REMOVE))
+ MSG message;
+ while (PeekMessage(&message, NULL, 0, 0, PM_REMOVE))
{
- TranslateMessage(&Message);
- DispatchMessage(&Message);
+ TranslateMessage(&message);
+ DispatchMessage(&message);
}
}
}
////////////////////////////////////////////////////////////
-/// /see WindowImpl::Display
-////////////////////////////////////////////////////////////
-void WindowImplWin32::Display()
+Vector2i WindowImplWin32::getPosition() const
{
- if (myDeviceContext && myGLContext)
- SwapBuffers(myDeviceContext);
-}
+ RECT rect;
+ GetWindowRect(m_handle, &rect);
-
-////////////////////////////////////////////////////////////
-/// /see WindowImpl::SetActive
-////////////////////////////////////////////////////////////
-void WindowImplWin32::SetActive(bool Active) const
-{
- if (Active)
- {
- if (myDeviceContext && myGLContext && (wglGetCurrentContext() != myGLContext))
- wglMakeCurrent(myDeviceContext, myGLContext);
- }
- else
- {
- if (wglGetCurrentContext() == myGLContext)
- wglMakeCurrent(NULL, NULL);
- }
+ return Vector2i(rect.left, rect.top);
}
////////////////////////////////////////////////////////////
-/// /see WindowImpl::UseVerticalSync
-////////////////////////////////////////////////////////////
-void WindowImplWin32::UseVerticalSync(bool Enabled)
-{
- PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = reinterpret_cast<PFNWGLSWAPINTERVALEXTPROC>(wglGetProcAddress("wglSwapIntervalEXT"));
- if (wglSwapIntervalEXT)
- wglSwapIntervalEXT(Enabled ? 1 : 0);
-}
-
-
-////////////////////////////////////////////////////////////
-/// /see WindowImpl::ShowMouseCursor
-////////////////////////////////////////////////////////////
-void WindowImplWin32::ShowMouseCursor(bool Show)
+void WindowImplWin32::setPosition(const Vector2i& position)
{
- if (Show)
- myCursor = LoadCursor(NULL, IDC_ARROW);
- else
- myCursor = NULL;
-
- SetCursor(myCursor);
+ SetWindowPos(m_handle, NULL, position.x, position.y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
}
////////////////////////////////////////////////////////////
-/// /see WindowImpl::SetCursorPosition
-////////////////////////////////////////////////////////////
-void WindowImplWin32::SetCursorPosition(unsigned int Left, unsigned int Top)
+Vector2u WindowImplWin32::getSize() const
{
- POINT Pos = {Left, Top};
- ClientToScreen(myHandle, &Pos);
- SetCursorPos(Pos.x, Pos.y);
-}
-
+ RECT rect;
+ GetClientRect(m_handle, &rect);
-////////////////////////////////////////////////////////////
-/// /see WindowImpl::SetPosition
-////////////////////////////////////////////////////////////
-void WindowImplWin32::SetPosition(int Left, int Top)
-{
- SetWindowPos(myHandle, NULL, Left, Top, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
+ return Vector2u(rect.right - rect.left, rect.bottom - rect.top);
}
////////////////////////////////////////////////////////////
-/// /see WindowImpl::SetSize
-////////////////////////////////////////////////////////////
-void WindowImplWin32::SetSize(unsigned int Width, unsigned int Height)
+void WindowImplWin32::setSize(const Vector2u& size)
{
// SetWindowPos wants the total size of the window (including title bar and borders),
// so we have to compute it
- RECT Rect = {0, 0, Width, Height};
- AdjustWindowRect(&Rect, GetWindowLong(myHandle, GWL_STYLE), false);
- Width = Rect.right - Rect.left;
- Height = Rect.bottom - Rect.top;
-
- SetWindowPos(myHandle, NULL, 0, 0, Width, Height, SWP_NOMOVE | SWP_NOZORDER);
-}
+ RECT rectangle = {0, 0, static_cast<long>(size.x), static_cast<long>(size.y)};
+ AdjustWindowRect(&rectangle, GetWindowLong(m_handle, GWL_STYLE), false);
+ int width = rectangle.right - rectangle.left;
+ int height = rectangle.bottom - rectangle.top;
-
-////////////////////////////////////////////////////////////
-/// /see WindowImpl::Show
-////////////////////////////////////////////////////////////
-void WindowImplWin32::Show(bool State)
-{
- ShowWindow(myHandle, State ? SW_SHOW : SW_HIDE);
+ SetWindowPos(m_handle, NULL, 0, 0, width, height, SWP_NOMOVE | SWP_NOZORDER);
}
////////////////////////////////////////////////////////////
-/// /see WindowImpl::EnableKeyRepeat
-////////////////////////////////////////////////////////////
-void WindowImplWin32::EnableKeyRepeat(bool Enabled)
+void WindowImplWin32::setTitle(const String& title)
{
- myKeyRepeatEnabled = Enabled;
+ if (hasUnicodeSupport())
+ {
+ SetWindowTextW(m_handle, title.toWideString().c_str());
+ }
+ else
+ {
+ SetWindowTextA(m_handle, title.toAnsiString().c_str());
+ }
}
////////////////////////////////////////////////////////////
-/// /see WindowImpl::SetIcon
-////////////////////////////////////////////////////////////
-void WindowImplWin32::SetIcon(unsigned int Width, unsigned int Height, const Uint8* Pixels)
+void WindowImplWin32::setIcon(unsigned int width, unsigned int height, const Uint8* pixels)
{
// First destroy the previous one
- if (myIcon)
- DestroyIcon(myIcon);
+ if (m_icon)
+ DestroyIcon(m_icon);
- // Windows wants BGRA pixels : swap red and blue channels
- std::vector<Uint8> IconPixels(Width * Height * 4);
- for (std::size_t i = 0; i < IconPixels.size() / 4; ++i)
+ // Windows wants BGRA pixels: swap red and blue channels
+ std::vector<Uint8> iconPixels(width * height * 4);
+ for (std::size_t i = 0; i < iconPixels.size() / 4; ++i)
{
- IconPixels[i * 4 + 0] = Pixels[i * 4 + 2];
- IconPixels[i * 4 + 1] = Pixels[i * 4 + 1];
- IconPixels[i * 4 + 2] = Pixels[i * 4 + 0];
- IconPixels[i * 4 + 3] = Pixels[i * 4 + 3];
+ iconPixels[i * 4 + 0] = pixels[i * 4 + 2];
+ iconPixels[i * 4 + 1] = pixels[i * 4 + 1];
+ iconPixels[i * 4 + 2] = pixels[i * 4 + 0];
+ iconPixels[i * 4 + 3] = pixels[i * 4 + 3];
}
- // Create the icon from the pixels array
- myIcon = CreateIcon(GetModuleHandle(NULL), Width, Height, 1, 32, NULL, &IconPixels[0]);
+ // Create the icon from the pixel array
+ m_icon = CreateIcon(GetModuleHandle(NULL), width, height, 1, 32, NULL, &iconPixels[0]);
// Set it as both big and small icon of the window
- if (myIcon)
+ if (m_icon)
{
- SendMessage(myHandle, WM_SETICON, ICON_BIG, (LPARAM)myIcon);
- SendMessage(myHandle, WM_SETICON, ICON_SMALL, (LPARAM)myIcon);
+ SendMessage(m_handle, WM_SETICON, ICON_BIG, (LPARAM)m_icon);
+ SendMessage(m_handle, WM_SETICON, ICON_SMALL, (LPARAM)m_icon);
}
else
{
- std::cerr << "Failed to set the window's icon" << std::endl;
+ err() << "Failed to set the window's icon" << std::endl;
}
}
////////////////////////////////////////////////////////////
-/// Register the window class
-////////////////////////////////////////////////////////////
-void WindowImplWin32::RegisterWindowClass()
+void WindowImplWin32::setVisible(bool visible)
{
- if (HasUnicodeSupport())
- {
- WNDCLASSW WindowClass;
- WindowClass.style = 0;
- WindowClass.lpfnWndProc = &WindowImplWin32::GlobalOnEvent;
- WindowClass.cbClsExtra = 0;
- WindowClass.cbWndExtra = 0;
- WindowClass.hInstance = GetModuleHandle(NULL);
- WindowClass.hIcon = NULL;
- WindowClass.hCursor = 0;
- WindowClass.hbrBackground = 0;
- WindowClass.lpszMenuName = NULL;
- WindowClass.lpszClassName = ourClassNameW;
- RegisterClassW(&WindowClass);
- }
- else
- {
- WNDCLASSA WindowClass;
- WindowClass.style = 0;
- WindowClass.lpfnWndProc = &WindowImplWin32::GlobalOnEvent;
- WindowClass.cbClsExtra = 0;
- WindowClass.cbWndExtra = 0;
- WindowClass.hInstance = GetModuleHandle(NULL);
- WindowClass.hIcon = NULL;
- WindowClass.hCursor = 0;
- WindowClass.hbrBackground = 0;
- WindowClass.lpszMenuName = NULL;
- WindowClass.lpszClassName = ourClassNameA;
- RegisterClassA(&WindowClass);
- }
+ ShowWindow(m_handle, visible ? SW_SHOW : SW_HIDE);
}
////////////////////////////////////////////////////////////
-/// Switch to fullscreen mode
-////////////////////////////////////////////////////////////
-void WindowImplWin32::SwitchToFullscreen(const VideoMode& Mode)
+void WindowImplWin32::setMouseCursorVisible(bool visible)
{
- DEVMODE DevMode;
- DevMode.dmSize = sizeof(DEVMODE);
- DevMode.dmPelsWidth = Mode.Width;
- DevMode.dmPelsHeight = Mode.Height;
- DevMode.dmBitsPerPel = Mode.BitsPerPixel;
- DevMode.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL;
-
- // Apply fullscreen mode
- if (ChangeDisplaySettings(&DevMode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
- {
- std::cerr << "Failed to change display mode for fullscreen" << std::endl;
- return;
- }
-
- // Make the window flags compatible with fullscreen mode
- SetWindowLong(myHandle, GWL_STYLE, WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS);
- SetWindowLong(myHandle, GWL_EXSTYLE, WS_EX_APPWINDOW);
-
- // Resize the window so that it fits the entire screen
- SetWindowPos(myHandle, HWND_TOP, 0, 0, Mode.Width, Mode.Height, SWP_FRAMECHANGED);
- ShowWindow(myHandle, SW_SHOW);
+ if (visible)
+ m_cursor = LoadCursor(NULL, IDC_ARROW);
+ else
+ m_cursor = NULL;
- // Set "this" as the current fullscreen window
- ourFullscreenWindow = this;
+ SetCursor(m_cursor);
}
////////////////////////////////////////////////////////////
-/// Construct the context from graphics settings
-////////////////////////////////////////////////////////////
-void WindowImplWin32::CreateContext(const VideoMode& Mode, WindowSettings& Params)
+void WindowImplWin32::setKeyRepeatEnabled(bool enabled)
{
- // Get the device context attached to the window
- myDeviceContext = GetDC(myHandle);
- if (myDeviceContext == NULL)
- {
- std::cerr << "Failed to get device context of window -- cannot create OpenGL context" << std::endl;
- return;
- }
-
- // Let's find a suitable pixel format -- first try with antialiasing
- int BestFormat = 0;
- if (Params.AntialiasingLevel > 0)
- {
- // Get the wglChoosePixelFormatARB function (it is an extension)
- PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = reinterpret_cast<PFNWGLCHOOSEPIXELFORMATARBPROC>(wglGetProcAddress("wglChoosePixelFormatARB"));
- if (wglChoosePixelFormatARB)
- {
- // Define the basic attributes we want for our window
- int IntAttributes[] =
- {
- WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
- WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
- WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
- WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
- WGL_SAMPLE_BUFFERS_ARB, (Params.AntialiasingLevel ? GL_TRUE : GL_FALSE),
- WGL_SAMPLES_ARB, Params.AntialiasingLevel,
- 0, 0
- };
-
- // Let's check how many formats are supporting our requirements
- int Formats[128];
- UINT NbFormats;
- float FloatAttributes[] = {0, 0};
- bool IsValid = wglChoosePixelFormatARB(myDeviceContext, IntAttributes, FloatAttributes, sizeof(Formats) / sizeof(*Formats), Formats, &NbFormats) != 0;
- if (!IsValid || (NbFormats == 0))
- {
- if (Params.AntialiasingLevel > 2)
- {
- // No format matching our needs : reduce the multisampling level
- std::cerr << "Failed to find a pixel format supporting "
- << Params.AntialiasingLevel << " antialiasing levels ; trying with 2 levels" << std::endl;
-
- Params.AntialiasingLevel = IntAttributes[11] = 2;
- IsValid = wglChoosePixelFormatARB(myDeviceContext, IntAttributes, FloatAttributes, sizeof(Formats) / sizeof(*Formats), Formats, &NbFormats) != 0;
- }
+ m_keyRepeatEnabled = enabled;
+}
- if (!IsValid || (NbFormats == 0))
- {
- // Cannot find any pixel format supporting multisampling ; disabling antialiasing
- std::cerr << "Failed to find a pixel format supporting antialiasing ; antialiasing will be disabled" << std::endl;
- Params.AntialiasingLevel = 0;
- }
- }
- // Get the best format among the returned ones
- if (IsValid && (NbFormats > 0))
- {
- int BestScore = 0xFFFF;
- for (UINT i = 0; i < NbFormats; ++i)
- {
- // Get the current format's attributes
- PIXELFORMATDESCRIPTOR Attribs;
- Attribs.nSize = sizeof(PIXELFORMATDESCRIPTOR);
- Attribs.nVersion = 1;
- DescribePixelFormat(myDeviceContext, Formats[i], sizeof(PIXELFORMATDESCRIPTOR), &Attribs);
-
- // Evaluate the current configuration
- int Color = Attribs.cRedBits + Attribs.cGreenBits + Attribs.cBlueBits + Attribs.cAlphaBits;
- int Score = EvaluateConfig(Mode, Params, Color, Attribs.cDepthBits, Attribs.cStencilBits, Params.AntialiasingLevel);
-
- // Keep it if it's better than the current best
- if (Score < BestScore)
- {
- BestScore = Score;
- BestFormat = Formats[i];
- }
- }
- }
- }
- else
- {
- // wglChoosePixelFormatARB not supported ; disabling antialiasing
- std::cerr << "Antialiasing is not supported ; it will be disabled" << std::endl;
- Params.AntialiasingLevel = 0;
- }
+////////////////////////////////////////////////////////////
+void WindowImplWin32::registerWindowClass()
+{
+ if (hasUnicodeSupport())
+ {
+ WNDCLASSW windowClass;
+ windowClass.style = 0;
+ windowClass.lpfnWndProc = &WindowImplWin32::globalOnEvent;
+ windowClass.cbClsExtra = 0;
+ windowClass.cbWndExtra = 0;
+ windowClass.hInstance = GetModuleHandle(NULL);
+ windowClass.hIcon = NULL;
+ windowClass.hCursor = 0;
+ windowClass.hbrBackground = 0;
+ windowClass.lpszMenuName = NULL;
+ windowClass.lpszClassName = classNameW;
+ RegisterClassW(&windowClass);
}
-
- // Find a pixel format with no antialiasing, if not needed or not supported
- if (BestFormat == 0)
+ else
{
- // Setup a pixel format descriptor from the rendering settings
- PIXELFORMATDESCRIPTOR PixelDescriptor;
- ZeroMemory(&PixelDescriptor, sizeof(PIXELFORMATDESCRIPTOR));
- PixelDescriptor.nSize = sizeof(PIXELFORMATDESCRIPTOR);
- PixelDescriptor.nVersion = 1;
- PixelDescriptor.iLayerType = PFD_MAIN_PLANE;
- PixelDescriptor.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
- PixelDescriptor.iPixelType = PFD_TYPE_RGBA;
- PixelDescriptor.cColorBits = static_cast<BYTE>(Mode.BitsPerPixel);
- PixelDescriptor.cDepthBits = static_cast<BYTE>(Params.DepthBits);
- PixelDescriptor.cStencilBits = static_cast<BYTE>(Params.StencilBits);
- PixelDescriptor.cAlphaBits = Mode.BitsPerPixel == 32 ? 8 : 0;
-
- // Get the pixel format that best matches our requirements
- BestFormat = ChoosePixelFormat(myDeviceContext, &PixelDescriptor);
- if (BestFormat == 0)
- {
- std::cerr << "Failed to find a suitable pixel format for device context -- cannot create OpenGL context" << std::endl;
- return;
- }
+ WNDCLASSA windowClass;
+ windowClass.style = 0;
+ windowClass.lpfnWndProc = &WindowImplWin32::globalOnEvent;
+ windowClass.cbClsExtra = 0;
+ windowClass.cbWndExtra = 0;
+ windowClass.hInstance = GetModuleHandle(NULL);
+ windowClass.hIcon = NULL;
+ windowClass.hCursor = 0;
+ windowClass.hbrBackground = 0;
+ windowClass.lpszMenuName = NULL;
+ windowClass.lpszClassName = classNameA;
+ RegisterClassA(&windowClass);
}
+}
- // Extract the depth and stencil bits from the chosen format
- PIXELFORMATDESCRIPTOR ActualFormat;
- ActualFormat.nSize = sizeof(PIXELFORMATDESCRIPTOR);
- ActualFormat.nVersion = 1;
- DescribePixelFormat(myDeviceContext, BestFormat, sizeof(PIXELFORMATDESCRIPTOR), &ActualFormat);
- Params.DepthBits = ActualFormat.cDepthBits;
- Params.StencilBits = ActualFormat.cStencilBits;
- // Set the chosen pixel format
- if (!SetPixelFormat(myDeviceContext, BestFormat, &ActualFormat))
- {
- std::cerr << "Failed to set pixel format for device context -- cannot create OpenGL context" << std::endl;
- return;
- }
+////////////////////////////////////////////////////////////
+void WindowImplWin32::switchToFullscreen(const VideoMode& mode)
+{
+ DEVMODE devMode;
+ devMode.dmSize = sizeof(devMode);
+ devMode.dmPelsWidth = mode.width;
+ devMode.dmPelsHeight = mode.height;
+ devMode.dmBitsPerPel = mode.bitsPerPixel;
+ devMode.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL;
- // Create the OpenGL context from the device context
- myGLContext = wglCreateContext(myDeviceContext);
- if (myGLContext == NULL)
+ // Apply fullscreen mode
+ if (ChangeDisplaySettings(&devMode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
{
- std::cerr << "Failed to create an OpenGL context for this window" << std::endl;
+ err() << "Failed to change display mode for fullscreen" << std::endl;
return;
}
- // Share display lists with other contexts
- HGLRC CurrentContext = wglGetCurrentContext();
- if (CurrentContext)
- wglShareLists(CurrentContext, myGLContext);
+ // Make the window flags compatible with fullscreen mode
+ SetWindowLong(m_handle, GWL_STYLE, WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS);
+ SetWindowLong(m_handle, GWL_EXSTYLE, WS_EX_APPWINDOW);
- // Activate the context
- SetActive(true);
+ // Resize the window so that it fits the entire screen
+ SetWindowPos(m_handle, HWND_TOP, 0, 0, mode.width, mode.height, SWP_FRAMECHANGED);
+ ShowWindow(m_handle, SW_SHOW);
- // Enable multisampling
- if (Params.AntialiasingLevel > 0)
- glEnable(GL_MULTISAMPLE_ARB);
+ // Set "this" as the current fullscreen window
+ fullscreenWindow = this;
}
////////////////////////////////////////////////////////////
-/// Free all the graphical resources attached to the window
-////////////////////////////////////////////////////////////
-void WindowImplWin32::Cleanup()
+void WindowImplWin32::cleanup()
{
// Restore the previous video mode (in case we were running in fullscreen)
- if (ourFullscreenWindow == this)
+ if (fullscreenWindow == this)
{
ChangeDisplaySettings(NULL, 0);
- ourFullscreenWindow = NULL;
+ fullscreenWindow = NULL;
}
// Unhide the mouse cursor (in case it was hidden)
- ShowMouseCursor(true);
-
- // Destroy the OpenGL context
- if (myGLContext)
- {
- // Unbind the context before destroying it
- SetActive(false);
-
- wglDeleteContext(myGLContext);
- myGLContext = NULL;
- }
- if (myDeviceContext)
- {
- ReleaseDC(myHandle, myDeviceContext);
- myDeviceContext = NULL;
- }
+ setMouseCursorVisible(true);
}
////////////////////////////////////////////////////////////
-/// Process a Win32 event
-////////////////////////////////////////////////////////////
-void WindowImplWin32::ProcessEvent(UINT Message, WPARAM WParam, LPARAM LParam)
+void WindowImplWin32::processEvent(UINT message, WPARAM wParam, LPARAM lParam)
{
// Don't process any message until window is created
- if (myHandle == NULL)
+ if (m_handle == NULL)
return;
- switch (Message)
+ switch (message)
{
// Destroy event
case WM_DESTROY :
{
// Here we must cleanup resources !
- Cleanup();
+ cleanup();
break;
}
@@ -702,8 +429,8 @@ void WindowImplWin32::ProcessEvent(UINT Message, WPARAM WParam, LPARAM LParam)
case WM_SETCURSOR :
{
// The mouse has moved, if the cursor is in our window we must refresh the cursor
- if (LOWORD(LParam) == HTCLIENT)
- SetCursor(myCursor);
+ if (LOWORD(lParam) == HTCLIENT)
+ SetCursor(m_cursor);
break;
}
@@ -711,56 +438,120 @@ void WindowImplWin32::ProcessEvent(UINT Message, WPARAM WParam, LPARAM LParam)
// Close event
case WM_CLOSE :
{
- Event Evt;
- Evt.Type = Event::Closed;
- SendEvent(Evt);
+ Event event;
+ event.type = Event::Closed;
+ pushEvent(event);
break;
}
// Resize event
case WM_SIZE :
{
- // Update window size
- RECT Rect;
- GetClientRect(myHandle, &Rect);
- myWidth = Rect.right - Rect.left;
- myHeight = Rect.bottom - Rect.top;
-
- Event Evt;
- Evt.Type = Event::Resized;
- Evt.Size.Width = myWidth;
- Evt.Size.Height = myHeight;
- SendEvent(Evt);
+ // Consider only events triggered by a maximize or a un-maximize
+ if (wParam != SIZE_MINIMIZED && !m_resizing && m_lastSize != getSize())
+ {
+ // Update the last handled size
+ m_lastSize = getSize();
+
+ // Push a resize event
+ Event event;
+ event.type = Event::Resized;
+ event.size.width = m_lastSize.x;
+ event.size.height = m_lastSize.y;
+ pushEvent(event);
+ }
+ break;
+ }
+
+ // Start resizing
+ case WM_ENTERSIZEMOVE:
+ {
+ m_resizing = true;
+ break;
+ }
+
+ // Stop resizing
+ case WM_EXITSIZEMOVE:
+ {
+ m_resizing = false;
+
+ // Ignore cases where the window has only been moved
+ if(m_lastSize != getSize())
+ {
+ // Update the last handled size
+ m_lastSize = getSize();
+
+ // Push a resize event
+ Event event;
+ event.type = Event::Resized;
+ event.size.width = m_lastSize.x;
+ event.size.height = m_lastSize.y;
+ pushEvent(event);
+ }
+ break;
+ }
+
+ // The system request the min/max window size and position
+ case WM_GETMINMAXINFO :
+ {
+ // We override the returned information to remove the default limit
+ // (the OS doesn't allow windows bigger than the desktop by default)
+ MINMAXINFO* info = reinterpret_cast<MINMAXINFO*>(lParam);
+ info->ptMaxTrackSize.x = 50000;
+ info->ptMaxTrackSize.y = 50000;
break;
}
// Gain focus event
case WM_SETFOCUS :
{
- Event Evt;
- Evt.Type = Event::GainedFocus;
- SendEvent(Evt);
+ Event event;
+ event.type = Event::GainedFocus;
+ pushEvent(event);
break;
}
// Lost focus event
case WM_KILLFOCUS :
{
- Event Evt;
- Evt.Type = Event::LostFocus;
- SendEvent(Evt);
+ Event event;
+ event.type = Event::LostFocus;
+ pushEvent(event);
break;
}
// Text event
case WM_CHAR :
{
- if (myKeyRepeatEnabled || ((LParam & (1 << 30)) == 0))
+ if (m_keyRepeatEnabled || ((lParam & (1 << 30)) == 0))
{
- Event Evt;
- Evt.Type = Event::TextEntered;
- Evt.Text.Unicode = static_cast<Uint32>(WParam);
- SendEvent(Evt);
+ // Get the code of the typed character
+ Uint32 character = static_cast<Uint32>(wParam);
+
+ // Check if it is the first part of a surrogate pair, or a regular character
+ if ((character >= 0xD800) && (character <= 0xDBFF))
+ {
+ // First part of a surrogate pair: store it and wait for the second one
+ m_surrogate = static_cast<Uint16>(character);
+ }
+ else
+ {
+
+ // Check if it is the second part of a surrogate pair, or a regular character
+ if ((character >= 0xDC00) && (character <= 0xDFFF))
+ {
+ // Convert the UTF-16 surrogate pair to a single UTF-32 value
+ Uint16 utf16[] = {m_surrogate, static_cast<Uint16>(character)};
+ sf::Utf16::toUtf32(utf16, utf16 + 2, &character);
+ m_surrogate = 0;
+ }
+
+ // Send a TextEntered event
+ Event event;
+ event.type = Event::TextEntered;
+ event.text.unicode = character;
+ pushEvent(event);
+ }
}
break;
}
@@ -769,15 +560,16 @@ void WindowImplWin32::ProcessEvent(UINT Message, WPARAM WParam, LPARAM LParam)
case WM_KEYDOWN :
case WM_SYSKEYDOWN :
{
- if (myKeyRepeatEnabled || ((HIWORD(LParam) & KF_REPEAT) == 0))
+ if (m_keyRepeatEnabled || ((HIWORD(lParam) & KF_REPEAT) == 0))
{
- Event Evt;
- Evt.Type = Event::KeyPressed;
- Evt.Key.Alt = HIWORD(GetAsyncKeyState(VK_MENU)) != 0;
- Evt.Key.Control = HIWORD(GetAsyncKeyState(VK_CONTROL)) != 0;
- Evt.Key.Shift = HIWORD(GetAsyncKeyState(VK_SHIFT)) != 0;
- Evt.Key.Code = VirtualKeyCodeToSF(WParam, LParam);
- SendEvent(Evt);
+ Event event;
+ event.type = Event::KeyPressed;
+ event.key.alt = HIWORD(GetAsyncKeyState(VK_MENU)) != 0;
+ event.key.control = HIWORD(GetAsyncKeyState(VK_CONTROL)) != 0;
+ event.key.shift = HIWORD(GetAsyncKeyState(VK_SHIFT)) != 0;
+ event.key.system = HIWORD(GetAsyncKeyState(VK_LWIN)) || HIWORD(GetAsyncKeyState(VK_RWIN));
+ event.key.code = virtualKeyCodeToSF(wParam, lParam);
+ pushEvent(event);
}
break;
}
@@ -786,301 +578,315 @@ void WindowImplWin32::ProcessEvent(UINT Message, WPARAM WParam, LPARAM LParam)
case WM_KEYUP :
case WM_SYSKEYUP :
{
- Event Evt;
- Evt.Type = Event::KeyReleased;
- Evt.Key.Alt = HIWORD(GetAsyncKeyState(VK_MENU)) != 0;
- Evt.Key.Control = HIWORD(GetAsyncKeyState(VK_CONTROL)) != 0;
- Evt.Key.Shift = HIWORD(GetAsyncKeyState(VK_SHIFT)) != 0;
- Evt.Key.Code = VirtualKeyCodeToSF(WParam, LParam);
- SendEvent(Evt);
-
+ Event event;
+ event.type = Event::KeyReleased;
+ event.key.alt = HIWORD(GetAsyncKeyState(VK_MENU)) != 0;
+ event.key.control = HIWORD(GetAsyncKeyState(VK_CONTROL)) != 0;
+ event.key.shift = HIWORD(GetAsyncKeyState(VK_SHIFT)) != 0;
+ event.key.system = HIWORD(GetAsyncKeyState(VK_LWIN)) || HIWORD(GetAsyncKeyState(VK_RWIN));
+ event.key.code = virtualKeyCodeToSF(wParam, lParam);
+ pushEvent(event);
break;
}
// Mouse wheel event
case WM_MOUSEWHEEL :
{
- Event Evt;
- Evt.Type = Event::MouseWheelMoved;
- Evt.MouseWheel.Delta = static_cast<Int16>(HIWORD(WParam)) / 120;
- SendEvent(Evt);
+ // Mouse position is in screen coordinates, convert it to window coordinates
+ POINT position;
+ position.x = static_cast<Int16>(LOWORD(lParam));
+ position.y = static_cast<Int16>(HIWORD(lParam));
+ ScreenToClient(m_handle, &position);
+
+ Event event;
+ event.type = Event::MouseWheelMoved;
+ event.mouseWheel.delta = static_cast<Int16>(HIWORD(wParam)) / 120;
+ event.mouseWheel.x = position.x;
+ event.mouseWheel.y = position.y;
+ pushEvent(event);
break;
}
// Mouse left button down event
case WM_LBUTTONDOWN :
{
- Event Evt;
- Evt.Type = Event::MouseButtonPressed;
- Evt.MouseButton.Button = Mouse::Left;
- Evt.MouseButton.X = LOWORD(LParam);
- Evt.MouseButton.Y = HIWORD(LParam);
- SendEvent(Evt);
+ Event event;
+ event.type = Event::MouseButtonPressed;
+ event.mouseButton.button = Mouse::Left;
+ event.mouseButton.x = static_cast<Int16>(LOWORD(lParam));
+ event.mouseButton.y = static_cast<Int16>(HIWORD(lParam));
+ pushEvent(event);
break;
}
// Mouse left button up event
case WM_LBUTTONUP :
{
- Event Evt;
- Evt.Type = Event::MouseButtonReleased;
- Evt.MouseButton.Button = Mouse::Left;
- Evt.MouseButton.X = LOWORD(LParam);
- Evt.MouseButton.Y = HIWORD(LParam);
- SendEvent(Evt);
+ Event event;
+ event.type = Event::MouseButtonReleased;
+ event.mouseButton.button = Mouse::Left;
+ event.mouseButton.x = static_cast<Int16>(LOWORD(lParam));
+ event.mouseButton.y = static_cast<Int16>(HIWORD(lParam));
+ pushEvent(event);
break;
}
// Mouse right button down event
case WM_RBUTTONDOWN :
{
- Event Evt;
- Evt.Type = Event::MouseButtonPressed;
- Evt.MouseButton.Button = Mouse::Right;
- Evt.MouseButton.X = LOWORD(LParam);
- Evt.MouseButton.Y = HIWORD(LParam);
- SendEvent(Evt);
+ Event event;
+ event.type = Event::MouseButtonPressed;
+ event.mouseButton.button = Mouse::Right;
+ event.mouseButton.x = static_cast<Int16>(LOWORD(lParam));
+ event.mouseButton.y = static_cast<Int16>(HIWORD(lParam));
+ pushEvent(event);
break;
}
// Mouse right button up event
case WM_RBUTTONUP :
{
- Event Evt;
- Evt.Type = Event::MouseButtonReleased;
- Evt.MouseButton.Button = Mouse::Right;
- Evt.MouseButton.X = LOWORD(LParam);
- Evt.MouseButton.Y = HIWORD(LParam);
- SendEvent(Evt);
+ Event event;
+ event.type = Event::MouseButtonReleased;
+ event.mouseButton.button = Mouse::Right;
+ event.mouseButton.x = static_cast<Int16>(LOWORD(lParam));
+ event.mouseButton.y = static_cast<Int16>(HIWORD(lParam));
+ pushEvent(event);
break;
}
// Mouse wheel button down event
case WM_MBUTTONDOWN :
{
- Event Evt;
- Evt.Type = Event::MouseButtonPressed;
- Evt.MouseButton.Button = Mouse::Middle;
- Evt.MouseButton.X = LOWORD(LParam);
- Evt.MouseButton.Y = HIWORD(LParam);
- SendEvent(Evt);
+ Event event;
+ event.type = Event::MouseButtonPressed;
+ event.mouseButton.button = Mouse::Middle;
+ event.mouseButton.x = static_cast<Int16>(LOWORD(lParam));
+ event.mouseButton.y = static_cast<Int16>(HIWORD(lParam));
+ pushEvent(event);
break;
}
// Mouse wheel button up event
case WM_MBUTTONUP :
{
- Event Evt;
- Evt.Type = Event::MouseButtonReleased;
- Evt.MouseButton.Button = Mouse::Middle;
- Evt.MouseButton.X = LOWORD(LParam);
- Evt.MouseButton.Y = HIWORD(LParam);
- SendEvent(Evt);
+ Event event;
+ event.type = Event::MouseButtonReleased;
+ event.mouseButton.button = Mouse::Middle;
+ event.mouseButton.x = static_cast<Int16>(LOWORD(lParam));
+ event.mouseButton.y = static_cast<Int16>(HIWORD(lParam));
+ pushEvent(event);
break;
}
// Mouse X button down event
case WM_XBUTTONDOWN :
{
- Event Evt;
- Evt.Type = Event::MouseButtonPressed;
- Evt.MouseButton.Button = HIWORD(WParam) == XBUTTON1 ? Mouse::XButton1 : Mouse::XButton2;
- Evt.MouseButton.X = LOWORD(LParam);
- Evt.MouseButton.Y = HIWORD(LParam);
- SendEvent(Evt);
+ Event event;
+ event.type = Event::MouseButtonPressed;
+ event.mouseButton.button = HIWORD(wParam) == XBUTTON1 ? Mouse::XButton1 : Mouse::XButton2;
+ event.mouseButton.x = static_cast<Int16>(LOWORD(lParam));
+ event.mouseButton.y = static_cast<Int16>(HIWORD(lParam));
+ pushEvent(event);
break;
}
// Mouse X button up event
case WM_XBUTTONUP :
{
- Event Evt;
- Evt.Type = Event::MouseButtonReleased;
- Evt.MouseButton.Button = HIWORD(WParam) == XBUTTON1 ? Mouse::XButton1 : Mouse::XButton2;
- Evt.MouseButton.X = LOWORD(LParam);
- Evt.MouseButton.Y = HIWORD(LParam);
- SendEvent(Evt);
+ Event event;
+ event.type = Event::MouseButtonReleased;
+ event.mouseButton.button = HIWORD(wParam) == XBUTTON1 ? Mouse::XButton1 : Mouse::XButton2;
+ event.mouseButton.x = static_cast<Int16>(LOWORD(lParam));
+ event.mouseButton.y = static_cast<Int16>(HIWORD(lParam));
+ pushEvent(event);
break;
}
// Mouse move event
case WM_MOUSEMOVE :
{
- // Check if we need to generate a MouseEntered event
- if (!myIsCursorIn)
+ // Extract the mouse local coordinates
+ int x = static_cast<Int16>(LOWORD(lParam));
+ int y = static_cast<Int16>(HIWORD(lParam));
+
+ // Get the client area of the window
+ RECT area;
+ GetClientRect(m_handle, &area);
+
+ // Check the mouse position against the window
+ if ((x < area.left) || (x > area.right) || (y < area.top) || (y > area.bottom))
{
- TRACKMOUSEEVENT MouseEvent;
- MouseEvent.cbSize = sizeof(TRACKMOUSEEVENT);
- MouseEvent.hwndTrack = myHandle;
- MouseEvent.dwFlags = TME_LEAVE;
- TrackMouseEvent(&MouseEvent);
+ // Mouse is outside
- myIsCursorIn = true;
+ // Release the mouse capture
+ ReleaseCapture();
- Event Evt;
- Evt.Type = Event::MouseEntered;
- SendEvent(Evt);
+ // Generate a MouseLeft event
+ Event event;
+ event.type = Event::MouseLeft;
+ pushEvent(event);
}
+ else
+ {
+ // Mouse is inside
+ if (GetCapture() != m_handle)
+ {
+ // Mouse was previously outside the window
- Event Evt;
- Evt.Type = Event::MouseMoved;
- Evt.MouseMove.X = LOWORD(LParam);
- Evt.MouseMove.Y = HIWORD(LParam);
- SendEvent(Evt);
- break;
- }
+ // Capture the mouse
+ SetCapture(m_handle);
- // Mouse leave event
- case WM_MOUSELEAVE :
- {
- myIsCursorIn = false;
+ // Generate a MouseEntered event
+ Event event;
+ event.type = Event::MouseEntered;
+ pushEvent(event);
+ }
- Event Evt;
- Evt.Type = Event::MouseLeft;
- SendEvent(Evt);
- break;
+ // Generate a MouseMove event
+ Event event;
+ event.type = Event::MouseMoved;
+ event.mouseMove.x = x;
+ event.mouseMove.y = y;
+ pushEvent(event);
+ break;
+ }
}
}
}
////////////////////////////////////////////////////////////
-/// Convert a Win32 virtual key code to a SFML key code
-////////////////////////////////////////////////////////////
-Key::Code WindowImplWin32::VirtualKeyCodeToSF(WPARAM VirtualKey, LPARAM Flags)
+Keyboard::Key WindowImplWin32::virtualKeyCodeToSF(WPARAM key, LPARAM flags)
{
- switch (VirtualKey)
+ switch (key)
{
// Check the scancode to distinguish between left and right shift
case VK_SHIFT :
{
- static UINT LShift = MapVirtualKey(VK_LSHIFT, MAPVK_VK_TO_VSC);
- UINT scancode = (Flags & (0xFF << 16)) >> 16;
- return scancode == LShift ? Key::LShift : Key::RShift;
+ static UINT lShift = MapVirtualKey(VK_LSHIFT, MAPVK_VK_TO_VSC);
+ UINT scancode = static_cast<UINT>((flags & (0xFF << 16)) >> 16);
+ return scancode == lShift ? Keyboard::LShift : Keyboard::RShift;
}
// Check the "extended" flag to distinguish between left and right alt
- case VK_MENU : return (HIWORD(Flags) & KF_EXTENDED) ? Key::RAlt : Key::LAlt;
+ case VK_MENU : return (HIWORD(flags) & KF_EXTENDED) ? Keyboard::RAlt : Keyboard::LAlt;
// Check the "extended" flag to distinguish between left and right control
- case VK_CONTROL : return (HIWORD(Flags) & KF_EXTENDED) ? Key::RControl : Key::LControl;
+ case VK_CONTROL : return (HIWORD(flags) & KF_EXTENDED) ? Keyboard::RControl : Keyboard::LControl;
// Other keys are reported properly
- case VK_LWIN : return Key::LSystem;
- case VK_RWIN : return Key::RSystem;
- case VK_APPS : return Key::Menu;
- case VK_OEM_1 : return Key::SemiColon;
- case VK_OEM_2 : return Key::Slash;
- case VK_OEM_PLUS : return Key::Equal;
- case VK_OEM_MINUS : return Key::Dash;
- case VK_OEM_4 : return Key::LBracket;
- case VK_OEM_6 : return Key::RBracket;
- case VK_OEM_COMMA : return Key::Comma;
- case VK_OEM_PERIOD : return Key::Period;
- case VK_OEM_7 : return Key::Quote;
- case VK_OEM_5 : return Key::BackSlash;
- case VK_OEM_3 : return Key::Tilde;
- case VK_ESCAPE : return Key::Escape;
- case VK_SPACE : return Key::Space;
- case VK_RETURN : return Key::Return;
- case VK_BACK : return Key::Back;
- case VK_TAB : return Key::Tab;
- case VK_PRIOR : return Key::PageUp;
- case VK_NEXT : return Key::PageDown;
- case VK_END : return Key::End;
- case VK_HOME : return Key::Home;
- case VK_INSERT : return Key::Insert;
- case VK_DELETE : return Key::Delete;
- case VK_ADD : return Key::Add;
- case VK_SUBTRACT : return Key::Subtract;
- case VK_MULTIPLY : return Key::Multiply;
- case VK_DIVIDE : return Key::Divide;
- case VK_PAUSE : return Key::Pause;
- case VK_F1 : return Key::F1;
- case VK_F2 : return Key::F2;
- case VK_F3 : return Key::F3;
- case VK_F4 : return Key::F4;
- case VK_F5 : return Key::F5;
- case VK_F6 : return Key::F6;
- case VK_F7 : return Key::F7;
- case VK_F8 : return Key::F8;
- case VK_F9 : return Key::F9;
- case VK_F10 : return Key::F10;
- case VK_F11 : return Key::F11;
- case VK_F12 : return Key::F12;
- case VK_F13 : return Key::F13;
- case VK_F14 : return Key::F14;
- case VK_F15 : return Key::F15;
- case VK_LEFT : return Key::Left;
- case VK_RIGHT : return Key::Right;
- case VK_UP : return Key::Up;
- case VK_DOWN : return Key::Down;
- case VK_NUMPAD0 : return Key::Numpad0;
- case VK_NUMPAD1 : return Key::Numpad1;
- case VK_NUMPAD2 : return Key::Numpad2;
- case VK_NUMPAD3 : return Key::Numpad3;
- case VK_NUMPAD4 : return Key::Numpad4;
- case VK_NUMPAD5 : return Key::Numpad5;
- case VK_NUMPAD6 : return Key::Numpad6;
- case VK_NUMPAD7 : return Key::Numpad7;
- case VK_NUMPAD8 : return Key::Numpad8;
- case VK_NUMPAD9 : return Key::Numpad9;
- case 'A' : return Key::A;
- case 'Z' : return Key::Z;
- case 'E' : return Key::E;
- case 'R' : return Key::R;
- case 'T' : return Key::T;
- case 'Y' : return Key::Y;
- case 'U' : return Key::U;
- case 'I' : return Key::I;
- case 'O' : return Key::O;
- case 'P' : return Key::P;
- case 'Q' : return Key::Q;
- case 'S' : return Key::S;
- case 'D' : return Key::D;
- case 'F' : return Key::F;
- case 'G' : return Key::G;
- case 'H' : return Key::H;
- case 'J' : return Key::J;
- case 'K' : return Key::K;
- case 'L' : return Key::L;
- case 'M' : return Key::M;
- case 'W' : return Key::W;
- case 'X' : return Key::X;
- case 'C' : return Key::C;
- case 'V' : return Key::V;
- case 'B' : return Key::B;
- case 'N' : return Key::N;
- case '0' : return Key::Num0;
- case '1' : return Key::Num1;
- case '2' : return Key::Num2;
- case '3' : return Key::Num3;
- case '4' : return Key::Num4;
- case '5' : return Key::Num5;
- case '6' : return Key::Num6;
- case '7' : return Key::Num7;
- case '8' : return Key::Num8;
- case '9' : return Key::Num9;
- }
-
- return Key::Code(0);
+ case VK_LWIN : return Keyboard::LSystem;
+ case VK_RWIN : return Keyboard::RSystem;
+ case VK_APPS : return Keyboard::Menu;
+ case VK_OEM_1 : return Keyboard::SemiColon;
+ case VK_OEM_2 : return Keyboard::Slash;
+ case VK_OEM_PLUS : return Keyboard::Equal;
+ case VK_OEM_MINUS : return Keyboard::Dash;
+ case VK_OEM_4 : return Keyboard::LBracket;
+ case VK_OEM_6 : return Keyboard::RBracket;
+ case VK_OEM_COMMA : return Keyboard::Comma;
+ case VK_OEM_PERIOD : return Keyboard::Period;
+ case VK_OEM_7 : return Keyboard::Quote;
+ case VK_OEM_5 : return Keyboard::BackSlash;
+ case VK_OEM_3 : return Keyboard::Tilde;
+ case VK_ESCAPE : return Keyboard::Escape;
+ case VK_SPACE : return Keyboard::Space;
+ case VK_RETURN : return Keyboard::Return;
+ case VK_BACK : return Keyboard::BackSpace;
+ case VK_TAB : return Keyboard::Tab;
+ case VK_PRIOR : return Keyboard::PageUp;
+ case VK_NEXT : return Keyboard::PageDown;
+ case VK_END : return Keyboard::End;
+ case VK_HOME : return Keyboard::Home;
+ case VK_INSERT : return Keyboard::Insert;
+ case VK_DELETE : return Keyboard::Delete;
+ case VK_ADD : return Keyboard::Add;
+ case VK_SUBTRACT : return Keyboard::Subtract;
+ case VK_MULTIPLY : return Keyboard::Multiply;
+ case VK_DIVIDE : return Keyboard::Divide;
+ case VK_PAUSE : return Keyboard::Pause;
+ case VK_F1 : return Keyboard::F1;
+ case VK_F2 : return Keyboard::F2;
+ case VK_F3 : return Keyboard::F3;
+ case VK_F4 : return Keyboard::F4;
+ case VK_F5 : return Keyboard::F5;
+ case VK_F6 : return Keyboard::F6;
+ case VK_F7 : return Keyboard::F7;
+ case VK_F8 : return Keyboard::F8;
+ case VK_F9 : return Keyboard::F9;
+ case VK_F10 : return Keyboard::F10;
+ case VK_F11 : return Keyboard::F11;
+ case VK_F12 : return Keyboard::F12;
+ case VK_F13 : return Keyboard::F13;
+ case VK_F14 : return Keyboard::F14;
+ case VK_F15 : return Keyboard::F15;
+ case VK_LEFT : return Keyboard::Left;
+ case VK_RIGHT : return Keyboard::Right;
+ case VK_UP : return Keyboard::Up;
+ case VK_DOWN : return Keyboard::Down;
+ case VK_NUMPAD0 : return Keyboard::Numpad0;
+ case VK_NUMPAD1 : return Keyboard::Numpad1;
+ case VK_NUMPAD2 : return Keyboard::Numpad2;
+ case VK_NUMPAD3 : return Keyboard::Numpad3;
+ case VK_NUMPAD4 : return Keyboard::Numpad4;
+ case VK_NUMPAD5 : return Keyboard::Numpad5;
+ case VK_NUMPAD6 : return Keyboard::Numpad6;
+ case VK_NUMPAD7 : return Keyboard::Numpad7;
+ case VK_NUMPAD8 : return Keyboard::Numpad8;
+ case VK_NUMPAD9 : return Keyboard::Numpad9;
+ case 'A' : return Keyboard::A;
+ case 'Z' : return Keyboard::Z;
+ case 'E' : return Keyboard::E;
+ case 'R' : return Keyboard::R;
+ case 'T' : return Keyboard::T;
+ case 'Y' : return Keyboard::Y;
+ case 'U' : return Keyboard::U;
+ case 'I' : return Keyboard::I;
+ case 'O' : return Keyboard::O;
+ case 'P' : return Keyboard::P;
+ case 'Q' : return Keyboard::Q;
+ case 'S' : return Keyboard::S;
+ case 'D' : return Keyboard::D;
+ case 'F' : return Keyboard::F;
+ case 'G' : return Keyboard::G;
+ case 'H' : return Keyboard::H;
+ case 'J' : return Keyboard::J;
+ case 'K' : return Keyboard::K;
+ case 'L' : return Keyboard::L;
+ case 'M' : return Keyboard::M;
+ case 'W' : return Keyboard::W;
+ case 'X' : return Keyboard::X;
+ case 'C' : return Keyboard::C;
+ case 'V' : return Keyboard::V;
+ case 'B' : return Keyboard::B;
+ case 'N' : return Keyboard::N;
+ case '0' : return Keyboard::Num0;
+ case '1' : return Keyboard::Num1;
+ case '2' : return Keyboard::Num2;
+ case '3' : return Keyboard::Num3;
+ case '4' : return Keyboard::Num4;
+ case '5' : return Keyboard::Num5;
+ case '6' : return Keyboard::Num6;
+ case '7' : return Keyboard::Num7;
+ case '8' : return Keyboard::Num8;
+ case '9' : return Keyboard::Num9;
+ }
+
+ return Keyboard::Unknown;
}
////////////////////////////////////////////////////////////
-/// Check if the current version of the OS supports unicode
-/// messages and functions ; Windows 95/98/Me may not support
-/// it, whereas Windows NT/2000/XP/Vista will
-////////////////////////////////////////////////////////////
-bool WindowImplWin32::HasUnicodeSupport()
+bool WindowImplWin32::hasUnicodeSupport()
{
- OSVERSIONINFO VersionInfo;
- ZeroMemory(&VersionInfo, sizeof(VersionInfo));
- VersionInfo.dwOSVersionInfoSize = sizeof(VersionInfo);
+ OSVERSIONINFO version;
+ ZeroMemory(&version, sizeof(version));
+ version.dwOSVersionInfoSize = sizeof(version);
- if (GetVersionEx(&VersionInfo))
+ if (GetVersionEx(&version))
{
- return VersionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT;
+ return version.dwPlatformId == VER_PLATFORM_WIN32_NT;
}
else
{
@@ -1090,41 +896,44 @@ bool WindowImplWin32::HasUnicodeSupport()
////////////////////////////////////////////////////////////
-/// Function called whenever one of our windows receives a message
-////////////////////////////////////////////////////////////
-LRESULT CALLBACK WindowImplWin32::GlobalOnEvent(HWND Handle, UINT Message, WPARAM WParam, LPARAM LParam)
+LRESULT CALLBACK WindowImplWin32::globalOnEvent(HWND handle, UINT message, WPARAM wParam, LPARAM lParam)
{
// Associate handle and Window instance when the creation message is received
- if (Message == WM_CREATE)
+ if (message == WM_CREATE)
{
// Get WindowImplWin32 instance (it was passed as the last argument of CreateWindow)
- long This = reinterpret_cast<long>(reinterpret_cast<CREATESTRUCT*>(LParam)->lpCreateParams);
+ LONG_PTR window = (LONG_PTR)reinterpret_cast<CREATESTRUCT*>(lParam)->lpCreateParams;
// Set as the "user data" parameter of the window
- SetWindowLongPtr(Handle, GWLP_USERDATA, This);
+ SetWindowLongPtr(handle, GWLP_USERDATA, window);
}
// Get the WindowImpl instance corresponding to the window handle
- WindowImplWin32* Window = reinterpret_cast<WindowImplWin32*>(GetWindowLongPtr(Handle, GWLP_USERDATA));
+ WindowImplWin32* window = handle ? reinterpret_cast<WindowImplWin32*>(GetWindowLongPtr(handle, GWLP_USERDATA)) : NULL;
// Forward the event to the appropriate function
- if (Window)
+ if (window)
{
- Window->ProcessEvent(Message, WParam, LParam);
+ window->processEvent(message, wParam, lParam);
- if (Window->myCallback)
- return CallWindowProc(reinterpret_cast<WNDPROC>(Window->myCallback), Handle, Message, WParam, LParam);
+ if (window->m_callback)
+ return CallWindowProc(reinterpret_cast<WNDPROC>(window->m_callback), handle, message, wParam, lParam);
}
// We don't forward the WM_CLOSE message to prevent the OS from automatically destroying the window
- if (Message == WM_CLOSE)
+ if (message == WM_CLOSE)
return 0;
- static const bool HasUnicode = HasUnicodeSupport();
- return HasUnicode ? DefWindowProcW(Handle, Message, WParam, LParam) :
- DefWindowProcA(Handle, Message, WParam, LParam);
+ // Don't forward the menu system command, so that pressing ALT or F10 doesn't steal the focus
+ if ((message == WM_SYSCOMMAND) && (wParam == SC_KEYMENU))
+ return 0;
+
+ static const bool hasUnicode = hasUnicodeSupport();
+ return hasUnicode ? DefWindowProcW(handle, message, wParam, lParam) :
+ DefWindowProcA(handle, message, wParam, lParam);
}
} // namespace priv
} // namespace sf
+
diff --git a/src/SFML/Window/Win32/WindowImplWin32.hpp b/src/SFML/Window/Win32/WindowImplWin32.hpp
index 20557dc..a0ccc61 100755..100644
--- a/src/SFML/Window/Win32/WindowImplWin32.hpp
+++ b/src/SFML/Window/Win32/WindowImplWin32.hpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -30,8 +30,8 @@
////////////////////////////////////////////////////////////
#include <SFML/Window/Event.hpp>
#include <SFML/Window/WindowImpl.hpp>
+#include <SFML/System/String.hpp>
#include <windows.h>
-#include <string>
namespace sf
@@ -39,213 +39,206 @@ namespace sf
namespace priv
{
////////////////////////////////////////////////////////////
-/// WindowImplWin32 is the Win32 implementation of WindowImpl
+/// \brief Windows implementation of WindowImpl
+///
////////////////////////////////////////////////////////////
class WindowImplWin32 : public WindowImpl
{
public :
////////////////////////////////////////////////////////////
- /// Default constructor
- /// (creates a dummy window to provide a valid OpenGL context)
+ /// \brief Construct the window implementation from an existing control
///
- ////////////////////////////////////////////////////////////
- WindowImplWin32();
-
- ////////////////////////////////////////////////////////////
- /// Construct the window implementation from an existing control
- ///
- /// \param Handle : Platform-specific handle of the control
- /// \param Params : Creation settings
+ /// \param handle Platform-specific handle of the control
///
////////////////////////////////////////////////////////////
- WindowImplWin32(WindowHandle Handle, WindowSettings& Params);
+ WindowImplWin32(WindowHandle handle);
////////////////////////////////////////////////////////////
- /// Create the window implementation
+ /// \brief Create the window implementation
///
- /// \param Mode : Video mode to use
- /// \param Title : Title of the window
- /// \param WindowStyle : Window style
- /// \param Params : Creation settings
+ /// \param mode Video mode to use
+ /// \param title Title of the window
+ /// \param style Window style
+ /// \param settings Additional settings for the underlying OpenGL context
///
////////////////////////////////////////////////////////////
- WindowImplWin32(VideoMode Mode, const std::string& Title, unsigned long WindowStyle, WindowSettings& Params);
+ WindowImplWin32(VideoMode mode, const String& title, Uint32 style, const ContextSettings& settings);
////////////////////////////////////////////////////////////
- /// Destructor
+ /// \brief Destructor
///
////////////////////////////////////////////////////////////
~WindowImplWin32();
////////////////////////////////////////////////////////////
- /// Check if there's an active context on the current thread
+ /// \brief Get the OS-specific handle of the window
///
- /// \return True if there's a context bound to the current thread
+ /// \return Handle of the window
///
////////////////////////////////////////////////////////////
- static bool IsContextActive();
-
-private :
+ virtual WindowHandle getSystemHandle() const;
////////////////////////////////////////////////////////////
- /// /see WindowImpl::ProcessEvents
+ /// \brief Get the position of the window
///
- ////////////////////////////////////////////////////////////
- virtual void ProcessEvents();
-
- ////////////////////////////////////////////////////////////
- /// /see WindowImpl::Display
+ /// \return Position of the window, in pixels
///
////////////////////////////////////////////////////////////
- virtual void Display();
+ virtual Vector2i getPosition() const;
////////////////////////////////////////////////////////////
- /// /see WindowImpl::SetActive
+ /// \brief Change the position of the window on screen
///
- ////////////////////////////////////////////////////////////
- virtual void SetActive(bool Active = true) const;
-
- ////////////////////////////////////////////////////////////
- /// /see WindowImpl::UseVerticalSync
+ /// \param position New position of the window, in pixels
///
////////////////////////////////////////////////////////////
- virtual void UseVerticalSync(bool Enabled);
+ virtual void setPosition(const Vector2i& position);
////////////////////////////////////////////////////////////
- /// /see WindowImpl::ShowMouseCursor
+ /// \brief Get the client size of the window
+ ///
+ /// \return Size of the window, in pixels
///
////////////////////////////////////////////////////////////
- virtual void ShowMouseCursor(bool Show);
+ virtual Vector2u getSize() const;
////////////////////////////////////////////////////////////
- /// /see WindowImpl::SetCursorPosition
+ /// \brief Change the size of the rendering region of the window
+ ///
+ /// \param size New size, in pixels
///
////////////////////////////////////////////////////////////
- virtual void SetCursorPosition(unsigned int Left, unsigned int Top);
+ virtual void setSize(const Vector2u& size);
////////////////////////////////////////////////////////////
- /// /see WindowImpl::SetPosition
+ /// \brief Change the title of the window
+ ///
+ /// \param title New title
///
////////////////////////////////////////////////////////////
- virtual void SetPosition(int Left, int Top);
+ virtual void setTitle(const String& title);
////////////////////////////////////////////////////////////
- /// /see WindowImpl::SetSize
+ /// \brief Change the window's icon
+ ///
+ /// \param width Icon's width, in pixels
+ /// \param height Icon's height, in pixels
+ /// \param pixels Pointer to the pixels in memory, format must be RGBA 32 bits
///
////////////////////////////////////////////////////////////
- virtual void SetSize(unsigned int Width, unsigned int Height);
+ virtual void setIcon(unsigned int width, unsigned int height, const Uint8* pixels);
////////////////////////////////////////////////////////////
- /// /see WindowImpl::Show
+ /// \brief Show or hide the window
+ ///
+ /// \param visible True to show, false to hide
///
////////////////////////////////////////////////////////////
- virtual void Show(bool State);
+ virtual void setVisible(bool visible);
////////////////////////////////////////////////////////////
- /// /see WindowImpl::EnableKeyRepeat
+ /// \brief Show or hide the mouse cursor
+ ///
+ /// \param visible True to show, false to hide
///
////////////////////////////////////////////////////////////
- virtual void EnableKeyRepeat(bool Enabled);
+ virtual void setMouseCursorVisible(bool visible);
////////////////////////////////////////////////////////////
- /// /see WindowImpl::SetIcon
+ /// \brief Enable or disable automatic key-repeat
+ ///
+ /// \param enabled True to enable, false to disable
///
////////////////////////////////////////////////////////////
- virtual void SetIcon(unsigned int Width, unsigned int Height, const Uint8* Pixels);
+ virtual void setKeyRepeatEnabled(bool enabled);
+
+protected:
////////////////////////////////////////////////////////////
- /// Register the window class
+ /// \brief Process incoming events from the operating system
///
////////////////////////////////////////////////////////////
- void RegisterWindowClass();
+ virtual void processEvents();
+
+private :
////////////////////////////////////////////////////////////
- /// Switch to fullscreen mode
- ///
- /// \param Mode : video mode to switch to
+ /// Register the window class
///
////////////////////////////////////////////////////////////
- void SwitchToFullscreen(const VideoMode& Mode);
+ void registerWindowClass();
////////////////////////////////////////////////////////////
- /// Construct the context from graphics settings
+ /// \brief Switch to fullscreen mode
///
- /// \param Mode : Video mode
- /// \param Params : Creation settings
+ /// \param mode Video mode to switch to
///
////////////////////////////////////////////////////////////
- void CreateContext(const VideoMode& Mode, WindowSettings& Params);
+ void switchToFullscreen(const VideoMode& mode);
////////////////////////////////////////////////////////////
- /// Free all the graphical resources attached to the window
+ /// \brief Free all the graphical resources attached to the window
///
////////////////////////////////////////////////////////////
- void Cleanup();
+ void cleanup();
////////////////////////////////////////////////////////////
- /// Process a Win32 event
+ /// \brief Process a Win32 event
///
- /// \param Message : Message to process
- /// \param WParam : First parameter of the event
- /// \param LParam : Second parameter of the event
+ /// \param message Message to process
+ /// \param wParam First parameter of the event
+ /// \param lParam Second parameter of the event
///
////////////////////////////////////////////////////////////
- void ProcessEvent(UINT Message, WPARAM WParam, LPARAM LParam);
+ void processEvent(UINT message, WPARAM wParam, LPARAM lParam);
////////////////////////////////////////////////////////////
- /// Convert a Win32 virtual key code to a SFML key code
+ /// \brief Convert a Win32 virtual key code to a SFML key code
///
- /// \param VirtualKey : Virtual key code to convert
- /// \param Flags : Additional flags
+ /// \param key Virtual key code to convert
+ /// \param flags Additional flags
///
- /// \return SFML key code corresponding to VirtualKey
+ /// \return SFML key code corresponding to the key
///
////////////////////////////////////////////////////////////
- static Key::Code VirtualKeyCodeToSF(WPARAM VirtualKey, LPARAM Flags);
+ static Keyboard::Key virtualKeyCodeToSF(WPARAM key, LPARAM flags);
////////////////////////////////////////////////////////////
- /// Check if the current version of the OS supports unicode
- /// messages and functions ; Windows 95/98/Me may not support
- /// it, whereas Windows NT/2000/XP/Vista will
+ /// \brief Check if the current version of the OS supports
+ /// unicode messages and functions ; Windows 95/98/Me
+ /// may not support it, whereas Windows NT/2000/XP/Vista
+ /// will
///
/// \return True if the OS supports unicode
///
////////////////////////////////////////////////////////////
- static bool HasUnicodeSupport();
+ static bool hasUnicodeSupport();
////////////////////////////////////////////////////////////
- /// Function called whenever one of our windows receives a message
+ /// \brief Function called whenever one of our windows receives a message
///
- /// \param Handle : Win32 handle of the window
- /// \param Message : Message received
- /// \param WParam : First parameter of the message
- /// \param LParam : Second parameter of the message
+ /// \param handle Win32 handle of the window
+ /// \param message Message received
+ /// \param wParam First parameter of the message
+ /// \param lParam Second parameter of the message
///
- /// \return Something...
+ /// \return True to discard the event after it has been processed
///
////////////////////////////////////////////////////////////
- static LRESULT CALLBACK GlobalOnEvent(HWND Handle, UINT Message, WPARAM WParam, LPARAM LParam);
-
- ////////////////////////////////////////////////////////////
- // Static member data
- ////////////////////////////////////////////////////////////
- static unsigned int ourWindowCount; ///< Number of windows that we own
- static const char* ourClassNameA; ///< Win32 window class name (ANSI version)
- static const wchar_t* ourClassNameW; ///< Win32 window class name (unicode version)
- static WindowImplWin32* ourFullscreenWindow; ///< Window currently in fullscreen
+ static LRESULT CALLBACK globalOnEvent(HWND handle, UINT message, WPARAM wParam, LPARAM lParam);
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
- HWND myHandle; ///< Win32 handle of the window
- long myCallback; ///< Stores the original event callback function of the control
- HCURSOR myCursor; ///< The system cursor to display into the window
- HICON myIcon; ///< Custom icon assigned to the window
- bool myKeyRepeatEnabled; ///< Automatic key-repeat state for keydown events
- bool myIsCursorIn; ///< Is the mouse cursor in the window's area ?
- HDC myDeviceContext; ///< HDC associated to the window
- HGLRC myGLContext; ///< OpenGL rendering context associated to the HDC
+ HWND m_handle; ///< Win32 handle of the window
+ LONG_PTR m_callback; ///< Stores the original event callback function of the control
+ HCURSOR m_cursor; ///< The system cursor to display into the window
+ HICON m_icon; ///< Custom icon assigned to the window
+ bool m_keyRepeatEnabled; ///< Automatic key-repeat state for keydown events
+ Vector2u m_lastSize; ///< The last handled size of the window
+ bool m_resizing; ///< Is the window being resized ?
+ Uint16 m_surrogate; ///< First half of the surrogate pair, in case we're receiving a Unicode character in two events
};
} // namespace priv
diff --git a/src/SFML/Window/Window.cpp b/src/SFML/Window/Window.cpp
index 7ea1963..0970c98 100755..100644
--- a/src/SFML/Window/Window.cpp
+++ b/src/SFML/Window/Window.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -26,448 +26,381 @@
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Window/Window.hpp>
-#include <SFML/Window/Context.hpp>
+#include <SFML/Window/GlContext.hpp>
#include <SFML/Window/WindowImpl.hpp>
#include <SFML/System/Sleep.hpp>
-#include <iostream>
+#include <SFML/System/Err.hpp>
-////////////////////////////////////////////////////////////
-// Private data
-////////////////////////////////////////////////////////////
namespace
{
- const sf::Window* FullscreenWindow = NULL;
+ const sf::Window* fullscreenWindow = NULL;
}
namespace sf
{
////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
Window::Window() :
-myWindow (NULL),
-myLastFrameTime (0.f),
-myIsExternal (false),
-myFramerateLimit(0),
-mySetCursorPosX (0xFFFF),
-mySetCursorPosY (0xFFFF)
+m_impl (NULL),
+m_context (NULL),
+m_frameTimeLimit(Time::Zero),
+m_size (0, 0)
{
}
////////////////////////////////////////////////////////////
-/// Construct a new window
-////////////////////////////////////////////////////////////
-Window::Window(VideoMode Mode, const std::string& Title, unsigned long WindowStyle, const WindowSettings& Params) :
-myWindow (NULL),
-myLastFrameTime (0.f),
-myIsExternal (false),
-myFramerateLimit(0),
-mySetCursorPosX (0xFFFF),
-mySetCursorPosY (0xFFFF)
+Window::Window(VideoMode mode, const String& title, Uint32 style, const ContextSettings& settings) :
+m_impl (NULL),
+m_context (NULL),
+m_frameTimeLimit(Time::Zero),
+m_size (0, 0)
{
- Create(Mode, Title, WindowStyle, Params);
+ create(mode, title, style, settings);
}
////////////////////////////////////////////////////////////
-/// Construct the window from an existing control
-////////////////////////////////////////////////////////////
-Window::Window(WindowHandle Handle, const WindowSettings& Params) :
-myWindow (NULL),
-myLastFrameTime (0.f),
-myIsExternal (true),
-myFramerateLimit(0),
-mySetCursorPosX (0xFFFF),
-mySetCursorPosY (0xFFFF)
+Window::Window(WindowHandle handle, const ContextSettings& settings) :
+m_impl (NULL),
+m_context (NULL),
+m_frameTimeLimit(Time::Zero),
+m_size (0, 0)
{
- Create(Handle, Params);
+ create(handle, settings);
}
////////////////////////////////////////////////////////////
-/// Destructor
-////////////////////////////////////////////////////////////
Window::~Window()
{
- // Close the window
- Close();
+ close();
}
////////////////////////////////////////////////////////////
-/// Create the window
-////////////////////////////////////////////////////////////
-void Window::Create(VideoMode Mode, const std::string& Title, unsigned long WindowStyle, const WindowSettings& Params)
+void Window::create(VideoMode mode, const String& title, Uint32 style, const ContextSettings& settings)
{
// Destroy the previous window implementation
- Close();
+ close();
// Fullscreen style requires some tests
- if (WindowStyle & Style::Fullscreen)
+ if (style & Style::Fullscreen)
{
// Make sure there's not already a fullscreen window (only one is allowed)
- if (FullscreenWindow)
+ if (fullscreenWindow)
{
- std::cerr << "Creating two fullscreen windows is not allowed, switching to windowed mode" << std::endl;
- WindowStyle &= ~Style::Fullscreen;
+ err() << "Creating two fullscreen windows is not allowed, switching to windowed mode" << std::endl;
+ style &= ~Style::Fullscreen;
}
else
{
- // Make sure the chosen video mode is compatible
- if (!Mode.IsValid())
+ // Make sure that the chosen video mode is compatible
+ if (!mode.isValid())
{
- std::cerr << "The requested video mode is not available, switching to a valid mode" << std::endl;
- Mode = VideoMode::GetMode(0);
+ err() << "The requested video mode is not available, switching to a valid mode" << std::endl;
+ mode = VideoMode::getFullscreenModes()[0];
}
// Update the fullscreen window
- FullscreenWindow = this;
+ fullscreenWindow = this;
}
}
// Check validity of style
- if ((WindowStyle & Style::Close) || (WindowStyle & Style::Resize))
- WindowStyle |= Style::Titlebar;
+ if ((style & Style::Close) || (style & Style::Resize))
+ style |= Style::Titlebar;
+
+ // Recreate the window implementation
+ m_impl = priv::WindowImpl::create(mode, title, style, settings);
- // Activate the global context
- Context::GetGlobal().SetActive(true);
+ // Recreate the context
+ m_context = priv::GlContext::create(settings, m_impl, mode.bitsPerPixel);
- mySettings = Params;
- Initialize(priv::WindowImpl::New(Mode, Title, WindowStyle, mySettings));
+ // Perform common initializations
+ initialize();
}
////////////////////////////////////////////////////////////
-/// Create the window from an existing control
-////////////////////////////////////////////////////////////
-void Window::Create(WindowHandle Handle, const WindowSettings& Params)
+void Window::create(WindowHandle handle, const ContextSettings& settings)
{
// Destroy the previous window implementation
- Close();
+ close();
- // Activate the global context
- Context::GetGlobal().SetActive(true);
+ // Recreate the window implementation
+ m_impl = priv::WindowImpl::create(handle);
- mySettings = Params;
- Initialize(priv::WindowImpl::New(Handle, mySettings));
+ // Recreate the context
+ m_context = priv::GlContext::create(settings, m_impl, VideoMode::getDesktopMode().bitsPerPixel);
+
+ // Perform common initializations
+ initialize();
}
////////////////////////////////////////////////////////////
-/// Close (destroy) the window.
-/// The sf::Window instance remains valid and you can call
-/// Create to recreate the window
-////////////////////////////////////////////////////////////
-void Window::Close()
+void Window::close()
{
- // Delete the window implementation
- delete myWindow;
- myWindow = NULL;
+ if (m_context)
+ {
+ // Delete the context
+ delete m_context;
+ m_context = NULL;
+ }
+
+ if (m_impl)
+ {
+ // Delete the window implementation
+ delete m_impl;
+ m_impl = NULL;
+ }
// Update the fullscreen window
- if (this == FullscreenWindow)
- FullscreenWindow = NULL;
+ if (this == fullscreenWindow)
+ fullscreenWindow = NULL;
}
////////////////////////////////////////////////////////////
-/// Tell whether or not the window is opened (ie. has been created).
-/// Note that a hidden window (Show(false))
-/// will still return true
-////////////////////////////////////////////////////////////
-bool Window::IsOpened() const
+bool Window::isOpen() const
{
- return myWindow != NULL;
+ return m_impl != NULL;
}
////////////////////////////////////////////////////////////
-/// Get the width of the rendering region of the window
-////////////////////////////////////////////////////////////
-unsigned int Window::GetWidth() const
+const ContextSettings& Window::getSettings() const
{
- return myWindow ? myWindow->GetWidth() : 0;
+ static const ContextSettings empty(0, 0, 0);
+
+ return m_context ? m_context->getSettings() : empty;
}
////////////////////////////////////////////////////////////
-/// Get the height of the rendering region of the window
-////////////////////////////////////////////////////////////
-unsigned int Window::GetHeight() const
+bool Window::pollEvent(Event& event)
{
- return myWindow ? myWindow->GetHeight() : 0;
+ if (m_impl && m_impl->popEvent(event, false))
+ {
+ return filterEvent(event);
+ }
+ else
+ {
+ return false;
+ }
}
////////////////////////////////////////////////////////////
-/// Get the creation settings of the window
-////////////////////////////////////////////////////////////
-const WindowSettings& Window::GetSettings() const
+bool Window::waitEvent(Event& event)
{
- return mySettings;
+ if (m_impl && m_impl->popEvent(event, true))
+ {
+ return filterEvent(event);
+ }
+ else
+ {
+ return false;
+ }
}
////////////////////////////////////////////////////////////
-/// Get the event on top of events stack, if any
-////////////////////////////////////////////////////////////
-bool Window::GetEvent(Event& EventReceived)
+Vector2i Window::getPosition() const
{
- // Let the window implementation process incoming events if the events queue is empty
- if (myWindow && myEvents.empty())
- myWindow->DoEvents();
-
- // Pop first event of queue, if not empty
- if (!myEvents.empty())
- {
- EventReceived = myEvents.front();
- myEvents.pop();
-
- return true;
- }
-
- return false;
+ return m_impl ? m_impl->getPosition() : Vector2i();
}
////////////////////////////////////////////////////////////
-/// Enable / disable vertical synchronization
-////////////////////////////////////////////////////////////
-void Window::UseVerticalSync(bool Enabled)
+void Window::setPosition(const Vector2i& position)
{
- if (SetActive())
- myWindow->UseVerticalSync(Enabled);
+ if (m_impl)
+ m_impl->setPosition(position);
}
////////////////////////////////////////////////////////////
-/// Show or hide the mouse cursor
-////////////////////////////////////////////////////////////
-void Window::ShowMouseCursor(bool Show)
+Vector2u Window::getSize() const
{
- if (myWindow)
- myWindow->ShowMouseCursor(Show);
+ return m_size;
}
////////////////////////////////////////////////////////////
-/// Change the position of the mouse cursor
-////////////////////////////////////////////////////////////
-void Window::SetCursorPosition(unsigned int Left, unsigned int Top)
+void Window::setSize(const Vector2u size)
{
- if (myWindow)
- {
- // Keep coordinates for later checking (to reject the generated MouseMoved event)
- mySetCursorPosX = Left;
- mySetCursorPosY = Top;
-
- myWindow->SetCursorPosition(Left, Top);
- }
+ if (m_impl)
+ m_impl->setSize(size);
}
////////////////////////////////////////////////////////////
-/// Change the position of the window on screen
-////////////////////////////////////////////////////////////
-void Window::SetPosition(int Left, int Top)
+void Window::setTitle(const String& title)
{
- if (!myIsExternal)
- {
- if (myWindow)
- myWindow->SetPosition(Left, Top);
- }
- else
- {
- std::cerr << "Warning : trying to change the position of an external SFML window, which is not allowed" << std::endl;
- }
+ if (m_impl)
+ m_impl->setTitle(title);
}
////////////////////////////////////////////////////////////
-/// Change the size of the rendering region of the window
-////////////////////////////////////////////////////////////
-void Window::SetSize(unsigned int Width, unsigned int Height)
+void Window::setIcon(unsigned int width, unsigned int height, const Uint8* pixels)
{
- if (myWindow)
- myWindow->SetSize(Width, Height);
+ if (m_impl)
+ m_impl->setIcon(width, height, pixels);
}
////////////////////////////////////////////////////////////
-/// Show or hide the window
-////////////////////////////////////////////////////////////
-void Window::Show(bool State)
+void Window::setVisible(bool visible)
{
- if (!myIsExternal)
- {
- if (myWindow)
- myWindow->Show(State);
- }
+ if (m_impl)
+ m_impl->setVisible(visible);
}
////////////////////////////////////////////////////////////
-/// Enable or disable automatic key-repeat.
-/// Automatic key-repeat is enabled by default
-////////////////////////////////////////////////////////////
-void Window::EnableKeyRepeat(bool Enabled)
+void Window::setVerticalSyncEnabled(bool enabled)
{
- if (myWindow)
- myWindow->EnableKeyRepeat(Enabled);
+ if (setActive())
+ m_context->setVerticalSyncEnabled(enabled);
}
////////////////////////////////////////////////////////////
-/// Change the window's icon
-////////////////////////////////////////////////////////////
-void Window::SetIcon(unsigned int Width, unsigned int Height, const Uint8* Pixels)
+void Window::setMouseCursorVisible(bool visible)
{
- if (myWindow)
- myWindow->SetIcon(Width, Height, Pixels);
+ if (m_impl)
+ m_impl->setMouseCursorVisible(visible);
}
////////////////////////////////////////////////////////////
-/// Activate of deactivate the window as the current target
-/// for rendering
-////////////////////////////////////////////////////////////
-bool Window::SetActive(bool Active) const
+void Window::setKeyRepeatEnabled(bool enabled)
{
- if (myWindow)
- {
- myWindow->SetActive(Active);
- return true;
- }
-
- return false;
+ if (m_impl)
+ m_impl->setKeyRepeatEnabled(enabled);
}
////////////////////////////////////////////////////////////
-/// Display the window on screen
-////////////////////////////////////////////////////////////
-void Window::Display()
+void Window::setFramerateLimit(unsigned int limit)
{
- // Limit the framerate if needed
- if (myFramerateLimit > 0)
- {
- float RemainingTime = 1.f / myFramerateLimit - myClock.GetElapsedTime();
- if (RemainingTime > 0)
- Sleep(RemainingTime);
- }
+ if (limit > 0)
+ m_frameTimeLimit = seconds(1.f / limit);
+ else
+ m_frameTimeLimit = Time::Zero;
+}
- // Measure the time elapsed since last frame
- myLastFrameTime = myClock.GetElapsedTime();
- myClock.Reset();
- // Display the backbuffer on screen
- if (SetActive())
- myWindow->Display();
+////////////////////////////////////////////////////////////
+void Window::setJoystickThreshold(float threshold)
+{
+ if (m_impl)
+ m_impl->setJoystickThreshold(threshold);
}
////////////////////////////////////////////////////////////
-/// Get the input manager of the window
-////////////////////////////////////////////////////////////
-const Input& Window::GetInput() const
+bool Window::setActive(bool active) const
{
- return myInput;
+ if (m_context)
+ {
+ if (m_context->setActive(active))
+ {
+ return true;
+ }
+ else
+ {
+ err() << "Failed to activate the window's context" << std::endl;
+ return false;
+ }
+ }
+ else
+ {
+ return false;
+ }
}
////////////////////////////////////////////////////////////
-/// Set the framerate at a fixed frequency
-////////////////////////////////////////////////////////////
-void Window::SetFramerateLimit(unsigned int Limit)
+void Window::display()
{
- myFramerateLimit = Limit;
+ // Display the backbuffer on screen
+ if (setActive())
+ m_context->display();
+
+ // Limit the framerate if needed
+ if (m_frameTimeLimit != Time::Zero)
+ {
+ sleep(m_frameTimeLimit - m_clock.getElapsedTime());
+ m_clock.restart();
+ }
}
////////////////////////////////////////////////////////////
-/// Get time elapsed since last frame
-////////////////////////////////////////////////////////////
-float Window::GetFrameTime() const
+WindowHandle Window::getSystemHandle() const
{
- return myLastFrameTime;
+ return m_impl ? m_impl->getSystemHandle() : 0;
}
////////////////////////////////////////////////////////////
-/// Change the joystick threshold, ie. the value below which
-/// no move event will be generated
-////////////////////////////////////////////////////////////
-void Window::SetJoystickThreshold(float Threshold)
+void Window::onCreate()
{
- if (myWindow)
- myWindow->SetJoystickThreshold(Threshold);
+ // Nothing by default
}
////////////////////////////////////////////////////////////
-/// Called after the window has been created
-////////////////////////////////////////////////////////////
-void Window::OnCreate()
+void Window::onResize()
{
// Nothing by default
}
////////////////////////////////////////////////////////////
-/// Receive an event from window
-////////////////////////////////////////////////////////////
-void Window::OnEvent(const Event& EventReceived)
+bool Window::filterEvent(const Event& event)
{
- // Discard MouseMove events generated by SetCursorPosition
- if ((EventReceived.Type == Event::MouseMoved) &&
- (EventReceived.MouseMove.X == mySetCursorPosX) &&
- (EventReceived.MouseMove.Y == mySetCursorPosY))
+ // Notify resize events to the derived class
+ if (event.type == Event::Resized)
{
- mySetCursorPosX = 0xFFFF;
- mySetCursorPosY = 0xFFFF;
- return;
+ // Cache the new size
+ m_size.x = event.size.width;
+ m_size.y = event.size.height;
+
+ // Notify the derived class
+ onResize();
}
- myEvents.push(EventReceived);
+ return true;
}
////////////////////////////////////////////////////////////
-/// Initialize internal window
-////////////////////////////////////////////////////////////
-void Window::Initialize(priv::WindowImpl* Window)
+void Window::initialize()
{
- // Assign and initialize the new window
- myWindow = Window;
- myWindow->Initialize();
-
- // Clear the event queue
- while (!myEvents.empty())
- myEvents.pop();
-
- // Listen to events from the new window
- myWindow->AddListener(this);
- myWindow->AddListener(&myInput);
-
// Setup default behaviours (to get a consistent behaviour across different implementations)
- Show(true);
- UseVerticalSync(false);
- ShowMouseCursor(true);
- EnableKeyRepeat(true);
+ setVisible(true);
+ setMouseCursorVisible(true);
+ setVerticalSyncEnabled(false);
+ setKeyRepeatEnabled(true);
+
+ // Get and cache the initial size of the window
+ m_size = m_impl->getSize();
// Reset frame time
- myClock.Reset();
- myLastFrameTime = 0.f;
+ m_clock.restart();
// Activate the window
- SetActive(true);
+ setActive();
// Notify the derived class
- OnCreate();
+ onCreate();
}
} // namespace sf
diff --git a/src/SFML/Window/WindowImpl.cpp b/src/SFML/Window/WindowImpl.cpp
index dd0584f..1b336c7 100755..100644
--- a/src/SFML/Window/WindowImpl.cpp
+++ b/src/SFML/Window/WindowImpl.cpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -27,7 +27,8 @@
////////////////////////////////////////////////////////////
#include <SFML/Window/WindowImpl.hpp>
#include <SFML/Window/Event.hpp>
-#include <SFML/Window/WindowListener.hpp>
+#include <SFML/Window/JoystickManager.hpp>
+#include <SFML/System/Sleep.hpp>
#include <algorithm>
#include <cmath>
@@ -43,8 +44,8 @@
#elif defined(SFML_SYSTEM_MACOS)
- #include <SFML/Window/Cocoa/WindowImplCocoa.hpp>
- typedef sf::priv::WindowImplCocoa WindowImplType;
+ #include <SFML/Window/OSX/WindowImplCocoa.hpp>
+ typedef sf::priv::WindowImplCocoa WindowImplType;
#endif
@@ -54,46 +55,31 @@ namespace sf
namespace priv
{
////////////////////////////////////////////////////////////
-/// Create a new window depending on the current OS
-////////////////////////////////////////////////////////////
-WindowImpl* WindowImpl::New()
-{
- return new WindowImplType();
-}
-
-
-////////////////////////////////////////////////////////////
-/// Create a new window depending on the current OS
-////////////////////////////////////////////////////////////
-WindowImpl* WindowImpl::New(VideoMode Mode, const std::string& Title, unsigned long WindowStyle, WindowSettings& Params)
+WindowImpl* WindowImpl::create(VideoMode mode, const String& title, Uint32 style, const ContextSettings& settings)
{
- return new WindowImplType(Mode, Title, WindowStyle, Params);
+ return new WindowImplType(mode, title, style, settings);
}
////////////////////////////////////////////////////////////
-/// Create a new window depending on the current OS
-////////////////////////////////////////////////////////////
-WindowImpl* WindowImpl::New(WindowHandle Handle, WindowSettings& Params)
+WindowImpl* WindowImpl::create(WindowHandle handle)
{
- return new WindowImplType(Handle, Params);
+ return new WindowImplType(handle);
}
////////////////////////////////////////////////////////////
-/// Default constructor
-////////////////////////////////////////////////////////////
WindowImpl::WindowImpl() :
-myWidth (0),
-myHeight (0),
-myJoyThreshold(0.1f)
+m_joyThreshold(0.1f)
{
+ // Get the initial joystick states
+ JoystickManager::getInstance().update();
+ for (unsigned int i = 0; i < Joystick::Count; ++i)
+ m_joyStates[i] = JoystickManager::getInstance().getState(i);
}
////////////////////////////////////////////////////////////
-/// Destructor
-////////////////////////////////////////////////////////////
WindowImpl::~WindowImpl()
{
// Nothing to do
@@ -101,158 +87,119 @@ WindowImpl::~WindowImpl()
////////////////////////////////////////////////////////////
-/// Add a listener to the window
-////////////////////////////////////////////////////////////
-void WindowImpl::AddListener(WindowListener* Listener)
+void WindowImpl::setJoystickThreshold(float threshold)
{
- if (Listener)
- myListeners.insert(Listener);
+ m_joyThreshold = threshold;
}
////////////////////////////////////////////////////////////
-/// Remove a listener from the window
-////////////////////////////////////////////////////////////
-void WindowImpl::RemoveListener(WindowListener* Listener)
+bool WindowImpl::popEvent(Event& event, bool block)
{
- myListeners.erase(Listener);
-}
-
-
-////////////////////////////////////////////////////////////
-/// Initialize window's states that can't be done at construction
-////////////////////////////////////////////////////////////
-void WindowImpl::Initialize()
-{
- // Initialize the joysticks
- for (unsigned int i = 0; i < Joy::Count; ++i)
+ // If the event queue is empty, let's first check if new events are available from the OS
+ if (m_events.empty())
{
- myJoysticks[i].Initialize(i);
- myJoyStates[i] = myJoysticks[i].UpdateState();
- }
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the client width of the window
-////////////////////////////////////////////////////////////
-unsigned int WindowImpl::GetWidth() const
-{
- return myWidth;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Get the client height of the window
-////////////////////////////////////////////////////////////
-unsigned int WindowImpl::GetHeight() const
-{
- return myHeight;
-}
-
-
-////////////////////////////////////////////////////////////
-/// Change the joystick threshold, ie. the value below which
-/// no move event will be generated
-////////////////////////////////////////////////////////////
-void WindowImpl::SetJoystickThreshold(float Threshold)
-{
- myJoyThreshold = Threshold;
-}
-
+ if (!block)
+ {
+ // Non-blocking mode: process events and continue
+ processJoystickEvents();
+ processEvents();
+ }
+ else
+ {
+ // Blocking mode: process events until one is triggered
-////////////////////////////////////////////////////////////
-/// Process incoming events from operating system
-////////////////////////////////////////////////////////////
-void WindowImpl::DoEvents()
-{
- // Read the joysticks state and generate the appropriate events
- ProcessJoystickEvents();
+ // Here we use a manual wait loop instead of the optimized
+ // wait-event provided by the OS, so that we don't skip joystick
+ // events (which require polling)
+ while (m_events.empty())
+ {
+ processJoystickEvents();
+ processEvents();
+ sleep(milliseconds(10));
+ }
+ }
+ }
- // Let the derived class process other events
- ProcessEvents();
-}
+ // Pop the first event of the queue, if it is not empty
+ if (!m_events.empty())
+ {
+ event = m_events.front();
+ m_events.pop();
+ return true;
+ }
-////////////////////////////////////////////////////////////
-/// Check if there's an active context on the current thread
-////////////////////////////////////////////////////////////
-bool WindowImpl::IsContextActive()
-{
- return WindowImplType::IsContextActive();
+ return false;
}
////////////////////////////////////////////////////////////
-/// Send an event to listeners
-////////////////////////////////////////////////////////////
-void WindowImpl::SendEvent(const Event& EventToSend)
+void WindowImpl::pushEvent(const Event& event)
{
- for (std::set<WindowListener*>::iterator i = myListeners.begin(); i != myListeners.end(); ++i)
- {
- (*i)->OnEvent(EventToSend);
- }
+ m_events.push(event);
}
////////////////////////////////////////////////////////////
-/// Evaluate a pixel format configuration.
-/// This functions can be used by implementations that have
-/// several valid formats and want to get the best one
-////////////////////////////////////////////////////////////
-int WindowImpl::EvaluateConfig(const VideoMode& Mode, const WindowSettings& Settings, int ColorBits, int DepthBits, int StencilBits, int Antialiasing)
+void WindowImpl::processJoystickEvents()
{
- return abs(static_cast<int>(Mode.BitsPerPixel - ColorBits)) +
- abs(static_cast<int>(Settings.DepthBits - DepthBits)) +
- abs(static_cast<int>(Settings.StencilBits - StencilBits)) +
- abs(static_cast<int>(Settings.AntialiasingLevel - Antialiasing));
-}
+ // First update the global joystick states
+ JoystickManager::getInstance().update();
-
-////////////////////////////////////////////////////////////
-/// Read the joysticks state and generate the appropriate events
-////////////////////////////////////////////////////////////
-void WindowImpl::ProcessJoystickEvents()
-{
- for (unsigned int i = 0; i < Joy::Count; ++i)
+ for (unsigned int i = 0; i < Joystick::Count; ++i)
{
// Copy the previous state of the joystick and get the new one
- JoystickState PreviousState = myJoyStates[i];
- myJoyStates[i] = myJoysticks[i].UpdateState();
+ JoystickState previousState = m_joyStates[i];
+ m_joyStates[i] = JoystickManager::getInstance().getState(i);
+ JoystickCaps caps = JoystickManager::getInstance().getCapabilities(i);
- // Axis
- for (unsigned int j = 0; j < Joy::AxisCount; ++j)
+ // Connection state
+ bool connected = m_joyStates[i].connected;
+ if (previousState.connected ^ connected)
{
- Joy::Axis Axis = static_cast<Joy::Axis>(j);
- if (myJoysticks[i].HasAxis(Axis))
+ Event event;
+ event.type = connected ? Event::JoystickConnected : Event::JoystickDisconnected;
+ event.joystickButton.joystickId = i;
+ pushEvent(event);
+ }
+
+ if (connected)
+ {
+ // Axes
+ for (unsigned int j = 0; j < Joystick::AxisCount; ++j)
{
- float PrevPos = PreviousState.Axis[j];
- float CurrPos = myJoyStates[i].Axis[j];
- if (fabs(CurrPos - PrevPos) >= myJoyThreshold)
+ if (caps.axes[j])
{
- Event Event;
- Event.Type = Event::JoyMoved;
- Event.JoyMove.JoystickId = i;
- Event.JoyMove.Axis = Axis;
- Event.JoyMove.Position = CurrPos;
- SendEvent(Event);
+ Joystick::Axis axis = static_cast<Joystick::Axis>(j);
+ float prevPos = previousState.axes[axis];
+ float currPos = m_joyStates[i].axes[axis];
+ if (fabs(currPos - prevPos) >= m_joyThreshold)
+ {
+ Event event;
+ event.type = Event::JoystickMoved;
+ event.joystickMove.joystickId = i;
+ event.joystickMove.axis = axis;
+ event.joystickMove.position = currPos;
+ pushEvent(event);
+ }
}
}
- }
- // Buttons
- for (unsigned int j = 0; j < myJoysticks[i].GetButtonsCount(); ++j)
- {
- bool PrevPressed = PreviousState.Buttons[j];
- bool CurrPressed = myJoyStates[i].Buttons[j];
-
- if ((!PrevPressed && CurrPressed) || (PrevPressed && !CurrPressed))
+ // Buttons
+ for (unsigned int j = 0; j < caps.buttonCount; ++j)
{
- Event Event;
- Event.Type = CurrPressed ? Event::JoyButtonPressed : Event::JoyButtonReleased;
- Event.JoyButton.JoystickId = i;
- Event.JoyButton.Button = j;
- SendEvent(Event);
+ bool prevPressed = previousState.buttons[j];
+ bool currPressed = m_joyStates[i].buttons[j];
+
+ if (prevPressed ^ currPressed)
+ {
+ Event event;
+ event.type = currPressed ? Event::JoystickButtonPressed : Event::JoystickButtonReleased;
+ event.joystickButton.joystickId = i;
+ event.joystickButton.button = j;
+ pushEvent(event);
+ }
}
}
}
diff --git a/src/SFML/Window/WindowImpl.hpp b/src/SFML/Window/WindowImpl.hpp
index 09f8b54..4d061a1 100755..100644
--- a/src/SFML/Window/WindowImpl.hpp
+++ b/src/SFML/Window/WindowImpl.hpp
@@ -1,7 +1,7 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
-// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
+// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
@@ -30,273 +30,208 @@
////////////////////////////////////////////////////////////
#include <SFML/Config.hpp>
#include <SFML/System/NonCopyable.hpp>
+#include <SFML/System/String.hpp>
+#include <SFML/Window/Event.hpp>
#include <SFML/Window/Joystick.hpp>
+#include <SFML/Window/JoystickImpl.hpp>
#include <SFML/Window/VideoMode.hpp>
#include <SFML/Window/WindowHandle.hpp>
-#include <SFML/Window/WindowSettings.hpp>
+#include <SFML/Window/ContextSettings.hpp>
+#include <queue>
#include <set>
-#include <string>
-
namespace sf
{
-class Event;
class WindowListener;
namespace priv
{
////////////////////////////////////////////////////////////
-/// Abstract base class for OS-specific window implementation
+/// \brief Abstract base class for OS-specific window implementation
+///
////////////////////////////////////////////////////////////
class WindowImpl : NonCopyable
{
public :
////////////////////////////////////////////////////////////
- /// Create a new window depending on the current OS
- ///
- /// \return Pointer to the created window
- ///
- ////////////////////////////////////////////////////////////
- static WindowImpl* New();
-
- ////////////////////////////////////////////////////////////
- /// Create a new window depending on the current OS
+ /// \brief Create a new window depending on the current OS
///
- /// \param Mode : Video mode to use
- /// \param Title : Title of the window
- /// \param WindowStyle : Window style
- /// \param Params : Creation parameters
+ /// \param mode Video mode to use
+ /// \param title Title of the window
+ /// \param style Window style
+ /// \param settings Additional settings for the underlying OpenGL context
///
- /// \return Pointer to the created window
+ /// \return Pointer to the created window (don't forget to delete it)
///
////////////////////////////////////////////////////////////
- static WindowImpl* New(VideoMode Mode, const std::string& Title, unsigned long WindowStyle, WindowSettings& Params);
+ static WindowImpl* create(VideoMode mode, const String& title, Uint32 style, const ContextSettings& settings);
////////////////////////////////////////////////////////////
- /// Create a new window depending on to the current OS
+ /// \brief Create a new window depending on to the current OS
///
- /// \param Handle : Platform-specific handle of the control
- /// \param Params : Creation parameters
+ /// \param handle Platform-specific handle of the control
///
- /// \return Pointer to the created window
+ /// \return Pointer to the created window (don't forget to delete it)
///
////////////////////////////////////////////////////////////
- static WindowImpl* New(WindowHandle Handle, WindowSettings& Params);
+ static WindowImpl* create(WindowHandle handle);
public :
////////////////////////////////////////////////////////////
- /// Destructor
+ /// \brief Destructor
///
////////////////////////////////////////////////////////////
virtual ~WindowImpl();
////////////////////////////////////////////////////////////
- /// Add a listener to the window
- ///
- /// \param Listener : Listener to add
- ///
- ////////////////////////////////////////////////////////////
- void AddListener(WindowListener* Listener);
-
- ////////////////////////////////////////////////////////////
- /// Remove a listener from the window
+ /// \brief Change the joystick threshold, ie. the value below which
+ /// no move event will be generated
///
- /// \param Listener : Listener to remove
+ /// \param threshold : New threshold, in range [0, 100]
///
////////////////////////////////////////////////////////////
- void RemoveListener(WindowListener* Listener);
+ void setJoystickThreshold(float threshold);
////////////////////////////////////////////////////////////
- /// Initialize window's states that can't be done at construction
+ /// \brief Return the next window event available
///
- ////////////////////////////////////////////////////////////
- void Initialize();
-
- ////////////////////////////////////////////////////////////
- /// Get the client width of the window
+ /// If there's no event available, this function calls the
+ /// window's internal event processing function.
+ /// The \a block parameter controls the behaviour of the function
+ /// if no event is available: if it is true then the function
+ /// doesn't return until a new event is triggered; otherwise it
+ /// returns false to indicate that no event is available.
///
- /// \return Width of the window in pixels
+ /// \param event Event to be returned
+ /// \param block Use true to block the thread until an event arrives
///
////////////////////////////////////////////////////////////
- unsigned int GetWidth() const;
+ bool popEvent(Event& event, bool block);
////////////////////////////////////////////////////////////
- /// Get the client height of the window
+ /// \brief Get the OS-specific handle of the window
///
- /// \return Height of the window in pixels
+ /// \return Handle of the window
///
////////////////////////////////////////////////////////////
- unsigned int GetHeight() const;
+ virtual WindowHandle getSystemHandle() const = 0;
////////////////////////////////////////////////////////////
- /// Activate of deactivate the window as the current target
- /// for rendering
+ /// \brief Get the position of the window
///
- /// \param Active : True to activate, false to deactivate (true by default)
+ /// \return Position of the window, in pixels
///
////////////////////////////////////////////////////////////
- virtual void SetActive(bool Active = true) const = 0;
+ virtual Vector2i getPosition() const = 0;
////////////////////////////////////////////////////////////
- /// Change the joystick threshold, ie. the value below which
- /// no move event will be generated
+ /// \brief Change the position of the window on screen
///
- /// \param Threshold : New threshold, in range [0, 100]
+ /// \param position New position of the window, in pixels
///
////////////////////////////////////////////////////////////
- void SetJoystickThreshold(float Threshold);
+ virtual void setPosition(const Vector2i& position) = 0;
////////////////////////////////////////////////////////////
- /// Process incoming events from operating system
+ /// \brief Get the client size of the window
///
- ////////////////////////////////////////////////////////////
- void DoEvents();
-
- ////////////////////////////////////////////////////////////
- /// Check if there's an active context on the current thread
- ///
- /// \return True if there's a context bound to the current thread
- ///
- ////////////////////////////////////////////////////////////
- static bool IsContextActive();
-
- ////////////////////////////////////////////////////////////
- /// Display the window on screen
+ /// \return Size of the window, in pixels
///
////////////////////////////////////////////////////////////
- virtual void Display() = 0;
+ virtual Vector2u getSize() const = 0;
////////////////////////////////////////////////////////////
- /// Enable / disable vertical synchronization
+ /// \brief Change the size of the rendering region of the window
///
- /// \param Enabled : True to enable v-sync, false to deactivate
+ /// \param size New size, in pixels
///
////////////////////////////////////////////////////////////
- virtual void UseVerticalSync(bool Enabled) = 0;
+ virtual void setSize(const Vector2u& size) = 0;
////////////////////////////////////////////////////////////
- /// Show or hide the mouse cursor
+ /// \brief Change the title of the window
///
- /// \param Show : True to show, false to hide
+ /// \param title New title
///
////////////////////////////////////////////////////////////
- virtual void ShowMouseCursor(bool Show) = 0;
+ virtual void setTitle(const String& title) = 0;
////////////////////////////////////////////////////////////
- /// Change the position of the mouse cursor
+ /// \brief Change the window's icon
///
- /// \param Left : Left coordinate of the cursor, relative to the window
- /// \param Top : Top coordinate of the cursor, relative to the window
+ /// \param width Icon's width, in pixels
+ /// \param height Icon's height, in pixels
+ /// \param pixels Pointer to the pixels in memory, format must be RGBA 32 bits
///
////////////////////////////////////////////////////////////
- virtual void SetCursorPosition(unsigned int Left, unsigned int Top) = 0;
+ virtual void setIcon(unsigned int width, unsigned int height, const Uint8* pixels) = 0;
////////////////////////////////////////////////////////////
- /// Change the position of the window on screen
+ /// \brief Show or hide the window
///
- /// \param Left : Left position
- /// \param Top : Top position
+ /// \param visible True to show, false to hide
///
////////////////////////////////////////////////////////////
- virtual void SetPosition(int Left, int Top) = 0;
+ virtual void setVisible(bool visible) = 0;
////////////////////////////////////////////////////////////
- /// Change the size of the rendering region of the window
+ /// \brief Show or hide the mouse cursor
///
- /// \param Width : New width
- /// \param Height : New height
+ /// \param visible True to show, false to hide
///
////////////////////////////////////////////////////////////
- virtual void SetSize(unsigned int Width, unsigned int Height) = 0;
+ virtual void setMouseCursorVisible(bool visible) = 0;
////////////////////////////////////////////////////////////
- /// Show or hide the window
+ /// \brief Enable or disable automatic key-repeat
///
- /// \param State : True to show, false to hide
+ /// \param enabled True to enable, false to disable
///
////////////////////////////////////////////////////////////
- virtual void Show(bool State) = 0;
-
- ////////////////////////////////////////////////////////////
- /// Enable or disable automatic key-repeat
- ///
- /// \param Enabled : True to enable, false to disable
- ///
- ////////////////////////////////////////////////////////////
- virtual void EnableKeyRepeat(bool Enabled) = 0;
-
- ////////////////////////////////////////////////////////////
- /// Change the window's icon
- ///
- /// \param Width : Icon's width, in pixels
- /// \param Height : Icon's height, in pixels
- /// \param Pixels : Pointer to the pixels in memory, format must be RGBA 32 bits
- ///
- ////////////////////////////////////////////////////////////
- virtual void SetIcon(unsigned int Width, unsigned int Height, const Uint8* Pixels) = 0;
+ virtual void setKeyRepeatEnabled(bool enabled) = 0;
protected :
////////////////////////////////////////////////////////////
- /// Default constructor
+ /// \brief Default constructor
///
////////////////////////////////////////////////////////////
WindowImpl();
////////////////////////////////////////////////////////////
- /// Send an event to listeners (for derived classes only)
+ /// \brief Push a new event into the event queue
///
- /// \param EventToSend : Event to send
+ /// This function is to be used by derived classes, to
+ /// notify the SFML window that a new event was triggered
+ /// by the system.
///
- ////////////////////////////////////////////////////////////
- void SendEvent(const Event& EventToSend);
-
- ////////////////////////////////////////////////////////////
- /// Evaluate a pixel format configuration.
- /// This functions can be used by implementations that have
- /// several valid formats and want to get the best one
- ///
- /// \param Mode : Requested video mode
- /// \param Settings : Requested additionnal settings
- /// \param ColorBits : Color bits of the configuration to evaluate
- /// \param DepthBits : Depth bits of the configuration to evaluate
- /// \param StencilBits : Stencil bits of the configuration to evaluate
- /// \param Antialiasing : Antialiasing level of the configuration to evaluate
- ///
- /// \return Score of the configuration : the lower the better
+ /// \param event Event to push
///
////////////////////////////////////////////////////////////
- static int EvaluateConfig(const VideoMode& Mode, const WindowSettings& Settings, int ColorBits, int DepthBits, int StencilBits, int Antialiasing);
+ void pushEvent(const Event& event);
////////////////////////////////////////////////////////////
- // Member data
+ /// \brief Process incoming events from the operating system
+ ///
////////////////////////////////////////////////////////////
- unsigned int myWidth; ///< Internal width of the window
- unsigned int myHeight; ///< Internal height of the window
+ virtual void processEvents() = 0;
private :
////////////////////////////////////////////////////////////
- /// Read the joysticks state and generate the appropriate events
- ///
- ////////////////////////////////////////////////////////////
- void ProcessJoystickEvents();
-
- ////////////////////////////////////////////////////////////
- /// Process incoming events from operating system
+ /// \brief Read the joysticks state and generate the appropriate events
///
////////////////////////////////////////////////////////////
- virtual void ProcessEvents() = 0;
+ void processJoystickEvents();
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
- std::set<WindowListener*> myListeners; ///< Array of listeners connected to the window
- Joystick myJoysticks[Joy::Count]; ///< Joysticks to observe
- JoystickState myJoyStates[Joy::Count]; ///< Current states of the joysticks
- float myJoyThreshold; ///< Joystick threshold (minimum motion for MOVE event to be generated)
+ std::queue<Event> m_events; ///< Queue of available events
+ JoystickState m_joyStates[Joystick::Count]; ///< Previous state of the joysticks
+ float m_joyThreshold; ///< Joystick threshold (minimum motion for MOVE event to be generated)
};
} // namespace priv
diff --git a/src/SFML/Window/glext/glext.h b/src/SFML/Window/glext/glext.h
new file mode 100644
index 0000000..22348a1
--- /dev/null
+++ b/src/SFML/Window/glext/glext.h
@@ -0,0 +1,11028 @@
+#ifndef __glext_h_
+#define __glext_h_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+** Copyright (c) 2007-2010 The Khronos Group Inc.
+**
+** Permission is hereby granted, free of charge, to any person obtaining a
+** copy of this software and/or associated documentation files (the
+** "Materials"), to deal in the Materials without restriction, including
+** without limitation the rights to use, copy, modify, merge, publish,
+** distribute, sublicense, and/or sell copies of the Materials, and to
+** permit persons to whom the Materials are furnished to do so, subject to
+** the following conditions:
+**
+** The above copyright notice and this permission notice shall be included
+** in all copies or substantial portions of the Materials.
+**
+** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
+*/
+
+/* Header file version number, required by OpenGL ABI for Linux */
+/* glext.h last updated $Date: 2010-08-03 01:30:25 -0700 (Tue, 03 Aug 2010) $ */
+/* Current version at http://www.opengl.org/registry/ */
+#define GL_GLEXT_VERSION 64
+/* Function declaration macros - to move into glplatform.h */
+
+#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__)
+#define WIN32_LEAN_AND_MEAN 1
+#include <windows.h>
+#endif
+
+#ifndef APIENTRY
+#define APIENTRY
+#endif
+#ifndef APIENTRYP
+#define APIENTRYP APIENTRY *
+#endif
+#ifndef GLAPI
+#define GLAPI extern
+#endif
+
+/*************************************************************/
+
+#ifndef GL_VERSION_1_2
+#define GL_UNSIGNED_BYTE_3_3_2 0x8032
+#define GL_UNSIGNED_SHORT_4_4_4_4 0x8033
+#define GL_UNSIGNED_SHORT_5_5_5_1 0x8034
+#define GL_UNSIGNED_INT_8_8_8_8 0x8035
+#define GL_UNSIGNED_INT_10_10_10_2 0x8036
+#define GL_TEXTURE_BINDING_3D 0x806A
+#define GL_PACK_SKIP_IMAGES 0x806B
+#define GL_PACK_IMAGE_HEIGHT 0x806C
+#define GL_UNPACK_SKIP_IMAGES 0x806D
+#define GL_UNPACK_IMAGE_HEIGHT 0x806E
+#define GL_TEXTURE_3D 0x806F
+#define GL_PROXY_TEXTURE_3D 0x8070
+#define GL_TEXTURE_DEPTH 0x8071
+#define GL_TEXTURE_WRAP_R 0x8072
+#define GL_MAX_3D_TEXTURE_SIZE 0x8073
+#define GL_UNSIGNED_BYTE_2_3_3_REV 0x8362
+#define GL_UNSIGNED_SHORT_5_6_5 0x8363
+#define GL_UNSIGNED_SHORT_5_6_5_REV 0x8364
+#define GL_UNSIGNED_SHORT_4_4_4_4_REV 0x8365
+#define GL_UNSIGNED_SHORT_1_5_5_5_REV 0x8366
+#define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367
+#define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368
+#define GL_BGR 0x80E0
+#define GL_BGRA 0x80E1
+#define GL_MAX_ELEMENTS_VERTICES 0x80E8
+#define GL_MAX_ELEMENTS_INDICES 0x80E9
+#define GL_CLAMP_TO_EDGE 0x812F
+#define GL_TEXTURE_MIN_LOD 0x813A
+#define GL_TEXTURE_MAX_LOD 0x813B
+#define GL_TEXTURE_BASE_LEVEL 0x813C
+#define GL_TEXTURE_MAX_LEVEL 0x813D
+#define GL_SMOOTH_POINT_SIZE_RANGE 0x0B12
+#define GL_SMOOTH_POINT_SIZE_GRANULARITY 0x0B13
+#define GL_SMOOTH_LINE_WIDTH_RANGE 0x0B22
+#define GL_SMOOTH_LINE_WIDTH_GRANULARITY 0x0B23
+#define GL_ALIASED_LINE_WIDTH_RANGE 0x846E
+#endif
+
+#ifndef GL_VERSION_1_2_DEPRECATED
+#define GL_RESCALE_NORMAL 0x803A
+#define GL_LIGHT_MODEL_COLOR_CONTROL 0x81F8
+#define GL_SINGLE_COLOR 0x81F9
+#define GL_SEPARATE_SPECULAR_COLOR 0x81FA
+#define GL_ALIASED_POINT_SIZE_RANGE 0x846D
+#endif
+
+#ifndef GL_ARB_imaging
+#define GL_CONSTANT_COLOR 0x8001
+#define GL_ONE_MINUS_CONSTANT_COLOR 0x8002
+#define GL_CONSTANT_ALPHA 0x8003
+#define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004
+#define GL_BLEND_COLOR 0x8005
+#define GL_FUNC_ADD 0x8006
+#define GL_MIN 0x8007
+#define GL_MAX 0x8008
+#define GL_BLEND_EQUATION 0x8009
+#define GL_FUNC_SUBTRACT 0x800A
+#define GL_FUNC_REVERSE_SUBTRACT 0x800B
+#endif
+
+#ifndef GL_ARB_imaging_DEPRECATED
+#define GL_CONVOLUTION_1D 0x8010
+#define GL_CONVOLUTION_2D 0x8011
+#define GL_SEPARABLE_2D 0x8012
+#define GL_CONVOLUTION_BORDER_MODE 0x8013
+#define GL_CONVOLUTION_FILTER_SCALE 0x8014
+#define GL_CONVOLUTION_FILTER_BIAS 0x8015
+#define GL_REDUCE 0x8016
+#define GL_CONVOLUTION_FORMAT 0x8017
+#define GL_CONVOLUTION_WIDTH 0x8018
+#define GL_CONVOLUTION_HEIGHT 0x8019
+#define GL_MAX_CONVOLUTION_WIDTH 0x801A
+#define GL_MAX_CONVOLUTION_HEIGHT 0x801B
+#define GL_POST_CONVOLUTION_RED_SCALE 0x801C
+#define GL_POST_CONVOLUTION_GREEN_SCALE 0x801D
+#define GL_POST_CONVOLUTION_BLUE_SCALE 0x801E
+#define GL_POST_CONVOLUTION_ALPHA_SCALE 0x801F
+#define GL_POST_CONVOLUTION_RED_BIAS 0x8020
+#define GL_POST_CONVOLUTION_GREEN_BIAS 0x8021
+#define GL_POST_CONVOLUTION_BLUE_BIAS 0x8022
+#define GL_POST_CONVOLUTION_ALPHA_BIAS 0x8023
+#define GL_HISTOGRAM 0x8024
+#define GL_PROXY_HISTOGRAM 0x8025
+#define GL_HISTOGRAM_WIDTH 0x8026
+#define GL_HISTOGRAM_FORMAT 0x8027
+#define GL_HISTOGRAM_RED_SIZE 0x8028
+#define GL_HISTOGRAM_GREEN_SIZE 0x8029
+#define GL_HISTOGRAM_BLUE_SIZE 0x802A
+#define GL_HISTOGRAM_ALPHA_SIZE 0x802B
+#define GL_HISTOGRAM_LUMINANCE_SIZE 0x802C
+#define GL_HISTOGRAM_SINK 0x802D
+#define GL_MINMAX 0x802E
+#define GL_MINMAX_FORMAT 0x802F
+#define GL_MINMAX_SINK 0x8030
+#define GL_TABLE_TOO_LARGE 0x8031
+#define GL_COLOR_MATRIX 0x80B1
+#define GL_COLOR_MATRIX_STACK_DEPTH 0x80B2
+#define GL_MAX_COLOR_MATRIX_STACK_DEPTH 0x80B3
+#define GL_POST_COLOR_MATRIX_RED_SCALE 0x80B4
+#define GL_POST_COLOR_MATRIX_GREEN_SCALE 0x80B5
+#define GL_POST_COLOR_MATRIX_BLUE_SCALE 0x80B6
+#define GL_POST_COLOR_MATRIX_ALPHA_SCALE 0x80B7
+#define GL_POST_COLOR_MATRIX_RED_BIAS 0x80B8
+#define GL_POST_COLOR_MATRIX_GREEN_BIAS 0x80B9
+#define GL_POST_COLOR_MATRIX_BLUE_BIAS 0x80BA
+#define GL_POST_COLOR_MATRIX_ALPHA_BIAS 0x80BB
+#define GL_COLOR_TABLE 0x80D0
+#define GL_POST_CONVOLUTION_COLOR_TABLE 0x80D1
+#define GL_POST_COLOR_MATRIX_COLOR_TABLE 0x80D2
+#define GL_PROXY_COLOR_TABLE 0x80D3
+#define GL_PROXY_POST_CONVOLUTION_COLOR_TABLE 0x80D4
+#define GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE 0x80D5
+#define GL_COLOR_TABLE_SCALE 0x80D6
+#define GL_COLOR_TABLE_BIAS 0x80D7
+#define GL_COLOR_TABLE_FORMAT 0x80D8
+#define GL_COLOR_TABLE_WIDTH 0x80D9
+#define GL_COLOR_TABLE_RED_SIZE 0x80DA
+#define GL_COLOR_TABLE_GREEN_SIZE 0x80DB
+#define GL_COLOR_TABLE_BLUE_SIZE 0x80DC
+#define GL_COLOR_TABLE_ALPHA_SIZE 0x80DD
+#define GL_COLOR_TABLE_LUMINANCE_SIZE 0x80DE
+#define GL_COLOR_TABLE_INTENSITY_SIZE 0x80DF
+#define GL_CONSTANT_BORDER 0x8151
+#define GL_REPLICATE_BORDER 0x8153
+#define GL_CONVOLUTION_BORDER_COLOR 0x8154
+#endif
+
+#ifndef GL_VERSION_1_3
+#define GL_TEXTURE0 0x84C0
+#define GL_TEXTURE1 0x84C1
+#define GL_TEXTURE2 0x84C2
+#define GL_TEXTURE3 0x84C3
+#define GL_TEXTURE4 0x84C4
+#define GL_TEXTURE5 0x84C5
+#define GL_TEXTURE6 0x84C6
+#define GL_TEXTURE7 0x84C7
+#define GL_TEXTURE8 0x84C8
+#define GL_TEXTURE9 0x84C9
+#define GL_TEXTURE10 0x84CA
+#define GL_TEXTURE11 0x84CB
+#define GL_TEXTURE12 0x84CC
+#define GL_TEXTURE13 0x84CD
+#define GL_TEXTURE14 0x84CE
+#define GL_TEXTURE15 0x84CF
+#define GL_TEXTURE16 0x84D0
+#define GL_TEXTURE17 0x84D1
+#define GL_TEXTURE18 0x84D2
+#define GL_TEXTURE19 0x84D3
+#define GL_TEXTURE20 0x84D4
+#define GL_TEXTURE21 0x84D5
+#define GL_TEXTURE22 0x84D6
+#define GL_TEXTURE23 0x84D7
+#define GL_TEXTURE24 0x84D8
+#define GL_TEXTURE25 0x84D9
+#define GL_TEXTURE26 0x84DA
+#define GL_TEXTURE27 0x84DB
+#define GL_TEXTURE28 0x84DC
+#define GL_TEXTURE29 0x84DD
+#define GL_TEXTURE30 0x84DE
+#define GL_TEXTURE31 0x84DF
+#define GL_ACTIVE_TEXTURE 0x84E0
+#define GL_MULTISAMPLE 0x809D
+#define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E
+#define GL_SAMPLE_ALPHA_TO_ONE 0x809F
+#define GL_SAMPLE_COVERAGE 0x80A0
+#define GL_SAMPLE_BUFFERS 0x80A8
+#define GL_SAMPLES 0x80A9
+#define GL_SAMPLE_COVERAGE_VALUE 0x80AA
+#define GL_SAMPLE_COVERAGE_INVERT 0x80AB
+#define GL_TEXTURE_CUBE_MAP 0x8513
+#define GL_TEXTURE_BINDING_CUBE_MAP 0x8514
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A
+#define GL_PROXY_TEXTURE_CUBE_MAP 0x851B
+#define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C
+#define GL_COMPRESSED_RGB 0x84ED
+#define GL_COMPRESSED_RGBA 0x84EE
+#define GL_TEXTURE_COMPRESSION_HINT 0x84EF
+#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE 0x86A0
+#define GL_TEXTURE_COMPRESSED 0x86A1
+#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2
+#define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3
+#define GL_CLAMP_TO_BORDER 0x812D
+#endif
+
+#ifndef GL_VERSION_1_3_DEPRECATED
+#define GL_CLIENT_ACTIVE_TEXTURE 0x84E1
+#define GL_MAX_TEXTURE_UNITS 0x84E2
+#define GL_TRANSPOSE_MODELVIEW_MATRIX 0x84E3
+#define GL_TRANSPOSE_PROJECTION_MATRIX 0x84E4
+#define GL_TRANSPOSE_TEXTURE_MATRIX 0x84E5
+#define GL_TRANSPOSE_COLOR_MATRIX 0x84E6
+#define GL_MULTISAMPLE_BIT 0x20000000
+#define GL_NORMAL_MAP 0x8511
+#define GL_REFLECTION_MAP 0x8512
+#define GL_COMPRESSED_ALPHA 0x84E9
+#define GL_COMPRESSED_LUMINANCE 0x84EA
+#define GL_COMPRESSED_LUMINANCE_ALPHA 0x84EB
+#define GL_COMPRESSED_INTENSITY 0x84EC
+#define GL_COMBINE 0x8570
+#define GL_COMBINE_RGB 0x8571
+#define GL_COMBINE_ALPHA 0x8572
+#define GL_SOURCE0_RGB 0x8580
+#define GL_SOURCE1_RGB 0x8581
+#define GL_SOURCE2_RGB 0x8582
+#define GL_SOURCE0_ALPHA 0x8588
+#define GL_SOURCE1_ALPHA 0x8589
+#define GL_SOURCE2_ALPHA 0x858A
+#define GL_OPERAND0_RGB 0x8590
+#define GL_OPERAND1_RGB 0x8591
+#define GL_OPERAND2_RGB 0x8592
+#define GL_OPERAND0_ALPHA 0x8598
+#define GL_OPERAND1_ALPHA 0x8599
+#define GL_OPERAND2_ALPHA 0x859A
+#define GL_RGB_SCALE 0x8573
+#define GL_ADD_SIGNED 0x8574
+#define GL_INTERPOLATE 0x8575
+#define GL_SUBTRACT 0x84E7
+#define GL_CONSTANT 0x8576
+#define GL_PRIMARY_COLOR 0x8577
+#define GL_PREVIOUS 0x8578
+#define GL_DOT3_RGB 0x86AE
+#define GL_DOT3_RGBA 0x86AF
+#endif
+
+#ifndef GL_VERSION_1_4
+#define GL_BLEND_DST_RGB 0x80C8
+#define GL_BLEND_SRC_RGB 0x80C9
+#define GL_BLEND_DST_ALPHA 0x80CA
+#define GL_BLEND_SRC_ALPHA 0x80CB
+#define GL_POINT_FADE_THRESHOLD_SIZE 0x8128
+#define GL_DEPTH_COMPONENT16 0x81A5
+#define GL_DEPTH_COMPONENT24 0x81A6
+#define GL_DEPTH_COMPONENT32 0x81A7
+#define GL_MIRRORED_REPEAT 0x8370
+#define GL_MAX_TEXTURE_LOD_BIAS 0x84FD
+#define GL_TEXTURE_LOD_BIAS 0x8501
+#define GL_INCR_WRAP 0x8507
+#define GL_DECR_WRAP 0x8508
+#define GL_TEXTURE_DEPTH_SIZE 0x884A
+#define GL_TEXTURE_COMPARE_MODE 0x884C
+#define GL_TEXTURE_COMPARE_FUNC 0x884D
+#endif
+
+#ifndef GL_VERSION_1_4_DEPRECATED
+#define GL_POINT_SIZE_MIN 0x8126
+#define GL_POINT_SIZE_MAX 0x8127
+#define GL_POINT_DISTANCE_ATTENUATION 0x8129
+#define GL_GENERATE_MIPMAP 0x8191
+#define GL_GENERATE_MIPMAP_HINT 0x8192
+#define GL_FOG_COORDINATE_SOURCE 0x8450
+#define GL_FOG_COORDINATE 0x8451
+#define GL_FRAGMENT_DEPTH 0x8452
+#define GL_CURRENT_FOG_COORDINATE 0x8453
+#define GL_FOG_COORDINATE_ARRAY_TYPE 0x8454
+#define GL_FOG_COORDINATE_ARRAY_STRIDE 0x8455
+#define GL_FOG_COORDINATE_ARRAY_POINTER 0x8456
+#define GL_FOG_COORDINATE_ARRAY 0x8457
+#define GL_COLOR_SUM 0x8458
+#define GL_CURRENT_SECONDARY_COLOR 0x8459
+#define GL_SECONDARY_COLOR_ARRAY_SIZE 0x845A
+#define GL_SECONDARY_COLOR_ARRAY_TYPE 0x845B
+#define GL_SECONDARY_COLOR_ARRAY_STRIDE 0x845C
+#define GL_SECONDARY_COLOR_ARRAY_POINTER 0x845D
+#define GL_SECONDARY_COLOR_ARRAY 0x845E
+#define GL_TEXTURE_FILTER_CONTROL 0x8500
+#define GL_DEPTH_TEXTURE_MODE 0x884B
+#define GL_COMPARE_R_TO_TEXTURE 0x884E
+#endif
+
+#ifndef GL_VERSION_1_5
+#define GL_BUFFER_SIZE 0x8764
+#define GL_BUFFER_USAGE 0x8765
+#define GL_QUERY_COUNTER_BITS 0x8864
+#define GL_CURRENT_QUERY 0x8865
+#define GL_QUERY_RESULT 0x8866
+#define GL_QUERY_RESULT_AVAILABLE 0x8867
+#define GL_ARRAY_BUFFER 0x8892
+#define GL_ELEMENT_ARRAY_BUFFER 0x8893
+#define GL_ARRAY_BUFFER_BINDING 0x8894
+#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895
+#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F
+#define GL_READ_ONLY 0x88B8
+#define GL_WRITE_ONLY 0x88B9
+#define GL_READ_WRITE 0x88BA
+#define GL_BUFFER_ACCESS 0x88BB
+#define GL_BUFFER_MAPPED 0x88BC
+#define GL_BUFFER_MAP_POINTER 0x88BD
+#define GL_STREAM_DRAW 0x88E0
+#define GL_STREAM_READ 0x88E1
+#define GL_STREAM_COPY 0x88E2
+#define GL_STATIC_DRAW 0x88E4
+#define GL_STATIC_READ 0x88E5
+#define GL_STATIC_COPY 0x88E6
+#define GL_DYNAMIC_DRAW 0x88E8
+#define GL_DYNAMIC_READ 0x88E9
+#define GL_DYNAMIC_COPY 0x88EA
+#define GL_SAMPLES_PASSED 0x8914
+#endif
+
+#ifndef GL_VERSION_1_5_DEPRECATED
+#define GL_VERTEX_ARRAY_BUFFER_BINDING 0x8896
+#define GL_NORMAL_ARRAY_BUFFER_BINDING 0x8897
+#define GL_COLOR_ARRAY_BUFFER_BINDING 0x8898
+#define GL_INDEX_ARRAY_BUFFER_BINDING 0x8899
+#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING 0x889A
+#define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING 0x889B
+#define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING 0x889C
+#define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING 0x889D
+#define GL_WEIGHT_ARRAY_BUFFER_BINDING 0x889E
+#define GL_FOG_COORD_SRC 0x8450
+#define GL_FOG_COORD 0x8451
+#define GL_CURRENT_FOG_COORD 0x8453
+#define GL_FOG_COORD_ARRAY_TYPE 0x8454
+#define GL_FOG_COORD_ARRAY_STRIDE 0x8455
+#define GL_FOG_COORD_ARRAY_POINTER 0x8456
+#define GL_FOG_COORD_ARRAY 0x8457
+#define GL_FOG_COORD_ARRAY_BUFFER_BINDING 0x889D
+#define GL_SRC0_RGB 0x8580
+#define GL_SRC1_RGB 0x8581
+#define GL_SRC2_RGB 0x8582
+#define GL_SRC0_ALPHA 0x8588
+#define GL_SRC1_ALPHA 0x8589
+#define GL_SRC2_ALPHA 0x858A
+#endif
+
+#ifndef GL_VERSION_2_0
+#define GL_BLEND_EQUATION_RGB 0x8009
+#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622
+#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623
+#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624
+#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625
+#define GL_CURRENT_VERTEX_ATTRIB 0x8626
+#define GL_VERTEX_PROGRAM_POINT_SIZE 0x8642
+#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645
+#define GL_STENCIL_BACK_FUNC 0x8800
+#define GL_STENCIL_BACK_FAIL 0x8801
+#define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802
+#define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803
+#define GL_MAX_DRAW_BUFFERS 0x8824
+#define GL_DRAW_BUFFER0 0x8825
+#define GL_DRAW_BUFFER1 0x8826
+#define GL_DRAW_BUFFER2 0x8827
+#define GL_DRAW_BUFFER3 0x8828
+#define GL_DRAW_BUFFER4 0x8829
+#define GL_DRAW_BUFFER5 0x882A
+#define GL_DRAW_BUFFER6 0x882B
+#define GL_DRAW_BUFFER7 0x882C
+#define GL_DRAW_BUFFER8 0x882D
+#define GL_DRAW_BUFFER9 0x882E
+#define GL_DRAW_BUFFER10 0x882F
+#define GL_DRAW_BUFFER11 0x8830
+#define GL_DRAW_BUFFER12 0x8831
+#define GL_DRAW_BUFFER13 0x8832
+#define GL_DRAW_BUFFER14 0x8833
+#define GL_DRAW_BUFFER15 0x8834
+#define GL_BLEND_EQUATION_ALPHA 0x883D
+#define GL_MAX_VERTEX_ATTRIBS 0x8869
+#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A
+#define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872
+#define GL_FRAGMENT_SHADER 0x8B30
+#define GL_VERTEX_SHADER 0x8B31
+#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49
+#define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A
+#define GL_MAX_VARYING_FLOATS 0x8B4B
+#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C
+#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D
+#define GL_SHADER_TYPE 0x8B4F
+#define GL_FLOAT_VEC2 0x8B50
+#define GL_FLOAT_VEC3 0x8B51
+#define GL_FLOAT_VEC4 0x8B52
+#define GL_INT_VEC2 0x8B53
+#define GL_INT_VEC3 0x8B54
+#define GL_INT_VEC4 0x8B55
+#define GL_BOOL 0x8B56
+#define GL_BOOL_VEC2 0x8B57
+#define GL_BOOL_VEC3 0x8B58
+#define GL_BOOL_VEC4 0x8B59
+#define GL_FLOAT_MAT2 0x8B5A
+#define GL_FLOAT_MAT3 0x8B5B
+#define GL_FLOAT_MAT4 0x8B5C
+#define GL_SAMPLER_1D 0x8B5D
+#define GL_SAMPLER_2D 0x8B5E
+#define GL_SAMPLER_3D 0x8B5F
+#define GL_SAMPLER_CUBE 0x8B60
+#define GL_SAMPLER_1D_SHADOW 0x8B61
+#define GL_SAMPLER_2D_SHADOW 0x8B62
+#define GL_DELETE_STATUS 0x8B80
+#define GL_COMPILE_STATUS 0x8B81
+#define GL_LINK_STATUS 0x8B82
+#define GL_VALIDATE_STATUS 0x8B83
+#define GL_INFO_LOG_LENGTH 0x8B84
+#define GL_ATTACHED_SHADERS 0x8B85
+#define GL_ACTIVE_UNIFORMS 0x8B86
+#define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87
+#define GL_SHADER_SOURCE_LENGTH 0x8B88
+#define GL_ACTIVE_ATTRIBUTES 0x8B89
+#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A
+#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT 0x8B8B
+#define GL_SHADING_LANGUAGE_VERSION 0x8B8C
+#define GL_CURRENT_PROGRAM 0x8B8D
+#define GL_POINT_SPRITE_COORD_ORIGIN 0x8CA0
+#define GL_LOWER_LEFT 0x8CA1
+#define GL_UPPER_LEFT 0x8CA2
+#define GL_STENCIL_BACK_REF 0x8CA3
+#define GL_STENCIL_BACK_VALUE_MASK 0x8CA4
+#define GL_STENCIL_BACK_WRITEMASK 0x8CA5
+#endif
+
+#ifndef GL_VERSION_2_0_DEPRECATED
+#define GL_VERTEX_PROGRAM_TWO_SIDE 0x8643
+#define GL_POINT_SPRITE 0x8861
+#define GL_COORD_REPLACE 0x8862
+#define GL_MAX_TEXTURE_COORDS 0x8871
+#endif
+
+#ifndef GL_VERSION_2_1
+#define GL_PIXEL_PACK_BUFFER 0x88EB
+#define GL_PIXEL_UNPACK_BUFFER 0x88EC
+#define GL_PIXEL_PACK_BUFFER_BINDING 0x88ED
+#define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF
+#define GL_FLOAT_MAT2x3 0x8B65
+#define GL_FLOAT_MAT2x4 0x8B66
+#define GL_FLOAT_MAT3x2 0x8B67
+#define GL_FLOAT_MAT3x4 0x8B68
+#define GL_FLOAT_MAT4x2 0x8B69
+#define GL_FLOAT_MAT4x3 0x8B6A
+#define GL_SRGB 0x8C40
+#define GL_SRGB8 0x8C41
+#define GL_SRGB_ALPHA 0x8C42
+#define GL_SRGB8_ALPHA8 0x8C43
+#define GL_COMPRESSED_SRGB 0x8C48
+#define GL_COMPRESSED_SRGB_ALPHA 0x8C49
+#endif
+
+#ifndef GL_VERSION_2_1_DEPRECATED
+#define GL_CURRENT_RASTER_SECONDARY_COLOR 0x845F
+#define GL_SLUMINANCE_ALPHA 0x8C44
+#define GL_SLUMINANCE8_ALPHA8 0x8C45
+#define GL_SLUMINANCE 0x8C46
+#define GL_SLUMINANCE8 0x8C47
+#define GL_COMPRESSED_SLUMINANCE 0x8C4A
+#define GL_COMPRESSED_SLUMINANCE_ALPHA 0x8C4B
+#endif
+
+#ifndef GL_VERSION_3_0
+#define GL_COMPARE_REF_TO_TEXTURE 0x884E
+#define GL_CLIP_DISTANCE0 0x3000
+#define GL_CLIP_DISTANCE1 0x3001
+#define GL_CLIP_DISTANCE2 0x3002
+#define GL_CLIP_DISTANCE3 0x3003
+#define GL_CLIP_DISTANCE4 0x3004
+#define GL_CLIP_DISTANCE5 0x3005
+#define GL_CLIP_DISTANCE6 0x3006
+#define GL_CLIP_DISTANCE7 0x3007
+#define GL_MAX_CLIP_DISTANCES 0x0D32
+#define GL_MAJOR_VERSION 0x821B
+#define GL_MINOR_VERSION 0x821C
+#define GL_NUM_EXTENSIONS 0x821D
+#define GL_CONTEXT_FLAGS 0x821E
+#define GL_DEPTH_BUFFER 0x8223
+#define GL_STENCIL_BUFFER 0x8224
+#define GL_COMPRESSED_RED 0x8225
+#define GL_COMPRESSED_RG 0x8226
+#define GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT 0x0001
+#define GL_RGBA32F 0x8814
+#define GL_RGB32F 0x8815
+#define GL_RGBA16F 0x881A
+#define GL_RGB16F 0x881B
+#define GL_VERTEX_ATTRIB_ARRAY_INTEGER 0x88FD
+#define GL_MAX_ARRAY_TEXTURE_LAYERS 0x88FF
+#define GL_MIN_PROGRAM_TEXEL_OFFSET 0x8904
+#define GL_MAX_PROGRAM_TEXEL_OFFSET 0x8905
+#define GL_CLAMP_READ_COLOR 0x891C
+#define GL_FIXED_ONLY 0x891D
+#define GL_MAX_VARYING_COMPONENTS 0x8B4B
+#define GL_TEXTURE_1D_ARRAY 0x8C18
+#define GL_PROXY_TEXTURE_1D_ARRAY 0x8C19
+#define GL_TEXTURE_2D_ARRAY 0x8C1A
+#define GL_PROXY_TEXTURE_2D_ARRAY 0x8C1B
+#define GL_TEXTURE_BINDING_1D_ARRAY 0x8C1C
+#define GL_TEXTURE_BINDING_2D_ARRAY 0x8C1D
+#define GL_R11F_G11F_B10F 0x8C3A
+#define GL_UNSIGNED_INT_10F_11F_11F_REV 0x8C3B
+#define GL_RGB9_E5 0x8C3D
+#define GL_UNSIGNED_INT_5_9_9_9_REV 0x8C3E
+#define GL_TEXTURE_SHARED_SIZE 0x8C3F
+#define GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH 0x8C76
+#define GL_TRANSFORM_FEEDBACK_BUFFER_MODE 0x8C7F
+#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS 0x8C80
+#define GL_TRANSFORM_FEEDBACK_VARYINGS 0x8C83
+#define GL_TRANSFORM_FEEDBACK_BUFFER_START 0x8C84
+#define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE 0x8C85
+#define GL_PRIMITIVES_GENERATED 0x8C87
+#define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN 0x8C88
+#define GL_RASTERIZER_DISCARD 0x8C89
+#define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS 0x8C8A
+#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS 0x8C8B
+#define GL_INTERLEAVED_ATTRIBS 0x8C8C
+#define GL_SEPARATE_ATTRIBS 0x8C8D
+#define GL_TRANSFORM_FEEDBACK_BUFFER 0x8C8E
+#define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING 0x8C8F
+#define GL_RGBA32UI 0x8D70
+#define GL_RGB32UI 0x8D71
+#define GL_RGBA16UI 0x8D76
+#define GL_RGB16UI 0x8D77
+#define GL_RGBA8UI 0x8D7C
+#define GL_RGB8UI 0x8D7D
+#define GL_RGBA32I 0x8D82
+#define GL_RGB32I 0x8D83
+#define GL_RGBA16I 0x8D88
+#define GL_RGB16I 0x8D89
+#define GL_RGBA8I 0x8D8E
+#define GL_RGB8I 0x8D8F
+#define GL_RED_INTEGER 0x8D94
+#define GL_GREEN_INTEGER 0x8D95
+#define GL_BLUE_INTEGER 0x8D96
+#define GL_RGB_INTEGER 0x8D98
+#define GL_RGBA_INTEGER 0x8D99
+#define GL_BGR_INTEGER 0x8D9A
+#define GL_BGRA_INTEGER 0x8D9B
+#define GL_SAMPLER_1D_ARRAY 0x8DC0
+#define GL_SAMPLER_2D_ARRAY 0x8DC1
+#define GL_SAMPLER_1D_ARRAY_SHADOW 0x8DC3
+#define GL_SAMPLER_2D_ARRAY_SHADOW 0x8DC4
+#define GL_SAMPLER_CUBE_SHADOW 0x8DC5
+#define GL_UNSIGNED_INT_VEC2 0x8DC6
+#define GL_UNSIGNED_INT_VEC3 0x8DC7
+#define GL_UNSIGNED_INT_VEC4 0x8DC8
+#define GL_INT_SAMPLER_1D 0x8DC9
+#define GL_INT_SAMPLER_2D 0x8DCA
+#define GL_INT_SAMPLER_3D 0x8DCB
+#define GL_INT_SAMPLER_CUBE 0x8DCC
+#define GL_INT_SAMPLER_1D_ARRAY 0x8DCE
+#define GL_INT_SAMPLER_2D_ARRAY 0x8DCF
+#define GL_UNSIGNED_INT_SAMPLER_1D 0x8DD1
+#define GL_UNSIGNED_INT_SAMPLER_2D 0x8DD2
+#define GL_UNSIGNED_INT_SAMPLER_3D 0x8DD3
+#define GL_UNSIGNED_INT_SAMPLER_CUBE 0x8DD4
+#define GL_UNSIGNED_INT_SAMPLER_1D_ARRAY 0x8DD6
+#define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY 0x8DD7
+#define GL_QUERY_WAIT 0x8E13
+#define GL_QUERY_NO_WAIT 0x8E14
+#define GL_QUERY_BY_REGION_WAIT 0x8E15
+#define GL_QUERY_BY_REGION_NO_WAIT 0x8E16
+#define GL_BUFFER_ACCESS_FLAGS 0x911F
+#define GL_BUFFER_MAP_LENGTH 0x9120
+#define GL_BUFFER_MAP_OFFSET 0x9121
+/* Reuse tokens from ARB_depth_buffer_float */
+/* reuse GL_DEPTH_COMPONENT32F */
+/* reuse GL_DEPTH32F_STENCIL8 */
+/* reuse GL_FLOAT_32_UNSIGNED_INT_24_8_REV */
+/* Reuse tokens from ARB_framebuffer_object */
+/* reuse GL_INVALID_FRAMEBUFFER_OPERATION */
+/* reuse GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING */
+/* reuse GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE */
+/* reuse GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE */
+/* reuse GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE */
+/* reuse GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE */
+/* reuse GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE */
+/* reuse GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE */
+/* reuse GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE */
+/* reuse GL_FRAMEBUFFER_DEFAULT */
+/* reuse GL_FRAMEBUFFER_UNDEFINED */
+/* reuse GL_DEPTH_STENCIL_ATTACHMENT */
+/* reuse GL_INDEX */
+/* reuse GL_MAX_RENDERBUFFER_SIZE */
+/* reuse GL_DEPTH_STENCIL */
+/* reuse GL_UNSIGNED_INT_24_8 */
+/* reuse GL_DEPTH24_STENCIL8 */
+/* reuse GL_TEXTURE_STENCIL_SIZE */
+/* reuse GL_TEXTURE_RED_TYPE */
+/* reuse GL_TEXTURE_GREEN_TYPE */
+/* reuse GL_TEXTURE_BLUE_TYPE */
+/* reuse GL_TEXTURE_ALPHA_TYPE */
+/* reuse GL_TEXTURE_DEPTH_TYPE */
+/* reuse GL_UNSIGNED_NORMALIZED */
+/* reuse GL_FRAMEBUFFER_BINDING */
+/* reuse GL_DRAW_FRAMEBUFFER_BINDING */
+/* reuse GL_RENDERBUFFER_BINDING */
+/* reuse GL_READ_FRAMEBUFFER */
+/* reuse GL_DRAW_FRAMEBUFFER */
+/* reuse GL_READ_FRAMEBUFFER_BINDING */
+/* reuse GL_RENDERBUFFER_SAMPLES */
+/* reuse GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE */
+/* reuse GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME */
+/* reuse GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL */
+/* reuse GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE */
+/* reuse GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER */
+/* reuse GL_FRAMEBUFFER_COMPLETE */
+/* reuse GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT */
+/* reuse GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT */
+/* reuse GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER */
+/* reuse GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER */
+/* reuse GL_FRAMEBUFFER_UNSUPPORTED */
+/* reuse GL_MAX_COLOR_ATTACHMENTS */
+/* reuse GL_COLOR_ATTACHMENT0 */
+/* reuse GL_COLOR_ATTACHMENT1 */
+/* reuse GL_COLOR_ATTACHMENT2 */
+/* reuse GL_COLOR_ATTACHMENT3 */
+/* reuse GL_COLOR_ATTACHMENT4 */
+/* reuse GL_COLOR_ATTACHMENT5 */
+/* reuse GL_COLOR_ATTACHMENT6 */
+/* reuse GL_COLOR_ATTACHMENT7 */
+/* reuse GL_COLOR_ATTACHMENT8 */
+/* reuse GL_COLOR_ATTACHMENT9 */
+/* reuse GL_COLOR_ATTACHMENT10 */
+/* reuse GL_COLOR_ATTACHMENT11 */
+/* reuse GL_COLOR_ATTACHMENT12 */
+/* reuse GL_COLOR_ATTACHMENT13 */
+/* reuse GL_COLOR_ATTACHMENT14 */
+/* reuse GL_COLOR_ATTACHMENT15 */
+/* reuse GL_DEPTH_ATTACHMENT */
+/* reuse GL_STENCIL_ATTACHMENT */
+/* reuse GL_FRAMEBUFFER */
+/* reuse GL_RENDERBUFFER */
+/* reuse GL_RENDERBUFFER_WIDTH */
+/* reuse GL_RENDERBUFFER_HEIGHT */
+/* reuse GL_RENDERBUFFER_INTERNAL_FORMAT */
+/* reuse GL_STENCIL_INDEX1 */
+/* reuse GL_STENCIL_INDEX4 */
+/* reuse GL_STENCIL_INDEX8 */
+/* reuse GL_STENCIL_INDEX16 */
+/* reuse GL_RENDERBUFFER_RED_SIZE */
+/* reuse GL_RENDERBUFFER_GREEN_SIZE */
+/* reuse GL_RENDERBUFFER_BLUE_SIZE */
+/* reuse GL_RENDERBUFFER_ALPHA_SIZE */
+/* reuse GL_RENDERBUFFER_DEPTH_SIZE */
+/* reuse GL_RENDERBUFFER_STENCIL_SIZE */
+/* reuse GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE */
+/* reuse GL_MAX_SAMPLES */
+/* Reuse tokens from ARB_framebuffer_sRGB */
+/* reuse GL_FRAMEBUFFER_SRGB */
+/* Reuse tokens from ARB_half_float_vertex */
+/* reuse GL_HALF_FLOAT */
+/* Reuse tokens from ARB_map_buffer_range */
+/* reuse GL_MAP_READ_BIT */
+/* reuse GL_MAP_WRITE_BIT */
+/* reuse GL_MAP_INVALIDATE_RANGE_BIT */
+/* reuse GL_MAP_INVALIDATE_BUFFER_BIT */
+/* reuse GL_MAP_FLUSH_EXPLICIT_BIT */
+/* reuse GL_MAP_UNSYNCHRONIZED_BIT */
+/* Reuse tokens from ARB_texture_compression_rgtc */
+/* reuse GL_COMPRESSED_RED_RGTC1 */
+/* reuse GL_COMPRESSED_SIGNED_RED_RGTC1 */
+/* reuse GL_COMPRESSED_RG_RGTC2 */
+/* reuse GL_COMPRESSED_SIGNED_RG_RGTC2 */
+/* Reuse tokens from ARB_texture_rg */
+/* reuse GL_RG */
+/* reuse GL_RG_INTEGER */
+/* reuse GL_R8 */
+/* reuse GL_R16 */
+/* reuse GL_RG8 */
+/* reuse GL_RG16 */
+/* reuse GL_R16F */
+/* reuse GL_R32F */
+/* reuse GL_RG16F */
+/* reuse GL_RG32F */
+/* reuse GL_R8I */
+/* reuse GL_R8UI */
+/* reuse GL_R16I */
+/* reuse GL_R16UI */
+/* reuse GL_R32I */
+/* reuse GL_R32UI */
+/* reuse GL_RG8I */
+/* reuse GL_RG8UI */
+/* reuse GL_RG16I */
+/* reuse GL_RG16UI */
+/* reuse GL_RG32I */
+/* reuse GL_RG32UI */
+/* Reuse tokens from ARB_vertex_array_object */
+/* reuse GL_VERTEX_ARRAY_BINDING */
+#endif
+
+#ifndef GL_VERSION_3_0_DEPRECATED
+#define GL_CLAMP_VERTEX_COLOR 0x891A
+#define GL_CLAMP_FRAGMENT_COLOR 0x891B
+#define GL_ALPHA_INTEGER 0x8D97
+/* Reuse tokens from ARB_framebuffer_object */
+/* reuse GL_TEXTURE_LUMINANCE_TYPE */
+/* reuse GL_TEXTURE_INTENSITY_TYPE */
+#endif
+
+#ifndef GL_VERSION_3_1
+#define GL_SAMPLER_2D_RECT 0x8B63
+#define GL_SAMPLER_2D_RECT_SHADOW 0x8B64
+#define GL_SAMPLER_BUFFER 0x8DC2
+#define GL_INT_SAMPLER_2D_RECT 0x8DCD
+#define GL_INT_SAMPLER_BUFFER 0x8DD0
+#define GL_UNSIGNED_INT_SAMPLER_2D_RECT 0x8DD5
+#define GL_UNSIGNED_INT_SAMPLER_BUFFER 0x8DD8
+#define GL_TEXTURE_BUFFER 0x8C2A
+#define GL_MAX_TEXTURE_BUFFER_SIZE 0x8C2B
+#define GL_TEXTURE_BINDING_BUFFER 0x8C2C
+#define GL_TEXTURE_BUFFER_DATA_STORE_BINDING 0x8C2D
+#define GL_TEXTURE_BUFFER_FORMAT 0x8C2E
+#define GL_TEXTURE_RECTANGLE 0x84F5
+#define GL_TEXTURE_BINDING_RECTANGLE 0x84F6
+#define GL_PROXY_TEXTURE_RECTANGLE 0x84F7
+#define GL_MAX_RECTANGLE_TEXTURE_SIZE 0x84F8
+#define GL_RED_SNORM 0x8F90
+#define GL_RG_SNORM 0x8F91
+#define GL_RGB_SNORM 0x8F92
+#define GL_RGBA_SNORM 0x8F93
+#define GL_R8_SNORM 0x8F94
+#define GL_RG8_SNORM 0x8F95
+#define GL_RGB8_SNORM 0x8F96
+#define GL_RGBA8_SNORM 0x8F97
+#define GL_R16_SNORM 0x8F98
+#define GL_RG16_SNORM 0x8F99
+#define GL_RGB16_SNORM 0x8F9A
+#define GL_RGBA16_SNORM 0x8F9B
+#define GL_SIGNED_NORMALIZED 0x8F9C
+#define GL_PRIMITIVE_RESTART 0x8F9D
+#define GL_PRIMITIVE_RESTART_INDEX 0x8F9E
+/* Reuse tokens from ARB_copy_buffer */
+/* reuse GL_COPY_READ_BUFFER */
+/* reuse GL_COPY_WRITE_BUFFER */
+/* Reuse tokens from ARB_draw_instanced (none) */
+/* Reuse tokens from ARB_uniform_buffer_object */
+/* reuse GL_UNIFORM_BUFFER */
+/* reuse GL_UNIFORM_BUFFER_BINDING */
+/* reuse GL_UNIFORM_BUFFER_START */
+/* reuse GL_UNIFORM_BUFFER_SIZE */
+/* reuse GL_MAX_VERTEX_UNIFORM_BLOCKS */
+/* reuse GL_MAX_FRAGMENT_UNIFORM_BLOCKS */
+/* reuse GL_MAX_COMBINED_UNIFORM_BLOCKS */
+/* reuse GL_MAX_UNIFORM_BUFFER_BINDINGS */
+/* reuse GL_MAX_UNIFORM_BLOCK_SIZE */
+/* reuse GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS */
+/* reuse GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS */
+/* reuse GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT */
+/* reuse GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH */
+/* reuse GL_ACTIVE_UNIFORM_BLOCKS */
+/* reuse GL_UNIFORM_TYPE */
+/* reuse GL_UNIFORM_SIZE */
+/* reuse GL_UNIFORM_NAME_LENGTH */
+/* reuse GL_UNIFORM_BLOCK_INDEX */
+/* reuse GL_UNIFORM_OFFSET */
+/* reuse GL_UNIFORM_ARRAY_STRIDE */
+/* reuse GL_UNIFORM_MATRIX_STRIDE */
+/* reuse GL_UNIFORM_IS_ROW_MAJOR */
+/* reuse GL_UNIFORM_BLOCK_BINDING */
+/* reuse GL_UNIFORM_BLOCK_DATA_SIZE */
+/* reuse GL_UNIFORM_BLOCK_NAME_LENGTH */
+/* reuse GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS */
+/* reuse GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES */
+/* reuse GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER */
+/* reuse GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER */
+/* reuse GL_INVALID_INDEX */
+#endif
+
+#ifndef GL_VERSION_3_2
+#define GL_CONTEXT_CORE_PROFILE_BIT 0x00000001
+#define GL_CONTEXT_COMPATIBILITY_PROFILE_BIT 0x00000002
+#define GL_LINES_ADJACENCY 0x000A
+#define GL_LINE_STRIP_ADJACENCY 0x000B
+#define GL_TRIANGLES_ADJACENCY 0x000C
+#define GL_TRIANGLE_STRIP_ADJACENCY 0x000D
+#define GL_PROGRAM_POINT_SIZE 0x8642
+#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS 0x8C29
+#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED 0x8DA7
+#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS 0x8DA8
+#define GL_GEOMETRY_SHADER 0x8DD9
+#define GL_GEOMETRY_VERTICES_OUT 0x8916
+#define GL_GEOMETRY_INPUT_TYPE 0x8917
+#define GL_GEOMETRY_OUTPUT_TYPE 0x8918
+#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS 0x8DDF
+#define GL_MAX_GEOMETRY_OUTPUT_VERTICES 0x8DE0
+#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS 0x8DE1
+#define GL_MAX_VERTEX_OUTPUT_COMPONENTS 0x9122
+#define GL_MAX_GEOMETRY_INPUT_COMPONENTS 0x9123
+#define GL_MAX_GEOMETRY_OUTPUT_COMPONENTS 0x9124
+#define GL_MAX_FRAGMENT_INPUT_COMPONENTS 0x9125
+#define GL_CONTEXT_PROFILE_MASK 0x9126
+/* reuse GL_MAX_VARYING_COMPONENTS */
+/* reuse GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER */
+/* Reuse tokens from ARB_depth_clamp */
+/* reuse GL_DEPTH_CLAMP */
+/* Reuse tokens from ARB_draw_elements_base_vertex (none) */
+/* Reuse tokens from ARB_fragment_coord_conventions (none) */
+/* Reuse tokens from ARB_provoking_vertex */
+/* reuse GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION */
+/* reuse GL_FIRST_VERTEX_CONVENTION */
+/* reuse GL_LAST_VERTEX_CONVENTION */
+/* reuse GL_PROVOKING_VERTEX */
+/* Reuse tokens from ARB_seamless_cube_map */
+/* reuse GL_TEXTURE_CUBE_MAP_SEAMLESS */
+/* Reuse tokens from ARB_sync */
+/* reuse GL_MAX_SERVER_WAIT_TIMEOUT */
+/* reuse GL_OBJECT_TYPE */
+/* reuse GL_SYNC_CONDITION */
+/* reuse GL_SYNC_STATUS */
+/* reuse GL_SYNC_FLAGS */
+/* reuse GL_SYNC_FENCE */
+/* reuse GL_SYNC_GPU_COMMANDS_COMPLETE */
+/* reuse GL_UNSIGNALED */
+/* reuse GL_SIGNALED */
+/* reuse GL_ALREADY_SIGNALED */
+/* reuse GL_TIMEOUT_EXPIRED */
+/* reuse GL_CONDITION_SATISFIED */
+/* reuse GL_WAIT_FAILED */
+/* reuse GL_TIMEOUT_IGNORED */
+/* reuse GL_SYNC_FLUSH_COMMANDS_BIT */
+/* reuse GL_TIMEOUT_IGNORED */
+/* Reuse tokens from ARB_texture_multisample */
+/* reuse GL_SAMPLE_POSITION */
+/* reuse GL_SAMPLE_MASK */
+/* reuse GL_SAMPLE_MASK_VALUE */
+/* reuse GL_MAX_SAMPLE_MASK_WORDS */
+/* reuse GL_TEXTURE_2D_MULTISAMPLE */
+/* reuse GL_PROXY_TEXTURE_2D_MULTISAMPLE */
+/* reuse GL_TEXTURE_2D_MULTISAMPLE_ARRAY */
+/* reuse GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY */
+/* reuse GL_TEXTURE_BINDING_2D_MULTISAMPLE */
+/* reuse GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY */
+/* reuse GL_TEXTURE_SAMPLES */
+/* reuse GL_TEXTURE_FIXED_SAMPLE_LOCATIONS */
+/* reuse GL_SAMPLER_2D_MULTISAMPLE */
+/* reuse GL_INT_SAMPLER_2D_MULTISAMPLE */
+/* reuse GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE */
+/* reuse GL_SAMPLER_2D_MULTISAMPLE_ARRAY */
+/* reuse GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY */
+/* reuse GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY */
+/* reuse GL_MAX_COLOR_TEXTURE_SAMPLES */
+/* reuse GL_MAX_DEPTH_TEXTURE_SAMPLES */
+/* reuse GL_MAX_INTEGER_SAMPLES */
+/* Don't need to reuse tokens from ARB_vertex_array_bgra since they're already in 1.2 core */
+#endif
+
+#ifndef GL_VERSION_3_3
+#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR 0x88FE
+/* Reuse tokens from ARB_blend_func_extended */
+/* reuse GL_SRC1_COLOR */
+/* reuse GL_ONE_MINUS_SRC1_COLOR */
+/* reuse GL_ONE_MINUS_SRC1_ALPHA */
+/* reuse GL_MAX_DUAL_SOURCE_DRAW_BUFFERS */
+/* Reuse tokens from ARB_explicit_attrib_location (none) */
+/* Reuse tokens from ARB_occlusion_query2 */
+/* reuse GL_ANY_SAMPLES_PASSED */
+/* Reuse tokens from ARB_sampler_objects */
+/* reuse GL_SAMPLER_BINDING */
+/* Reuse tokens from ARB_shader_bit_encoding (none) */
+/* Reuse tokens from ARB_texture_rgb10_a2ui */
+/* reuse GL_RGB10_A2UI */
+/* Reuse tokens from ARB_texture_swizzle */
+/* reuse GL_TEXTURE_SWIZZLE_R */
+/* reuse GL_TEXTURE_SWIZZLE_G */
+/* reuse GL_TEXTURE_SWIZZLE_B */
+/* reuse GL_TEXTURE_SWIZZLE_A */
+/* reuse GL_TEXTURE_SWIZZLE_RGBA */
+/* Reuse tokens from ARB_timer_query */
+/* reuse GL_TIME_ELAPSED */
+/* reuse GL_TIMESTAMP */
+/* Reuse tokens from ARB_vertex_type_2_10_10_10_rev */
+/* reuse GL_INT_2_10_10_10_REV */
+#endif
+
+#ifndef GL_VERSION_4_0
+#define GL_SAMPLE_SHADING 0x8C36
+#define GL_MIN_SAMPLE_SHADING_VALUE 0x8C37
+#define GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET 0x8E5E
+#define GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET 0x8E5F
+#define GL_TEXTURE_CUBE_MAP_ARRAY 0x9009
+#define GL_TEXTURE_BINDING_CUBE_MAP_ARRAY 0x900A
+#define GL_PROXY_TEXTURE_CUBE_MAP_ARRAY 0x900B
+#define GL_SAMPLER_CUBE_MAP_ARRAY 0x900C
+#define GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW 0x900D
+#define GL_INT_SAMPLER_CUBE_MAP_ARRAY 0x900E
+#define GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY 0x900F
+/* Reuse tokens from ARB_texture_query_lod (none) */
+/* Reuse tokens from ARB_draw_buffers_blend (none) */
+/* Reuse tokens from ARB_draw_indirect */
+/* reuse GL_DRAW_INDIRECT_BUFFER */
+/* reuse GL_DRAW_INDIRECT_BUFFER_BINDING */
+/* Reuse tokens from ARB_gpu_shader5 */
+/* reuse GL_GEOMETRY_SHADER_INVOCATIONS */
+/* reuse GL_MAX_GEOMETRY_SHADER_INVOCATIONS */
+/* reuse GL_MIN_FRAGMENT_INTERPOLATION_OFFSET */
+/* reuse GL_MAX_FRAGMENT_INTERPOLATION_OFFSET */
+/* reuse GL_FRAGMENT_INTERPOLATION_OFFSET_BITS */
+/* reuse GL_MAX_VERTEX_STREAMS */
+/* Reuse tokens from ARB_gpu_shader_fp64 */
+/* reuse GL_DOUBLE_VEC2 */
+/* reuse GL_DOUBLE_VEC3 */
+/* reuse GL_DOUBLE_VEC4 */
+/* reuse GL_DOUBLE_MAT2 */
+/* reuse GL_DOUBLE_MAT3 */
+/* reuse GL_DOUBLE_MAT4 */
+/* reuse GL_DOUBLE_MAT2x3 */
+/* reuse GL_DOUBLE_MAT2x4 */
+/* reuse GL_DOUBLE_MAT3x2 */
+/* reuse GL_DOUBLE_MAT3x4 */
+/* reuse GL_DOUBLE_MAT4x2 */
+/* reuse GL_DOUBLE_MAT4x3 */
+/* Reuse tokens from ARB_shader_subroutine */
+/* reuse GL_ACTIVE_SUBROUTINES */
+/* reuse GL_ACTIVE_SUBROUTINE_UNIFORMS */
+/* reuse GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS */
+/* reuse GL_ACTIVE_SUBROUTINE_MAX_LENGTH */
+/* reuse GL_ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH */
+/* reuse GL_MAX_SUBROUTINES */
+/* reuse GL_MAX_SUBROUTINE_UNIFORM_LOCATIONS */
+/* reuse GL_NUM_COMPATIBLE_SUBROUTINES */
+/* reuse GL_COMPATIBLE_SUBROUTINES */
+/* Reuse tokens from ARB_tessellation_shader */
+/* reuse GL_PATCHES */
+/* reuse GL_PATCH_VERTICES */
+/* reuse GL_PATCH_DEFAULT_INNER_LEVEL */
+/* reuse GL_PATCH_DEFAULT_OUTER_LEVEL */
+/* reuse GL_TESS_CONTROL_OUTPUT_VERTICES */
+/* reuse GL_TESS_GEN_MODE */
+/* reuse GL_TESS_GEN_SPACING */
+/* reuse GL_TESS_GEN_VERTEX_ORDER */
+/* reuse GL_TESS_GEN_POINT_MODE */
+/* reuse GL_ISOLINES */
+/* reuse GL_FRACTIONAL_ODD */
+/* reuse GL_FRACTIONAL_EVEN */
+/* reuse GL_MAX_PATCH_VERTICES */
+/* reuse GL_MAX_TESS_GEN_LEVEL */
+/* reuse GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS */
+/* reuse GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS */
+/* reuse GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS */
+/* reuse GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS */
+/* reuse GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS */
+/* reuse GL_MAX_TESS_PATCH_COMPONENTS */
+/* reuse GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS */
+/* reuse GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS */
+/* reuse GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS */
+/* reuse GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS */
+/* reuse GL_MAX_TESS_CONTROL_INPUT_COMPONENTS */
+/* reuse GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS */
+/* reuse GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS */
+/* reuse GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS */
+/* reuse GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_CONTROL_SHADER */
+/* reuse GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_EVALUATION_SHADER */
+/* reuse GL_TESS_EVALUATION_SHADER */
+/* reuse GL_TESS_CONTROL_SHADER */
+/* Reuse tokens from ARB_texture_buffer_object_rgb32 (none) */
+/* Reuse tokens from ARB_transform_feedback2 */
+/* reuse GL_TRANSFORM_FEEDBACK */
+/* reuse GL_TRANSFORM_FEEDBACK_BUFFER_PAUSED */
+/* reuse GL_TRANSFORM_FEEDBACK_BUFFER_ACTIVE */
+/* reuse GL_TRANSFORM_FEEDBACK_BINDING */
+/* Reuse tokens from ARB_transform_feedback3 */
+/* reuse GL_MAX_TRANSFORM_FEEDBACK_BUFFERS */
+/* reuse GL_MAX_VERTEX_STREAMS */
+#endif
+
+#ifndef GL_VERSION_4_1
+/* Reuse tokens from ARB_ES2_compatibility */
+/* reuse GL_FIXED */
+/* reuse GL_IMPLEMENTATION_COLOR_READ_TYPE */
+/* reuse GL_IMPLEMENTATION_COLOR_READ_FORMAT */
+/* reuse GL_LOW_FLOAT */
+/* reuse GL_MEDIUM_FLOAT */
+/* reuse GL_HIGH_FLOAT */
+/* reuse GL_LOW_INT */
+/* reuse GL_MEDIUM_INT */
+/* reuse GL_HIGH_INT */
+/* reuse GL_SHADER_COMPILER */
+/* reuse GL_NUM_SHADER_BINARY_FORMATS */
+/* reuse GL_MAX_VERTEX_UNIFORM_VECTORS */
+/* reuse GL_MAX_VARYING_VECTORS */
+/* reuse GL_MAX_FRAGMENT_UNIFORM_VECTORS */
+/* Reuse tokens from ARB_get_program_binary */
+/* reuse GL_PROGRAM_BINARY_RETRIEVABLE_HINT */
+/* reuse GL_PROGRAM_BINARY_LENGTH */
+/* reuse GL_NUM_PROGRAM_BINARY_FORMATS */
+/* reuse GL_PROGRAM_BINARY_FORMATS */
+/* Reuse tokens from ARB_separate_shader_objects */
+/* reuse GL_VERTEX_SHADER_BIT */
+/* reuse GL_FRAGMENT_SHADER_BIT */
+/* reuse GL_GEOMETRY_SHADER_BIT */
+/* reuse GL_TESS_CONTROL_SHADER_BIT */
+/* reuse GL_TESS_EVALUATION_SHADER_BIT */
+/* reuse GL_ALL_SHADER_BITS */
+/* reuse GL_PROGRAM_SEPARABLE */
+/* reuse GL_ACTIVE_PROGRAM */
+/* reuse GL_PROGRAM_PIPELINE_BINDING */
+/* Reuse tokens from ARB_shader_precision (none) */
+/* Reuse tokens from ARB_vertex_attrib_64bit - all are in GL 3.0 and 4.0 already */
+/* Reuse tokens from ARB_viewport_array - some are in GL 1.1 and ARB_provoking_vertex already */
+/* reuse GL_MAX_VIEWPORTS */
+/* reuse GL_VIEWPORT_SUBPIXEL_BITS */
+/* reuse GL_VIEWPORT_BOUNDS_RANGE */
+/* reuse GL_LAYER_PROVOKING_VERTEX */
+/* reuse GL_VIEWPORT_INDEX_PROVOKING_VERTEX */
+/* reuse GL_UNDEFINED_VERTEX */
+#endif
+
+#ifndef GL_ARB_multitexture
+#define GL_TEXTURE0_ARB 0x84C0
+#define GL_TEXTURE1_ARB 0x84C1
+#define GL_TEXTURE2_ARB 0x84C2
+#define GL_TEXTURE3_ARB 0x84C3
+#define GL_TEXTURE4_ARB 0x84C4
+#define GL_TEXTURE5_ARB 0x84C5
+#define GL_TEXTURE6_ARB 0x84C6
+#define GL_TEXTURE7_ARB 0x84C7
+#define GL_TEXTURE8_ARB 0x84C8
+#define GL_TEXTURE9_ARB 0x84C9
+#define GL_TEXTURE10_ARB 0x84CA
+#define GL_TEXTURE11_ARB 0x84CB
+#define GL_TEXTURE12_ARB 0x84CC
+#define GL_TEXTURE13_ARB 0x84CD
+#define GL_TEXTURE14_ARB 0x84CE
+#define GL_TEXTURE15_ARB 0x84CF
+#define GL_TEXTURE16_ARB 0x84D0
+#define GL_TEXTURE17_ARB 0x84D1
+#define GL_TEXTURE18_ARB 0x84D2
+#define GL_TEXTURE19_ARB 0x84D3
+#define GL_TEXTURE20_ARB 0x84D4
+#define GL_TEXTURE21_ARB 0x84D5
+#define GL_TEXTURE22_ARB 0x84D6
+#define GL_TEXTURE23_ARB 0x84D7
+#define GL_TEXTURE24_ARB 0x84D8
+#define GL_TEXTURE25_ARB 0x84D9
+#define GL_TEXTURE26_ARB 0x84DA
+#define GL_TEXTURE27_ARB 0x84DB
+#define GL_TEXTURE28_ARB 0x84DC
+#define GL_TEXTURE29_ARB 0x84DD
+#define GL_TEXTURE30_ARB 0x84DE
+#define GL_TEXTURE31_ARB 0x84DF
+#define GL_ACTIVE_TEXTURE_ARB 0x84E0
+#define GL_CLIENT_ACTIVE_TEXTURE_ARB 0x84E1
+#define GL_MAX_TEXTURE_UNITS_ARB 0x84E2
+#endif
+
+#ifndef GL_ARB_transpose_matrix
+#define GL_TRANSPOSE_MODELVIEW_MATRIX_ARB 0x84E3
+#define GL_TRANSPOSE_PROJECTION_MATRIX_ARB 0x84E4
+#define GL_TRANSPOSE_TEXTURE_MATRIX_ARB 0x84E5
+#define GL_TRANSPOSE_COLOR_MATRIX_ARB 0x84E6
+#endif
+
+#ifndef GL_ARB_multisample
+#define GL_MULTISAMPLE_ARB 0x809D
+#define GL_SAMPLE_ALPHA_TO_COVERAGE_ARB 0x809E
+#define GL_SAMPLE_ALPHA_TO_ONE_ARB 0x809F
+#define GL_SAMPLE_COVERAGE_ARB 0x80A0
+#define GL_SAMPLE_BUFFERS_ARB 0x80A8
+#define GL_SAMPLES_ARB 0x80A9
+#define GL_SAMPLE_COVERAGE_VALUE_ARB 0x80AA
+#define GL_SAMPLE_COVERAGE_INVERT_ARB 0x80AB
+#define GL_MULTISAMPLE_BIT_ARB 0x20000000
+#endif
+
+#ifndef GL_ARB_texture_env_add
+#endif
+
+#ifndef GL_ARB_texture_cube_map
+#define GL_NORMAL_MAP_ARB 0x8511
+#define GL_REFLECTION_MAP_ARB 0x8512
+#define GL_TEXTURE_CUBE_MAP_ARB 0x8513
+#define GL_TEXTURE_BINDING_CUBE_MAP_ARB 0x8514
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB 0x8515
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB 0x8516
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB 0x8517
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB 0x8518
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB 0x8519
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB 0x851A
+#define GL_PROXY_TEXTURE_CUBE_MAP_ARB 0x851B
+#define GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB 0x851C
+#endif
+
+#ifndef GL_ARB_texture_compression
+#define GL_COMPRESSED_ALPHA_ARB 0x84E9
+#define GL_COMPRESSED_LUMINANCE_ARB 0x84EA
+#define GL_COMPRESSED_LUMINANCE_ALPHA_ARB 0x84EB
+#define GL_COMPRESSED_INTENSITY_ARB 0x84EC
+#define GL_COMPRESSED_RGB_ARB 0x84ED
+#define GL_COMPRESSED_RGBA_ARB 0x84EE
+#define GL_TEXTURE_COMPRESSION_HINT_ARB 0x84EF
+#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB 0x86A0
+#define GL_TEXTURE_COMPRESSED_ARB 0x86A1
+#define GL_NUM_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A2
+#define GL_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A3
+#endif
+
+#ifndef GL_ARB_texture_border_clamp
+#define GL_CLAMP_TO_BORDER_ARB 0x812D
+#endif
+
+#ifndef GL_ARB_point_parameters
+#define GL_POINT_SIZE_MIN_ARB 0x8126
+#define GL_POINT_SIZE_MAX_ARB 0x8127
+#define GL_POINT_FADE_THRESHOLD_SIZE_ARB 0x8128
+#define GL_POINT_DISTANCE_ATTENUATION_ARB 0x8129
+#endif
+
+#ifndef GL_ARB_vertex_blend
+#define GL_MAX_VERTEX_UNITS_ARB 0x86A4
+#define GL_ACTIVE_VERTEX_UNITS_ARB 0x86A5
+#define GL_WEIGHT_SUM_UNITY_ARB 0x86A6
+#define GL_VERTEX_BLEND_ARB 0x86A7
+#define GL_CURRENT_WEIGHT_ARB 0x86A8
+#define GL_WEIGHT_ARRAY_TYPE_ARB 0x86A9
+#define GL_WEIGHT_ARRAY_STRIDE_ARB 0x86AA
+#define GL_WEIGHT_ARRAY_SIZE_ARB 0x86AB
+#define GL_WEIGHT_ARRAY_POINTER_ARB 0x86AC
+#define GL_WEIGHT_ARRAY_ARB 0x86AD
+#define GL_MODELVIEW0_ARB 0x1700
+#define GL_MODELVIEW1_ARB 0x850A
+#define GL_MODELVIEW2_ARB 0x8722
+#define GL_MODELVIEW3_ARB 0x8723
+#define GL_MODELVIEW4_ARB 0x8724
+#define GL_MODELVIEW5_ARB 0x8725
+#define GL_MODELVIEW6_ARB 0x8726
+#define GL_MODELVIEW7_ARB 0x8727
+#define GL_MODELVIEW8_ARB 0x8728
+#define GL_MODELVIEW9_ARB 0x8729
+#define GL_MODELVIEW10_ARB 0x872A
+#define GL_MODELVIEW11_ARB 0x872B
+#define GL_MODELVIEW12_ARB 0x872C
+#define GL_MODELVIEW13_ARB 0x872D
+#define GL_MODELVIEW14_ARB 0x872E
+#define GL_MODELVIEW15_ARB 0x872F
+#define GL_MODELVIEW16_ARB 0x8730
+#define GL_MODELVIEW17_ARB 0x8731
+#define GL_MODELVIEW18_ARB 0x8732
+#define GL_MODELVIEW19_ARB 0x8733
+#define GL_MODELVIEW20_ARB 0x8734
+#define GL_MODELVIEW21_ARB 0x8735
+#define GL_MODELVIEW22_ARB 0x8736
+#define GL_MODELVIEW23_ARB 0x8737
+#define GL_MODELVIEW24_ARB 0x8738
+#define GL_MODELVIEW25_ARB 0x8739
+#define GL_MODELVIEW26_ARB 0x873A
+#define GL_MODELVIEW27_ARB 0x873B
+#define GL_MODELVIEW28_ARB 0x873C
+#define GL_MODELVIEW29_ARB 0x873D
+#define GL_MODELVIEW30_ARB 0x873E
+#define GL_MODELVIEW31_ARB 0x873F
+#endif
+
+#ifndef GL_ARB_matrix_palette
+#define GL_MATRIX_PALETTE_ARB 0x8840
+#define GL_MAX_MATRIX_PALETTE_STACK_DEPTH_ARB 0x8841
+#define GL_MAX_PALETTE_MATRICES_ARB 0x8842
+#define GL_CURRENT_PALETTE_MATRIX_ARB 0x8843
+#define GL_MATRIX_INDEX_ARRAY_ARB 0x8844
+#define GL_CURRENT_MATRIX_INDEX_ARB 0x8845
+#define GL_MATRIX_INDEX_ARRAY_SIZE_ARB 0x8846
+#define GL_MATRIX_INDEX_ARRAY_TYPE_ARB 0x8847
+#define GL_MATRIX_INDEX_ARRAY_STRIDE_ARB 0x8848
+#define GL_MATRIX_INDEX_ARRAY_POINTER_ARB 0x8849
+#endif
+
+#ifndef GL_ARB_texture_env_combine
+#define GL_COMBINE_ARB 0x8570
+#define GL_COMBINE_RGB_ARB 0x8571
+#define GL_COMBINE_ALPHA_ARB 0x8572
+#define GL_SOURCE0_RGB_ARB 0x8580
+#define GL_SOURCE1_RGB_ARB 0x8581
+#define GL_SOURCE2_RGB_ARB 0x8582
+#define GL_SOURCE0_ALPHA_ARB 0x8588
+#define GL_SOURCE1_ALPHA_ARB 0x8589
+#define GL_SOURCE2_ALPHA_ARB 0x858A
+#define GL_OPERAND0_RGB_ARB 0x8590
+#define GL_OPERAND1_RGB_ARB 0x8591
+#define GL_OPERAND2_RGB_ARB 0x8592
+#define GL_OPERAND0_ALPHA_ARB 0x8598
+#define GL_OPERAND1_ALPHA_ARB 0x8599
+#define GL_OPERAND2_ALPHA_ARB 0x859A
+#define GL_RGB_SCALE_ARB 0x8573
+#define GL_ADD_SIGNED_ARB 0x8574
+#define GL_INTERPOLATE_ARB 0x8575
+#define GL_SUBTRACT_ARB 0x84E7
+#define GL_CONSTANT_ARB 0x8576
+#define GL_PRIMARY_COLOR_ARB 0x8577
+#define GL_PREVIOUS_ARB 0x8578
+#endif
+
+#ifndef GL_ARB_texture_env_crossbar
+#endif
+
+#ifndef GL_ARB_texture_env_dot3
+#define GL_DOT3_RGB_ARB 0x86AE
+#define GL_DOT3_RGBA_ARB 0x86AF
+#endif
+
+#ifndef GL_ARB_texture_mirrored_repeat
+#define GL_MIRRORED_REPEAT_ARB 0x8370
+#endif
+
+#ifndef GL_ARB_depth_texture
+#define GL_DEPTH_COMPONENT16_ARB 0x81A5
+#define GL_DEPTH_COMPONENT24_ARB 0x81A6
+#define GL_DEPTH_COMPONENT32_ARB 0x81A7
+#define GL_TEXTURE_DEPTH_SIZE_ARB 0x884A
+#define GL_DEPTH_TEXTURE_MODE_ARB 0x884B
+#endif
+
+#ifndef GL_ARB_shadow
+#define GL_TEXTURE_COMPARE_MODE_ARB 0x884C
+#define GL_TEXTURE_COMPARE_FUNC_ARB 0x884D
+#define GL_COMPARE_R_TO_TEXTURE_ARB 0x884E
+#endif
+
+#ifndef GL_ARB_shadow_ambient
+#define GL_TEXTURE_COMPARE_FAIL_VALUE_ARB 0x80BF
+#endif
+
+#ifndef GL_ARB_window_pos
+#endif
+
+#ifndef GL_ARB_vertex_program
+#define GL_COLOR_SUM_ARB 0x8458
+#define GL_VERTEX_PROGRAM_ARB 0x8620
+#define GL_VERTEX_ATTRIB_ARRAY_ENABLED_ARB 0x8622
+#define GL_VERTEX_ATTRIB_ARRAY_SIZE_ARB 0x8623
+#define GL_VERTEX_ATTRIB_ARRAY_STRIDE_ARB 0x8624
+#define GL_VERTEX_ATTRIB_ARRAY_TYPE_ARB 0x8625
+#define GL_CURRENT_VERTEX_ATTRIB_ARB 0x8626
+#define GL_PROGRAM_LENGTH_ARB 0x8627
+#define GL_PROGRAM_STRING_ARB 0x8628
+#define GL_MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB 0x862E
+#define GL_MAX_PROGRAM_MATRICES_ARB 0x862F
+#define GL_CURRENT_MATRIX_STACK_DEPTH_ARB 0x8640
+#define GL_CURRENT_MATRIX_ARB 0x8641
+#define GL_VERTEX_PROGRAM_POINT_SIZE_ARB 0x8642
+#define GL_VERTEX_PROGRAM_TWO_SIDE_ARB 0x8643
+#define GL_VERTEX_ATTRIB_ARRAY_POINTER_ARB 0x8645
+#define GL_PROGRAM_ERROR_POSITION_ARB 0x864B
+#define GL_PROGRAM_BINDING_ARB 0x8677
+#define GL_MAX_VERTEX_ATTRIBS_ARB 0x8869
+#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB 0x886A
+#define GL_PROGRAM_ERROR_STRING_ARB 0x8874
+#define GL_PROGRAM_FORMAT_ASCII_ARB 0x8875
+#define GL_PROGRAM_FORMAT_ARB 0x8876
+#define GL_PROGRAM_INSTRUCTIONS_ARB 0x88A0
+#define GL_MAX_PROGRAM_INSTRUCTIONS_ARB 0x88A1
+#define GL_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A2
+#define GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A3
+#define GL_PROGRAM_TEMPORARIES_ARB 0x88A4
+#define GL_MAX_PROGRAM_TEMPORARIES_ARB 0x88A5
+#define GL_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A6
+#define GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A7
+#define GL_PROGRAM_PARAMETERS_ARB 0x88A8
+#define GL_MAX_PROGRAM_PARAMETERS_ARB 0x88A9
+#define GL_PROGRAM_NATIVE_PARAMETERS_ARB 0x88AA
+#define GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB 0x88AB
+#define GL_PROGRAM_ATTRIBS_ARB 0x88AC
+#define GL_MAX_PROGRAM_ATTRIBS_ARB 0x88AD
+#define GL_PROGRAM_NATIVE_ATTRIBS_ARB 0x88AE
+#define GL_MAX_PROGRAM_NATIVE_ATTRIBS_ARB 0x88AF
+#define GL_PROGRAM_ADDRESS_REGISTERS_ARB 0x88B0
+#define GL_MAX_PROGRAM_ADDRESS_REGISTERS_ARB 0x88B1
+#define GL_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB 0x88B2
+#define GL_MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB 0x88B3
+#define GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB 0x88B4
+#define GL_MAX_PROGRAM_ENV_PARAMETERS_ARB 0x88B5
+#define GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB 0x88B6
+#define GL_TRANSPOSE_CURRENT_MATRIX_ARB 0x88B7
+#define GL_MATRIX0_ARB 0x88C0
+#define GL_MATRIX1_ARB 0x88C1
+#define GL_MATRIX2_ARB 0x88C2
+#define GL_MATRIX3_ARB 0x88C3
+#define GL_MATRIX4_ARB 0x88C4
+#define GL_MATRIX5_ARB 0x88C5
+#define GL_MATRIX6_ARB 0x88C6
+#define GL_MATRIX7_ARB 0x88C7
+#define GL_MATRIX8_ARB 0x88C8
+#define GL_MATRIX9_ARB 0x88C9
+#define GL_MATRIX10_ARB 0x88CA
+#define GL_MATRIX11_ARB 0x88CB
+#define GL_MATRIX12_ARB 0x88CC
+#define GL_MATRIX13_ARB 0x88CD
+#define GL_MATRIX14_ARB 0x88CE
+#define GL_MATRIX15_ARB 0x88CF
+#define GL_MATRIX16_ARB 0x88D0
+#define GL_MATRIX17_ARB 0x88D1
+#define GL_MATRIX18_ARB 0x88D2
+#define GL_MATRIX19_ARB 0x88D3
+#define GL_MATRIX20_ARB 0x88D4
+#define GL_MATRIX21_ARB 0x88D5
+#define GL_MATRIX22_ARB 0x88D6
+#define GL_MATRIX23_ARB 0x88D7
+#define GL_MATRIX24_ARB 0x88D8
+#define GL_MATRIX25_ARB 0x88D9
+#define GL_MATRIX26_ARB 0x88DA
+#define GL_MATRIX27_ARB 0x88DB
+#define GL_MATRIX28_ARB 0x88DC
+#define GL_MATRIX29_ARB 0x88DD
+#define GL_MATRIX30_ARB 0x88DE
+#define GL_MATRIX31_ARB 0x88DF
+#endif
+
+#ifndef GL_ARB_fragment_program
+#define GL_FRAGMENT_PROGRAM_ARB 0x8804
+#define GL_PROGRAM_ALU_INSTRUCTIONS_ARB 0x8805
+#define GL_PROGRAM_TEX_INSTRUCTIONS_ARB 0x8806
+#define GL_PROGRAM_TEX_INDIRECTIONS_ARB 0x8807
+#define GL_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB 0x8808
+#define GL_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB 0x8809
+#define GL_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB 0x880A
+#define GL_MAX_PROGRAM_ALU_INSTRUCTIONS_ARB 0x880B
+#define GL_MAX_PROGRAM_TEX_INSTRUCTIONS_ARB 0x880C
+#define GL_MAX_PROGRAM_TEX_INDIRECTIONS_ARB 0x880D
+#define GL_MAX_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB 0x880E
+#define GL_MAX_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB 0x880F
+#define GL_MAX_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB 0x8810
+#define GL_MAX_TEXTURE_COORDS_ARB 0x8871
+#define GL_MAX_TEXTURE_IMAGE_UNITS_ARB 0x8872
+#endif
+
+#ifndef GL_ARB_vertex_buffer_object
+#define GL_BUFFER_SIZE_ARB 0x8764
+#define GL_BUFFER_USAGE_ARB 0x8765
+#define GL_ARRAY_BUFFER_ARB 0x8892
+#define GL_ELEMENT_ARRAY_BUFFER_ARB 0x8893
+#define GL_ARRAY_BUFFER_BINDING_ARB 0x8894
+#define GL_ELEMENT_ARRAY_BUFFER_BINDING_ARB 0x8895
+#define GL_VERTEX_ARRAY_BUFFER_BINDING_ARB 0x8896
+#define GL_NORMAL_ARRAY_BUFFER_BINDING_ARB 0x8897
+#define GL_COLOR_ARRAY_BUFFER_BINDING_ARB 0x8898
+#define GL_INDEX_ARRAY_BUFFER_BINDING_ARB 0x8899
+#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING_ARB 0x889A
+#define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING_ARB 0x889B
+#define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING_ARB 0x889C
+#define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING_ARB 0x889D
+#define GL_WEIGHT_ARRAY_BUFFER_BINDING_ARB 0x889E
+#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB 0x889F
+#define GL_READ_ONLY_ARB 0x88B8
+#define GL_WRITE_ONLY_ARB 0x88B9
+#define GL_READ_WRITE_ARB 0x88BA
+#define GL_BUFFER_ACCESS_ARB 0x88BB
+#define GL_BUFFER_MAPPED_ARB 0x88BC
+#define GL_BUFFER_MAP_POINTER_ARB 0x88BD
+#define GL_STREAM_DRAW_ARB 0x88E0
+#define GL_STREAM_READ_ARB 0x88E1
+#define GL_STREAM_COPY_ARB 0x88E2
+#define GL_STATIC_DRAW_ARB 0x88E4
+#define GL_STATIC_READ_ARB 0x88E5
+#define GL_STATIC_COPY_ARB 0x88E6
+#define GL_DYNAMIC_DRAW_ARB 0x88E8
+#define GL_DYNAMIC_READ_ARB 0x88E9
+#define GL_DYNAMIC_COPY_ARB 0x88EA
+#endif
+
+#ifndef GL_ARB_occlusion_query
+#define GL_QUERY_COUNTER_BITS_ARB 0x8864
+#define GL_CURRENT_QUERY_ARB 0x8865
+#define GL_QUERY_RESULT_ARB 0x8866
+#define GL_QUERY_RESULT_AVAILABLE_ARB 0x8867
+#define GL_SAMPLES_PASSED_ARB 0x8914
+#endif
+
+#ifndef GL_ARB_shader_objects
+#define GL_PROGRAM_OBJECT_ARB 0x8B40
+#define GL_SHADER_OBJECT_ARB 0x8B48
+#define GL_OBJECT_TYPE_ARB 0x8B4E
+#define GL_OBJECT_SUBTYPE_ARB 0x8B4F
+#define GL_FLOAT_VEC2_ARB 0x8B50
+#define GL_FLOAT_VEC3_ARB 0x8B51
+#define GL_FLOAT_VEC4_ARB 0x8B52
+#define GL_INT_VEC2_ARB 0x8B53
+#define GL_INT_VEC3_ARB 0x8B54
+#define GL_INT_VEC4_ARB 0x8B55
+#define GL_BOOL_ARB 0x8B56
+#define GL_BOOL_VEC2_ARB 0x8B57
+#define GL_BOOL_VEC3_ARB 0x8B58
+#define GL_BOOL_VEC4_ARB 0x8B59
+#define GL_FLOAT_MAT2_ARB 0x8B5A
+#define GL_FLOAT_MAT3_ARB 0x8B5B
+#define GL_FLOAT_MAT4_ARB 0x8B5C
+#define GL_SAMPLER_1D_ARB 0x8B5D
+#define GL_SAMPLER_2D_ARB 0x8B5E
+#define GL_SAMPLER_3D_ARB 0x8B5F
+#define GL_SAMPLER_CUBE_ARB 0x8B60
+#define GL_SAMPLER_1D_SHADOW_ARB 0x8B61
+#define GL_SAMPLER_2D_SHADOW_ARB 0x8B62
+#define GL_SAMPLER_2D_RECT_ARB 0x8B63
+#define GL_SAMPLER_2D_RECT_SHADOW_ARB 0x8B64
+#define GL_OBJECT_DELETE_STATUS_ARB 0x8B80
+#define GL_OBJECT_COMPILE_STATUS_ARB 0x8B81
+#define GL_OBJECT_LINK_STATUS_ARB 0x8B82
+#define GL_OBJECT_VALIDATE_STATUS_ARB 0x8B83
+#define GL_OBJECT_INFO_LOG_LENGTH_ARB 0x8B84
+#define GL_OBJECT_ATTACHED_OBJECTS_ARB 0x8B85
+#define GL_OBJECT_ACTIVE_UNIFORMS_ARB 0x8B86
+#define GL_OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB 0x8B87
+#define GL_OBJECT_SHADER_SOURCE_LENGTH_ARB 0x8B88
+#endif
+
+#ifndef GL_ARB_vertex_shader
+#define GL_VERTEX_SHADER_ARB 0x8B31
+#define GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB 0x8B4A
+#define GL_MAX_VARYING_FLOATS_ARB 0x8B4B
+#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB 0x8B4C
+#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB 0x8B4D
+#define GL_OBJECT_ACTIVE_ATTRIBUTES_ARB 0x8B89
+#define GL_OBJECT_ACTIVE_ATTRIBUTE_MAX_LENGTH_ARB 0x8B8A
+#endif
+
+#ifndef GL_ARB_fragment_shader
+#define GL_FRAGMENT_SHADER_ARB 0x8B30
+#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB 0x8B49
+#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT_ARB 0x8B8B
+#endif
+
+#ifndef GL_ARB_shading_language_100
+#define GL_SHADING_LANGUAGE_VERSION_ARB 0x8B8C
+#endif
+
+#ifndef GL_ARB_texture_non_power_of_two
+#endif
+
+#ifndef GL_ARB_point_sprite
+#define GL_POINT_SPRITE_ARB 0x8861
+#define GL_COORD_REPLACE_ARB 0x8862
+#endif
+
+#ifndef GL_ARB_fragment_program_shadow
+#endif
+
+#ifndef GL_ARB_draw_buffers
+#define GL_MAX_DRAW_BUFFERS_ARB 0x8824
+#define GL_DRAW_BUFFER0_ARB 0x8825
+#define GL_DRAW_BUFFER1_ARB 0x8826
+#define GL_DRAW_BUFFER2_ARB 0x8827
+#define GL_DRAW_BUFFER3_ARB 0x8828
+#define GL_DRAW_BUFFER4_ARB 0x8829
+#define GL_DRAW_BUFFER5_ARB 0x882A
+#define GL_DRAW_BUFFER6_ARB 0x882B
+#define GL_DRAW_BUFFER7_ARB 0x882C
+#define GL_DRAW_BUFFER8_ARB 0x882D
+#define GL_DRAW_BUFFER9_ARB 0x882E
+#define GL_DRAW_BUFFER10_ARB 0x882F
+#define GL_DRAW_BUFFER11_ARB 0x8830
+#define GL_DRAW_BUFFER12_ARB 0x8831
+#define GL_DRAW_BUFFER13_ARB 0x8832
+#define GL_DRAW_BUFFER14_ARB 0x8833
+#define GL_DRAW_BUFFER15_ARB 0x8834
+#endif
+
+#ifndef GL_ARB_texture_rectangle
+#define GL_TEXTURE_RECTANGLE_ARB 0x84F5
+#define GL_TEXTURE_BINDING_RECTANGLE_ARB 0x84F6
+#define GL_PROXY_TEXTURE_RECTANGLE_ARB 0x84F7
+#define GL_MAX_RECTANGLE_TEXTURE_SIZE_ARB 0x84F8
+#endif
+
+#ifndef GL_ARB_color_buffer_float
+#define GL_RGBA_FLOAT_MODE_ARB 0x8820
+#define GL_CLAMP_VERTEX_COLOR_ARB 0x891A
+#define GL_CLAMP_FRAGMENT_COLOR_ARB 0x891B
+#define GL_CLAMP_READ_COLOR_ARB 0x891C
+#define GL_FIXED_ONLY_ARB 0x891D
+#endif
+
+#ifndef GL_ARB_half_float_pixel
+#define GL_HALF_FLOAT_ARB 0x140B
+#endif
+
+#ifndef GL_ARB_texture_float
+#define GL_TEXTURE_RED_TYPE_ARB 0x8C10
+#define GL_TEXTURE_GREEN_TYPE_ARB 0x8C11
+#define GL_TEXTURE_BLUE_TYPE_ARB 0x8C12
+#define GL_TEXTURE_ALPHA_TYPE_ARB 0x8C13
+#define GL_TEXTURE_LUMINANCE_TYPE_ARB 0x8C14
+#define GL_TEXTURE_INTENSITY_TYPE_ARB 0x8C15
+#define GL_TEXTURE_DEPTH_TYPE_ARB 0x8C16
+#define GL_UNSIGNED_NORMALIZED_ARB 0x8C17
+#define GL_RGBA32F_ARB 0x8814
+#define GL_RGB32F_ARB 0x8815
+#define GL_ALPHA32F_ARB 0x8816
+#define GL_INTENSITY32F_ARB 0x8817
+#define GL_LUMINANCE32F_ARB 0x8818
+#define GL_LUMINANCE_ALPHA32F_ARB 0x8819
+#define GL_RGBA16F_ARB 0x881A
+#define GL_RGB16F_ARB 0x881B
+#define GL_ALPHA16F_ARB 0x881C
+#define GL_INTENSITY16F_ARB 0x881D
+#define GL_LUMINANCE16F_ARB 0x881E
+#define GL_LUMINANCE_ALPHA16F_ARB 0x881F
+#endif
+
+#ifndef GL_ARB_pixel_buffer_object
+#define GL_PIXEL_PACK_BUFFER_ARB 0x88EB
+#define GL_PIXEL_UNPACK_BUFFER_ARB 0x88EC
+#define GL_PIXEL_PACK_BUFFER_BINDING_ARB 0x88ED
+#define GL_PIXEL_UNPACK_BUFFER_BINDING_ARB 0x88EF
+#endif
+
+#ifndef GL_ARB_depth_buffer_float
+#define GL_DEPTH_COMPONENT32F 0x8CAC
+#define GL_DEPTH32F_STENCIL8 0x8CAD
+#define GL_FLOAT_32_UNSIGNED_INT_24_8_REV 0x8DAD
+#endif
+
+#ifndef GL_ARB_draw_instanced
+#endif
+
+#ifndef GL_ARB_framebuffer_object
+#define GL_INVALID_FRAMEBUFFER_OPERATION 0x0506
+#define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING 0x8210
+#define GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE 0x8211
+#define GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE 0x8212
+#define GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE 0x8213
+#define GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE 0x8214
+#define GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE 0x8215
+#define GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE 0x8216
+#define GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE 0x8217
+#define GL_FRAMEBUFFER_DEFAULT 0x8218
+#define GL_FRAMEBUFFER_UNDEFINED 0x8219
+#define GL_DEPTH_STENCIL_ATTACHMENT 0x821A
+#define GL_MAX_RENDERBUFFER_SIZE 0x84E8
+#define GL_DEPTH_STENCIL 0x84F9
+#define GL_UNSIGNED_INT_24_8 0x84FA
+#define GL_DEPTH24_STENCIL8 0x88F0
+#define GL_TEXTURE_STENCIL_SIZE 0x88F1
+#define GL_TEXTURE_RED_TYPE 0x8C10
+#define GL_TEXTURE_GREEN_TYPE 0x8C11
+#define GL_TEXTURE_BLUE_TYPE 0x8C12
+#define GL_TEXTURE_ALPHA_TYPE 0x8C13
+#define GL_TEXTURE_DEPTH_TYPE 0x8C16
+#define GL_UNSIGNED_NORMALIZED 0x8C17
+#define GL_FRAMEBUFFER_BINDING 0x8CA6
+#define GL_DRAW_FRAMEBUFFER_BINDING GL_FRAMEBUFFER_BINDING
+#define GL_RENDERBUFFER_BINDING 0x8CA7
+#define GL_READ_FRAMEBUFFER 0x8CA8
+#define GL_DRAW_FRAMEBUFFER 0x8CA9
+#define GL_READ_FRAMEBUFFER_BINDING 0x8CAA
+#define GL_RENDERBUFFER_SAMPLES 0x8CAB
+#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0
+#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER 0x8CD4
+#define GL_FRAMEBUFFER_COMPLETE 0x8CD5
+#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6
+#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7
+#define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER 0x8CDB
+#define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER 0x8CDC
+#define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD
+#define GL_MAX_COLOR_ATTACHMENTS 0x8CDF
+#define GL_COLOR_ATTACHMENT0 0x8CE0
+#define GL_COLOR_ATTACHMENT1 0x8CE1
+#define GL_COLOR_ATTACHMENT2 0x8CE2
+#define GL_COLOR_ATTACHMENT3 0x8CE3
+#define GL_COLOR_ATTACHMENT4 0x8CE4
+#define GL_COLOR_ATTACHMENT5 0x8CE5
+#define GL_COLOR_ATTACHMENT6 0x8CE6
+#define GL_COLOR_ATTACHMENT7 0x8CE7
+#define GL_COLOR_ATTACHMENT8 0x8CE8
+#define GL_COLOR_ATTACHMENT9 0x8CE9
+#define GL_COLOR_ATTACHMENT10 0x8CEA
+#define GL_COLOR_ATTACHMENT11 0x8CEB
+#define GL_COLOR_ATTACHMENT12 0x8CEC
+#define GL_COLOR_ATTACHMENT13 0x8CED
+#define GL_COLOR_ATTACHMENT14 0x8CEE
+#define GL_COLOR_ATTACHMENT15 0x8CEF
+#define GL_DEPTH_ATTACHMENT 0x8D00
+#define GL_STENCIL_ATTACHMENT 0x8D20
+#define GL_FRAMEBUFFER 0x8D40
+#define GL_RENDERBUFFER 0x8D41
+#define GL_RENDERBUFFER_WIDTH 0x8D42
+#define GL_RENDERBUFFER_HEIGHT 0x8D43
+#define GL_RENDERBUFFER_INTERNAL_FORMAT 0x8D44
+#define GL_STENCIL_INDEX1 0x8D46
+#define GL_STENCIL_INDEX4 0x8D47
+#define GL_STENCIL_INDEX8 0x8D48
+#define GL_STENCIL_INDEX16 0x8D49
+#define GL_RENDERBUFFER_RED_SIZE 0x8D50
+#define GL_RENDERBUFFER_GREEN_SIZE 0x8D51
+#define GL_RENDERBUFFER_BLUE_SIZE 0x8D52
+#define GL_RENDERBUFFER_ALPHA_SIZE 0x8D53
+#define GL_RENDERBUFFER_DEPTH_SIZE 0x8D54
+#define GL_RENDERBUFFER_STENCIL_SIZE 0x8D55
+#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE 0x8D56
+#define GL_MAX_SAMPLES 0x8D57
+#endif
+
+#ifndef GL_ARB_framebuffer_object_DEPRECATED
+#define GL_INDEX 0x8222
+#define GL_TEXTURE_LUMINANCE_TYPE 0x8C14
+#define GL_TEXTURE_INTENSITY_TYPE 0x8C15
+#endif
+
+#ifndef GL_ARB_framebuffer_sRGB
+#define GL_FRAMEBUFFER_SRGB 0x8DB9
+#endif
+
+#ifndef GL_ARB_geometry_shader4
+#define GL_LINES_ADJACENCY_ARB 0x000A
+#define GL_LINE_STRIP_ADJACENCY_ARB 0x000B
+#define GL_TRIANGLES_ADJACENCY_ARB 0x000C
+#define GL_TRIANGLE_STRIP_ADJACENCY_ARB 0x000D
+#define GL_PROGRAM_POINT_SIZE_ARB 0x8642
+#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS_ARB 0x8C29
+#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED_ARB 0x8DA7
+#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_ARB 0x8DA8
+#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_COUNT_ARB 0x8DA9
+#define GL_GEOMETRY_SHADER_ARB 0x8DD9
+#define GL_GEOMETRY_VERTICES_OUT_ARB 0x8DDA
+#define GL_GEOMETRY_INPUT_TYPE_ARB 0x8DDB
+#define GL_GEOMETRY_OUTPUT_TYPE_ARB 0x8DDC
+#define GL_MAX_GEOMETRY_VARYING_COMPONENTS_ARB 0x8DDD
+#define GL_MAX_VERTEX_VARYING_COMPONENTS_ARB 0x8DDE
+#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_ARB 0x8DDF
+#define GL_MAX_GEOMETRY_OUTPUT_VERTICES_ARB 0x8DE0
+#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS_ARB 0x8DE1
+/* reuse GL_MAX_VARYING_COMPONENTS */
+/* reuse GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER */
+#endif
+
+#ifndef GL_ARB_half_float_vertex
+#define GL_HALF_FLOAT 0x140B
+#endif
+
+#ifndef GL_ARB_instanced_arrays
+#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR_ARB 0x88FE
+#endif
+
+#ifndef GL_ARB_map_buffer_range
+#define GL_MAP_READ_BIT 0x0001
+#define GL_MAP_WRITE_BIT 0x0002
+#define GL_MAP_INVALIDATE_RANGE_BIT 0x0004
+#define GL_MAP_INVALIDATE_BUFFER_BIT 0x0008
+#define GL_MAP_FLUSH_EXPLICIT_BIT 0x0010
+#define GL_MAP_UNSYNCHRONIZED_BIT 0x0020
+#endif
+
+#ifndef GL_ARB_texture_buffer_object
+#define GL_TEXTURE_BUFFER_ARB 0x8C2A
+#define GL_MAX_TEXTURE_BUFFER_SIZE_ARB 0x8C2B
+#define GL_TEXTURE_BINDING_BUFFER_ARB 0x8C2C
+#define GL_TEXTURE_BUFFER_DATA_STORE_BINDING_ARB 0x8C2D
+#define GL_TEXTURE_BUFFER_FORMAT_ARB 0x8C2E
+#endif
+
+#ifndef GL_ARB_texture_compression_rgtc
+#define GL_COMPRESSED_RED_RGTC1 0x8DBB
+#define GL_COMPRESSED_SIGNED_RED_RGTC1 0x8DBC
+#define GL_COMPRESSED_RG_RGTC2 0x8DBD
+#define GL_COMPRESSED_SIGNED_RG_RGTC2 0x8DBE
+#endif
+
+#ifndef GL_ARB_texture_rg
+#define GL_RG 0x8227
+#define GL_RG_INTEGER 0x8228
+#define GL_R8 0x8229
+#define GL_R16 0x822A
+#define GL_RG8 0x822B
+#define GL_RG16 0x822C
+#define GL_R16F 0x822D
+#define GL_R32F 0x822E
+#define GL_RG16F 0x822F
+#define GL_RG32F 0x8230
+#define GL_R8I 0x8231
+#define GL_R8UI 0x8232
+#define GL_R16I 0x8233
+#define GL_R16UI 0x8234
+#define GL_R32I 0x8235
+#define GL_R32UI 0x8236
+#define GL_RG8I 0x8237
+#define GL_RG8UI 0x8238
+#define GL_RG16I 0x8239
+#define GL_RG16UI 0x823A
+#define GL_RG32I 0x823B
+#define GL_RG32UI 0x823C
+#endif
+
+#ifndef GL_ARB_vertex_array_object
+#define GL_VERTEX_ARRAY_BINDING 0x85B5
+#endif
+
+#ifndef GL_ARB_uniform_buffer_object
+#define GL_UNIFORM_BUFFER 0x8A11
+#define GL_UNIFORM_BUFFER_BINDING 0x8A28
+#define GL_UNIFORM_BUFFER_START 0x8A29
+#define GL_UNIFORM_BUFFER_SIZE 0x8A2A
+#define GL_MAX_VERTEX_UNIFORM_BLOCKS 0x8A2B
+#define GL_MAX_GEOMETRY_UNIFORM_BLOCKS 0x8A2C
+#define GL_MAX_FRAGMENT_UNIFORM_BLOCKS 0x8A2D
+#define GL_MAX_COMBINED_UNIFORM_BLOCKS 0x8A2E
+#define GL_MAX_UNIFORM_BUFFER_BINDINGS 0x8A2F
+#define GL_MAX_UNIFORM_BLOCK_SIZE 0x8A30
+#define GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS 0x8A31
+#define GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS 0x8A32
+#define GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS 0x8A33
+#define GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT 0x8A34
+#define GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH 0x8A35
+#define GL_ACTIVE_UNIFORM_BLOCKS 0x8A36
+#define GL_UNIFORM_TYPE 0x8A37
+#define GL_UNIFORM_SIZE 0x8A38
+#define GL_UNIFORM_NAME_LENGTH 0x8A39
+#define GL_UNIFORM_BLOCK_INDEX 0x8A3A
+#define GL_UNIFORM_OFFSET 0x8A3B
+#define GL_UNIFORM_ARRAY_STRIDE 0x8A3C
+#define GL_UNIFORM_MATRIX_STRIDE 0x8A3D
+#define GL_UNIFORM_IS_ROW_MAJOR 0x8A3E
+#define GL_UNIFORM_BLOCK_BINDING 0x8A3F
+#define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40
+#define GL_UNIFORM_BLOCK_NAME_LENGTH 0x8A41
+#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42
+#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES 0x8A43
+#define GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER 0x8A44
+#define GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER 0x8A45
+#define GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER 0x8A46
+#define GL_INVALID_INDEX 0xFFFFFFFFu
+#endif
+
+#ifndef GL_ARB_compatibility
+/* ARB_compatibility just defines tokens from core 3.0 */
+#endif
+
+#ifndef GL_ARB_copy_buffer
+#define GL_COPY_READ_BUFFER 0x8F36
+#define GL_COPY_WRITE_BUFFER 0x8F37
+#endif
+
+#ifndef GL_ARB_shader_texture_lod
+#endif
+
+#ifndef GL_ARB_depth_clamp
+#define GL_DEPTH_CLAMP 0x864F
+#endif
+
+#ifndef GL_ARB_draw_elements_base_vertex
+#endif
+
+#ifndef GL_ARB_fragment_coord_conventions
+#endif
+
+#ifndef GL_ARB_provoking_vertex
+#define GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION 0x8E4C
+#define GL_FIRST_VERTEX_CONVENTION 0x8E4D
+#define GL_LAST_VERTEX_CONVENTION 0x8E4E
+#define GL_PROVOKING_VERTEX 0x8E4F
+#endif
+
+#ifndef GL_ARB_seamless_cube_map
+#define GL_TEXTURE_CUBE_MAP_SEAMLESS 0x884F
+#endif
+
+#ifndef GL_ARB_sync
+#define GL_MAX_SERVER_WAIT_TIMEOUT 0x9111
+#define GL_OBJECT_TYPE 0x9112
+#define GL_SYNC_CONDITION 0x9113
+#define GL_SYNC_STATUS 0x9114
+#define GL_SYNC_FLAGS 0x9115
+#define GL_SYNC_FENCE 0x9116
+#define GL_SYNC_GPU_COMMANDS_COMPLETE 0x9117
+#define GL_UNSIGNALED 0x9118
+#define GL_SIGNALED 0x9119
+#define GL_ALREADY_SIGNALED 0x911A
+#define GL_TIMEOUT_EXPIRED 0x911B
+#define GL_CONDITION_SATISFIED 0x911C
+#define GL_WAIT_FAILED 0x911D
+#define GL_SYNC_FLUSH_COMMANDS_BIT 0x00000001
+#define GL_TIMEOUT_IGNORED 0xFFFFFFFFFFFFFFFFull
+#endif
+
+#ifndef GL_ARB_texture_multisample
+#define GL_SAMPLE_POSITION 0x8E50
+#define GL_SAMPLE_MASK 0x8E51
+#define GL_SAMPLE_MASK_VALUE 0x8E52
+#define GL_MAX_SAMPLE_MASK_WORDS 0x8E59
+#define GL_TEXTURE_2D_MULTISAMPLE 0x9100
+#define GL_PROXY_TEXTURE_2D_MULTISAMPLE 0x9101
+#define GL_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9102
+#define GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9103
+#define GL_TEXTURE_BINDING_2D_MULTISAMPLE 0x9104
+#define GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY 0x9105
+#define GL_TEXTURE_SAMPLES 0x9106
+#define GL_TEXTURE_FIXED_SAMPLE_LOCATIONS 0x9107
+#define GL_SAMPLER_2D_MULTISAMPLE 0x9108
+#define GL_INT_SAMPLER_2D_MULTISAMPLE 0x9109
+#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE 0x910A
+#define GL_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910B
+#define GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910C
+#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910D
+#define GL_MAX_COLOR_TEXTURE_SAMPLES 0x910E
+#define GL_MAX_DEPTH_TEXTURE_SAMPLES 0x910F
+#define GL_MAX_INTEGER_SAMPLES 0x9110
+#endif
+
+#ifndef GL_ARB_vertex_array_bgra
+/* reuse GL_BGRA */
+#endif
+
+#ifndef GL_ARB_draw_buffers_blend
+#endif
+
+#ifndef GL_ARB_sample_shading
+#define GL_SAMPLE_SHADING_ARB 0x8C36
+#define GL_MIN_SAMPLE_SHADING_VALUE_ARB 0x8C37
+#endif
+
+#ifndef GL_ARB_texture_cube_map_array
+#define GL_TEXTURE_CUBE_MAP_ARRAY_ARB 0x9009
+#define GL_TEXTURE_BINDING_CUBE_MAP_ARRAY_ARB 0x900A
+#define GL_PROXY_TEXTURE_CUBE_MAP_ARRAY_ARB 0x900B
+#define GL_SAMPLER_CUBE_MAP_ARRAY_ARB 0x900C
+#define GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW_ARB 0x900D
+#define GL_INT_SAMPLER_CUBE_MAP_ARRAY_ARB 0x900E
+#define GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY_ARB 0x900F
+#endif
+
+#ifndef GL_ARB_texture_gather
+#define GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET_ARB 0x8E5E
+#define GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET_ARB 0x8E5F
+#endif
+
+#ifndef GL_ARB_texture_query_lod
+#endif
+
+#ifndef GL_ARB_shading_language_include
+#define GL_SHADER_INCLUDE_ARB 0x8DAE
+#define GL_NAMED_STRING_LENGTH_ARB 0x8DE9
+#define GL_NAMED_STRING_TYPE_ARB 0x8DEA
+#endif
+
+#ifndef GL_ARB_texture_compression_bptc
+#define GL_COMPRESSED_RGBA_BPTC_UNORM_ARB 0x8E8C
+#define GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB 0x8E8D
+#define GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB 0x8E8E
+#define GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB 0x8E8F
+#endif
+
+#ifndef GL_ARB_blend_func_extended
+#define GL_SRC1_COLOR 0x88F9
+/* reuse GL_SRC1_ALPHA */
+#define GL_ONE_MINUS_SRC1_COLOR 0x88FA
+#define GL_ONE_MINUS_SRC1_ALPHA 0x88FB
+#define GL_MAX_DUAL_SOURCE_DRAW_BUFFERS 0x88FC
+#endif
+
+#ifndef GL_ARB_explicit_attrib_location
+#endif
+
+#ifndef GL_ARB_occlusion_query2
+#define GL_ANY_SAMPLES_PASSED 0x8C2F
+#endif
+
+#ifndef GL_ARB_sampler_objects
+#define GL_SAMPLER_BINDING 0x8919
+#endif
+
+#ifndef GL_ARB_shader_bit_encoding
+#endif
+
+#ifndef GL_ARB_texture_rgb10_a2ui
+#define GL_RGB10_A2UI 0x906F
+#endif
+
+#ifndef GL_ARB_texture_swizzle
+#define GL_TEXTURE_SWIZZLE_R 0x8E42
+#define GL_TEXTURE_SWIZZLE_G 0x8E43
+#define GL_TEXTURE_SWIZZLE_B 0x8E44
+#define GL_TEXTURE_SWIZZLE_A 0x8E45
+#define GL_TEXTURE_SWIZZLE_RGBA 0x8E46
+#endif
+
+#ifndef GL_ARB_timer_query
+#define GL_TIME_ELAPSED 0x88BF
+#define GL_TIMESTAMP 0x8E28
+#endif
+
+#ifndef GL_ARB_vertex_type_2_10_10_10_rev
+/* reuse GL_UNSIGNED_INT_2_10_10_10_REV */
+#define GL_INT_2_10_10_10_REV 0x8D9F
+#endif
+
+#ifndef GL_ARB_draw_indirect
+#define GL_DRAW_INDIRECT_BUFFER 0x8F3F
+#define GL_DRAW_INDIRECT_BUFFER_BINDING 0x8F43
+#endif
+
+#ifndef GL_ARB_gpu_shader5
+#define GL_GEOMETRY_SHADER_INVOCATIONS 0x887F
+#define GL_MAX_GEOMETRY_SHADER_INVOCATIONS 0x8E5A
+#define GL_MIN_FRAGMENT_INTERPOLATION_OFFSET 0x8E5B
+#define GL_MAX_FRAGMENT_INTERPOLATION_OFFSET 0x8E5C
+#define GL_FRAGMENT_INTERPOLATION_OFFSET_BITS 0x8E5D
+/* reuse GL_MAX_VERTEX_STREAMS */
+#endif
+
+#ifndef GL_ARB_gpu_shader_fp64
+/* reuse GL_DOUBLE */
+#define GL_DOUBLE_VEC2 0x8FFC
+#define GL_DOUBLE_VEC3 0x8FFD
+#define GL_DOUBLE_VEC4 0x8FFE
+#define GL_DOUBLE_MAT2 0x8F46
+#define GL_DOUBLE_MAT3 0x8F47
+#define GL_DOUBLE_MAT4 0x8F48
+#define GL_DOUBLE_MAT2x3 0x8F49
+#define GL_DOUBLE_MAT2x4 0x8F4A
+#define GL_DOUBLE_MAT3x2 0x8F4B
+#define GL_DOUBLE_MAT3x4 0x8F4C
+#define GL_DOUBLE_MAT4x2 0x8F4D
+#define GL_DOUBLE_MAT4x3 0x8F4E
+#endif
+
+#ifndef GL_ARB_shader_subroutine
+#define GL_ACTIVE_SUBROUTINES 0x8DE5
+#define GL_ACTIVE_SUBROUTINE_UNIFORMS 0x8DE6
+#define GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS 0x8E47
+#define GL_ACTIVE_SUBROUTINE_MAX_LENGTH 0x8E48
+#define GL_ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH 0x8E49
+#define GL_MAX_SUBROUTINES 0x8DE7
+#define GL_MAX_SUBROUTINE_UNIFORM_LOCATIONS 0x8DE8
+#define GL_NUM_COMPATIBLE_SUBROUTINES 0x8E4A
+#define GL_COMPATIBLE_SUBROUTINES 0x8E4B
+/* reuse GL_UNIFORM_SIZE */
+/* reuse GL_UNIFORM_NAME_LENGTH */
+#endif
+
+#ifndef GL_ARB_tessellation_shader
+#define GL_PATCHES 0x000E
+#define GL_PATCH_VERTICES 0x8E72
+#define GL_PATCH_DEFAULT_INNER_LEVEL 0x8E73
+#define GL_PATCH_DEFAULT_OUTER_LEVEL 0x8E74
+#define GL_TESS_CONTROL_OUTPUT_VERTICES 0x8E75
+#define GL_TESS_GEN_MODE 0x8E76
+#define GL_TESS_GEN_SPACING 0x8E77
+#define GL_TESS_GEN_VERTEX_ORDER 0x8E78
+#define GL_TESS_GEN_POINT_MODE 0x8E79
+/* reuse GL_TRIANGLES */
+/* reuse GL_QUADS */
+#define GL_ISOLINES 0x8E7A
+/* reuse GL_EQUAL */
+#define GL_FRACTIONAL_ODD 0x8E7B
+#define GL_FRACTIONAL_EVEN 0x8E7C
+/* reuse GL_CCW */
+/* reuse GL_CW */
+#define GL_MAX_PATCH_VERTICES 0x8E7D
+#define GL_MAX_TESS_GEN_LEVEL 0x8E7E
+#define GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS 0x8E7F
+#define GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS 0x8E80
+#define GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS 0x8E81
+#define GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS 0x8E82
+#define GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS 0x8E83
+#define GL_MAX_TESS_PATCH_COMPONENTS 0x8E84
+#define GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS 0x8E85
+#define GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS 0x8E86
+#define GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS 0x8E89
+#define GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS 0x8E8A
+#define GL_MAX_TESS_CONTROL_INPUT_COMPONENTS 0x886C
+#define GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS 0x886D
+#define GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS 0x8E1E
+#define GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS 0x8E1F
+#define GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_CONTROL_SHADER 0x84F0
+#define GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_EVALUATION_SHADER 0x84F1
+#define GL_TESS_EVALUATION_SHADER 0x8E87
+#define GL_TESS_CONTROL_SHADER 0x8E88
+#endif
+
+#ifndef GL_ARB_texture_buffer_object_rgb32
+/* reuse GL_RGB32F */
+/* reuse GL_RGB32UI */
+/* reuse GL_RGB32I */
+#endif
+
+#ifndef GL_ARB_transform_feedback2
+#define GL_TRANSFORM_FEEDBACK 0x8E22
+#define GL_TRANSFORM_FEEDBACK_BUFFER_PAUSED 0x8E23
+#define GL_TRANSFORM_FEEDBACK_BUFFER_ACTIVE 0x8E24
+#define GL_TRANSFORM_FEEDBACK_BINDING 0x8E25
+#endif
+
+#ifndef GL_ARB_transform_feedback3
+#define GL_MAX_TRANSFORM_FEEDBACK_BUFFERS 0x8E70
+#define GL_MAX_VERTEX_STREAMS 0x8E71
+#endif
+
+#ifndef GL_ARB_ES2_compatibility
+#define GL_FIXED 0x140C
+#define GL_IMPLEMENTATION_COLOR_READ_TYPE 0x8B9A
+#define GL_IMPLEMENTATION_COLOR_READ_FORMAT 0x8B9B
+#define GL_LOW_FLOAT 0x8DF0
+#define GL_MEDIUM_FLOAT 0x8DF1
+#define GL_HIGH_FLOAT 0x8DF2
+#define GL_LOW_INT 0x8DF3
+#define GL_MEDIUM_INT 0x8DF4
+#define GL_HIGH_INT 0x8DF5
+#define GL_SHADER_COMPILER 0x8DFA
+#define GL_NUM_SHADER_BINARY_FORMATS 0x8DF9
+#define GL_MAX_VERTEX_UNIFORM_VECTORS 0x8DFB
+#define GL_MAX_VARYING_VECTORS 0x8DFC
+#define GL_MAX_FRAGMENT_UNIFORM_VECTORS 0x8DFD
+#endif
+
+#ifndef GL_ARB_get_program_binary
+#define GL_PROGRAM_BINARY_RETRIEVABLE_HINT 0x8257
+#define GL_PROGRAM_BINARY_LENGTH 0x8741
+#define GL_NUM_PROGRAM_BINARY_FORMATS 0x87FE
+#define GL_PROGRAM_BINARY_FORMATS 0x87FF
+#endif
+
+#ifndef GL_ARB_separate_shader_objects
+#define GL_VERTEX_SHADER_BIT 0x00000001
+#define GL_FRAGMENT_SHADER_BIT 0x00000002
+#define GL_GEOMETRY_SHADER_BIT 0x00000004
+#define GL_TESS_CONTROL_SHADER_BIT 0x00000008
+#define GL_TESS_EVALUATION_SHADER_BIT 0x00000010
+#define GL_ALL_SHADER_BITS 0xFFFFFFFF
+#define GL_PROGRAM_SEPARABLE 0x8258
+#define GL_ACTIVE_PROGRAM 0x8259
+#define GL_PROGRAM_PIPELINE_BINDING 0x825A
+#endif
+
+#ifndef GL_ARB_shader_precision
+#endif
+
+#ifndef GL_ARB_vertex_attrib_64bit
+/* reuse GL_RGB32I */
+/* reuse GL_DOUBLE_VEC2 */
+/* reuse GL_DOUBLE_VEC3 */
+/* reuse GL_DOUBLE_VEC4 */
+/* reuse GL_DOUBLE_MAT2 */
+/* reuse GL_DOUBLE_MAT3 */
+/* reuse GL_DOUBLE_MAT4 */
+/* reuse GL_DOUBLE_MAT2x3 */
+/* reuse GL_DOUBLE_MAT2x4 */
+/* reuse GL_DOUBLE_MAT3x2 */
+/* reuse GL_DOUBLE_MAT3x4 */
+/* reuse GL_DOUBLE_MAT4x2 */
+/* reuse GL_DOUBLE_MAT4x3 */
+#endif
+
+#ifndef GL_ARB_viewport_array
+/* reuse GL_SCISSOR_BOX */
+/* reuse GL_VIEWPORT */
+/* reuse GL_DEPTH_RANGE */
+/* reuse GL_SCISSOR_TEST */
+#define GL_MAX_VIEWPORTS 0x825B
+#define GL_VIEWPORT_SUBPIXEL_BITS 0x825C
+#define GL_VIEWPORT_BOUNDS_RANGE 0x825D
+#define GL_LAYER_PROVOKING_VERTEX 0x825E
+#define GL_VIEWPORT_INDEX_PROVOKING_VERTEX 0x825F
+#define GL_UNDEFINED_VERTEX 0x8260
+/* reuse GL_FIRST_VERTEX_CONVENTION */
+/* reuse GL_LAST_VERTEX_CONVENTION */
+/* reuse GL_PROVOKING_VERTEX */
+#endif
+
+#ifndef GL_ARB_cl_event
+#define GL_SYNC_CL_EVENT_ARB 0x8240
+#define GL_SYNC_CL_EVENT_COMPLETE_ARB 0x8241
+#endif
+
+#ifndef GL_ARB_debug_output
+#define GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB 0x8242
+#define GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH_ARB 0x8243
+#define GL_DEBUG_CALLBACK_FUNCTION_ARB 0x8244
+#define GL_DEBUG_CALLBACK_USER_PARAM_ARB 0x8245
+#define GL_DEBUG_SOURCE_API_ARB 0x8246
+#define GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB 0x8247
+#define GL_DEBUG_SOURCE_SHADER_COMPILER_ARB 0x8248
+#define GL_DEBUG_SOURCE_THIRD_PARTY_ARB 0x8249
+#define GL_DEBUG_SOURCE_APPLICATION_ARB 0x824A
+#define GL_DEBUG_SOURCE_OTHER_ARB 0x824B
+#define GL_DEBUG_TYPE_ERROR_ARB 0x824C
+#define GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB 0x824D
+#define GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB 0x824E
+#define GL_DEBUG_TYPE_PORTABILITY_ARB 0x824F
+#define GL_DEBUG_TYPE_PERFORMANCE_ARB 0x8250
+#define GL_DEBUG_TYPE_OTHER_ARB 0x8251
+#define GL_MAX_DEBUG_MESSAGE_LENGTH_ARB 0x9143
+#define GL_MAX_DEBUG_LOGGED_MESSAGES_ARB 0x9144
+#define GL_DEBUG_LOGGED_MESSAGES_ARB 0x9145
+#define GL_DEBUG_SEVERITY_HIGH_ARB 0x9146
+#define GL_DEBUG_SEVERITY_MEDIUM_ARB 0x9147
+#define GL_DEBUG_SEVERITY_LOW_ARB 0x9148
+#endif
+
+#ifndef GL_ARB_robustness
+/* reuse GL_NO_ERROR */
+#define GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT_ARB 0x00000004
+#define GL_LOSE_CONTEXT_ON_RESET_ARB 0x8252
+#define GL_GUILTY_CONTEXT_RESET_ARB 0x8253
+#define GL_INNOCENT_CONTEXT_RESET_ARB 0x8254
+#define GL_UNKNOWN_CONTEXT_RESET_ARB 0x8255
+#define GL_RESET_NOTIFICATION_STRATEGY_ARB 0x8256
+#define GL_NO_RESET_NOTIFICATION_ARB 0x8261
+#endif
+
+#ifndef GL_ARB_shader_stencil_export
+#endif
+
+#ifndef GL_EXT_abgr
+#define GL_ABGR_EXT 0x8000
+#endif
+
+#ifndef GL_EXT_blend_color
+#define GL_CONSTANT_COLOR_EXT 0x8001
+#define GL_ONE_MINUS_CONSTANT_COLOR_EXT 0x8002
+#define GL_CONSTANT_ALPHA_EXT 0x8003
+#define GL_ONE_MINUS_CONSTANT_ALPHA_EXT 0x8004
+#define GL_BLEND_COLOR_EXT 0x8005
+#endif
+
+#ifndef GL_EXT_polygon_offset
+#define GL_POLYGON_OFFSET_EXT 0x8037
+#define GL_POLYGON_OFFSET_FACTOR_EXT 0x8038
+#define GL_POLYGON_OFFSET_BIAS_EXT 0x8039
+#endif
+
+#ifndef GL_EXT_texture
+#define GL_ALPHA4_EXT 0x803B
+#define GL_ALPHA8_EXT 0x803C
+#define GL_ALPHA12_EXT 0x803D
+#define GL_ALPHA16_EXT 0x803E
+#define GL_LUMINANCE4_EXT 0x803F
+#define GL_LUMINANCE8_EXT 0x8040
+#define GL_LUMINANCE12_EXT 0x8041
+#define GL_LUMINANCE16_EXT 0x8042
+#define GL_LUMINANCE4_ALPHA4_EXT 0x8043
+#define GL_LUMINANCE6_ALPHA2_EXT 0x8044
+#define GL_LUMINANCE8_ALPHA8_EXT 0x8045
+#define GL_LUMINANCE12_ALPHA4_EXT 0x8046
+#define GL_LUMINANCE12_ALPHA12_EXT 0x8047
+#define GL_LUMINANCE16_ALPHA16_EXT 0x8048
+#define GL_INTENSITY_EXT 0x8049
+#define GL_INTENSITY4_EXT 0x804A
+#define GL_INTENSITY8_EXT 0x804B
+#define GL_INTENSITY12_EXT 0x804C
+#define GL_INTENSITY16_EXT 0x804D
+#define GL_RGB2_EXT 0x804E
+#define GL_RGB4_EXT 0x804F
+#define GL_RGB5_EXT 0x8050
+#define GL_RGB8_EXT 0x8051
+#define GL_RGB10_EXT 0x8052
+#define GL_RGB12_EXT 0x8053
+#define GL_RGB16_EXT 0x8054
+#define GL_RGBA2_EXT 0x8055
+#define GL_RGBA4_EXT 0x8056
+#define GL_RGB5_A1_EXT 0x8057
+#define GL_RGBA8_EXT 0x8058
+#define GL_RGB10_A2_EXT 0x8059
+#define GL_RGBA12_EXT 0x805A
+#define GL_RGBA16_EXT 0x805B
+#define GL_TEXTURE_RED_SIZE_EXT 0x805C
+#define GL_TEXTURE_GREEN_SIZE_EXT 0x805D
+#define GL_TEXTURE_BLUE_SIZE_EXT 0x805E
+#define GL_TEXTURE_ALPHA_SIZE_EXT 0x805F
+#define GL_TEXTURE_LUMINANCE_SIZE_EXT 0x8060
+#define GL_TEXTURE_INTENSITY_SIZE_EXT 0x8061
+#define GL_REPLACE_EXT 0x8062
+#define GL_PROXY_TEXTURE_1D_EXT 0x8063
+#define GL_PROXY_TEXTURE_2D_EXT 0x8064
+#define GL_TEXTURE_TOO_LARGE_EXT 0x8065
+#endif
+
+#ifndef GL_EXT_texture3D
+#define GL_PACK_SKIP_IMAGES_EXT 0x806B
+#define GL_PACK_IMAGE_HEIGHT_EXT 0x806C
+#define GL_UNPACK_SKIP_IMAGES_EXT 0x806D
+#define GL_UNPACK_IMAGE_HEIGHT_EXT 0x806E
+#define GL_TEXTURE_3D_EXT 0x806F
+#define GL_PROXY_TEXTURE_3D_EXT 0x8070
+#define GL_TEXTURE_DEPTH_EXT 0x8071
+#define GL_TEXTURE_WRAP_R_EXT 0x8072
+#define GL_MAX_3D_TEXTURE_SIZE_EXT 0x8073
+#endif
+
+#ifndef GL_SGIS_texture_filter4
+#define GL_FILTER4_SGIS 0x8146
+#define GL_TEXTURE_FILTER4_SIZE_SGIS 0x8147
+#endif
+
+#ifndef GL_EXT_subtexture
+#endif
+
+#ifndef GL_EXT_copy_texture
+#endif
+
+#ifndef GL_EXT_histogram
+#define GL_HISTOGRAM_EXT 0x8024
+#define GL_PROXY_HISTOGRAM_EXT 0x8025
+#define GL_HISTOGRAM_WIDTH_EXT 0x8026
+#define GL_HISTOGRAM_FORMAT_EXT 0x8027
+#define GL_HISTOGRAM_RED_SIZE_EXT 0x8028
+#define GL_HISTOGRAM_GREEN_SIZE_EXT 0x8029
+#define GL_HISTOGRAM_BLUE_SIZE_EXT 0x802A
+#define GL_HISTOGRAM_ALPHA_SIZE_EXT 0x802B
+#define GL_HISTOGRAM_LUMINANCE_SIZE_EXT 0x802C
+#define GL_HISTOGRAM_SINK_EXT 0x802D
+#define GL_MINMAX_EXT 0x802E
+#define GL_MINMAX_FORMAT_EXT 0x802F
+#define GL_MINMAX_SINK_EXT 0x8030
+#define GL_TABLE_TOO_LARGE_EXT 0x8031
+#endif
+
+#ifndef GL_EXT_convolution
+#define GL_CONVOLUTION_1D_EXT 0x8010
+#define GL_CONVOLUTION_2D_EXT 0x8011
+#define GL_SEPARABLE_2D_EXT 0x8012
+#define GL_CONVOLUTION_BORDER_MODE_EXT 0x8013
+#define GL_CONVOLUTION_FILTER_SCALE_EXT 0x8014
+#define GL_CONVOLUTION_FILTER_BIAS_EXT 0x8015
+#define GL_REDUCE_EXT 0x8016
+#define GL_CONVOLUTION_FORMAT_EXT 0x8017
+#define GL_CONVOLUTION_WIDTH_EXT 0x8018
+#define GL_CONVOLUTION_HEIGHT_EXT 0x8019
+#define GL_MAX_CONVOLUTION_WIDTH_EXT 0x801A
+#define GL_MAX_CONVOLUTION_HEIGHT_EXT 0x801B
+#define GL_POST_CONVOLUTION_RED_SCALE_EXT 0x801C
+#define GL_POST_CONVOLUTION_GREEN_SCALE_EXT 0x801D
+#define GL_POST_CONVOLUTION_BLUE_SCALE_EXT 0x801E
+#define GL_POST_CONVOLUTION_ALPHA_SCALE_EXT 0x801F
+#define GL_POST_CONVOLUTION_RED_BIAS_EXT 0x8020
+#define GL_POST_CONVOLUTION_GREEN_BIAS_EXT 0x8021
+#define GL_POST_CONVOLUTION_BLUE_BIAS_EXT 0x8022
+#define GL_POST_CONVOLUTION_ALPHA_BIAS_EXT 0x8023
+#endif
+
+#ifndef GL_SGI_color_matrix
+#define GL_COLOR_MATRIX_SGI 0x80B1
+#define GL_COLOR_MATRIX_STACK_DEPTH_SGI 0x80B2
+#define GL_MAX_COLOR_MATRIX_STACK_DEPTH_SGI 0x80B3
+#define GL_POST_COLOR_MATRIX_RED_SCALE_SGI 0x80B4
+#define GL_POST_COLOR_MATRIX_GREEN_SCALE_SGI 0x80B5
+#define GL_POST_COLOR_MATRIX_BLUE_SCALE_SGI 0x80B6
+#define GL_POST_COLOR_MATRIX_ALPHA_SCALE_SGI 0x80B7
+#define GL_POST_COLOR_MATRIX_RED_BIAS_SGI 0x80B8
+#define GL_POST_COLOR_MATRIX_GREEN_BIAS_SGI 0x80B9
+#define GL_POST_COLOR_MATRIX_BLUE_BIAS_SGI 0x80BA
+#define GL_POST_COLOR_MATRIX_ALPHA_BIAS_SGI 0x80BB
+#endif
+
+#ifndef GL_SGI_color_table
+#define GL_COLOR_TABLE_SGI 0x80D0
+#define GL_POST_CONVOLUTION_COLOR_TABLE_SGI 0x80D1
+#define GL_POST_COLOR_MATRIX_COLOR_TABLE_SGI 0x80D2
+#define GL_PROXY_COLOR_TABLE_SGI 0x80D3
+#define GL_PROXY_POST_CONVOLUTION_COLOR_TABLE_SGI 0x80D4
+#define GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE_SGI 0x80D5
+#define GL_COLOR_TABLE_SCALE_SGI 0x80D6
+#define GL_COLOR_TABLE_BIAS_SGI 0x80D7
+#define GL_COLOR_TABLE_FORMAT_SGI 0x80D8
+#define GL_COLOR_TABLE_WIDTH_SGI 0x80D9
+#define GL_COLOR_TABLE_RED_SIZE_SGI 0x80DA
+#define GL_COLOR_TABLE_GREEN_SIZE_SGI 0x80DB
+#define GL_COLOR_TABLE_BLUE_SIZE_SGI 0x80DC
+#define GL_COLOR_TABLE_ALPHA_SIZE_SGI 0x80DD
+#define GL_COLOR_TABLE_LUMINANCE_SIZE_SGI 0x80DE
+#define GL_COLOR_TABLE_INTENSITY_SIZE_SGI 0x80DF
+#endif
+
+#ifndef GL_SGIS_pixel_texture
+#define GL_PIXEL_TEXTURE_SGIS 0x8353
+#define GL_PIXEL_FRAGMENT_RGB_SOURCE_SGIS 0x8354
+#define GL_PIXEL_FRAGMENT_ALPHA_SOURCE_SGIS 0x8355
+#define GL_PIXEL_GROUP_COLOR_SGIS 0x8356
+#endif
+
+#ifndef GL_SGIX_pixel_texture
+#define GL_PIXEL_TEX_GEN_SGIX 0x8139
+#define GL_PIXEL_TEX_GEN_MODE_SGIX 0x832B
+#endif
+
+#ifndef GL_SGIS_texture4D
+#define GL_PACK_SKIP_VOLUMES_SGIS 0x8130
+#define GL_PACK_IMAGE_DEPTH_SGIS 0x8131
+#define GL_UNPACK_SKIP_VOLUMES_SGIS 0x8132
+#define GL_UNPACK_IMAGE_DEPTH_SGIS 0x8133
+#define GL_TEXTURE_4D_SGIS 0x8134
+#define GL_PROXY_TEXTURE_4D_SGIS 0x8135
+#define GL_TEXTURE_4DSIZE_SGIS 0x8136
+#define GL_TEXTURE_WRAP_Q_SGIS 0x8137
+#define GL_MAX_4D_TEXTURE_SIZE_SGIS 0x8138
+#define GL_TEXTURE_4D_BINDING_SGIS 0x814F
+#endif
+
+#ifndef GL_SGI_texture_color_table
+#define GL_TEXTURE_COLOR_TABLE_SGI 0x80BC
+#define GL_PROXY_TEXTURE_COLOR_TABLE_SGI 0x80BD
+#endif
+
+#ifndef GL_EXT_cmyka
+#define GL_CMYK_EXT 0x800C
+#define GL_CMYKA_EXT 0x800D
+#define GL_PACK_CMYK_HINT_EXT 0x800E
+#define GL_UNPACK_CMYK_HINT_EXT 0x800F
+#endif
+
+#ifndef GL_EXT_texture_object
+#define GL_TEXTURE_PRIORITY_EXT 0x8066
+#define GL_TEXTURE_RESIDENT_EXT 0x8067
+#define GL_TEXTURE_1D_BINDING_EXT 0x8068
+#define GL_TEXTURE_2D_BINDING_EXT 0x8069
+#define GL_TEXTURE_3D_BINDING_EXT 0x806A
+#endif
+
+#ifndef GL_SGIS_detail_texture
+#define GL_DETAIL_TEXTURE_2D_SGIS 0x8095
+#define GL_DETAIL_TEXTURE_2D_BINDING_SGIS 0x8096
+#define GL_LINEAR_DETAIL_SGIS 0x8097
+#define GL_LINEAR_DETAIL_ALPHA_SGIS 0x8098
+#define GL_LINEAR_DETAIL_COLOR_SGIS 0x8099
+#define GL_DETAIL_TEXTURE_LEVEL_SGIS 0x809A
+#define GL_DETAIL_TEXTURE_MODE_SGIS 0x809B
+#define GL_DETAIL_TEXTURE_FUNC_POINTS_SGIS 0x809C
+#endif
+
+#ifndef GL_SGIS_sharpen_texture
+#define GL_LINEAR_SHARPEN_SGIS 0x80AD
+#define GL_LINEAR_SHARPEN_ALPHA_SGIS 0x80AE
+#define GL_LINEAR_SHARPEN_COLOR_SGIS 0x80AF
+#define GL_SHARPEN_TEXTURE_FUNC_POINTS_SGIS 0x80B0
+#endif
+
+#ifndef GL_EXT_packed_pixels
+#define GL_UNSIGNED_BYTE_3_3_2_EXT 0x8032
+#define GL_UNSIGNED_SHORT_4_4_4_4_EXT 0x8033
+#define GL_UNSIGNED_SHORT_5_5_5_1_EXT 0x8034
+#define GL_UNSIGNED_INT_8_8_8_8_EXT 0x8035
+#define GL_UNSIGNED_INT_10_10_10_2_EXT 0x8036
+#endif
+
+#ifndef GL_SGIS_texture_lod
+#define GL_TEXTURE_MIN_LOD_SGIS 0x813A
+#define GL_TEXTURE_MAX_LOD_SGIS 0x813B
+#define GL_TEXTURE_BASE_LEVEL_SGIS 0x813C
+#define GL_TEXTURE_MAX_LEVEL_SGIS 0x813D
+#endif
+
+#ifndef GL_SGIS_multisample
+#define GL_MULTISAMPLE_SGIS 0x809D
+#define GL_SAMPLE_ALPHA_TO_MASK_SGIS 0x809E
+#define GL_SAMPLE_ALPHA_TO_ONE_SGIS 0x809F
+#define GL_SAMPLE_MASK_SGIS 0x80A0
+#define GL_1PASS_SGIS 0x80A1
+#define GL_2PASS_0_SGIS 0x80A2
+#define GL_2PASS_1_SGIS 0x80A3
+#define GL_4PASS_0_SGIS 0x80A4
+#define GL_4PASS_1_SGIS 0x80A5
+#define GL_4PASS_2_SGIS 0x80A6
+#define GL_4PASS_3_SGIS 0x80A7
+#define GL_SAMPLE_BUFFERS_SGIS 0x80A8
+#define GL_SAMPLES_SGIS 0x80A9
+#define GL_SAMPLE_MASK_VALUE_SGIS 0x80AA
+#define GL_SAMPLE_MASK_INVERT_SGIS 0x80AB
+#define GL_SAMPLE_PATTERN_SGIS 0x80AC
+#endif
+
+#ifndef GL_EXT_rescale_normal
+#define GL_RESCALE_NORMAL_EXT 0x803A
+#endif
+
+#ifndef GL_EXT_vertex_array
+#define GL_VERTEX_ARRAY_EXT 0x8074
+#define GL_NORMAL_ARRAY_EXT 0x8075
+#define GL_COLOR_ARRAY_EXT 0x8076
+#define GL_INDEX_ARRAY_EXT 0x8077
+#define GL_TEXTURE_COORD_ARRAY_EXT 0x8078
+#define GL_EDGE_FLAG_ARRAY_EXT 0x8079
+#define GL_VERTEX_ARRAY_SIZE_EXT 0x807A
+#define GL_VERTEX_ARRAY_TYPE_EXT 0x807B
+#define GL_VERTEX_ARRAY_STRIDE_EXT 0x807C
+#define GL_VERTEX_ARRAY_COUNT_EXT 0x807D
+#define GL_NORMAL_ARRAY_TYPE_EXT 0x807E
+#define GL_NORMAL_ARRAY_STRIDE_EXT 0x807F
+#define GL_NORMAL_ARRAY_COUNT_EXT 0x8080
+#define GL_COLOR_ARRAY_SIZE_EXT 0x8081
+#define GL_COLOR_ARRAY_TYPE_EXT 0x8082
+#define GL_COLOR_ARRAY_STRIDE_EXT 0x8083
+#define GL_COLOR_ARRAY_COUNT_EXT 0x8084
+#define GL_INDEX_ARRAY_TYPE_EXT 0x8085
+#define GL_INDEX_ARRAY_STRIDE_EXT 0x8086
+#define GL_INDEX_ARRAY_COUNT_EXT 0x8087
+#define GL_TEXTURE_COORD_ARRAY_SIZE_EXT 0x8088
+#define GL_TEXTURE_COORD_ARRAY_TYPE_EXT 0x8089
+#define GL_TEXTURE_COORD_ARRAY_STRIDE_EXT 0x808A
+#define GL_TEXTURE_COORD_ARRAY_COUNT_EXT 0x808B
+#define GL_EDGE_FLAG_ARRAY_STRIDE_EXT 0x808C
+#define GL_EDGE_FLAG_ARRAY_COUNT_EXT 0x808D
+#define GL_VERTEX_ARRAY_POINTER_EXT 0x808E
+#define GL_NORMAL_ARRAY_POINTER_EXT 0x808F
+#define GL_COLOR_ARRAY_POINTER_EXT 0x8090
+#define GL_INDEX_ARRAY_POINTER_EXT 0x8091
+#define GL_TEXTURE_COORD_ARRAY_POINTER_EXT 0x8092
+#define GL_EDGE_FLAG_ARRAY_POINTER_EXT 0x8093
+#endif
+
+#ifndef GL_EXT_misc_attribute
+#endif
+
+#ifndef GL_SGIS_generate_mipmap
+#define GL_GENERATE_MIPMAP_SGIS 0x8191
+#define GL_GENERATE_MIPMAP_HINT_SGIS 0x8192
+#endif
+
+#ifndef GL_SGIX_clipmap
+#define GL_LINEAR_CLIPMAP_LINEAR_SGIX 0x8170
+#define GL_TEXTURE_CLIPMAP_CENTER_SGIX 0x8171
+#define GL_TEXTURE_CLIPMAP_FRAME_SGIX 0x8172
+#define GL_TEXTURE_CLIPMAP_OFFSET_SGIX 0x8173
+#define GL_TEXTURE_CLIPMAP_VIRTUAL_DEPTH_SGIX 0x8174
+#define GL_TEXTURE_CLIPMAP_LOD_OFFSET_SGIX 0x8175
+#define GL_TEXTURE_CLIPMAP_DEPTH_SGIX 0x8176
+#define GL_MAX_CLIPMAP_DEPTH_SGIX 0x8177
+#define GL_MAX_CLIPMAP_VIRTUAL_DEPTH_SGIX 0x8178
+#define GL_NEAREST_CLIPMAP_NEAREST_SGIX 0x844D
+#define GL_NEAREST_CLIPMAP_LINEAR_SGIX 0x844E
+#define GL_LINEAR_CLIPMAP_NEAREST_SGIX 0x844F
+#endif
+
+#ifndef GL_SGIX_shadow
+#define GL_TEXTURE_COMPARE_SGIX 0x819A
+#define GL_TEXTURE_COMPARE_OPERATOR_SGIX 0x819B
+#define GL_TEXTURE_LEQUAL_R_SGIX 0x819C
+#define GL_TEXTURE_GEQUAL_R_SGIX 0x819D
+#endif
+
+#ifndef GL_SGIS_texture_edge_clamp
+#define GL_CLAMP_TO_EDGE_SGIS 0x812F
+#endif
+
+#ifndef GL_SGIS_texture_border_clamp
+#define GL_CLAMP_TO_BORDER_SGIS 0x812D
+#endif
+
+#ifndef GL_EXT_blend_minmax
+#define GL_FUNC_ADD_EXT 0x8006
+#define GL_MIN_EXT 0x8007
+#define GL_MAX_EXT 0x8008
+#define GL_BLEND_EQUATION_EXT 0x8009
+#endif
+
+#ifndef GL_EXT_blend_subtract
+#define GL_FUNC_SUBTRACT_EXT 0x800A
+#define GL_FUNC_REVERSE_SUBTRACT_EXT 0x800B
+#endif
+
+#ifndef GL_EXT_blend_logic_op
+#endif
+
+#ifndef GL_SGIX_interlace
+#define GL_INTERLACE_SGIX 0x8094
+#endif
+
+#ifndef GL_SGIX_pixel_tiles
+#define GL_PIXEL_TILE_BEST_ALIGNMENT_SGIX 0x813E
+#define GL_PIXEL_TILE_CACHE_INCREMENT_SGIX 0x813F
+#define GL_PIXEL_TILE_WIDTH_SGIX 0x8140
+#define GL_PIXEL_TILE_HEIGHT_SGIX 0x8141
+#define GL_PIXEL_TILE_GRID_WIDTH_SGIX 0x8142
+#define GL_PIXEL_TILE_GRID_HEIGHT_SGIX 0x8143
+#define GL_PIXEL_TILE_GRID_DEPTH_SGIX 0x8144
+#define GL_PIXEL_TILE_CACHE_SIZE_SGIX 0x8145
+#endif
+
+#ifndef GL_SGIS_texture_select
+#define GL_DUAL_ALPHA4_SGIS 0x8110
+#define GL_DUAL_ALPHA8_SGIS 0x8111
+#define GL_DUAL_ALPHA12_SGIS 0x8112
+#define GL_DUAL_ALPHA16_SGIS 0x8113
+#define GL_DUAL_LUMINANCE4_SGIS 0x8114
+#define GL_DUAL_LUMINANCE8_SGIS 0x8115
+#define GL_DUAL_LUMINANCE12_SGIS 0x8116
+#define GL_DUAL_LUMINANCE16_SGIS 0x8117
+#define GL_DUAL_INTENSITY4_SGIS 0x8118
+#define GL_DUAL_INTENSITY8_SGIS 0x8119
+#define GL_DUAL_INTENSITY12_SGIS 0x811A
+#define GL_DUAL_INTENSITY16_SGIS 0x811B
+#define GL_DUAL_LUMINANCE_ALPHA4_SGIS 0x811C
+#define GL_DUAL_LUMINANCE_ALPHA8_SGIS 0x811D
+#define GL_QUAD_ALPHA4_SGIS 0x811E
+#define GL_QUAD_ALPHA8_SGIS 0x811F
+#define GL_QUAD_LUMINANCE4_SGIS 0x8120
+#define GL_QUAD_LUMINANCE8_SGIS 0x8121
+#define GL_QUAD_INTENSITY4_SGIS 0x8122
+#define GL_QUAD_INTENSITY8_SGIS 0x8123
+#define GL_DUAL_TEXTURE_SELECT_SGIS 0x8124
+#define GL_QUAD_TEXTURE_SELECT_SGIS 0x8125
+#endif
+
+#ifndef GL_SGIX_sprite
+#define GL_SPRITE_SGIX 0x8148
+#define GL_SPRITE_MODE_SGIX 0x8149
+#define GL_SPRITE_AXIS_SGIX 0x814A
+#define GL_SPRITE_TRANSLATION_SGIX 0x814B
+#define GL_SPRITE_AXIAL_SGIX 0x814C
+#define GL_SPRITE_OBJECT_ALIGNED_SGIX 0x814D
+#define GL_SPRITE_EYE_ALIGNED_SGIX 0x814E
+#endif
+
+#ifndef GL_SGIX_texture_multi_buffer
+#define GL_TEXTURE_MULTI_BUFFER_HINT_SGIX 0x812E
+#endif
+
+#ifndef GL_EXT_point_parameters
+#define GL_POINT_SIZE_MIN_EXT 0x8126
+#define GL_POINT_SIZE_MAX_EXT 0x8127
+#define GL_POINT_FADE_THRESHOLD_SIZE_EXT 0x8128
+#define GL_DISTANCE_ATTENUATION_EXT 0x8129
+#endif
+
+#ifndef GL_SGIS_point_parameters
+#define GL_POINT_SIZE_MIN_SGIS 0x8126
+#define GL_POINT_SIZE_MAX_SGIS 0x8127
+#define GL_POINT_FADE_THRESHOLD_SIZE_SGIS 0x8128
+#define GL_DISTANCE_ATTENUATION_SGIS 0x8129
+#endif
+
+#ifndef GL_SGIX_instruments
+#define GL_INSTRUMENT_BUFFER_POINTER_SGIX 0x8180
+#define GL_INSTRUMENT_MEASUREMENTS_SGIX 0x8181
+#endif
+
+#ifndef GL_SGIX_texture_scale_bias
+#define GL_POST_TEXTURE_FILTER_BIAS_SGIX 0x8179
+#define GL_POST_TEXTURE_FILTER_SCALE_SGIX 0x817A
+#define GL_POST_TEXTURE_FILTER_BIAS_RANGE_SGIX 0x817B
+#define GL_POST_TEXTURE_FILTER_SCALE_RANGE_SGIX 0x817C
+#endif
+
+#ifndef GL_SGIX_framezoom
+#define GL_FRAMEZOOM_SGIX 0x818B
+#define GL_FRAMEZOOM_FACTOR_SGIX 0x818C
+#define GL_MAX_FRAMEZOOM_FACTOR_SGIX 0x818D
+#endif
+
+#ifndef GL_SGIX_tag_sample_buffer
+#endif
+
+#ifndef GL_FfdMaskSGIX
+#define GL_TEXTURE_DEFORMATION_BIT_SGIX 0x00000001
+#define GL_GEOMETRY_DEFORMATION_BIT_SGIX 0x00000002
+#endif
+
+#ifndef GL_SGIX_polynomial_ffd
+#define GL_GEOMETRY_DEFORMATION_SGIX 0x8194
+#define GL_TEXTURE_DEFORMATION_SGIX 0x8195
+#define GL_DEFORMATIONS_MASK_SGIX 0x8196
+#define GL_MAX_DEFORMATION_ORDER_SGIX 0x8197
+#endif
+
+#ifndef GL_SGIX_reference_plane
+#define GL_REFERENCE_PLANE_SGIX 0x817D
+#define GL_REFERENCE_PLANE_EQUATION_SGIX 0x817E
+#endif
+
+#ifndef GL_SGIX_flush_raster
+#endif
+
+#ifndef GL_SGIX_depth_texture
+#define GL_DEPTH_COMPONENT16_SGIX 0x81A5
+#define GL_DEPTH_COMPONENT24_SGIX 0x81A6
+#define GL_DEPTH_COMPONENT32_SGIX 0x81A7
+#endif
+
+#ifndef GL_SGIS_fog_function
+#define GL_FOG_FUNC_SGIS 0x812A
+#define GL_FOG_FUNC_POINTS_SGIS 0x812B
+#define GL_MAX_FOG_FUNC_POINTS_SGIS 0x812C
+#endif
+
+#ifndef GL_SGIX_fog_offset
+#define GL_FOG_OFFSET_SGIX 0x8198
+#define GL_FOG_OFFSET_VALUE_SGIX 0x8199
+#endif
+
+#ifndef GL_HP_image_transform
+#define GL_IMAGE_SCALE_X_HP 0x8155
+#define GL_IMAGE_SCALE_Y_HP 0x8156
+#define GL_IMAGE_TRANSLATE_X_HP 0x8157
+#define GL_IMAGE_TRANSLATE_Y_HP 0x8158
+#define GL_IMAGE_ROTATE_ANGLE_HP 0x8159
+#define GL_IMAGE_ROTATE_ORIGIN_X_HP 0x815A
+#define GL_IMAGE_ROTATE_ORIGIN_Y_HP 0x815B
+#define GL_IMAGE_MAG_FILTER_HP 0x815C
+#define GL_IMAGE_MIN_FILTER_HP 0x815D
+#define GL_IMAGE_CUBIC_WEIGHT_HP 0x815E
+#define GL_CUBIC_HP 0x815F
+#define GL_AVERAGE_HP 0x8160
+#define GL_IMAGE_TRANSFORM_2D_HP 0x8161
+#define GL_POST_IMAGE_TRANSFORM_COLOR_TABLE_HP 0x8162
+#define GL_PROXY_POST_IMAGE_TRANSFORM_COLOR_TABLE_HP 0x8163
+#endif
+
+#ifndef GL_HP_convolution_border_modes
+#define GL_IGNORE_BORDER_HP 0x8150
+#define GL_CONSTANT_BORDER_HP 0x8151
+#define GL_REPLICATE_BORDER_HP 0x8153
+#define GL_CONVOLUTION_BORDER_COLOR_HP 0x8154
+#endif
+
+#ifndef GL_INGR_palette_buffer
+#endif
+
+#ifndef GL_SGIX_texture_add_env
+#define GL_TEXTURE_ENV_BIAS_SGIX 0x80BE
+#endif
+
+#ifndef GL_EXT_color_subtable
+#endif
+
+#ifndef GL_PGI_vertex_hints
+#define GL_VERTEX_DATA_HINT_PGI 0x1A22A
+#define GL_VERTEX_CONSISTENT_HINT_PGI 0x1A22B
+#define GL_MATERIAL_SIDE_HINT_PGI 0x1A22C
+#define GL_MAX_VERTEX_HINT_PGI 0x1A22D
+#define GL_COLOR3_BIT_PGI 0x00010000
+#define GL_COLOR4_BIT_PGI 0x00020000
+#define GL_EDGEFLAG_BIT_PGI 0x00040000
+#define GL_INDEX_BIT_PGI 0x00080000
+#define GL_MAT_AMBIENT_BIT_PGI 0x00100000
+#define GL_MAT_AMBIENT_AND_DIFFUSE_BIT_PGI 0x00200000
+#define GL_MAT_DIFFUSE_BIT_PGI 0x00400000
+#define GL_MAT_EMISSION_BIT_PGI 0x00800000
+#define GL_MAT_COLOR_INDEXES_BIT_PGI 0x01000000
+#define GL_MAT_SHININESS_BIT_PGI 0x02000000
+#define GL_MAT_SPECULAR_BIT_PGI 0x04000000
+#define GL_NORMAL_BIT_PGI 0x08000000
+#define GL_TEXCOORD1_BIT_PGI 0x10000000
+#define GL_TEXCOORD2_BIT_PGI 0x20000000
+#define GL_TEXCOORD3_BIT_PGI 0x40000000
+#define GL_TEXCOORD4_BIT_PGI 0x80000000
+#define GL_VERTEX23_BIT_PGI 0x00000004
+#define GL_VERTEX4_BIT_PGI 0x00000008
+#endif
+
+#ifndef GL_PGI_misc_hints
+#define GL_PREFER_DOUBLEBUFFER_HINT_PGI 0x1A1F8
+#define GL_CONSERVE_MEMORY_HINT_PGI 0x1A1FD
+#define GL_RECLAIM_MEMORY_HINT_PGI 0x1A1FE
+#define GL_NATIVE_GRAPHICS_HANDLE_PGI 0x1A202
+#define GL_NATIVE_GRAPHICS_BEGIN_HINT_PGI 0x1A203
+#define GL_NATIVE_GRAPHICS_END_HINT_PGI 0x1A204
+#define GL_ALWAYS_FAST_HINT_PGI 0x1A20C
+#define GL_ALWAYS_SOFT_HINT_PGI 0x1A20D
+#define GL_ALLOW_DRAW_OBJ_HINT_PGI 0x1A20E
+#define GL_ALLOW_DRAW_WIN_HINT_PGI 0x1A20F
+#define GL_ALLOW_DRAW_FRG_HINT_PGI 0x1A210
+#define GL_ALLOW_DRAW_MEM_HINT_PGI 0x1A211
+#define GL_STRICT_DEPTHFUNC_HINT_PGI 0x1A216
+#define GL_STRICT_LIGHTING_HINT_PGI 0x1A217
+#define GL_STRICT_SCISSOR_HINT_PGI 0x1A218
+#define GL_FULL_STIPPLE_HINT_PGI 0x1A219
+#define GL_CLIP_NEAR_HINT_PGI 0x1A220
+#define GL_CLIP_FAR_HINT_PGI 0x1A221
+#define GL_WIDE_LINE_HINT_PGI 0x1A222
+#define GL_BACK_NORMALS_HINT_PGI 0x1A223
+#endif
+
+#ifndef GL_EXT_paletted_texture
+#define GL_COLOR_INDEX1_EXT 0x80E2
+#define GL_COLOR_INDEX2_EXT 0x80E3
+#define GL_COLOR_INDEX4_EXT 0x80E4
+#define GL_COLOR_INDEX8_EXT 0x80E5
+#define GL_COLOR_INDEX12_EXT 0x80E6
+#define GL_COLOR_INDEX16_EXT 0x80E7
+#define GL_TEXTURE_INDEX_SIZE_EXT 0x80ED
+#endif
+
+#ifndef GL_EXT_clip_volume_hint
+#define GL_CLIP_VOLUME_CLIPPING_HINT_EXT 0x80F0
+#endif
+
+#ifndef GL_SGIX_list_priority
+#define GL_LIST_PRIORITY_SGIX 0x8182
+#endif
+
+#ifndef GL_SGIX_ir_instrument1
+#define GL_IR_INSTRUMENT1_SGIX 0x817F
+#endif
+
+#ifndef GL_SGIX_calligraphic_fragment
+#define GL_CALLIGRAPHIC_FRAGMENT_SGIX 0x8183
+#endif
+
+#ifndef GL_SGIX_texture_lod_bias
+#define GL_TEXTURE_LOD_BIAS_S_SGIX 0x818E
+#define GL_TEXTURE_LOD_BIAS_T_SGIX 0x818F
+#define GL_TEXTURE_LOD_BIAS_R_SGIX 0x8190
+#endif
+
+#ifndef GL_SGIX_shadow_ambient
+#define GL_SHADOW_AMBIENT_SGIX 0x80BF
+#endif
+
+#ifndef GL_EXT_index_texture
+#endif
+
+#ifndef GL_EXT_index_material
+#define GL_INDEX_MATERIAL_EXT 0x81B8
+#define GL_INDEX_MATERIAL_PARAMETER_EXT 0x81B9
+#define GL_INDEX_MATERIAL_FACE_EXT 0x81BA
+#endif
+
+#ifndef GL_EXT_index_func
+#define GL_INDEX_TEST_EXT 0x81B5
+#define GL_INDEX_TEST_FUNC_EXT 0x81B6
+#define GL_INDEX_TEST_REF_EXT 0x81B7
+#endif
+
+#ifndef GL_EXT_index_array_formats
+#define GL_IUI_V2F_EXT 0x81AD
+#define GL_IUI_V3F_EXT 0x81AE
+#define GL_IUI_N3F_V2F_EXT 0x81AF
+#define GL_IUI_N3F_V3F_EXT 0x81B0
+#define GL_T2F_IUI_V2F_EXT 0x81B1
+#define GL_T2F_IUI_V3F_EXT 0x81B2
+#define GL_T2F_IUI_N3F_V2F_EXT 0x81B3
+#define GL_T2F_IUI_N3F_V3F_EXT 0x81B4
+#endif
+
+#ifndef GL_EXT_compiled_vertex_array
+#define GL_ARRAY_ELEMENT_LOCK_FIRST_EXT 0x81A8
+#define GL_ARRAY_ELEMENT_LOCK_COUNT_EXT 0x81A9
+#endif
+
+#ifndef GL_EXT_cull_vertex
+#define GL_CULL_VERTEX_EXT 0x81AA
+#define GL_CULL_VERTEX_EYE_POSITION_EXT 0x81AB
+#define GL_CULL_VERTEX_OBJECT_POSITION_EXT 0x81AC
+#endif
+
+#ifndef GL_SGIX_ycrcb
+#define GL_YCRCB_422_SGIX 0x81BB
+#define GL_YCRCB_444_SGIX 0x81BC
+#endif
+
+#ifndef GL_SGIX_fragment_lighting
+#define GL_FRAGMENT_LIGHTING_SGIX 0x8400
+#define GL_FRAGMENT_COLOR_MATERIAL_SGIX 0x8401
+#define GL_FRAGMENT_COLOR_MATERIAL_FACE_SGIX 0x8402
+#define GL_FRAGMENT_COLOR_MATERIAL_PARAMETER_SGIX 0x8403
+#define GL_MAX_FRAGMENT_LIGHTS_SGIX 0x8404
+#define GL_MAX_ACTIVE_LIGHTS_SGIX 0x8405
+#define GL_CURRENT_RASTER_NORMAL_SGIX 0x8406
+#define GL_LIGHT_ENV_MODE_SGIX 0x8407
+#define GL_FRAGMENT_LIGHT_MODEL_LOCAL_VIEWER_SGIX 0x8408
+#define GL_FRAGMENT_LIGHT_MODEL_TWO_SIDE_SGIX 0x8409
+#define GL_FRAGMENT_LIGHT_MODEL_AMBIENT_SGIX 0x840A
+#define GL_FRAGMENT_LIGHT_MODEL_NORMAL_INTERPOLATION_SGIX 0x840B
+#define GL_FRAGMENT_LIGHT0_SGIX 0x840C
+#define GL_FRAGMENT_LIGHT1_SGIX 0x840D
+#define GL_FRAGMENT_LIGHT2_SGIX 0x840E
+#define GL_FRAGMENT_LIGHT3_SGIX 0x840F
+#define GL_FRAGMENT_LIGHT4_SGIX 0x8410
+#define GL_FRAGMENT_LIGHT5_SGIX 0x8411
+#define GL_FRAGMENT_LIGHT6_SGIX 0x8412
+#define GL_FRAGMENT_LIGHT7_SGIX 0x8413
+#endif
+
+#ifndef GL_IBM_rasterpos_clip
+#define GL_RASTER_POSITION_UNCLIPPED_IBM 0x19262
+#endif
+
+#ifndef GL_HP_texture_lighting
+#define GL_TEXTURE_LIGHTING_MODE_HP 0x8167
+#define GL_TEXTURE_POST_SPECULAR_HP 0x8168
+#define GL_TEXTURE_PRE_SPECULAR_HP 0x8169
+#endif
+
+#ifndef GL_EXT_draw_range_elements
+#define GL_MAX_ELEMENTS_VERTICES_EXT 0x80E8
+#define GL_MAX_ELEMENTS_INDICES_EXT 0x80E9
+#endif
+
+#ifndef GL_WIN_phong_shading
+#define GL_PHONG_WIN 0x80EA
+#define GL_PHONG_HINT_WIN 0x80EB
+#endif
+
+#ifndef GL_WIN_specular_fog
+#define GL_FOG_SPECULAR_TEXTURE_WIN 0x80EC
+#endif
+
+#ifndef GL_EXT_light_texture
+#define GL_FRAGMENT_MATERIAL_EXT 0x8349
+#define GL_FRAGMENT_NORMAL_EXT 0x834A
+#define GL_FRAGMENT_COLOR_EXT 0x834C
+#define GL_ATTENUATION_EXT 0x834D
+#define GL_SHADOW_ATTENUATION_EXT 0x834E
+#define GL_TEXTURE_APPLICATION_MODE_EXT 0x834F
+#define GL_TEXTURE_LIGHT_EXT 0x8350
+#define GL_TEXTURE_MATERIAL_FACE_EXT 0x8351
+#define GL_TEXTURE_MATERIAL_PARAMETER_EXT 0x8352
+/* reuse GL_FRAGMENT_DEPTH_EXT */
+#endif
+
+#ifndef GL_SGIX_blend_alpha_minmax
+#define GL_ALPHA_MIN_SGIX 0x8320
+#define GL_ALPHA_MAX_SGIX 0x8321
+#endif
+
+#ifndef GL_SGIX_impact_pixel_texture
+#define GL_PIXEL_TEX_GEN_Q_CEILING_SGIX 0x8184
+#define GL_PIXEL_TEX_GEN_Q_ROUND_SGIX 0x8185
+#define GL_PIXEL_TEX_GEN_Q_FLOOR_SGIX 0x8186
+#define GL_PIXEL_TEX_GEN_ALPHA_REPLACE_SGIX 0x8187
+#define GL_PIXEL_TEX_GEN_ALPHA_NO_REPLACE_SGIX 0x8188
+#define GL_PIXEL_TEX_GEN_ALPHA_LS_SGIX 0x8189
+#define GL_PIXEL_TEX_GEN_ALPHA_MS_SGIX 0x818A
+#endif
+
+#ifndef GL_EXT_bgra
+#define GL_BGR_EXT 0x80E0
+#define GL_BGRA_EXT 0x80E1
+#endif
+
+#ifndef GL_SGIX_async
+#define GL_ASYNC_MARKER_SGIX 0x8329
+#endif
+
+#ifndef GL_SGIX_async_pixel
+#define GL_ASYNC_TEX_IMAGE_SGIX 0x835C
+#define GL_ASYNC_DRAW_PIXELS_SGIX 0x835D
+#define GL_ASYNC_READ_PIXELS_SGIX 0x835E
+#define GL_MAX_ASYNC_TEX_IMAGE_SGIX 0x835F
+#define GL_MAX_ASYNC_DRAW_PIXELS_SGIX 0x8360
+#define GL_MAX_ASYNC_READ_PIXELS_SGIX 0x8361
+#endif
+
+#ifndef GL_SGIX_async_histogram
+#define GL_ASYNC_HISTOGRAM_SGIX 0x832C
+#define GL_MAX_ASYNC_HISTOGRAM_SGIX 0x832D
+#endif
+
+#ifndef GL_INTEL_texture_scissor
+#endif
+
+#ifndef GL_INTEL_parallel_arrays
+#define GL_PARALLEL_ARRAYS_INTEL 0x83F4
+#define GL_VERTEX_ARRAY_PARALLEL_POINTERS_INTEL 0x83F5
+#define GL_NORMAL_ARRAY_PARALLEL_POINTERS_INTEL 0x83F6
+#define GL_COLOR_ARRAY_PARALLEL_POINTERS_INTEL 0x83F7
+#define GL_TEXTURE_COORD_ARRAY_PARALLEL_POINTERS_INTEL 0x83F8
+#endif
+
+#ifndef GL_HP_occlusion_test
+#define GL_OCCLUSION_TEST_HP 0x8165
+#define GL_OCCLUSION_TEST_RESULT_HP 0x8166
+#endif
+
+#ifndef GL_EXT_pixel_transform
+#define GL_PIXEL_TRANSFORM_2D_EXT 0x8330
+#define GL_PIXEL_MAG_FILTER_EXT 0x8331
+#define GL_PIXEL_MIN_FILTER_EXT 0x8332
+#define GL_PIXEL_CUBIC_WEIGHT_EXT 0x8333
+#define GL_CUBIC_EXT 0x8334
+#define GL_AVERAGE_EXT 0x8335
+#define GL_PIXEL_TRANSFORM_2D_STACK_DEPTH_EXT 0x8336
+#define GL_MAX_PIXEL_TRANSFORM_2D_STACK_DEPTH_EXT 0x8337
+#define GL_PIXEL_TRANSFORM_2D_MATRIX_EXT 0x8338
+#endif
+
+#ifndef GL_EXT_pixel_transform_color_table
+#endif
+
+#ifndef GL_EXT_shared_texture_palette
+#define GL_SHARED_TEXTURE_PALETTE_EXT 0x81FB
+#endif
+
+#ifndef GL_EXT_separate_specular_color
+#define GL_LIGHT_MODEL_COLOR_CONTROL_EXT 0x81F8
+#define GL_SINGLE_COLOR_EXT 0x81F9
+#define GL_SEPARATE_SPECULAR_COLOR_EXT 0x81FA
+#endif
+
+#ifndef GL_EXT_secondary_color
+#define GL_COLOR_SUM_EXT 0x8458
+#define GL_CURRENT_SECONDARY_COLOR_EXT 0x8459
+#define GL_SECONDARY_COLOR_ARRAY_SIZE_EXT 0x845A
+#define GL_SECONDARY_COLOR_ARRAY_TYPE_EXT 0x845B
+#define GL_SECONDARY_COLOR_ARRAY_STRIDE_EXT 0x845C
+#define GL_SECONDARY_COLOR_ARRAY_POINTER_EXT 0x845D
+#define GL_SECONDARY_COLOR_ARRAY_EXT 0x845E
+#endif
+
+#ifndef GL_EXT_texture_perturb_normal
+#define GL_PERTURB_EXT 0x85AE
+#define GL_TEXTURE_NORMAL_EXT 0x85AF
+#endif
+
+#ifndef GL_EXT_multi_draw_arrays
+#endif
+
+#ifndef GL_EXT_fog_coord
+#define GL_FOG_COORDINATE_SOURCE_EXT 0x8450
+#define GL_FOG_COORDINATE_EXT 0x8451
+#define GL_FRAGMENT_DEPTH_EXT 0x8452
+#define GL_CURRENT_FOG_COORDINATE_EXT 0x8453
+#define GL_FOG_COORDINATE_ARRAY_TYPE_EXT 0x8454
+#define GL_FOG_COORDINATE_ARRAY_STRIDE_EXT 0x8455
+#define GL_FOG_COORDINATE_ARRAY_POINTER_EXT 0x8456
+#define GL_FOG_COORDINATE_ARRAY_EXT 0x8457
+#endif
+
+#ifndef GL_REND_screen_coordinates
+#define GL_SCREEN_COORDINATES_REND 0x8490
+#define GL_INVERTED_SCREEN_W_REND 0x8491
+#endif
+
+#ifndef GL_EXT_coordinate_frame
+#define GL_TANGENT_ARRAY_EXT 0x8439
+#define GL_BINORMAL_ARRAY_EXT 0x843A
+#define GL_CURRENT_TANGENT_EXT 0x843B
+#define GL_CURRENT_BINORMAL_EXT 0x843C
+#define GL_TANGENT_ARRAY_TYPE_EXT 0x843E
+#define GL_TANGENT_ARRAY_STRIDE_EXT 0x843F
+#define GL_BINORMAL_ARRAY_TYPE_EXT 0x8440
+#define GL_BINORMAL_ARRAY_STRIDE_EXT 0x8441
+#define GL_TANGENT_ARRAY_POINTER_EXT 0x8442
+#define GL_BINORMAL_ARRAY_POINTER_EXT 0x8443
+#define GL_MAP1_TANGENT_EXT 0x8444
+#define GL_MAP2_TANGENT_EXT 0x8445
+#define GL_MAP1_BINORMAL_EXT 0x8446
+#define GL_MAP2_BINORMAL_EXT 0x8447
+#endif
+
+#ifndef GL_EXT_texture_env_combine
+#define GL_COMBINE_EXT 0x8570
+#define GL_COMBINE_RGB_EXT 0x8571
+#define GL_COMBINE_ALPHA_EXT 0x8572
+#define GL_RGB_SCALE_EXT 0x8573
+#define GL_ADD_SIGNED_EXT 0x8574
+#define GL_INTERPOLATE_EXT 0x8575
+#define GL_CONSTANT_EXT 0x8576
+#define GL_PRIMARY_COLOR_EXT 0x8577
+#define GL_PREVIOUS_EXT 0x8578
+#define GL_SOURCE0_RGB_EXT 0x8580
+#define GL_SOURCE1_RGB_EXT 0x8581
+#define GL_SOURCE2_RGB_EXT 0x8582
+#define GL_SOURCE0_ALPHA_EXT 0x8588
+#define GL_SOURCE1_ALPHA_EXT 0x8589
+#define GL_SOURCE2_ALPHA_EXT 0x858A
+#define GL_OPERAND0_RGB_EXT 0x8590
+#define GL_OPERAND1_RGB_EXT 0x8591
+#define GL_OPERAND2_RGB_EXT 0x8592
+#define GL_OPERAND0_ALPHA_EXT 0x8598
+#define GL_OPERAND1_ALPHA_EXT 0x8599
+#define GL_OPERAND2_ALPHA_EXT 0x859A
+#endif
+
+#ifndef GL_APPLE_specular_vector
+#define GL_LIGHT_MODEL_SPECULAR_VECTOR_APPLE 0x85B0
+#endif
+
+#ifndef GL_APPLE_transform_hint
+#define GL_TRANSFORM_HINT_APPLE 0x85B1
+#endif
+
+#ifndef GL_SGIX_fog_scale
+#define GL_FOG_SCALE_SGIX 0x81FC
+#define GL_FOG_SCALE_VALUE_SGIX 0x81FD
+#endif
+
+#ifndef GL_SUNX_constant_data
+#define GL_UNPACK_CONSTANT_DATA_SUNX 0x81D5
+#define GL_TEXTURE_CONSTANT_DATA_SUNX 0x81D6
+#endif
+
+#ifndef GL_SUN_global_alpha
+#define GL_GLOBAL_ALPHA_SUN 0x81D9
+#define GL_GLOBAL_ALPHA_FACTOR_SUN 0x81DA
+#endif
+
+#ifndef GL_SUN_triangle_list
+#define GL_RESTART_SUN 0x0001
+#define GL_REPLACE_MIDDLE_SUN 0x0002
+#define GL_REPLACE_OLDEST_SUN 0x0003
+#define GL_TRIANGLE_LIST_SUN 0x81D7
+#define GL_REPLACEMENT_CODE_SUN 0x81D8
+#define GL_REPLACEMENT_CODE_ARRAY_SUN 0x85C0
+#define GL_REPLACEMENT_CODE_ARRAY_TYPE_SUN 0x85C1
+#define GL_REPLACEMENT_CODE_ARRAY_STRIDE_SUN 0x85C2
+#define GL_REPLACEMENT_CODE_ARRAY_POINTER_SUN 0x85C3
+#define GL_R1UI_V3F_SUN 0x85C4
+#define GL_R1UI_C4UB_V3F_SUN 0x85C5
+#define GL_R1UI_C3F_V3F_SUN 0x85C6
+#define GL_R1UI_N3F_V3F_SUN 0x85C7
+#define GL_R1UI_C4F_N3F_V3F_SUN 0x85C8
+#define GL_R1UI_T2F_V3F_SUN 0x85C9
+#define GL_R1UI_T2F_N3F_V3F_SUN 0x85CA
+#define GL_R1UI_T2F_C4F_N3F_V3F_SUN 0x85CB
+#endif
+
+#ifndef GL_SUN_vertex
+#endif
+
+#ifndef GL_EXT_blend_func_separate
+#define GL_BLEND_DST_RGB_EXT 0x80C8
+#define GL_BLEND_SRC_RGB_EXT 0x80C9
+#define GL_BLEND_DST_ALPHA_EXT 0x80CA
+#define GL_BLEND_SRC_ALPHA_EXT 0x80CB
+#endif
+
+#ifndef GL_INGR_color_clamp
+#define GL_RED_MIN_CLAMP_INGR 0x8560
+#define GL_GREEN_MIN_CLAMP_INGR 0x8561
+#define GL_BLUE_MIN_CLAMP_INGR 0x8562
+#define GL_ALPHA_MIN_CLAMP_INGR 0x8563
+#define GL_RED_MAX_CLAMP_INGR 0x8564
+#define GL_GREEN_MAX_CLAMP_INGR 0x8565
+#define GL_BLUE_MAX_CLAMP_INGR 0x8566
+#define GL_ALPHA_MAX_CLAMP_INGR 0x8567
+#endif
+
+#ifndef GL_INGR_interlace_read
+#define GL_INTERLACE_READ_INGR 0x8568
+#endif
+
+#ifndef GL_EXT_stencil_wrap
+#define GL_INCR_WRAP_EXT 0x8507
+#define GL_DECR_WRAP_EXT 0x8508
+#endif
+
+#ifndef GL_EXT_422_pixels
+#define GL_422_EXT 0x80CC
+#define GL_422_REV_EXT 0x80CD
+#define GL_422_AVERAGE_EXT 0x80CE
+#define GL_422_REV_AVERAGE_EXT 0x80CF
+#endif
+
+#ifndef GL_NV_texgen_reflection
+#define GL_NORMAL_MAP_NV 0x8511
+#define GL_REFLECTION_MAP_NV 0x8512
+#endif
+
+#ifndef GL_EXT_texture_cube_map
+#define GL_NORMAL_MAP_EXT 0x8511
+#define GL_REFLECTION_MAP_EXT 0x8512
+#define GL_TEXTURE_CUBE_MAP_EXT 0x8513
+#define GL_TEXTURE_BINDING_CUBE_MAP_EXT 0x8514
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT 0x8515
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT 0x8516
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT 0x8517
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT 0x8518
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT 0x8519
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT 0x851A
+#define GL_PROXY_TEXTURE_CUBE_MAP_EXT 0x851B
+#define GL_MAX_CUBE_MAP_TEXTURE_SIZE_EXT 0x851C
+#endif
+
+#ifndef GL_SUN_convolution_border_modes
+#define GL_WRAP_BORDER_SUN 0x81D4
+#endif
+
+#ifndef GL_EXT_texture_env_add
+#endif
+
+#ifndef GL_EXT_texture_lod_bias
+#define GL_MAX_TEXTURE_LOD_BIAS_EXT 0x84FD
+#define GL_TEXTURE_FILTER_CONTROL_EXT 0x8500
+#define GL_TEXTURE_LOD_BIAS_EXT 0x8501
+#endif
+
+#ifndef GL_EXT_texture_filter_anisotropic
+#define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE
+#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF
+#endif
+
+#ifndef GL_EXT_vertex_weighting
+#define GL_MODELVIEW0_STACK_DEPTH_EXT GL_MODELVIEW_STACK_DEPTH
+#define GL_MODELVIEW1_STACK_DEPTH_EXT 0x8502
+#define GL_MODELVIEW0_MATRIX_EXT GL_MODELVIEW_MATRIX
+#define GL_MODELVIEW1_MATRIX_EXT 0x8506
+#define GL_VERTEX_WEIGHTING_EXT 0x8509
+#define GL_MODELVIEW0_EXT GL_MODELVIEW
+#define GL_MODELVIEW1_EXT 0x850A
+#define GL_CURRENT_VERTEX_WEIGHT_EXT 0x850B
+#define GL_VERTEX_WEIGHT_ARRAY_EXT 0x850C
+#define GL_VERTEX_WEIGHT_ARRAY_SIZE_EXT 0x850D
+#define GL_VERTEX_WEIGHT_ARRAY_TYPE_EXT 0x850E
+#define GL_VERTEX_WEIGHT_ARRAY_STRIDE_EXT 0x850F
+#define GL_VERTEX_WEIGHT_ARRAY_POINTER_EXT 0x8510
+#endif
+
+#ifndef GL_NV_light_max_exponent
+#define GL_MAX_SHININESS_NV 0x8504
+#define GL_MAX_SPOT_EXPONENT_NV 0x8505
+#endif
+
+#ifndef GL_NV_vertex_array_range
+#define GL_VERTEX_ARRAY_RANGE_NV 0x851D
+#define GL_VERTEX_ARRAY_RANGE_LENGTH_NV 0x851E
+#define GL_VERTEX_ARRAY_RANGE_VALID_NV 0x851F
+#define GL_MAX_VERTEX_ARRAY_RANGE_ELEMENT_NV 0x8520
+#define GL_VERTEX_ARRAY_RANGE_POINTER_NV 0x8521
+#endif
+
+#ifndef GL_NV_register_combiners
+#define GL_REGISTER_COMBINERS_NV 0x8522
+#define GL_VARIABLE_A_NV 0x8523
+#define GL_VARIABLE_B_NV 0x8524
+#define GL_VARIABLE_C_NV 0x8525
+#define GL_VARIABLE_D_NV 0x8526
+#define GL_VARIABLE_E_NV 0x8527
+#define GL_VARIABLE_F_NV 0x8528
+#define GL_VARIABLE_G_NV 0x8529
+#define GL_CONSTANT_COLOR0_NV 0x852A
+#define GL_CONSTANT_COLOR1_NV 0x852B
+#define GL_PRIMARY_COLOR_NV 0x852C
+#define GL_SECONDARY_COLOR_NV 0x852D
+#define GL_SPARE0_NV 0x852E
+#define GL_SPARE1_NV 0x852F
+#define GL_DISCARD_NV 0x8530
+#define GL_E_TIMES_F_NV 0x8531
+#define GL_SPARE0_PLUS_SECONDARY_COLOR_NV 0x8532
+#define GL_UNSIGNED_IDENTITY_NV 0x8536
+#define GL_UNSIGNED_INVERT_NV 0x8537
+#define GL_EXPAND_NORMAL_NV 0x8538
+#define GL_EXPAND_NEGATE_NV 0x8539
+#define GL_HALF_BIAS_NORMAL_NV 0x853A
+#define GL_HALF_BIAS_NEGATE_NV 0x853B
+#define GL_SIGNED_IDENTITY_NV 0x853C
+#define GL_SIGNED_NEGATE_NV 0x853D
+#define GL_SCALE_BY_TWO_NV 0x853E
+#define GL_SCALE_BY_FOUR_NV 0x853F
+#define GL_SCALE_BY_ONE_HALF_NV 0x8540
+#define GL_BIAS_BY_NEGATIVE_ONE_HALF_NV 0x8541
+#define GL_COMBINER_INPUT_NV 0x8542
+#define GL_COMBINER_MAPPING_NV 0x8543
+#define GL_COMBINER_COMPONENT_USAGE_NV 0x8544
+#define GL_COMBINER_AB_DOT_PRODUCT_NV 0x8545
+#define GL_COMBINER_CD_DOT_PRODUCT_NV 0x8546
+#define GL_COMBINER_MUX_SUM_NV 0x8547
+#define GL_COMBINER_SCALE_NV 0x8548
+#define GL_COMBINER_BIAS_NV 0x8549
+#define GL_COMBINER_AB_OUTPUT_NV 0x854A
+#define GL_COMBINER_CD_OUTPUT_NV 0x854B
+#define GL_COMBINER_SUM_OUTPUT_NV 0x854C
+#define GL_MAX_GENERAL_COMBINERS_NV 0x854D
+#define GL_NUM_GENERAL_COMBINERS_NV 0x854E
+#define GL_COLOR_SUM_CLAMP_NV 0x854F
+#define GL_COMBINER0_NV 0x8550
+#define GL_COMBINER1_NV 0x8551
+#define GL_COMBINER2_NV 0x8552
+#define GL_COMBINER3_NV 0x8553
+#define GL_COMBINER4_NV 0x8554
+#define GL_COMBINER5_NV 0x8555
+#define GL_COMBINER6_NV 0x8556
+#define GL_COMBINER7_NV 0x8557
+/* reuse GL_TEXTURE0_ARB */
+/* reuse GL_TEXTURE1_ARB */
+/* reuse GL_ZERO */
+/* reuse GL_NONE */
+/* reuse GL_FOG */
+#endif
+
+#ifndef GL_NV_fog_distance
+#define GL_FOG_DISTANCE_MODE_NV 0x855A
+#define GL_EYE_RADIAL_NV 0x855B
+#define GL_EYE_PLANE_ABSOLUTE_NV 0x855C
+/* reuse GL_EYE_PLANE */
+#endif
+
+#ifndef GL_NV_texgen_emboss
+#define GL_EMBOSS_LIGHT_NV 0x855D
+#define GL_EMBOSS_CONSTANT_NV 0x855E
+#define GL_EMBOSS_MAP_NV 0x855F
+#endif
+
+#ifndef GL_NV_blend_square
+#endif
+
+#ifndef GL_NV_texture_env_combine4
+#define GL_COMBINE4_NV 0x8503
+#define GL_SOURCE3_RGB_NV 0x8583
+#define GL_SOURCE3_ALPHA_NV 0x858B
+#define GL_OPERAND3_RGB_NV 0x8593
+#define GL_OPERAND3_ALPHA_NV 0x859B
+#endif
+
+#ifndef GL_MESA_resize_buffers
+#endif
+
+#ifndef GL_MESA_window_pos
+#endif
+
+#ifndef GL_EXT_texture_compression_s3tc
+#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0
+#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1
+#define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2
+#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3
+#endif
+
+#ifndef GL_IBM_cull_vertex
+#define GL_CULL_VERTEX_IBM 103050
+#endif
+
+#ifndef GL_IBM_multimode_draw_arrays
+#endif
+
+#ifndef GL_IBM_vertex_array_lists
+#define GL_VERTEX_ARRAY_LIST_IBM 103070
+#define GL_NORMAL_ARRAY_LIST_IBM 103071
+#define GL_COLOR_ARRAY_LIST_IBM 103072
+#define GL_INDEX_ARRAY_LIST_IBM 103073
+#define GL_TEXTURE_COORD_ARRAY_LIST_IBM 103074
+#define GL_EDGE_FLAG_ARRAY_LIST_IBM 103075
+#define GL_FOG_COORDINATE_ARRAY_LIST_IBM 103076
+#define GL_SECONDARY_COLOR_ARRAY_LIST_IBM 103077
+#define GL_VERTEX_ARRAY_LIST_STRIDE_IBM 103080
+#define GL_NORMAL_ARRAY_LIST_STRIDE_IBM 103081
+#define GL_COLOR_ARRAY_LIST_STRIDE_IBM 103082
+#define GL_INDEX_ARRAY_LIST_STRIDE_IBM 103083
+#define GL_TEXTURE_COORD_ARRAY_LIST_STRIDE_IBM 103084
+#define GL_EDGE_FLAG_ARRAY_LIST_STRIDE_IBM 103085
+#define GL_FOG_COORDINATE_ARRAY_LIST_STRIDE_IBM 103086
+#define GL_SECONDARY_COLOR_ARRAY_LIST_STRIDE_IBM 103087
+#endif
+
+#ifndef GL_SGIX_subsample
+#define GL_PACK_SUBSAMPLE_RATE_SGIX 0x85A0
+#define GL_UNPACK_SUBSAMPLE_RATE_SGIX 0x85A1
+#define GL_PIXEL_SUBSAMPLE_4444_SGIX 0x85A2
+#define GL_PIXEL_SUBSAMPLE_2424_SGIX 0x85A3
+#define GL_PIXEL_SUBSAMPLE_4242_SGIX 0x85A4
+#endif
+
+#ifndef GL_SGIX_ycrcb_subsample
+#endif
+
+#ifndef GL_SGIX_ycrcba
+#define GL_YCRCB_SGIX 0x8318
+#define GL_YCRCBA_SGIX 0x8319
+#endif
+
+#ifndef GL_SGI_depth_pass_instrument
+#define GL_DEPTH_PASS_INSTRUMENT_SGIX 0x8310
+#define GL_DEPTH_PASS_INSTRUMENT_COUNTERS_SGIX 0x8311
+#define GL_DEPTH_PASS_INSTRUMENT_MAX_SGIX 0x8312
+#endif
+
+#ifndef GL_3DFX_texture_compression_FXT1
+#define GL_COMPRESSED_RGB_FXT1_3DFX 0x86B0
+#define GL_COMPRESSED_RGBA_FXT1_3DFX 0x86B1
+#endif
+
+#ifndef GL_3DFX_multisample
+#define GL_MULTISAMPLE_3DFX 0x86B2
+#define GL_SAMPLE_BUFFERS_3DFX 0x86B3
+#define GL_SAMPLES_3DFX 0x86B4
+#define GL_MULTISAMPLE_BIT_3DFX 0x20000000
+#endif
+
+#ifndef GL_3DFX_tbuffer
+#endif
+
+#ifndef GL_EXT_multisample
+#define GL_MULTISAMPLE_EXT 0x809D
+#define GL_SAMPLE_ALPHA_TO_MASK_EXT 0x809E
+#define GL_SAMPLE_ALPHA_TO_ONE_EXT 0x809F
+#define GL_SAMPLE_MASK_EXT 0x80A0
+#define GL_1PASS_EXT 0x80A1
+#define GL_2PASS_0_EXT 0x80A2
+#define GL_2PASS_1_EXT 0x80A3
+#define GL_4PASS_0_EXT 0x80A4
+#define GL_4PASS_1_EXT 0x80A5
+#define GL_4PASS_2_EXT 0x80A6
+#define GL_4PASS_3_EXT 0x80A7
+#define GL_SAMPLE_BUFFERS_EXT 0x80A8
+#define GL_SAMPLES_EXT 0x80A9
+#define GL_SAMPLE_MASK_VALUE_EXT 0x80AA
+#define GL_SAMPLE_MASK_INVERT_EXT 0x80AB
+#define GL_SAMPLE_PATTERN_EXT 0x80AC
+#define GL_MULTISAMPLE_BIT_EXT 0x20000000
+#endif
+
+#ifndef GL_SGIX_vertex_preclip
+#define GL_VERTEX_PRECLIP_SGIX 0x83EE
+#define GL_VERTEX_PRECLIP_HINT_SGIX 0x83EF
+#endif
+
+#ifndef GL_SGIX_convolution_accuracy
+#define GL_CONVOLUTION_HINT_SGIX 0x8316
+#endif
+
+#ifndef GL_SGIX_resample
+#define GL_PACK_RESAMPLE_SGIX 0x842C
+#define GL_UNPACK_RESAMPLE_SGIX 0x842D
+#define GL_RESAMPLE_REPLICATE_SGIX 0x842E
+#define GL_RESAMPLE_ZERO_FILL_SGIX 0x842F
+#define GL_RESAMPLE_DECIMATE_SGIX 0x8430
+#endif
+
+#ifndef GL_SGIS_point_line_texgen
+#define GL_EYE_DISTANCE_TO_POINT_SGIS 0x81F0
+#define GL_OBJECT_DISTANCE_TO_POINT_SGIS 0x81F1
+#define GL_EYE_DISTANCE_TO_LINE_SGIS 0x81F2
+#define GL_OBJECT_DISTANCE_TO_LINE_SGIS 0x81F3
+#define GL_EYE_POINT_SGIS 0x81F4
+#define GL_OBJECT_POINT_SGIS 0x81F5
+#define GL_EYE_LINE_SGIS 0x81F6
+#define GL_OBJECT_LINE_SGIS 0x81F7
+#endif
+
+#ifndef GL_SGIS_texture_color_mask
+#define GL_TEXTURE_COLOR_WRITEMASK_SGIS 0x81EF
+#endif
+
+#ifndef GL_EXT_texture_env_dot3
+#define GL_DOT3_RGB_EXT 0x8740
+#define GL_DOT3_RGBA_EXT 0x8741
+#endif
+
+#ifndef GL_ATI_texture_mirror_once
+#define GL_MIRROR_CLAMP_ATI 0x8742
+#define GL_MIRROR_CLAMP_TO_EDGE_ATI 0x8743
+#endif
+
+#ifndef GL_NV_fence
+#define GL_ALL_COMPLETED_NV 0x84F2
+#define GL_FENCE_STATUS_NV 0x84F3
+#define GL_FENCE_CONDITION_NV 0x84F4
+#endif
+
+#ifndef GL_IBM_texture_mirrored_repeat
+#define GL_MIRRORED_REPEAT_IBM 0x8370
+#endif
+
+#ifndef GL_NV_evaluators
+#define GL_EVAL_2D_NV 0x86C0
+#define GL_EVAL_TRIANGULAR_2D_NV 0x86C1
+#define GL_MAP_TESSELLATION_NV 0x86C2
+#define GL_MAP_ATTRIB_U_ORDER_NV 0x86C3
+#define GL_MAP_ATTRIB_V_ORDER_NV 0x86C4
+#define GL_EVAL_FRACTIONAL_TESSELLATION_NV 0x86C5
+#define GL_EVAL_VERTEX_ATTRIB0_NV 0x86C6
+#define GL_EVAL_VERTEX_ATTRIB1_NV 0x86C7
+#define GL_EVAL_VERTEX_ATTRIB2_NV 0x86C8
+#define GL_EVAL_VERTEX_ATTRIB3_NV 0x86C9
+#define GL_EVAL_VERTEX_ATTRIB4_NV 0x86CA
+#define GL_EVAL_VERTEX_ATTRIB5_NV 0x86CB
+#define GL_EVAL_VERTEX_ATTRIB6_NV 0x86CC
+#define GL_EVAL_VERTEX_ATTRIB7_NV 0x86CD
+#define GL_EVAL_VERTEX_ATTRIB8_NV 0x86CE
+#define GL_EVAL_VERTEX_ATTRIB9_NV 0x86CF
+#define GL_EVAL_VERTEX_ATTRIB10_NV 0x86D0
+#define GL_EVAL_VERTEX_ATTRIB11_NV 0x86D1
+#define GL_EVAL_VERTEX_ATTRIB12_NV 0x86D2
+#define GL_EVAL_VERTEX_ATTRIB13_NV 0x86D3
+#define GL_EVAL_VERTEX_ATTRIB14_NV 0x86D4
+#define GL_EVAL_VERTEX_ATTRIB15_NV 0x86D5
+#define GL_MAX_MAP_TESSELLATION_NV 0x86D6
+#define GL_MAX_RATIONAL_EVAL_ORDER_NV 0x86D7
+#endif
+
+#ifndef GL_NV_packed_depth_stencil
+#define GL_DEPTH_STENCIL_NV 0x84F9
+#define GL_UNSIGNED_INT_24_8_NV 0x84FA
+#endif
+
+#ifndef GL_NV_register_combiners2
+#define GL_PER_STAGE_CONSTANTS_NV 0x8535
+#endif
+
+#ifndef GL_NV_texture_compression_vtc
+#endif
+
+#ifndef GL_NV_texture_rectangle
+#define GL_TEXTURE_RECTANGLE_NV 0x84F5
+#define GL_TEXTURE_BINDING_RECTANGLE_NV 0x84F6
+#define GL_PROXY_TEXTURE_RECTANGLE_NV 0x84F7
+#define GL_MAX_RECTANGLE_TEXTURE_SIZE_NV 0x84F8
+#endif
+
+#ifndef GL_NV_texture_shader
+#define GL_OFFSET_TEXTURE_RECTANGLE_NV 0x864C
+#define GL_OFFSET_TEXTURE_RECTANGLE_SCALE_NV 0x864D
+#define GL_DOT_PRODUCT_TEXTURE_RECTANGLE_NV 0x864E
+#define GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV 0x86D9
+#define GL_UNSIGNED_INT_S8_S8_8_8_NV 0x86DA
+#define GL_UNSIGNED_INT_8_8_S8_S8_REV_NV 0x86DB
+#define GL_DSDT_MAG_INTENSITY_NV 0x86DC
+#define GL_SHADER_CONSISTENT_NV 0x86DD
+#define GL_TEXTURE_SHADER_NV 0x86DE
+#define GL_SHADER_OPERATION_NV 0x86DF
+#define GL_CULL_MODES_NV 0x86E0
+#define GL_OFFSET_TEXTURE_MATRIX_NV 0x86E1
+#define GL_OFFSET_TEXTURE_SCALE_NV 0x86E2
+#define GL_OFFSET_TEXTURE_BIAS_NV 0x86E3
+#define GL_OFFSET_TEXTURE_2D_MATRIX_NV GL_OFFSET_TEXTURE_MATRIX_NV
+#define GL_OFFSET_TEXTURE_2D_SCALE_NV GL_OFFSET_TEXTURE_SCALE_NV
+#define GL_OFFSET_TEXTURE_2D_BIAS_NV GL_OFFSET_TEXTURE_BIAS_NV
+#define GL_PREVIOUS_TEXTURE_INPUT_NV 0x86E4
+#define GL_CONST_EYE_NV 0x86E5
+#define GL_PASS_THROUGH_NV 0x86E6
+#define GL_CULL_FRAGMENT_NV 0x86E7
+#define GL_OFFSET_TEXTURE_2D_NV 0x86E8
+#define GL_DEPENDENT_AR_TEXTURE_2D_NV 0x86E9
+#define GL_DEPENDENT_GB_TEXTURE_2D_NV 0x86EA
+#define GL_DOT_PRODUCT_NV 0x86EC
+#define GL_DOT_PRODUCT_DEPTH_REPLACE_NV 0x86ED
+#define GL_DOT_PRODUCT_TEXTURE_2D_NV 0x86EE
+#define GL_DOT_PRODUCT_TEXTURE_CUBE_MAP_NV 0x86F0
+#define GL_DOT_PRODUCT_DIFFUSE_CUBE_MAP_NV 0x86F1
+#define GL_DOT_PRODUCT_REFLECT_CUBE_MAP_NV 0x86F2
+#define GL_DOT_PRODUCT_CONST_EYE_REFLECT_CUBE_MAP_NV 0x86F3
+#define GL_HILO_NV 0x86F4
+#define GL_DSDT_NV 0x86F5
+#define GL_DSDT_MAG_NV 0x86F6
+#define GL_DSDT_MAG_VIB_NV 0x86F7
+#define GL_HILO16_NV 0x86F8
+#define GL_SIGNED_HILO_NV 0x86F9
+#define GL_SIGNED_HILO16_NV 0x86FA
+#define GL_SIGNED_RGBA_NV 0x86FB
+#define GL_SIGNED_RGBA8_NV 0x86FC
+#define GL_SIGNED_RGB_NV 0x86FE
+#define GL_SIGNED_RGB8_NV 0x86FF
+#define GL_SIGNED_LUMINANCE_NV 0x8701
+#define GL_SIGNED_LUMINANCE8_NV 0x8702
+#define GL_SIGNED_LUMINANCE_ALPHA_NV 0x8703
+#define GL_SIGNED_LUMINANCE8_ALPHA8_NV 0x8704
+#define GL_SIGNED_ALPHA_NV 0x8705
+#define GL_SIGNED_ALPHA8_NV 0x8706
+#define GL_SIGNED_INTENSITY_NV 0x8707
+#define GL_SIGNED_INTENSITY8_NV 0x8708
+#define GL_DSDT8_NV 0x8709
+#define GL_DSDT8_MAG8_NV 0x870A
+#define GL_DSDT8_MAG8_INTENSITY8_NV 0x870B
+#define GL_SIGNED_RGB_UNSIGNED_ALPHA_NV 0x870C
+#define GL_SIGNED_RGB8_UNSIGNED_ALPHA8_NV 0x870D
+#define GL_HI_SCALE_NV 0x870E
+#define GL_LO_SCALE_NV 0x870F
+#define GL_DS_SCALE_NV 0x8710
+#define GL_DT_SCALE_NV 0x8711
+#define GL_MAGNITUDE_SCALE_NV 0x8712
+#define GL_VIBRANCE_SCALE_NV 0x8713
+#define GL_HI_BIAS_NV 0x8714
+#define GL_LO_BIAS_NV 0x8715
+#define GL_DS_BIAS_NV 0x8716
+#define GL_DT_BIAS_NV 0x8717
+#define GL_MAGNITUDE_BIAS_NV 0x8718
+#define GL_VIBRANCE_BIAS_NV 0x8719
+#define GL_TEXTURE_BORDER_VALUES_NV 0x871A
+#define GL_TEXTURE_HI_SIZE_NV 0x871B
+#define GL_TEXTURE_LO_SIZE_NV 0x871C
+#define GL_TEXTURE_DS_SIZE_NV 0x871D
+#define GL_TEXTURE_DT_SIZE_NV 0x871E
+#define GL_TEXTURE_MAG_SIZE_NV 0x871F
+#endif
+
+#ifndef GL_NV_texture_shader2
+#define GL_DOT_PRODUCT_TEXTURE_3D_NV 0x86EF
+#endif
+
+#ifndef GL_NV_vertex_array_range2
+#define GL_VERTEX_ARRAY_RANGE_WITHOUT_FLUSH_NV 0x8533
+#endif
+
+#ifndef GL_NV_vertex_program
+#define GL_VERTEX_PROGRAM_NV 0x8620
+#define GL_VERTEX_STATE_PROGRAM_NV 0x8621
+#define GL_ATTRIB_ARRAY_SIZE_NV 0x8623
+#define GL_ATTRIB_ARRAY_STRIDE_NV 0x8624
+#define GL_ATTRIB_ARRAY_TYPE_NV 0x8625
+#define GL_CURRENT_ATTRIB_NV 0x8626
+#define GL_PROGRAM_LENGTH_NV 0x8627
+#define GL_PROGRAM_STRING_NV 0x8628
+#define GL_MODELVIEW_PROJECTION_NV 0x8629
+#define GL_IDENTITY_NV 0x862A
+#define GL_INVERSE_NV 0x862B
+#define GL_TRANSPOSE_NV 0x862C
+#define GL_INVERSE_TRANSPOSE_NV 0x862D
+#define GL_MAX_TRACK_MATRIX_STACK_DEPTH_NV 0x862E
+#define GL_MAX_TRACK_MATRICES_NV 0x862F
+#define GL_MATRIX0_NV 0x8630
+#define GL_MATRIX1_NV 0x8631
+#define GL_MATRIX2_NV 0x8632
+#define GL_MATRIX3_NV 0x8633
+#define GL_MATRIX4_NV 0x8634
+#define GL_MATRIX5_NV 0x8635
+#define GL_MATRIX6_NV 0x8636
+#define GL_MATRIX7_NV 0x8637
+#define GL_CURRENT_MATRIX_STACK_DEPTH_NV 0x8640
+#define GL_CURRENT_MATRIX_NV 0x8641
+#define GL_VERTEX_PROGRAM_POINT_SIZE_NV 0x8642
+#define GL_VERTEX_PROGRAM_TWO_SIDE_NV 0x8643
+#define GL_PROGRAM_PARAMETER_NV 0x8644
+#define GL_ATTRIB_ARRAY_POINTER_NV 0x8645
+#define GL_PROGRAM_TARGET_NV 0x8646
+#define GL_PROGRAM_RESIDENT_NV 0x8647
+#define GL_TRACK_MATRIX_NV 0x8648
+#define GL_TRACK_MATRIX_TRANSFORM_NV 0x8649
+#define GL_VERTEX_PROGRAM_BINDING_NV 0x864A
+#define GL_PROGRAM_ERROR_POSITION_NV 0x864B
+#define GL_VERTEX_ATTRIB_ARRAY0_NV 0x8650
+#define GL_VERTEX_ATTRIB_ARRAY1_NV 0x8651
+#define GL_VERTEX_ATTRIB_ARRAY2_NV 0x8652
+#define GL_VERTEX_ATTRIB_ARRAY3_NV 0x8653
+#define GL_VERTEX_ATTRIB_ARRAY4_NV 0x8654
+#define GL_VERTEX_ATTRIB_ARRAY5_NV 0x8655
+#define GL_VERTEX_ATTRIB_ARRAY6_NV 0x8656
+#define GL_VERTEX_ATTRIB_ARRAY7_NV 0x8657
+#define GL_VERTEX_ATTRIB_ARRAY8_NV 0x8658
+#define GL_VERTEX_ATTRIB_ARRAY9_NV 0x8659
+#define GL_VERTEX_ATTRIB_ARRAY10_NV 0x865A
+#define GL_VERTEX_ATTRIB_ARRAY11_NV 0x865B
+#define GL_VERTEX_ATTRIB_ARRAY12_NV 0x865C
+#define GL_VERTEX_ATTRIB_ARRAY13_NV 0x865D
+#define GL_VERTEX_ATTRIB_ARRAY14_NV 0x865E
+#define GL_VERTEX_ATTRIB_ARRAY15_NV 0x865F
+#define GL_MAP1_VERTEX_ATTRIB0_4_NV 0x8660
+#define GL_MAP1_VERTEX_ATTRIB1_4_NV 0x8661
+#define GL_MAP1_VERTEX_ATTRIB2_4_NV 0x8662
+#define GL_MAP1_VERTEX_ATTRIB3_4_NV 0x8663
+#define GL_MAP1_VERTEX_ATTRIB4_4_NV 0x8664
+#define GL_MAP1_VERTEX_ATTRIB5_4_NV 0x8665
+#define GL_MAP1_VERTEX_ATTRIB6_4_NV 0x8666
+#define GL_MAP1_VERTEX_ATTRIB7_4_NV 0x8667
+#define GL_MAP1_VERTEX_ATTRIB8_4_NV 0x8668
+#define GL_MAP1_VERTEX_ATTRIB9_4_NV 0x8669
+#define GL_MAP1_VERTEX_ATTRIB10_4_NV 0x866A
+#define GL_MAP1_VERTEX_ATTRIB11_4_NV 0x866B
+#define GL_MAP1_VERTEX_ATTRIB12_4_NV 0x866C
+#define GL_MAP1_VERTEX_ATTRIB13_4_NV 0x866D
+#define GL_MAP1_VERTEX_ATTRIB14_4_NV 0x866E
+#define GL_MAP1_VERTEX_ATTRIB15_4_NV 0x866F
+#define GL_MAP2_VERTEX_ATTRIB0_4_NV 0x8670
+#define GL_MAP2_VERTEX_ATTRIB1_4_NV 0x8671
+#define GL_MAP2_VERTEX_ATTRIB2_4_NV 0x8672
+#define GL_MAP2_VERTEX_ATTRIB3_4_NV 0x8673
+#define GL_MAP2_VERTEX_ATTRIB4_4_NV 0x8674
+#define GL_MAP2_VERTEX_ATTRIB5_4_NV 0x8675
+#define GL_MAP2_VERTEX_ATTRIB6_4_NV 0x8676
+#define GL_MAP2_VERTEX_ATTRIB7_4_NV 0x8677
+#define GL_MAP2_VERTEX_ATTRIB8_4_NV 0x8678
+#define GL_MAP2_VERTEX_ATTRIB9_4_NV 0x8679
+#define GL_MAP2_VERTEX_ATTRIB10_4_NV 0x867A
+#define GL_MAP2_VERTEX_ATTRIB11_4_NV 0x867B
+#define GL_MAP2_VERTEX_ATTRIB12_4_NV 0x867C
+#define GL_MAP2_VERTEX_ATTRIB13_4_NV 0x867D
+#define GL_MAP2_VERTEX_ATTRIB14_4_NV 0x867E
+#define GL_MAP2_VERTEX_ATTRIB15_4_NV 0x867F
+#endif
+
+#ifndef GL_SGIX_texture_coordinate_clamp
+#define GL_TEXTURE_MAX_CLAMP_S_SGIX 0x8369
+#define GL_TEXTURE_MAX_CLAMP_T_SGIX 0x836A
+#define GL_TEXTURE_MAX_CLAMP_R_SGIX 0x836B
+#endif
+
+#ifndef GL_SGIX_scalebias_hint
+#define GL_SCALEBIAS_HINT_SGIX 0x8322
+#endif
+
+#ifndef GL_OML_interlace
+#define GL_INTERLACE_OML 0x8980
+#define GL_INTERLACE_READ_OML 0x8981
+#endif
+
+#ifndef GL_OML_subsample
+#define GL_FORMAT_SUBSAMPLE_24_24_OML 0x8982
+#define GL_FORMAT_SUBSAMPLE_244_244_OML 0x8983
+#endif
+
+#ifndef GL_OML_resample
+#define GL_PACK_RESAMPLE_OML 0x8984
+#define GL_UNPACK_RESAMPLE_OML 0x8985
+#define GL_RESAMPLE_REPLICATE_OML 0x8986
+#define GL_RESAMPLE_ZERO_FILL_OML 0x8987
+#define GL_RESAMPLE_AVERAGE_OML 0x8988
+#define GL_RESAMPLE_DECIMATE_OML 0x8989
+#endif
+
+#ifndef GL_NV_copy_depth_to_color
+#define GL_DEPTH_STENCIL_TO_RGBA_NV 0x886E
+#define GL_DEPTH_STENCIL_TO_BGRA_NV 0x886F
+#endif
+
+#ifndef GL_ATI_envmap_bumpmap
+#define GL_BUMP_ROT_MATRIX_ATI 0x8775
+#define GL_BUMP_ROT_MATRIX_SIZE_ATI 0x8776
+#define GL_BUMP_NUM_TEX_UNITS_ATI 0x8777
+#define GL_BUMP_TEX_UNITS_ATI 0x8778
+#define GL_DUDV_ATI 0x8779
+#define GL_DU8DV8_ATI 0x877A
+#define GL_BUMP_ENVMAP_ATI 0x877B
+#define GL_BUMP_TARGET_ATI 0x877C
+#endif
+
+#ifndef GL_ATI_fragment_shader
+#define GL_FRAGMENT_SHADER_ATI 0x8920
+#define GL_REG_0_ATI 0x8921
+#define GL_REG_1_ATI 0x8922
+#define GL_REG_2_ATI 0x8923
+#define GL_REG_3_ATI 0x8924
+#define GL_REG_4_ATI 0x8925
+#define GL_REG_5_ATI 0x8926
+#define GL_REG_6_ATI 0x8927
+#define GL_REG_7_ATI 0x8928
+#define GL_REG_8_ATI 0x8929
+#define GL_REG_9_ATI 0x892A
+#define GL_REG_10_ATI 0x892B
+#define GL_REG_11_ATI 0x892C
+#define GL_REG_12_ATI 0x892D
+#define GL_REG_13_ATI 0x892E
+#define GL_REG_14_ATI 0x892F
+#define GL_REG_15_ATI 0x8930
+#define GL_REG_16_ATI 0x8931
+#define GL_REG_17_ATI 0x8932
+#define GL_REG_18_ATI 0x8933
+#define GL_REG_19_ATI 0x8934
+#define GL_REG_20_ATI 0x8935
+#define GL_REG_21_ATI 0x8936
+#define GL_REG_22_ATI 0x8937
+#define GL_REG_23_ATI 0x8938
+#define GL_REG_24_ATI 0x8939
+#define GL_REG_25_ATI 0x893A
+#define GL_REG_26_ATI 0x893B
+#define GL_REG_27_ATI 0x893C
+#define GL_REG_28_ATI 0x893D
+#define GL_REG_29_ATI 0x893E
+#define GL_REG_30_ATI 0x893F
+#define GL_REG_31_ATI 0x8940
+#define GL_CON_0_ATI 0x8941
+#define GL_CON_1_ATI 0x8942
+#define GL_CON_2_ATI 0x8943
+#define GL_CON_3_ATI 0x8944
+#define GL_CON_4_ATI 0x8945
+#define GL_CON_5_ATI 0x8946
+#define GL_CON_6_ATI 0x8947
+#define GL_CON_7_ATI 0x8948
+#define GL_CON_8_ATI 0x8949
+#define GL_CON_9_ATI 0x894A
+#define GL_CON_10_ATI 0x894B
+#define GL_CON_11_ATI 0x894C
+#define GL_CON_12_ATI 0x894D
+#define GL_CON_13_ATI 0x894E
+#define GL_CON_14_ATI 0x894F
+#define GL_CON_15_ATI 0x8950
+#define GL_CON_16_ATI 0x8951
+#define GL_CON_17_ATI 0x8952
+#define GL_CON_18_ATI 0x8953
+#define GL_CON_19_ATI 0x8954
+#define GL_CON_20_ATI 0x8955
+#define GL_CON_21_ATI 0x8956
+#define GL_CON_22_ATI 0x8957
+#define GL_CON_23_ATI 0x8958
+#define GL_CON_24_ATI 0x8959
+#define GL_CON_25_ATI 0x895A
+#define GL_CON_26_ATI 0x895B
+#define GL_CON_27_ATI 0x895C
+#define GL_CON_28_ATI 0x895D
+#define GL_CON_29_ATI 0x895E
+#define GL_CON_30_ATI 0x895F
+#define GL_CON_31_ATI 0x8960
+#define GL_MOV_ATI 0x8961
+#define GL_ADD_ATI 0x8963
+#define GL_MUL_ATI 0x8964
+#define GL_SUB_ATI 0x8965
+#define GL_DOT3_ATI 0x8966
+#define GL_DOT4_ATI 0x8967
+#define GL_MAD_ATI 0x8968
+#define GL_LERP_ATI 0x8969
+#define GL_CND_ATI 0x896A
+#define GL_CND0_ATI 0x896B
+#define GL_DOT2_ADD_ATI 0x896C
+#define GL_SECONDARY_INTERPOLATOR_ATI 0x896D
+#define GL_NUM_FRAGMENT_REGISTERS_ATI 0x896E
+#define GL_NUM_FRAGMENT_CONSTANTS_ATI 0x896F
+#define GL_NUM_PASSES_ATI 0x8970
+#define GL_NUM_INSTRUCTIONS_PER_PASS_ATI 0x8971
+#define GL_NUM_INSTRUCTIONS_TOTAL_ATI 0x8972
+#define GL_NUM_INPUT_INTERPOLATOR_COMPONENTS_ATI 0x8973
+#define GL_NUM_LOOPBACK_COMPONENTS_ATI 0x8974
+#define GL_COLOR_ALPHA_PAIRING_ATI 0x8975
+#define GL_SWIZZLE_STR_ATI 0x8976
+#define GL_SWIZZLE_STQ_ATI 0x8977
+#define GL_SWIZZLE_STR_DR_ATI 0x8978
+#define GL_SWIZZLE_STQ_DQ_ATI 0x8979
+#define GL_SWIZZLE_STRQ_ATI 0x897A
+#define GL_SWIZZLE_STRQ_DQ_ATI 0x897B
+#define GL_RED_BIT_ATI 0x00000001
+#define GL_GREEN_BIT_ATI 0x00000002
+#define GL_BLUE_BIT_ATI 0x00000004
+#define GL_2X_BIT_ATI 0x00000001
+#define GL_4X_BIT_ATI 0x00000002
+#define GL_8X_BIT_ATI 0x00000004
+#define GL_HALF_BIT_ATI 0x00000008
+#define GL_QUARTER_BIT_ATI 0x00000010
+#define GL_EIGHTH_BIT_ATI 0x00000020
+#define GL_SATURATE_BIT_ATI 0x00000040
+#define GL_COMP_BIT_ATI 0x00000002
+#define GL_NEGATE_BIT_ATI 0x00000004
+#define GL_BIAS_BIT_ATI 0x00000008
+#endif
+
+#ifndef GL_ATI_pn_triangles
+#define GL_PN_TRIANGLES_ATI 0x87F0
+#define GL_MAX_PN_TRIANGLES_TESSELATION_LEVEL_ATI 0x87F1
+#define GL_PN_TRIANGLES_POINT_MODE_ATI 0x87F2
+#define GL_PN_TRIANGLES_NORMAL_MODE_ATI 0x87F3
+#define GL_PN_TRIANGLES_TESSELATION_LEVEL_ATI 0x87F4
+#define GL_PN_TRIANGLES_POINT_MODE_LINEAR_ATI 0x87F5
+#define GL_PN_TRIANGLES_POINT_MODE_CUBIC_ATI 0x87F6
+#define GL_PN_TRIANGLES_NORMAL_MODE_LINEAR_ATI 0x87F7
+#define GL_PN_TRIANGLES_NORMAL_MODE_QUADRATIC_ATI 0x87F8
+#endif
+
+#ifndef GL_ATI_vertex_array_object
+#define GL_STATIC_ATI 0x8760
+#define GL_DYNAMIC_ATI 0x8761
+#define GL_PRESERVE_ATI 0x8762
+#define GL_DISCARD_ATI 0x8763
+#define GL_OBJECT_BUFFER_SIZE_ATI 0x8764
+#define GL_OBJECT_BUFFER_USAGE_ATI 0x8765
+#define GL_ARRAY_OBJECT_BUFFER_ATI 0x8766
+#define GL_ARRAY_OBJECT_OFFSET_ATI 0x8767
+#endif
+
+#ifndef GL_EXT_vertex_shader
+#define GL_VERTEX_SHADER_EXT 0x8780
+#define GL_VERTEX_SHADER_BINDING_EXT 0x8781
+#define GL_OP_INDEX_EXT 0x8782
+#define GL_OP_NEGATE_EXT 0x8783
+#define GL_OP_DOT3_EXT 0x8784
+#define GL_OP_DOT4_EXT 0x8785
+#define GL_OP_MUL_EXT 0x8786
+#define GL_OP_ADD_EXT 0x8787
+#define GL_OP_MADD_EXT 0x8788
+#define GL_OP_FRAC_EXT 0x8789
+#define GL_OP_MAX_EXT 0x878A
+#define GL_OP_MIN_EXT 0x878B
+#define GL_OP_SET_GE_EXT 0x878C
+#define GL_OP_SET_LT_EXT 0x878D
+#define GL_OP_CLAMP_EXT 0x878E
+#define GL_OP_FLOOR_EXT 0x878F
+#define GL_OP_ROUND_EXT 0x8790
+#define GL_OP_EXP_BASE_2_EXT 0x8791
+#define GL_OP_LOG_BASE_2_EXT 0x8792
+#define GL_OP_POWER_EXT 0x8793
+#define GL_OP_RECIP_EXT 0x8794
+#define GL_OP_RECIP_SQRT_EXT 0x8795
+#define GL_OP_SUB_EXT 0x8796
+#define GL_OP_CROSS_PRODUCT_EXT 0x8797
+#define GL_OP_MULTIPLY_MATRIX_EXT 0x8798
+#define GL_OP_MOV_EXT 0x8799
+#define GL_OUTPUT_VERTEX_EXT 0x879A
+#define GL_OUTPUT_COLOR0_EXT 0x879B
+#define GL_OUTPUT_COLOR1_EXT 0x879C
+#define GL_OUTPUT_TEXTURE_COORD0_EXT 0x879D
+#define GL_OUTPUT_TEXTURE_COORD1_EXT 0x879E
+#define GL_OUTPUT_TEXTURE_COORD2_EXT 0x879F
+#define GL_OUTPUT_TEXTURE_COORD3_EXT 0x87A0
+#define GL_OUTPUT_TEXTURE_COORD4_EXT 0x87A1
+#define GL_OUTPUT_TEXTURE_COORD5_EXT 0x87A2
+#define GL_OUTPUT_TEXTURE_COORD6_EXT 0x87A3
+#define GL_OUTPUT_TEXTURE_COORD7_EXT 0x87A4
+#define GL_OUTPUT_TEXTURE_COORD8_EXT 0x87A5
+#define GL_OUTPUT_TEXTURE_COORD9_EXT 0x87A6
+#define GL_OUTPUT_TEXTURE_COORD10_EXT 0x87A7
+#define GL_OUTPUT_TEXTURE_COORD11_EXT 0x87A8
+#define GL_OUTPUT_TEXTURE_COORD12_EXT 0x87A9
+#define GL_OUTPUT_TEXTURE_COORD13_EXT 0x87AA
+#define GL_OUTPUT_TEXTURE_COORD14_EXT 0x87AB
+#define GL_OUTPUT_TEXTURE_COORD15_EXT 0x87AC
+#define GL_OUTPUT_TEXTURE_COORD16_EXT 0x87AD
+#define GL_OUTPUT_TEXTURE_COORD17_EXT 0x87AE
+#define GL_OUTPUT_TEXTURE_COORD18_EXT 0x87AF
+#define GL_OUTPUT_TEXTURE_COORD19_EXT 0x87B0
+#define GL_OUTPUT_TEXTURE_COORD20_EXT 0x87B1
+#define GL_OUTPUT_TEXTURE_COORD21_EXT 0x87B2
+#define GL_OUTPUT_TEXTURE_COORD22_EXT 0x87B3
+#define GL_OUTPUT_TEXTURE_COORD23_EXT 0x87B4
+#define GL_OUTPUT_TEXTURE_COORD24_EXT 0x87B5
+#define GL_OUTPUT_TEXTURE_COORD25_EXT 0x87B6
+#define GL_OUTPUT_TEXTURE_COORD26_EXT 0x87B7
+#define GL_OUTPUT_TEXTURE_COORD27_EXT 0x87B8
+#define GL_OUTPUT_TEXTURE_COORD28_EXT 0x87B9
+#define GL_OUTPUT_TEXTURE_COORD29_EXT 0x87BA
+#define GL_OUTPUT_TEXTURE_COORD30_EXT 0x87BB
+#define GL_OUTPUT_TEXTURE_COORD31_EXT 0x87BC
+#define GL_OUTPUT_FOG_EXT 0x87BD
+#define GL_SCALAR_EXT 0x87BE
+#define GL_VECTOR_EXT 0x87BF
+#define GL_MATRIX_EXT 0x87C0
+#define GL_VARIANT_EXT 0x87C1
+#define GL_INVARIANT_EXT 0x87C2
+#define GL_LOCAL_CONSTANT_EXT 0x87C3
+#define GL_LOCAL_EXT 0x87C4
+#define GL_MAX_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87C5
+#define GL_MAX_VERTEX_SHADER_VARIANTS_EXT 0x87C6
+#define GL_MAX_VERTEX_SHADER_INVARIANTS_EXT 0x87C7
+#define GL_MAX_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87C8
+#define GL_MAX_VERTEX_SHADER_LOCALS_EXT 0x87C9
+#define GL_MAX_OPTIMIZED_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87CA
+#define GL_MAX_OPTIMIZED_VERTEX_SHADER_VARIANTS_EXT 0x87CB
+#define GL_MAX_OPTIMIZED_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87CC
+#define GL_MAX_OPTIMIZED_VERTEX_SHADER_INVARIANTS_EXT 0x87CD
+#define GL_MAX_OPTIMIZED_VERTEX_SHADER_LOCALS_EXT 0x87CE
+#define GL_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87CF
+#define GL_VERTEX_SHADER_VARIANTS_EXT 0x87D0
+#define GL_VERTEX_SHADER_INVARIANTS_EXT 0x87D1
+#define GL_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87D2
+#define GL_VERTEX_SHADER_LOCALS_EXT 0x87D3
+#define GL_VERTEX_SHADER_OPTIMIZED_EXT 0x87D4
+#define GL_X_EXT 0x87D5
+#define GL_Y_EXT 0x87D6
+#define GL_Z_EXT 0x87D7
+#define GL_W_EXT 0x87D8
+#define GL_NEGATIVE_X_EXT 0x87D9
+#define GL_NEGATIVE_Y_EXT 0x87DA
+#define GL_NEGATIVE_Z_EXT 0x87DB
+#define GL_NEGATIVE_W_EXT 0x87DC
+#define GL_ZERO_EXT 0x87DD
+#define GL_ONE_EXT 0x87DE
+#define GL_NEGATIVE_ONE_EXT 0x87DF
+#define GL_NORMALIZED_RANGE_EXT 0x87E0
+#define GL_FULL_RANGE_EXT 0x87E1
+#define GL_CURRENT_VERTEX_EXT 0x87E2
+#define GL_MVP_MATRIX_EXT 0x87E3
+#define GL_VARIANT_VALUE_EXT 0x87E4
+#define GL_VARIANT_DATATYPE_EXT 0x87E5
+#define GL_VARIANT_ARRAY_STRIDE_EXT 0x87E6
+#define GL_VARIANT_ARRAY_TYPE_EXT 0x87E7
+#define GL_VARIANT_ARRAY_EXT 0x87E8
+#define GL_VARIANT_ARRAY_POINTER_EXT 0x87E9
+#define GL_INVARIANT_VALUE_EXT 0x87EA
+#define GL_INVARIANT_DATATYPE_EXT 0x87EB
+#define GL_LOCAL_CONSTANT_VALUE_EXT 0x87EC
+#define GL_LOCAL_CONSTANT_DATATYPE_EXT 0x87ED
+#endif
+
+#ifndef GL_ATI_vertex_streams
+#define GL_MAX_VERTEX_STREAMS_ATI 0x876B
+#define GL_VERTEX_STREAM0_ATI 0x876C
+#define GL_VERTEX_STREAM1_ATI 0x876D
+#define GL_VERTEX_STREAM2_ATI 0x876E
+#define GL_VERTEX_STREAM3_ATI 0x876F
+#define GL_VERTEX_STREAM4_ATI 0x8770
+#define GL_VERTEX_STREAM5_ATI 0x8771
+#define GL_VERTEX_STREAM6_ATI 0x8772
+#define GL_VERTEX_STREAM7_ATI 0x8773
+#define GL_VERTEX_SOURCE_ATI 0x8774
+#endif
+
+#ifndef GL_ATI_element_array
+#define GL_ELEMENT_ARRAY_ATI 0x8768
+#define GL_ELEMENT_ARRAY_TYPE_ATI 0x8769
+#define GL_ELEMENT_ARRAY_POINTER_ATI 0x876A
+#endif
+
+#ifndef GL_SUN_mesh_array
+#define GL_QUAD_MESH_SUN 0x8614
+#define GL_TRIANGLE_MESH_SUN 0x8615
+#endif
+
+#ifndef GL_SUN_slice_accum
+#define GL_SLICE_ACCUM_SUN 0x85CC
+#endif
+
+#ifndef GL_NV_multisample_filter_hint
+#define GL_MULTISAMPLE_FILTER_HINT_NV 0x8534
+#endif
+
+#ifndef GL_NV_depth_clamp
+#define GL_DEPTH_CLAMP_NV 0x864F
+#endif
+
+#ifndef GL_NV_occlusion_query
+#define GL_PIXEL_COUNTER_BITS_NV 0x8864
+#define GL_CURRENT_OCCLUSION_QUERY_ID_NV 0x8865
+#define GL_PIXEL_COUNT_NV 0x8866
+#define GL_PIXEL_COUNT_AVAILABLE_NV 0x8867
+#endif
+
+#ifndef GL_NV_point_sprite
+#define GL_POINT_SPRITE_NV 0x8861
+#define GL_COORD_REPLACE_NV 0x8862
+#define GL_POINT_SPRITE_R_MODE_NV 0x8863
+#endif
+
+#ifndef GL_NV_texture_shader3
+#define GL_OFFSET_PROJECTIVE_TEXTURE_2D_NV 0x8850
+#define GL_OFFSET_PROJECTIVE_TEXTURE_2D_SCALE_NV 0x8851
+#define GL_OFFSET_PROJECTIVE_TEXTURE_RECTANGLE_NV 0x8852
+#define GL_OFFSET_PROJECTIVE_TEXTURE_RECTANGLE_SCALE_NV 0x8853
+#define GL_OFFSET_HILO_TEXTURE_2D_NV 0x8854
+#define GL_OFFSET_HILO_TEXTURE_RECTANGLE_NV 0x8855
+#define GL_OFFSET_HILO_PROJECTIVE_TEXTURE_2D_NV 0x8856
+#define GL_OFFSET_HILO_PROJECTIVE_TEXTURE_RECTANGLE_NV 0x8857
+#define GL_DEPENDENT_HILO_TEXTURE_2D_NV 0x8858
+#define GL_DEPENDENT_RGB_TEXTURE_3D_NV 0x8859
+#define GL_DEPENDENT_RGB_TEXTURE_CUBE_MAP_NV 0x885A
+#define GL_DOT_PRODUCT_PASS_THROUGH_NV 0x885B
+#define GL_DOT_PRODUCT_TEXTURE_1D_NV 0x885C
+#define GL_DOT_PRODUCT_AFFINE_DEPTH_REPLACE_NV 0x885D
+#define GL_HILO8_NV 0x885E
+#define GL_SIGNED_HILO8_NV 0x885F
+#define GL_FORCE_BLUE_TO_ONE_NV 0x8860
+#endif
+
+#ifndef GL_NV_vertex_program1_1
+#endif
+
+#ifndef GL_EXT_shadow_funcs
+#endif
+
+#ifndef GL_EXT_stencil_two_side
+#define GL_STENCIL_TEST_TWO_SIDE_EXT 0x8910
+#define GL_ACTIVE_STENCIL_FACE_EXT 0x8911
+#endif
+
+#ifndef GL_ATI_text_fragment_shader
+#define GL_TEXT_FRAGMENT_SHADER_ATI 0x8200
+#endif
+
+#ifndef GL_APPLE_client_storage
+#define GL_UNPACK_CLIENT_STORAGE_APPLE 0x85B2
+#endif
+
+#ifndef GL_APPLE_element_array
+#define GL_ELEMENT_ARRAY_APPLE 0x8A0C
+#define GL_ELEMENT_ARRAY_TYPE_APPLE 0x8A0D
+#define GL_ELEMENT_ARRAY_POINTER_APPLE 0x8A0E
+#endif
+
+#ifndef GL_APPLE_fence
+#define GL_DRAW_PIXELS_APPLE 0x8A0A
+#define GL_FENCE_APPLE 0x8A0B
+#endif
+
+#ifndef GL_APPLE_vertex_array_object
+#define GL_VERTEX_ARRAY_BINDING_APPLE 0x85B5
+#endif
+
+#ifndef GL_APPLE_vertex_array_range
+#define GL_VERTEX_ARRAY_RANGE_APPLE 0x851D
+#define GL_VERTEX_ARRAY_RANGE_LENGTH_APPLE 0x851E
+#define GL_VERTEX_ARRAY_STORAGE_HINT_APPLE 0x851F
+#define GL_VERTEX_ARRAY_RANGE_POINTER_APPLE 0x8521
+#define GL_STORAGE_CLIENT_APPLE 0x85B4
+#define GL_STORAGE_CACHED_APPLE 0x85BE
+#define GL_STORAGE_SHARED_APPLE 0x85BF
+#endif
+
+#ifndef GL_APPLE_ycbcr_422
+#define GL_YCBCR_422_APPLE 0x85B9
+#define GL_UNSIGNED_SHORT_8_8_APPLE 0x85BA
+#define GL_UNSIGNED_SHORT_8_8_REV_APPLE 0x85BB
+#endif
+
+#ifndef GL_S3_s3tc
+#define GL_RGB_S3TC 0x83A0
+#define GL_RGB4_S3TC 0x83A1
+#define GL_RGBA_S3TC 0x83A2
+#define GL_RGBA4_S3TC 0x83A3
+#endif
+
+#ifndef GL_ATI_draw_buffers
+#define GL_MAX_DRAW_BUFFERS_ATI 0x8824
+#define GL_DRAW_BUFFER0_ATI 0x8825
+#define GL_DRAW_BUFFER1_ATI 0x8826
+#define GL_DRAW_BUFFER2_ATI 0x8827
+#define GL_DRAW_BUFFER3_ATI 0x8828
+#define GL_DRAW_BUFFER4_ATI 0x8829
+#define GL_DRAW_BUFFER5_ATI 0x882A
+#define GL_DRAW_BUFFER6_ATI 0x882B
+#define GL_DRAW_BUFFER7_ATI 0x882C
+#define GL_DRAW_BUFFER8_ATI 0x882D
+#define GL_DRAW_BUFFER9_ATI 0x882E
+#define GL_DRAW_BUFFER10_ATI 0x882F
+#define GL_DRAW_BUFFER11_ATI 0x8830
+#define GL_DRAW_BUFFER12_ATI 0x8831
+#define GL_DRAW_BUFFER13_ATI 0x8832
+#define GL_DRAW_BUFFER14_ATI 0x8833
+#define GL_DRAW_BUFFER15_ATI 0x8834
+#endif
+
+#ifndef GL_ATI_pixel_format_float
+#define GL_TYPE_RGBA_FLOAT_ATI 0x8820
+#define GL_COLOR_CLEAR_UNCLAMPED_VALUE_ATI 0x8835
+#endif
+
+#ifndef GL_ATI_texture_env_combine3
+#define GL_MODULATE_ADD_ATI 0x8744
+#define GL_MODULATE_SIGNED_ADD_ATI 0x8745
+#define GL_MODULATE_SUBTRACT_ATI 0x8746
+#endif
+
+#ifndef GL_ATI_texture_float
+#define GL_RGBA_FLOAT32_ATI 0x8814
+#define GL_RGB_FLOAT32_ATI 0x8815
+#define GL_ALPHA_FLOAT32_ATI 0x8816
+#define GL_INTENSITY_FLOAT32_ATI 0x8817
+#define GL_LUMINANCE_FLOAT32_ATI 0x8818
+#define GL_LUMINANCE_ALPHA_FLOAT32_ATI 0x8819
+#define GL_RGBA_FLOAT16_ATI 0x881A
+#define GL_RGB_FLOAT16_ATI 0x881B
+#define GL_ALPHA_FLOAT16_ATI 0x881C
+#define GL_INTENSITY_FLOAT16_ATI 0x881D
+#define GL_LUMINANCE_FLOAT16_ATI 0x881E
+#define GL_LUMINANCE_ALPHA_FLOAT16_ATI 0x881F
+#endif
+
+#ifndef GL_NV_float_buffer
+#define GL_FLOAT_R_NV 0x8880
+#define GL_FLOAT_RG_NV 0x8881
+#define GL_FLOAT_RGB_NV 0x8882
+#define GL_FLOAT_RGBA_NV 0x8883
+#define GL_FLOAT_R16_NV 0x8884
+#define GL_FLOAT_R32_NV 0x8885
+#define GL_FLOAT_RG16_NV 0x8886
+#define GL_FLOAT_RG32_NV 0x8887
+#define GL_FLOAT_RGB16_NV 0x8888
+#define GL_FLOAT_RGB32_NV 0x8889
+#define GL_FLOAT_RGBA16_NV 0x888A
+#define GL_FLOAT_RGBA32_NV 0x888B
+#define GL_TEXTURE_FLOAT_COMPONENTS_NV 0x888C
+#define GL_FLOAT_CLEAR_COLOR_VALUE_NV 0x888D
+#define GL_FLOAT_RGBA_MODE_NV 0x888E
+#endif
+
+#ifndef GL_NV_fragment_program
+#define GL_MAX_FRAGMENT_PROGRAM_LOCAL_PARAMETERS_NV 0x8868
+#define GL_FRAGMENT_PROGRAM_NV 0x8870
+#define GL_MAX_TEXTURE_COORDS_NV 0x8871
+#define GL_MAX_TEXTURE_IMAGE_UNITS_NV 0x8872
+#define GL_FRAGMENT_PROGRAM_BINDING_NV 0x8873
+#define GL_PROGRAM_ERROR_STRING_NV 0x8874
+#endif
+
+#ifndef GL_NV_half_float
+#define GL_HALF_FLOAT_NV 0x140B
+#endif
+
+#ifndef GL_NV_pixel_data_range
+#define GL_WRITE_PIXEL_DATA_RANGE_NV 0x8878
+#define GL_READ_PIXEL_DATA_RANGE_NV 0x8879
+#define GL_WRITE_PIXEL_DATA_RANGE_LENGTH_NV 0x887A
+#define GL_READ_PIXEL_DATA_RANGE_LENGTH_NV 0x887B
+#define GL_WRITE_PIXEL_DATA_RANGE_POINTER_NV 0x887C
+#define GL_READ_PIXEL_DATA_RANGE_POINTER_NV 0x887D
+#endif
+
+#ifndef GL_NV_primitive_restart
+#define GL_PRIMITIVE_RESTART_NV 0x8558
+#define GL_PRIMITIVE_RESTART_INDEX_NV 0x8559
+#endif
+
+#ifndef GL_NV_texture_expand_normal
+#define GL_TEXTURE_UNSIGNED_REMAP_MODE_NV 0x888F
+#endif
+
+#ifndef GL_NV_vertex_program2
+#endif
+
+#ifndef GL_ATI_map_object_buffer
+#endif
+
+#ifndef GL_ATI_separate_stencil
+#define GL_STENCIL_BACK_FUNC_ATI 0x8800
+#define GL_STENCIL_BACK_FAIL_ATI 0x8801
+#define GL_STENCIL_BACK_PASS_DEPTH_FAIL_ATI 0x8802
+#define GL_STENCIL_BACK_PASS_DEPTH_PASS_ATI 0x8803
+#endif
+
+#ifndef GL_ATI_vertex_attrib_array_object
+#endif
+
+#ifndef GL_OES_read_format
+#define GL_IMPLEMENTATION_COLOR_READ_TYPE_OES 0x8B9A
+#define GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES 0x8B9B
+#endif
+
+#ifndef GL_EXT_depth_bounds_test
+#define GL_DEPTH_BOUNDS_TEST_EXT 0x8890
+#define GL_DEPTH_BOUNDS_EXT 0x8891
+#endif
+
+#ifndef GL_EXT_texture_mirror_clamp
+#define GL_MIRROR_CLAMP_EXT 0x8742
+#define GL_MIRROR_CLAMP_TO_EDGE_EXT 0x8743
+#define GL_MIRROR_CLAMP_TO_BORDER_EXT 0x8912
+#endif
+
+#ifndef GL_EXT_blend_equation_separate
+#define GL_BLEND_EQUATION_RGB_EXT 0x8009
+#define GL_BLEND_EQUATION_ALPHA_EXT 0x883D
+#endif
+
+#ifndef GL_MESA_pack_invert
+#define GL_PACK_INVERT_MESA 0x8758
+#endif
+
+#ifndef GL_MESA_ycbcr_texture
+#define GL_UNSIGNED_SHORT_8_8_MESA 0x85BA
+#define GL_UNSIGNED_SHORT_8_8_REV_MESA 0x85BB
+#define GL_YCBCR_MESA 0x8757
+#endif
+
+#ifndef GL_EXT_pixel_buffer_object
+#define GL_PIXEL_PACK_BUFFER_EXT 0x88EB
+#define GL_PIXEL_UNPACK_BUFFER_EXT 0x88EC
+#define GL_PIXEL_PACK_BUFFER_BINDING_EXT 0x88ED
+#define GL_PIXEL_UNPACK_BUFFER_BINDING_EXT 0x88EF
+#endif
+
+#ifndef GL_NV_fragment_program_option
+#endif
+
+#ifndef GL_NV_fragment_program2
+#define GL_MAX_PROGRAM_EXEC_INSTRUCTIONS_NV 0x88F4
+#define GL_MAX_PROGRAM_CALL_DEPTH_NV 0x88F5
+#define GL_MAX_PROGRAM_IF_DEPTH_NV 0x88F6
+#define GL_MAX_PROGRAM_LOOP_DEPTH_NV 0x88F7
+#define GL_MAX_PROGRAM_LOOP_COUNT_NV 0x88F8
+#endif
+
+#ifndef GL_NV_vertex_program2_option
+/* reuse GL_MAX_PROGRAM_EXEC_INSTRUCTIONS_NV */
+/* reuse GL_MAX_PROGRAM_CALL_DEPTH_NV */
+#endif
+
+#ifndef GL_NV_vertex_program3
+/* reuse GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB */
+#endif
+
+#ifndef GL_EXT_framebuffer_object
+#define GL_INVALID_FRAMEBUFFER_OPERATION_EXT 0x0506
+#define GL_MAX_RENDERBUFFER_SIZE_EXT 0x84E8
+#define GL_FRAMEBUFFER_BINDING_EXT 0x8CA6
+#define GL_RENDERBUFFER_BINDING_EXT 0x8CA7
+#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_EXT 0x8CD0
+#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT 0x8CD1
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_EXT 0x8CD2
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_EXT 0x8CD3
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_EXT 0x8CD4
+#define GL_FRAMEBUFFER_COMPLETE_EXT 0x8CD5
+#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT 0x8CD6
+#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT 0x8CD7
+#define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT 0x8CD9
+#define GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT 0x8CDA
+#define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT 0x8CDB
+#define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT 0x8CDC
+#define GL_FRAMEBUFFER_UNSUPPORTED_EXT 0x8CDD
+#define GL_MAX_COLOR_ATTACHMENTS_EXT 0x8CDF
+#define GL_COLOR_ATTACHMENT0_EXT 0x8CE0
+#define GL_COLOR_ATTACHMENT1_EXT 0x8CE1
+#define GL_COLOR_ATTACHMENT2_EXT 0x8CE2
+#define GL_COLOR_ATTACHMENT3_EXT 0x8CE3
+#define GL_COLOR_ATTACHMENT4_EXT 0x8CE4
+#define GL_COLOR_ATTACHMENT5_EXT 0x8CE5
+#define GL_COLOR_ATTACHMENT6_EXT 0x8CE6
+#define GL_COLOR_ATTACHMENT7_EXT 0x8CE7
+#define GL_COLOR_ATTACHMENT8_EXT 0x8CE8
+#define GL_COLOR_ATTACHMENT9_EXT 0x8CE9
+#define GL_COLOR_ATTACHMENT10_EXT 0x8CEA
+#define GL_COLOR_ATTACHMENT11_EXT 0x8CEB
+#define GL_COLOR_ATTACHMENT12_EXT 0x8CEC
+#define GL_COLOR_ATTACHMENT13_EXT 0x8CED
+#define GL_COLOR_ATTACHMENT14_EXT 0x8CEE
+#define GL_COLOR_ATTACHMENT15_EXT 0x8CEF
+#define GL_DEPTH_ATTACHMENT_EXT 0x8D00
+#define GL_STENCIL_ATTACHMENT_EXT 0x8D20
+#define GL_FRAMEBUFFER_EXT 0x8D40
+#define GL_RENDERBUFFER_EXT 0x8D41
+#define GL_RENDERBUFFER_WIDTH_EXT 0x8D42
+#define GL_RENDERBUFFER_HEIGHT_EXT 0x8D43
+#define GL_RENDERBUFFER_INTERNAL_FORMAT_EXT 0x8D44
+#define GL_STENCIL_INDEX1_EXT 0x8D46
+#define GL_STENCIL_INDEX4_EXT 0x8D47
+#define GL_STENCIL_INDEX8_EXT 0x8D48
+#define GL_STENCIL_INDEX16_EXT 0x8D49
+#define GL_RENDERBUFFER_RED_SIZE_EXT 0x8D50
+#define GL_RENDERBUFFER_GREEN_SIZE_EXT 0x8D51
+#define GL_RENDERBUFFER_BLUE_SIZE_EXT 0x8D52
+#define GL_RENDERBUFFER_ALPHA_SIZE_EXT 0x8D53
+#define GL_RENDERBUFFER_DEPTH_SIZE_EXT 0x8D54
+#define GL_RENDERBUFFER_STENCIL_SIZE_EXT 0x8D55
+#endif
+
+#ifndef GL_GREMEDY_string_marker
+#endif
+
+#ifndef GL_EXT_packed_depth_stencil
+#define GL_DEPTH_STENCIL_EXT 0x84F9
+#define GL_UNSIGNED_INT_24_8_EXT 0x84FA
+#define GL_DEPTH24_STENCIL8_EXT 0x88F0
+#define GL_TEXTURE_STENCIL_SIZE_EXT 0x88F1
+#endif
+
+#ifndef GL_EXT_stencil_clear_tag
+#define GL_STENCIL_TAG_BITS_EXT 0x88F2
+#define GL_STENCIL_CLEAR_TAG_VALUE_EXT 0x88F3
+#endif
+
+#ifndef GL_EXT_texture_sRGB
+#define GL_SRGB_EXT 0x8C40
+#define GL_SRGB8_EXT 0x8C41
+#define GL_SRGB_ALPHA_EXT 0x8C42
+#define GL_SRGB8_ALPHA8_EXT 0x8C43
+#define GL_SLUMINANCE_ALPHA_EXT 0x8C44
+#define GL_SLUMINANCE8_ALPHA8_EXT 0x8C45
+#define GL_SLUMINANCE_EXT 0x8C46
+#define GL_SLUMINANCE8_EXT 0x8C47
+#define GL_COMPRESSED_SRGB_EXT 0x8C48
+#define GL_COMPRESSED_SRGB_ALPHA_EXT 0x8C49
+#define GL_COMPRESSED_SLUMINANCE_EXT 0x8C4A
+#define GL_COMPRESSED_SLUMINANCE_ALPHA_EXT 0x8C4B
+#define GL_COMPRESSED_SRGB_S3TC_DXT1_EXT 0x8C4C
+#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT 0x8C4D
+#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT 0x8C4E
+#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT 0x8C4F
+#endif
+
+#ifndef GL_EXT_framebuffer_blit
+#define GL_READ_FRAMEBUFFER_EXT 0x8CA8
+#define GL_DRAW_FRAMEBUFFER_EXT 0x8CA9
+#define GL_DRAW_FRAMEBUFFER_BINDING_EXT GL_FRAMEBUFFER_BINDING_EXT
+#define GL_READ_FRAMEBUFFER_BINDING_EXT 0x8CAA
+#endif
+
+#ifndef GL_EXT_framebuffer_multisample
+#define GL_RENDERBUFFER_SAMPLES_EXT 0x8CAB
+#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT 0x8D56
+#define GL_MAX_SAMPLES_EXT 0x8D57
+#endif
+
+#ifndef GL_MESAX_texture_stack
+#define GL_TEXTURE_1D_STACK_MESAX 0x8759
+#define GL_TEXTURE_2D_STACK_MESAX 0x875A
+#define GL_PROXY_TEXTURE_1D_STACK_MESAX 0x875B
+#define GL_PROXY_TEXTURE_2D_STACK_MESAX 0x875C
+#define GL_TEXTURE_1D_STACK_BINDING_MESAX 0x875D
+#define GL_TEXTURE_2D_STACK_BINDING_MESAX 0x875E
+#endif
+
+#ifndef GL_EXT_timer_query
+#define GL_TIME_ELAPSED_EXT 0x88BF
+#endif
+
+#ifndef GL_EXT_gpu_program_parameters
+#endif
+
+#ifndef GL_APPLE_flush_buffer_range
+#define GL_BUFFER_SERIALIZED_MODIFY_APPLE 0x8A12
+#define GL_BUFFER_FLUSHING_UNMAP_APPLE 0x8A13
+#endif
+
+#ifndef GL_NV_gpu_program4
+#define GL_MIN_PROGRAM_TEXEL_OFFSET_NV 0x8904
+#define GL_MAX_PROGRAM_TEXEL_OFFSET_NV 0x8905
+#define GL_PROGRAM_ATTRIB_COMPONENTS_NV 0x8906
+#define GL_PROGRAM_RESULT_COMPONENTS_NV 0x8907
+#define GL_MAX_PROGRAM_ATTRIB_COMPONENTS_NV 0x8908
+#define GL_MAX_PROGRAM_RESULT_COMPONENTS_NV 0x8909
+#define GL_MAX_PROGRAM_GENERIC_ATTRIBS_NV 0x8DA5
+#define GL_MAX_PROGRAM_GENERIC_RESULTS_NV 0x8DA6
+#endif
+
+#ifndef GL_NV_geometry_program4
+#define GL_LINES_ADJACENCY_EXT 0x000A
+#define GL_LINE_STRIP_ADJACENCY_EXT 0x000B
+#define GL_TRIANGLES_ADJACENCY_EXT 0x000C
+#define GL_TRIANGLE_STRIP_ADJACENCY_EXT 0x000D
+#define GL_GEOMETRY_PROGRAM_NV 0x8C26
+#define GL_MAX_PROGRAM_OUTPUT_VERTICES_NV 0x8C27
+#define GL_MAX_PROGRAM_TOTAL_OUTPUT_COMPONENTS_NV 0x8C28
+#define GL_GEOMETRY_VERTICES_OUT_EXT 0x8DDA
+#define GL_GEOMETRY_INPUT_TYPE_EXT 0x8DDB
+#define GL_GEOMETRY_OUTPUT_TYPE_EXT 0x8DDC
+#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS_EXT 0x8C29
+#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED_EXT 0x8DA7
+#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_EXT 0x8DA8
+#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_COUNT_EXT 0x8DA9
+#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER_EXT 0x8CD4
+#define GL_PROGRAM_POINT_SIZE_EXT 0x8642
+#endif
+
+#ifndef GL_EXT_geometry_shader4
+#define GL_GEOMETRY_SHADER_EXT 0x8DD9
+/* reuse GL_GEOMETRY_VERTICES_OUT_EXT */
+/* reuse GL_GEOMETRY_INPUT_TYPE_EXT */
+/* reuse GL_GEOMETRY_OUTPUT_TYPE_EXT */
+/* reuse GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS_EXT */
+#define GL_MAX_GEOMETRY_VARYING_COMPONENTS_EXT 0x8DDD
+#define GL_MAX_VERTEX_VARYING_COMPONENTS_EXT 0x8DDE
+#define GL_MAX_VARYING_COMPONENTS_EXT 0x8B4B
+#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_EXT 0x8DDF
+#define GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT 0x8DE0
+#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS_EXT 0x8DE1
+/* reuse GL_LINES_ADJACENCY_EXT */
+/* reuse GL_LINE_STRIP_ADJACENCY_EXT */
+/* reuse GL_TRIANGLES_ADJACENCY_EXT */
+/* reuse GL_TRIANGLE_STRIP_ADJACENCY_EXT */
+/* reuse GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_EXT */
+/* reuse GL_FRAMEBUFFER_INCOMPLETE_LAYER_COUNT_EXT */
+/* reuse GL_FRAMEBUFFER_ATTACHMENT_LAYERED_EXT */
+/* reuse GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER_EXT */
+/* reuse GL_PROGRAM_POINT_SIZE_EXT */
+#endif
+
+#ifndef GL_NV_vertex_program4
+#define GL_VERTEX_ATTRIB_ARRAY_INTEGER_NV 0x88FD
+#endif
+
+#ifndef GL_EXT_gpu_shader4
+#define GL_SAMPLER_1D_ARRAY_EXT 0x8DC0
+#define GL_SAMPLER_2D_ARRAY_EXT 0x8DC1
+#define GL_SAMPLER_BUFFER_EXT 0x8DC2
+#define GL_SAMPLER_1D_ARRAY_SHADOW_EXT 0x8DC3
+#define GL_SAMPLER_2D_ARRAY_SHADOW_EXT 0x8DC4
+#define GL_SAMPLER_CUBE_SHADOW_EXT 0x8DC5
+#define GL_UNSIGNED_INT_VEC2_EXT 0x8DC6
+#define GL_UNSIGNED_INT_VEC3_EXT 0x8DC7
+#define GL_UNSIGNED_INT_VEC4_EXT 0x8DC8
+#define GL_INT_SAMPLER_1D_EXT 0x8DC9
+#define GL_INT_SAMPLER_2D_EXT 0x8DCA
+#define GL_INT_SAMPLER_3D_EXT 0x8DCB
+#define GL_INT_SAMPLER_CUBE_EXT 0x8DCC
+#define GL_INT_SAMPLER_2D_RECT_EXT 0x8DCD
+#define GL_INT_SAMPLER_1D_ARRAY_EXT 0x8DCE
+#define GL_INT_SAMPLER_2D_ARRAY_EXT 0x8DCF
+#define GL_INT_SAMPLER_BUFFER_EXT 0x8DD0
+#define GL_UNSIGNED_INT_SAMPLER_1D_EXT 0x8DD1
+#define GL_UNSIGNED_INT_SAMPLER_2D_EXT 0x8DD2
+#define GL_UNSIGNED_INT_SAMPLER_3D_EXT 0x8DD3
+#define GL_UNSIGNED_INT_SAMPLER_CUBE_EXT 0x8DD4
+#define GL_UNSIGNED_INT_SAMPLER_2D_RECT_EXT 0x8DD5
+#define GL_UNSIGNED_INT_SAMPLER_1D_ARRAY_EXT 0x8DD6
+#define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY_EXT 0x8DD7
+#define GL_UNSIGNED_INT_SAMPLER_BUFFER_EXT 0x8DD8
+#endif
+
+#ifndef GL_EXT_draw_instanced
+#endif
+
+#ifndef GL_EXT_packed_float
+#define GL_R11F_G11F_B10F_EXT 0x8C3A
+#define GL_UNSIGNED_INT_10F_11F_11F_REV_EXT 0x8C3B
+#define GL_RGBA_SIGNED_COMPONENTS_EXT 0x8C3C
+#endif
+
+#ifndef GL_EXT_texture_array
+#define GL_TEXTURE_1D_ARRAY_EXT 0x8C18
+#define GL_PROXY_TEXTURE_1D_ARRAY_EXT 0x8C19
+#define GL_TEXTURE_2D_ARRAY_EXT 0x8C1A
+#define GL_PROXY_TEXTURE_2D_ARRAY_EXT 0x8C1B
+#define GL_TEXTURE_BINDING_1D_ARRAY_EXT 0x8C1C
+#define GL_TEXTURE_BINDING_2D_ARRAY_EXT 0x8C1D
+#define GL_MAX_ARRAY_TEXTURE_LAYERS_EXT 0x88FF
+#define GL_COMPARE_REF_DEPTH_TO_TEXTURE_EXT 0x884E
+/* reuse GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER_EXT */
+#endif
+
+#ifndef GL_EXT_texture_buffer_object
+#define GL_TEXTURE_BUFFER_EXT 0x8C2A
+#define GL_MAX_TEXTURE_BUFFER_SIZE_EXT 0x8C2B
+#define GL_TEXTURE_BINDING_BUFFER_EXT 0x8C2C
+#define GL_TEXTURE_BUFFER_DATA_STORE_BINDING_EXT 0x8C2D
+#define GL_TEXTURE_BUFFER_FORMAT_EXT 0x8C2E
+#endif
+
+#ifndef GL_EXT_texture_compression_latc
+#define GL_COMPRESSED_LUMINANCE_LATC1_EXT 0x8C70
+#define GL_COMPRESSED_SIGNED_LUMINANCE_LATC1_EXT 0x8C71
+#define GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT 0x8C72
+#define GL_COMPRESSED_SIGNED_LUMINANCE_ALPHA_LATC2_EXT 0x8C73
+#endif
+
+#ifndef GL_EXT_texture_compression_rgtc
+#define GL_COMPRESSED_RED_RGTC1_EXT 0x8DBB
+#define GL_COMPRESSED_SIGNED_RED_RGTC1_EXT 0x8DBC
+#define GL_COMPRESSED_RED_GREEN_RGTC2_EXT 0x8DBD
+#define GL_COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT 0x8DBE
+#endif
+
+#ifndef GL_EXT_texture_shared_exponent
+#define GL_RGB9_E5_EXT 0x8C3D
+#define GL_UNSIGNED_INT_5_9_9_9_REV_EXT 0x8C3E
+#define GL_TEXTURE_SHARED_SIZE_EXT 0x8C3F
+#endif
+
+#ifndef GL_NV_depth_buffer_float
+#define GL_DEPTH_COMPONENT32F_NV 0x8DAB
+#define GL_DEPTH32F_STENCIL8_NV 0x8DAC
+#define GL_FLOAT_32_UNSIGNED_INT_24_8_REV_NV 0x8DAD
+#define GL_DEPTH_BUFFER_FLOAT_MODE_NV 0x8DAF
+#endif
+
+#ifndef GL_NV_fragment_program4
+#endif
+
+#ifndef GL_NV_framebuffer_multisample_coverage
+#define GL_RENDERBUFFER_COVERAGE_SAMPLES_NV 0x8CAB
+#define GL_RENDERBUFFER_COLOR_SAMPLES_NV 0x8E10
+#define GL_MAX_MULTISAMPLE_COVERAGE_MODES_NV 0x8E11
+#define GL_MULTISAMPLE_COVERAGE_MODES_NV 0x8E12
+#endif
+
+#ifndef GL_EXT_framebuffer_sRGB
+#define GL_FRAMEBUFFER_SRGB_EXT 0x8DB9
+#define GL_FRAMEBUFFER_SRGB_CAPABLE_EXT 0x8DBA
+#endif
+
+#ifndef GL_NV_geometry_shader4
+#endif
+
+#ifndef GL_NV_parameter_buffer_object
+#define GL_MAX_PROGRAM_PARAMETER_BUFFER_BINDINGS_NV 0x8DA0
+#define GL_MAX_PROGRAM_PARAMETER_BUFFER_SIZE_NV 0x8DA1
+#define GL_VERTEX_PROGRAM_PARAMETER_BUFFER_NV 0x8DA2
+#define GL_GEOMETRY_PROGRAM_PARAMETER_BUFFER_NV 0x8DA3
+#define GL_FRAGMENT_PROGRAM_PARAMETER_BUFFER_NV 0x8DA4
+#endif
+
+#ifndef GL_EXT_draw_buffers2
+#endif
+
+#ifndef GL_NV_transform_feedback
+#define GL_BACK_PRIMARY_COLOR_NV 0x8C77
+#define GL_BACK_SECONDARY_COLOR_NV 0x8C78
+#define GL_TEXTURE_COORD_NV 0x8C79
+#define GL_CLIP_DISTANCE_NV 0x8C7A
+#define GL_VERTEX_ID_NV 0x8C7B
+#define GL_PRIMITIVE_ID_NV 0x8C7C
+#define GL_GENERIC_ATTRIB_NV 0x8C7D
+#define GL_TRANSFORM_FEEDBACK_ATTRIBS_NV 0x8C7E
+#define GL_TRANSFORM_FEEDBACK_BUFFER_MODE_NV 0x8C7F
+#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_NV 0x8C80
+#define GL_ACTIVE_VARYINGS_NV 0x8C81
+#define GL_ACTIVE_VARYING_MAX_LENGTH_NV 0x8C82
+#define GL_TRANSFORM_FEEDBACK_VARYINGS_NV 0x8C83
+#define GL_TRANSFORM_FEEDBACK_BUFFER_START_NV 0x8C84
+#define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE_NV 0x8C85
+#define GL_TRANSFORM_FEEDBACK_RECORD_NV 0x8C86
+#define GL_PRIMITIVES_GENERATED_NV 0x8C87
+#define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN_NV 0x8C88
+#define GL_RASTERIZER_DISCARD_NV 0x8C89
+#define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_ATTRIBS_NV 0x8C8A
+#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS_NV 0x8C8B
+#define GL_INTERLEAVED_ATTRIBS_NV 0x8C8C
+#define GL_SEPARATE_ATTRIBS_NV 0x8C8D
+#define GL_TRANSFORM_FEEDBACK_BUFFER_NV 0x8C8E
+#define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING_NV 0x8C8F
+#define GL_LAYER_NV 0x8DAA
+#define GL_NEXT_BUFFER_NV -2
+#define GL_SKIP_COMPONENTS4_NV -3
+#define GL_SKIP_COMPONENTS3_NV -4
+#define GL_SKIP_COMPONENTS2_NV -5
+#define GL_SKIP_COMPONENTS1_NV -6
+#endif
+
+#ifndef GL_EXT_bindable_uniform
+#define GL_MAX_VERTEX_BINDABLE_UNIFORMS_EXT 0x8DE2
+#define GL_MAX_FRAGMENT_BINDABLE_UNIFORMS_EXT 0x8DE3
+#define GL_MAX_GEOMETRY_BINDABLE_UNIFORMS_EXT 0x8DE4
+#define GL_MAX_BINDABLE_UNIFORM_SIZE_EXT 0x8DED
+#define GL_UNIFORM_BUFFER_EXT 0x8DEE
+#define GL_UNIFORM_BUFFER_BINDING_EXT 0x8DEF
+#endif
+
+#ifndef GL_EXT_texture_integer
+#define GL_RGBA32UI_EXT 0x8D70
+#define GL_RGB32UI_EXT 0x8D71
+#define GL_ALPHA32UI_EXT 0x8D72
+#define GL_INTENSITY32UI_EXT 0x8D73
+#define GL_LUMINANCE32UI_EXT 0x8D74
+#define GL_LUMINANCE_ALPHA32UI_EXT 0x8D75
+#define GL_RGBA16UI_EXT 0x8D76
+#define GL_RGB16UI_EXT 0x8D77
+#define GL_ALPHA16UI_EXT 0x8D78
+#define GL_INTENSITY16UI_EXT 0x8D79
+#define GL_LUMINANCE16UI_EXT 0x8D7A
+#define GL_LUMINANCE_ALPHA16UI_EXT 0x8D7B
+#define GL_RGBA8UI_EXT 0x8D7C
+#define GL_RGB8UI_EXT 0x8D7D
+#define GL_ALPHA8UI_EXT 0x8D7E
+#define GL_INTENSITY8UI_EXT 0x8D7F
+#define GL_LUMINANCE8UI_EXT 0x8D80
+#define GL_LUMINANCE_ALPHA8UI_EXT 0x8D81
+#define GL_RGBA32I_EXT 0x8D82
+#define GL_RGB32I_EXT 0x8D83
+#define GL_ALPHA32I_EXT 0x8D84
+#define GL_INTENSITY32I_EXT 0x8D85
+#define GL_LUMINANCE32I_EXT 0x8D86
+#define GL_LUMINANCE_ALPHA32I_EXT 0x8D87
+#define GL_RGBA16I_EXT 0x8D88
+#define GL_RGB16I_EXT 0x8D89
+#define GL_ALPHA16I_EXT 0x8D8A
+#define GL_INTENSITY16I_EXT 0x8D8B
+#define GL_LUMINANCE16I_EXT 0x8D8C
+#define GL_LUMINANCE_ALPHA16I_EXT 0x8D8D
+#define GL_RGBA8I_EXT 0x8D8E
+#define GL_RGB8I_EXT 0x8D8F
+#define GL_ALPHA8I_EXT 0x8D90
+#define GL_INTENSITY8I_EXT 0x8D91
+#define GL_LUMINANCE8I_EXT 0x8D92
+#define GL_LUMINANCE_ALPHA8I_EXT 0x8D93
+#define GL_RED_INTEGER_EXT 0x8D94
+#define GL_GREEN_INTEGER_EXT 0x8D95
+#define GL_BLUE_INTEGER_EXT 0x8D96
+#define GL_ALPHA_INTEGER_EXT 0x8D97
+#define GL_RGB_INTEGER_EXT 0x8D98
+#define GL_RGBA_INTEGER_EXT 0x8D99
+#define GL_BGR_INTEGER_EXT 0x8D9A
+#define GL_BGRA_INTEGER_EXT 0x8D9B
+#define GL_LUMINANCE_INTEGER_EXT 0x8D9C
+#define GL_LUMINANCE_ALPHA_INTEGER_EXT 0x8D9D
+#define GL_RGBA_INTEGER_MODE_EXT 0x8D9E
+#endif
+
+#ifndef GL_GREMEDY_frame_terminator
+#endif
+
+#ifndef GL_NV_conditional_render
+#define GL_QUERY_WAIT_NV 0x8E13
+#define GL_QUERY_NO_WAIT_NV 0x8E14
+#define GL_QUERY_BY_REGION_WAIT_NV 0x8E15
+#define GL_QUERY_BY_REGION_NO_WAIT_NV 0x8E16
+#endif
+
+#ifndef GL_NV_present_video
+#define GL_FRAME_NV 0x8E26
+#define GL_FIELDS_NV 0x8E27
+#define GL_CURRENT_TIME_NV 0x8E28
+#define GL_NUM_FILL_STREAMS_NV 0x8E29
+#define GL_PRESENT_TIME_NV 0x8E2A
+#define GL_PRESENT_DURATION_NV 0x8E2B
+#endif
+
+#ifndef GL_EXT_transform_feedback
+#define GL_TRANSFORM_FEEDBACK_BUFFER_EXT 0x8C8E
+#define GL_TRANSFORM_FEEDBACK_BUFFER_START_EXT 0x8C84
+#define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE_EXT 0x8C85
+#define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING_EXT 0x8C8F
+#define GL_INTERLEAVED_ATTRIBS_EXT 0x8C8C
+#define GL_SEPARATE_ATTRIBS_EXT 0x8C8D
+#define GL_PRIMITIVES_GENERATED_EXT 0x8C87
+#define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN_EXT 0x8C88
+#define GL_RASTERIZER_DISCARD_EXT 0x8C89
+#define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_EXT 0x8C8A
+#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS_EXT 0x8C8B
+#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_EXT 0x8C80
+#define GL_TRANSFORM_FEEDBACK_VARYINGS_EXT 0x8C83
+#define GL_TRANSFORM_FEEDBACK_BUFFER_MODE_EXT 0x8C7F
+#define GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH_EXT 0x8C76
+#endif
+
+#ifndef GL_EXT_direct_state_access
+#define GL_PROGRAM_MATRIX_EXT 0x8E2D
+#define GL_TRANSPOSE_PROGRAM_MATRIX_EXT 0x8E2E
+#define GL_PROGRAM_MATRIX_STACK_DEPTH_EXT 0x8E2F
+#endif
+
+#ifndef GL_EXT_vertex_array_bgra
+/* reuse GL_BGRA */
+#endif
+
+#ifndef GL_EXT_texture_swizzle
+#define GL_TEXTURE_SWIZZLE_R_EXT 0x8E42
+#define GL_TEXTURE_SWIZZLE_G_EXT 0x8E43
+#define GL_TEXTURE_SWIZZLE_B_EXT 0x8E44
+#define GL_TEXTURE_SWIZZLE_A_EXT 0x8E45
+#define GL_TEXTURE_SWIZZLE_RGBA_EXT 0x8E46
+#endif
+
+#ifndef GL_NV_explicit_multisample
+#define GL_SAMPLE_POSITION_NV 0x8E50
+#define GL_SAMPLE_MASK_NV 0x8E51
+#define GL_SAMPLE_MASK_VALUE_NV 0x8E52
+#define GL_TEXTURE_BINDING_RENDERBUFFER_NV 0x8E53
+#define GL_TEXTURE_RENDERBUFFER_DATA_STORE_BINDING_NV 0x8E54
+#define GL_TEXTURE_RENDERBUFFER_NV 0x8E55
+#define GL_SAMPLER_RENDERBUFFER_NV 0x8E56
+#define GL_INT_SAMPLER_RENDERBUFFER_NV 0x8E57
+#define GL_UNSIGNED_INT_SAMPLER_RENDERBUFFER_NV 0x8E58
+#define GL_MAX_SAMPLE_MASK_WORDS_NV 0x8E59
+#endif
+
+#ifndef GL_NV_transform_feedback2
+#define GL_TRANSFORM_FEEDBACK_NV 0x8E22
+#define GL_TRANSFORM_FEEDBACK_BUFFER_PAUSED_NV 0x8E23
+#define GL_TRANSFORM_FEEDBACK_BUFFER_ACTIVE_NV 0x8E24
+#define GL_TRANSFORM_FEEDBACK_BINDING_NV 0x8E25
+#endif
+
+#ifndef GL_ATI_meminfo
+#define GL_VBO_FREE_MEMORY_ATI 0x87FB
+#define GL_TEXTURE_FREE_MEMORY_ATI 0x87FC
+#define GL_RENDERBUFFER_FREE_MEMORY_ATI 0x87FD
+#endif
+
+#ifndef GL_AMD_performance_monitor
+#define GL_COUNTER_TYPE_AMD 0x8BC0
+#define GL_COUNTER_RANGE_AMD 0x8BC1
+#define GL_UNSIGNED_INT64_AMD 0x8BC2
+#define GL_PERCENTAGE_AMD 0x8BC3
+#define GL_PERFMON_RESULT_AVAILABLE_AMD 0x8BC4
+#define GL_PERFMON_RESULT_SIZE_AMD 0x8BC5
+#define GL_PERFMON_RESULT_AMD 0x8BC6
+#endif
+
+#ifndef GL_AMD_texture_texture4
+#endif
+
+#ifndef GL_AMD_vertex_shader_tesselator
+#define GL_SAMPLER_BUFFER_AMD 0x9001
+#define GL_INT_SAMPLER_BUFFER_AMD 0x9002
+#define GL_UNSIGNED_INT_SAMPLER_BUFFER_AMD 0x9003
+#define GL_TESSELLATION_MODE_AMD 0x9004
+#define GL_TESSELLATION_FACTOR_AMD 0x9005
+#define GL_DISCRETE_AMD 0x9006
+#define GL_CONTINUOUS_AMD 0x9007
+#endif
+
+#ifndef GL_EXT_provoking_vertex
+#define GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION_EXT 0x8E4C
+#define GL_FIRST_VERTEX_CONVENTION_EXT 0x8E4D
+#define GL_LAST_VERTEX_CONVENTION_EXT 0x8E4E
+#define GL_PROVOKING_VERTEX_EXT 0x8E4F
+#endif
+
+#ifndef GL_EXT_texture_snorm
+#define GL_ALPHA_SNORM 0x9010
+#define GL_LUMINANCE_SNORM 0x9011
+#define GL_LUMINANCE_ALPHA_SNORM 0x9012
+#define GL_INTENSITY_SNORM 0x9013
+#define GL_ALPHA8_SNORM 0x9014
+#define GL_LUMINANCE8_SNORM 0x9015
+#define GL_LUMINANCE8_ALPHA8_SNORM 0x9016
+#define GL_INTENSITY8_SNORM 0x9017
+#define GL_ALPHA16_SNORM 0x9018
+#define GL_LUMINANCE16_SNORM 0x9019
+#define GL_LUMINANCE16_ALPHA16_SNORM 0x901A
+#define GL_INTENSITY16_SNORM 0x901B
+/* reuse GL_RED_SNORM */
+/* reuse GL_RG_SNORM */
+/* reuse GL_RGB_SNORM */
+/* reuse GL_RGBA_SNORM */
+/* reuse GL_R8_SNORM */
+/* reuse GL_RG8_SNORM */
+/* reuse GL_RGB8_SNORM */
+/* reuse GL_RGBA8_SNORM */
+/* reuse GL_R16_SNORM */
+/* reuse GL_RG16_SNORM */
+/* reuse GL_RGB16_SNORM */
+/* reuse GL_RGBA16_SNORM */
+/* reuse GL_SIGNED_NORMALIZED */
+#endif
+
+#ifndef GL_AMD_draw_buffers_blend
+#endif
+
+#ifndef GL_APPLE_texture_range
+#define GL_TEXTURE_RANGE_LENGTH_APPLE 0x85B7
+#define GL_TEXTURE_RANGE_POINTER_APPLE 0x85B8
+#define GL_TEXTURE_STORAGE_HINT_APPLE 0x85BC
+#define GL_STORAGE_PRIVATE_APPLE 0x85BD
+/* reuse GL_STORAGE_CACHED_APPLE */
+/* reuse GL_STORAGE_SHARED_APPLE */
+#endif
+
+#ifndef GL_APPLE_float_pixels
+#define GL_HALF_APPLE 0x140B
+#define GL_RGBA_FLOAT32_APPLE 0x8814
+#define GL_RGB_FLOAT32_APPLE 0x8815
+#define GL_ALPHA_FLOAT32_APPLE 0x8816
+#define GL_INTENSITY_FLOAT32_APPLE 0x8817
+#define GL_LUMINANCE_FLOAT32_APPLE 0x8818
+#define GL_LUMINANCE_ALPHA_FLOAT32_APPLE 0x8819
+#define GL_RGBA_FLOAT16_APPLE 0x881A
+#define GL_RGB_FLOAT16_APPLE 0x881B
+#define GL_ALPHA_FLOAT16_APPLE 0x881C
+#define GL_INTENSITY_FLOAT16_APPLE 0x881D
+#define GL_LUMINANCE_FLOAT16_APPLE 0x881E
+#define GL_LUMINANCE_ALPHA_FLOAT16_APPLE 0x881F
+#define GL_COLOR_FLOAT_APPLE 0x8A0F
+#endif
+
+#ifndef GL_APPLE_vertex_program_evaluators
+#define GL_VERTEX_ATTRIB_MAP1_APPLE 0x8A00
+#define GL_VERTEX_ATTRIB_MAP2_APPLE 0x8A01
+#define GL_VERTEX_ATTRIB_MAP1_SIZE_APPLE 0x8A02
+#define GL_VERTEX_ATTRIB_MAP1_COEFF_APPLE 0x8A03
+#define GL_VERTEX_ATTRIB_MAP1_ORDER_APPLE 0x8A04
+#define GL_VERTEX_ATTRIB_MAP1_DOMAIN_APPLE 0x8A05
+#define GL_VERTEX_ATTRIB_MAP2_SIZE_APPLE 0x8A06
+#define GL_VERTEX_ATTRIB_MAP2_COEFF_APPLE 0x8A07
+#define GL_VERTEX_ATTRIB_MAP2_ORDER_APPLE 0x8A08
+#define GL_VERTEX_ATTRIB_MAP2_DOMAIN_APPLE 0x8A09
+#endif
+
+#ifndef GL_APPLE_aux_depth_stencil
+#define GL_AUX_DEPTH_STENCIL_APPLE 0x8A14
+#endif
+
+#ifndef GL_APPLE_object_purgeable
+#define GL_BUFFER_OBJECT_APPLE 0x85B3
+#define GL_RELEASED_APPLE 0x8A19
+#define GL_VOLATILE_APPLE 0x8A1A
+#define GL_RETAINED_APPLE 0x8A1B
+#define GL_UNDEFINED_APPLE 0x8A1C
+#define GL_PURGEABLE_APPLE 0x8A1D
+#endif
+
+#ifndef GL_APPLE_row_bytes
+#define GL_PACK_ROW_BYTES_APPLE 0x8A15
+#define GL_UNPACK_ROW_BYTES_APPLE 0x8A16
+#endif
+
+#ifndef GL_APPLE_rgb_422
+#define GL_RGB_422_APPLE 0x8A1F
+/* reuse GL_UNSIGNED_SHORT_8_8_APPLE */
+/* reuse GL_UNSIGNED_SHORT_8_8_REV_APPLE */
+#endif
+
+#ifndef GL_NV_video_capture
+#define GL_VIDEO_BUFFER_NV 0x9020
+#define GL_VIDEO_BUFFER_BINDING_NV 0x9021
+#define GL_FIELD_UPPER_NV 0x9022
+#define GL_FIELD_LOWER_NV 0x9023
+#define GL_NUM_VIDEO_CAPTURE_STREAMS_NV 0x9024
+#define GL_NEXT_VIDEO_CAPTURE_BUFFER_STATUS_NV 0x9025
+#define GL_VIDEO_CAPTURE_TO_422_SUPPORTED_NV 0x9026
+#define GL_LAST_VIDEO_CAPTURE_STATUS_NV 0x9027
+#define GL_VIDEO_BUFFER_PITCH_NV 0x9028
+#define GL_VIDEO_COLOR_CONVERSION_MATRIX_NV 0x9029
+#define GL_VIDEO_COLOR_CONVERSION_MAX_NV 0x902A
+#define GL_VIDEO_COLOR_CONVERSION_MIN_NV 0x902B
+#define GL_VIDEO_COLOR_CONVERSION_OFFSET_NV 0x902C
+#define GL_VIDEO_BUFFER_INTERNAL_FORMAT_NV 0x902D
+#define GL_PARTIAL_SUCCESS_NV 0x902E
+#define GL_SUCCESS_NV 0x902F
+#define GL_FAILURE_NV 0x9030
+#define GL_YCBYCR8_422_NV 0x9031
+#define GL_YCBAYCR8A_4224_NV 0x9032
+#define GL_Z6Y10Z6CB10Z6Y10Z6CR10_422_NV 0x9033
+#define GL_Z6Y10Z6CB10Z6A10Z6Y10Z6CR10Z6A10_4224_NV 0x9034
+#define GL_Z4Y12Z4CB12Z4Y12Z4CR12_422_NV 0x9035
+#define GL_Z4Y12Z4CB12Z4A12Z4Y12Z4CR12Z4A12_4224_NV 0x9036
+#define GL_Z4Y12Z4CB12Z4CR12_444_NV 0x9037
+#define GL_VIDEO_CAPTURE_FRAME_WIDTH_NV 0x9038
+#define GL_VIDEO_CAPTURE_FRAME_HEIGHT_NV 0x9039
+#define GL_VIDEO_CAPTURE_FIELD_UPPER_HEIGHT_NV 0x903A
+#define GL_VIDEO_CAPTURE_FIELD_LOWER_HEIGHT_NV 0x903B
+#define GL_VIDEO_CAPTURE_SURFACE_ORIGIN_NV 0x903C
+#endif
+
+#ifndef GL_NV_copy_image
+#endif
+
+#ifndef GL_EXT_separate_shader_objects
+#define GL_ACTIVE_PROGRAM_EXT 0x8B8D
+#endif
+
+#ifndef GL_NV_parameter_buffer_object2
+#endif
+
+#ifndef GL_NV_shader_buffer_load
+#define GL_BUFFER_GPU_ADDRESS_NV 0x8F1D
+#define GL_GPU_ADDRESS_NV 0x8F34
+#define GL_MAX_SHADER_BUFFER_ADDRESS_NV 0x8F35
+#endif
+
+#ifndef GL_NV_vertex_buffer_unified_memory
+#define GL_VERTEX_ATTRIB_ARRAY_UNIFIED_NV 0x8F1E
+#define GL_ELEMENT_ARRAY_UNIFIED_NV 0x8F1F
+#define GL_VERTEX_ATTRIB_ARRAY_ADDRESS_NV 0x8F20
+#define GL_VERTEX_ARRAY_ADDRESS_NV 0x8F21
+#define GL_NORMAL_ARRAY_ADDRESS_NV 0x8F22
+#define GL_COLOR_ARRAY_ADDRESS_NV 0x8F23
+#define GL_INDEX_ARRAY_ADDRESS_NV 0x8F24
+#define GL_TEXTURE_COORD_ARRAY_ADDRESS_NV 0x8F25
+#define GL_EDGE_FLAG_ARRAY_ADDRESS_NV 0x8F26
+#define GL_SECONDARY_COLOR_ARRAY_ADDRESS_NV 0x8F27
+#define GL_FOG_COORD_ARRAY_ADDRESS_NV 0x8F28
+#define GL_ELEMENT_ARRAY_ADDRESS_NV 0x8F29
+#define GL_VERTEX_ATTRIB_ARRAY_LENGTH_NV 0x8F2A
+#define GL_VERTEX_ARRAY_LENGTH_NV 0x8F2B
+#define GL_NORMAL_ARRAY_LENGTH_NV 0x8F2C
+#define GL_COLOR_ARRAY_LENGTH_NV 0x8F2D
+#define GL_INDEX_ARRAY_LENGTH_NV 0x8F2E
+#define GL_TEXTURE_COORD_ARRAY_LENGTH_NV 0x8F2F
+#define GL_EDGE_FLAG_ARRAY_LENGTH_NV 0x8F30
+#define GL_SECONDARY_COLOR_ARRAY_LENGTH_NV 0x8F31
+#define GL_FOG_COORD_ARRAY_LENGTH_NV 0x8F32
+#define GL_ELEMENT_ARRAY_LENGTH_NV 0x8F33
+#define GL_DRAW_INDIRECT_UNIFIED_NV 0x8F40
+#define GL_DRAW_INDIRECT_ADDRESS_NV 0x8F41
+#define GL_DRAW_INDIRECT_LENGTH_NV 0x8F42
+#endif
+
+#ifndef GL_NV_texture_barrier
+#endif
+
+#ifndef GL_AMD_shader_stencil_export
+#endif
+
+#ifndef GL_AMD_seamless_cubemap_per_texture
+/* reuse GL_TEXTURE_CUBE_MAP_SEAMLESS_ARB */
+#endif
+
+#ifndef GL_AMD_conservative_depth
+#endif
+
+#ifndef GL_EXT_shader_image_load_store
+#define GL_MAX_IMAGE_UNITS_EXT 0x8F38
+#define GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS_EXT 0x8F39
+#define GL_IMAGE_BINDING_NAME_EXT 0x8F3A
+#define GL_IMAGE_BINDING_LEVEL_EXT 0x8F3B
+#define GL_IMAGE_BINDING_LAYERED_EXT 0x8F3C
+#define GL_IMAGE_BINDING_LAYER_EXT 0x8F3D
+#define GL_IMAGE_BINDING_ACCESS_EXT 0x8F3E
+#define GL_IMAGE_1D_EXT 0x904C
+#define GL_IMAGE_2D_EXT 0x904D
+#define GL_IMAGE_3D_EXT 0x904E
+#define GL_IMAGE_2D_RECT_EXT 0x904F
+#define GL_IMAGE_CUBE_EXT 0x9050
+#define GL_IMAGE_BUFFER_EXT 0x9051
+#define GL_IMAGE_1D_ARRAY_EXT 0x9052
+#define GL_IMAGE_2D_ARRAY_EXT 0x9053
+#define GL_IMAGE_CUBE_MAP_ARRAY_EXT 0x9054
+#define GL_IMAGE_2D_MULTISAMPLE_EXT 0x9055
+#define GL_IMAGE_2D_MULTISAMPLE_ARRAY_EXT 0x9056
+#define GL_INT_IMAGE_1D_EXT 0x9057
+#define GL_INT_IMAGE_2D_EXT 0x9058
+#define GL_INT_IMAGE_3D_EXT 0x9059
+#define GL_INT_IMAGE_2D_RECT_EXT 0x905A
+#define GL_INT_IMAGE_CUBE_EXT 0x905B
+#define GL_INT_IMAGE_BUFFER_EXT 0x905C
+#define GL_INT_IMAGE_1D_ARRAY_EXT 0x905D
+#define GL_INT_IMAGE_2D_ARRAY_EXT 0x905E
+#define GL_INT_IMAGE_CUBE_MAP_ARRAY_EXT 0x905F
+#define GL_INT_IMAGE_2D_MULTISAMPLE_EXT 0x9060
+#define GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY_EXT 0x9061
+#define GL_UNSIGNED_INT_IMAGE_1D_EXT 0x9062
+#define GL_UNSIGNED_INT_IMAGE_2D_EXT 0x9063
+#define GL_UNSIGNED_INT_IMAGE_3D_EXT 0x9064
+#define GL_UNSIGNED_INT_IMAGE_2D_RECT_EXT 0x9065
+#define GL_UNSIGNED_INT_IMAGE_CUBE_EXT 0x9066
+#define GL_UNSIGNED_INT_IMAGE_BUFFER_EXT 0x9067
+#define GL_UNSIGNED_INT_IMAGE_1D_ARRAY_EXT 0x9068
+#define GL_UNSIGNED_INT_IMAGE_2D_ARRAY_EXT 0x9069
+#define GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY_EXT 0x906A
+#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_EXT 0x906B
+#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY_EXT 0x906C
+#define GL_MAX_IMAGE_SAMPLES_EXT 0x906D
+#define GL_IMAGE_BINDING_FORMAT_EXT 0x906E
+#define GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT_EXT 0x00000001
+#define GL_ELEMENT_ARRAY_BARRIER_BIT_EXT 0x00000002
+#define GL_UNIFORM_BARRIER_BIT_EXT 0x00000004
+#define GL_TEXTURE_FETCH_BARRIER_BIT_EXT 0x00000008
+#define GL_SHADER_IMAGE_ACCESS_BARRIER_BIT_EXT 0x00000020
+#define GL_COMMAND_BARRIER_BIT_EXT 0x00000040
+#define GL_PIXEL_BUFFER_BARRIER_BIT_EXT 0x00000080
+#define GL_TEXTURE_UPDATE_BARRIER_BIT_EXT 0x00000100
+#define GL_BUFFER_UPDATE_BARRIER_BIT_EXT 0x00000200
+#define GL_FRAMEBUFFER_BARRIER_BIT_EXT 0x00000400
+#define GL_TRANSFORM_FEEDBACK_BARRIER_BIT_EXT 0x00000800
+#define GL_ATOMIC_COUNTER_BARRIER_BIT_EXT 0x00001000
+#define GL_ALL_BARRIER_BITS_EXT 0xFFFFFFFF
+#endif
+
+#ifndef GL_EXT_vertex_attrib_64bit
+/* reuse GL_DOUBLE */
+#define GL_DOUBLE_VEC2_EXT 0x8FFC
+#define GL_DOUBLE_VEC3_EXT 0x8FFD
+#define GL_DOUBLE_VEC4_EXT 0x8FFE
+#define GL_DOUBLE_MAT2_EXT 0x8F46
+#define GL_DOUBLE_MAT3_EXT 0x8F47
+#define GL_DOUBLE_MAT4_EXT 0x8F48
+#define GL_DOUBLE_MAT2x3_EXT 0x8F49
+#define GL_DOUBLE_MAT2x4_EXT 0x8F4A
+#define GL_DOUBLE_MAT3x2_EXT 0x8F4B
+#define GL_DOUBLE_MAT3x4_EXT 0x8F4C
+#define GL_DOUBLE_MAT4x2_EXT 0x8F4D
+#define GL_DOUBLE_MAT4x3_EXT 0x8F4E
+#endif
+
+#ifndef GL_NV_gpu_program5
+#define GL_MAX_GEOMETRY_PROGRAM_INVOCATIONS_NV 0x8E5A
+#define GL_MIN_FRAGMENT_INTERPOLATION_OFFSET_NV 0x8E5B
+#define GL_MAX_FRAGMENT_INTERPOLATION_OFFSET_NV 0x8E5C
+#define GL_FRAGMENT_PROGRAM_INTERPOLATION_OFFSET_BITS_NV 0x8E5D
+#define GL_MAX_PROGRAM_SUBROUTINE_PARAMETERS_NV 0x8F44
+#define GL_MAX_PROGRAM_SUBROUTINE_NUM_NV 0x8F45
+#endif
+
+#ifndef GL_NV_gpu_shader5
+#define GL_INT64_NV 0x140E
+#define GL_UNSIGNED_INT64_NV 0x140F
+#define GL_INT8_NV 0x8FE0
+#define GL_INT8_VEC2_NV 0x8FE1
+#define GL_INT8_VEC3_NV 0x8FE2
+#define GL_INT8_VEC4_NV 0x8FE3
+#define GL_INT16_NV 0x8FE4
+#define GL_INT16_VEC2_NV 0x8FE5
+#define GL_INT16_VEC3_NV 0x8FE6
+#define GL_INT16_VEC4_NV 0x8FE7
+#define GL_INT64_VEC2_NV 0x8FE9
+#define GL_INT64_VEC3_NV 0x8FEA
+#define GL_INT64_VEC4_NV 0x8FEB
+#define GL_UNSIGNED_INT8_NV 0x8FEC
+#define GL_UNSIGNED_INT8_VEC2_NV 0x8FED
+#define GL_UNSIGNED_INT8_VEC3_NV 0x8FEE
+#define GL_UNSIGNED_INT8_VEC4_NV 0x8FEF
+#define GL_UNSIGNED_INT16_NV 0x8FF0
+#define GL_UNSIGNED_INT16_VEC2_NV 0x8FF1
+#define GL_UNSIGNED_INT16_VEC3_NV 0x8FF2
+#define GL_UNSIGNED_INT16_VEC4_NV 0x8FF3
+#define GL_UNSIGNED_INT64_VEC2_NV 0x8FF5
+#define GL_UNSIGNED_INT64_VEC3_NV 0x8FF6
+#define GL_UNSIGNED_INT64_VEC4_NV 0x8FF7
+#define GL_FLOAT16_NV 0x8FF8
+#define GL_FLOAT16_VEC2_NV 0x8FF9
+#define GL_FLOAT16_VEC3_NV 0x8FFA
+#define GL_FLOAT16_VEC4_NV 0x8FFB
+/* reuse GL_PATCHES */
+#endif
+
+#ifndef GL_NV_shader_buffer_store
+#define GL_SHADER_GLOBAL_ACCESS_BARRIER_BIT_NV 0x00000010
+/* reuse GL_READ_WRITE */
+/* reuse GL_WRITE_ONLY */
+#endif
+
+#ifndef GL_NV_tessellation_program5
+#define GL_MAX_PROGRAM_PATCH_ATTRIBS_NV 0x86D8
+#define GL_TESS_CONTROL_PROGRAM_NV 0x891E
+#define GL_TESS_EVALUATION_PROGRAM_NV 0x891F
+#define GL_TESS_CONTROL_PROGRAM_PARAMETER_BUFFER_NV 0x8C74
+#define GL_TESS_EVALUATION_PROGRAM_PARAMETER_BUFFER_NV 0x8C75
+#endif
+
+#ifndef GL_NV_vertex_attrib_integer_64bit
+/* reuse GL_INT64_NV */
+/* reuse GL_UNSIGNED_INT64_NV */
+#endif
+
+#ifndef GL_NV_multisample_coverage
+#define GL_COVERAGE_SAMPLES_NV 0x80A9
+#define GL_COLOR_SAMPLES_NV 0x8E20
+#endif
+
+#ifndef GL_AMD_name_gen_delete
+#define GL_DATA_BUFFER_AMD 0x9151
+#define GL_PERFORMANCE_MONITOR_AMD 0x9152
+#define GL_QUERY_OBJECT_AMD 0x9153
+#define GL_VERTEX_ARRAY_OBJECT_AMD 0x9154
+#define GL_SAMPLER_OBJECT_AMD 0x9155
+#endif
+
+#ifndef GL_AMD_debug_output
+#define GL_MAX_DEBUG_LOGGED_MESSAGES_AMD 0x9144
+#define GL_DEBUG_LOGGED_MESSAGES_AMD 0x9145
+#define GL_DEBUG_SEVERITY_HIGH_AMD 0x9146
+#define GL_DEBUG_SEVERITY_MEDIUM_AMD 0x9147
+#define GL_DEBUG_SEVERITY_LOW_AMD 0x9148
+#define GL_DEBUG_CATEGORY_API_ERROR_AMD 0x9149
+#define GL_DEBUG_CATEGORY_WINDOW_SYSTEM_AMD 0x914A
+#define GL_DEBUG_CATEGORY_DEPRECATION_AMD 0x914B
+#define GL_DEBUG_CATEGORY_UNDEFINED_BEHAVIOR_AMD 0x914C
+#define GL_DEBUG_CATEGORY_PERFORMANCE_AMD 0x914D
+#define GL_DEBUG_CATEGORY_SHADER_COMPILER_AMD 0x914E
+#define GL_DEBUG_CATEGORY_APPLICATION_AMD 0x914F
+#define GL_DEBUG_CATEGORY_OTHER_AMD 0x9150
+#endif
+
+#ifndef GL_NV_vdpau_interop
+#define GL_SURFACE_STATE_NV 0x86EB
+#define GL_SURFACE_REGISTERED_NV 0x86FD
+#define GL_SURFACE_MAPPED_NV 0x8700
+#define GL_WRITE_DISCARD_NV 0x88BE
+#endif
+
+#ifndef GL_AMD_transform_feedback3_lines_triangles
+#endif
+
+
+/*************************************************************/
+
+#include <stddef.h>
+#ifndef GL_VERSION_2_0
+/* GL type for program/shader text */
+typedef char GLchar;
+#endif
+
+#ifndef GL_VERSION_1_5
+/* GL types for handling large vertex buffer objects */
+typedef ptrdiff_t GLintptr;
+typedef ptrdiff_t GLsizeiptr;
+#endif
+
+#ifndef GL_ARB_vertex_buffer_object
+/* GL types for handling large vertex buffer objects */
+typedef ptrdiff_t GLintptrARB;
+typedef ptrdiff_t GLsizeiptrARB;
+#endif
+
+#ifndef GL_ARB_shader_objects
+/* GL types for program/shader text and shader object handles */
+typedef char GLcharARB;
+typedef unsigned int GLhandleARB;
+#endif
+
+/* GL type for "half" precision (s10e5) float data in host memory */
+#ifndef GL_ARB_half_float_pixel
+typedef unsigned short GLhalfARB;
+#endif
+
+#ifndef GL_NV_half_float
+typedef unsigned short GLhalfNV;
+#endif
+
+#ifndef GLEXT_64_TYPES_DEFINED
+/* This code block is duplicated in glxext.h, so must be protected */
+#define GLEXT_64_TYPES_DEFINED
+/* Define int32_t, int64_t, and uint64_t types for UST/MSC */
+/* (as used in the GL_EXT_timer_query extension). */
+#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
+#include <inttypes.h>
+#elif defined(__sun__) || defined(__digital__)
+#include <inttypes.h>
+#if defined(__STDC__)
+#if defined(__arch64__) || defined(_LP64)
+typedef long int int64_t;
+typedef unsigned long int uint64_t;
+#else
+typedef long long int int64_t;
+typedef unsigned long long int uint64_t;
+#endif /* __arch64__ */
+#endif /* __STDC__ */
+#elif defined( __VMS ) || defined(__sgi)
+#include <inttypes.h>
+#elif defined(__SCO__) || defined(__USLC__)
+#include <stdint.h>
+#elif defined(__UNIXOS2__) || defined(__SOL64__)
+typedef long int int32_t;
+typedef long long int int64_t;
+typedef unsigned long long int uint64_t;
+#elif defined(_WIN32) && defined(__GNUC__)
+#include <stdint.h>
+#elif defined(_WIN32)
+typedef __int32 int32_t;
+typedef __int64 int64_t;
+typedef unsigned __int64 uint64_t;
+#else
+/* Fallback if nothing above works */
+#include <inttypes.h>
+#endif
+#endif
+
+#ifndef GL_EXT_timer_query
+typedef int64_t GLint64EXT;
+typedef uint64_t GLuint64EXT;
+#endif
+
+#ifndef GL_ARB_sync
+typedef int64_t GLint64;
+typedef uint64_t GLuint64;
+typedef struct __GLsync *GLsync;
+#endif
+
+#ifndef GL_ARB_cl_event
+/* These incomplete types let us declare types compatible with OpenCL's cl_context and cl_event */
+struct _cl_context;
+struct _cl_event;
+#endif
+
+#ifndef GL_ARB_debug_output
+typedef void (APIENTRY *GLDEBUGPROCARB)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,GLvoid *userParam);
+#endif
+
+#ifndef GL_AMD_debug_output
+typedef void (APIENTRY *GLDEBUGPROCAMD)(GLuint id,GLenum category,GLenum severity,GLsizei length,const GLchar *message,GLvoid *userParam);
+#endif
+
+#ifndef GL_NV_vdpau_interop
+typedef GLintptr GLvdpauSurfaceNV;
+#endif
+
+#ifndef GL_VERSION_1_2
+#define GL_VERSION_1_2 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBlendColor (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+GLAPI void APIENTRY glBlendEquation (GLenum mode);
+GLAPI void APIENTRY glDrawRangeElements (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices);
+GLAPI void APIENTRY glTexImage3D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+GLAPI void APIENTRY glTexSubImage3D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels);
+GLAPI void APIENTRY glCopyTexSubImage3D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBLENDCOLORPROC) (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+typedef void (APIENTRYP PFNGLBLENDEQUATIONPROC) (GLenum mode);
+typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices);
+typedef void (APIENTRYP PFNGLTEXIMAGE3DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+typedef void (APIENTRYP PFNGLTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels);
+typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+#endif
+
+#ifndef GL_VERSION_1_2_DEPRECATED
+#define GL_VERSION_1_2_DEPRECATED 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glColorTable (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *table);
+GLAPI void APIENTRY glColorTableParameterfv (GLenum target, GLenum pname, const GLfloat *params);
+GLAPI void APIENTRY glColorTableParameteriv (GLenum target, GLenum pname, const GLint *params);
+GLAPI void APIENTRY glCopyColorTable (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);
+GLAPI void APIENTRY glGetColorTable (GLenum target, GLenum format, GLenum type, GLvoid *table);
+GLAPI void APIENTRY glGetColorTableParameterfv (GLenum target, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetColorTableParameteriv (GLenum target, GLenum pname, GLint *params);
+GLAPI void APIENTRY glColorSubTable (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const GLvoid *data);
+GLAPI void APIENTRY glCopyColorSubTable (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width);
+GLAPI void APIENTRY glConvolutionFilter1D (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *image);
+GLAPI void APIENTRY glConvolutionFilter2D (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *image);
+GLAPI void APIENTRY glConvolutionParameterf (GLenum target, GLenum pname, GLfloat params);
+GLAPI void APIENTRY glConvolutionParameterfv (GLenum target, GLenum pname, const GLfloat *params);
+GLAPI void APIENTRY glConvolutionParameteri (GLenum target, GLenum pname, GLint params);
+GLAPI void APIENTRY glConvolutionParameteriv (GLenum target, GLenum pname, const GLint *params);
+GLAPI void APIENTRY glCopyConvolutionFilter1D (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);
+GLAPI void APIENTRY glCopyConvolutionFilter2D (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height);
+GLAPI void APIENTRY glGetConvolutionFilter (GLenum target, GLenum format, GLenum type, GLvoid *image);
+GLAPI void APIENTRY glGetConvolutionParameterfv (GLenum target, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetConvolutionParameteriv (GLenum target, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetSeparableFilter (GLenum target, GLenum format, GLenum type, GLvoid *row, GLvoid *column, GLvoid *span);
+GLAPI void APIENTRY glSeparableFilter2D (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *row, const GLvoid *column);
+GLAPI void APIENTRY glGetHistogram (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values);
+GLAPI void APIENTRY glGetHistogramParameterfv (GLenum target, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetHistogramParameteriv (GLenum target, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetMinmax (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values);
+GLAPI void APIENTRY glGetMinmaxParameterfv (GLenum target, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetMinmaxParameteriv (GLenum target, GLenum pname, GLint *params);
+GLAPI void APIENTRY glHistogram (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink);
+GLAPI void APIENTRY glMinmax (GLenum target, GLenum internalformat, GLboolean sink);
+GLAPI void APIENTRY glResetHistogram (GLenum target);
+GLAPI void APIENTRY glResetMinmax (GLenum target);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCOLORTABLEPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *table);
+typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERFVPROC) (GLenum target, GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERIVPROC) (GLenum target, GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLCOPYCOLORTABLEPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);
+typedef void (APIENTRYP PFNGLGETCOLORTABLEPROC) (GLenum target, GLenum format, GLenum type, GLvoid *table);
+typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLCOLORSUBTABLEPROC) (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const GLvoid *data);
+typedef void (APIENTRYP PFNGLCOPYCOLORSUBTABLEPROC) (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width);
+typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER1DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *image);
+typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER2DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *image);
+typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFPROC) (GLenum target, GLenum pname, GLfloat params);
+typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFVPROC) (GLenum target, GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIPROC) (GLenum target, GLenum pname, GLint params);
+typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIVPROC) (GLenum target, GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER1DPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);
+typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER2DPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height);
+typedef void (APIENTRYP PFNGLGETCONVOLUTIONFILTERPROC) (GLenum target, GLenum format, GLenum type, GLvoid *image);
+typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETSEPARABLEFILTERPROC) (GLenum target, GLenum format, GLenum type, GLvoid *row, GLvoid *column, GLvoid *span);
+typedef void (APIENTRYP PFNGLSEPARABLEFILTER2DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *row, const GLvoid *column);
+typedef void (APIENTRYP PFNGLGETHISTOGRAMPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values);
+typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETMINMAXPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values);
+typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLHISTOGRAMPROC) (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink);
+typedef void (APIENTRYP PFNGLMINMAXPROC) (GLenum target, GLenum internalformat, GLboolean sink);
+typedef void (APIENTRYP PFNGLRESETHISTOGRAMPROC) (GLenum target);
+typedef void (APIENTRYP PFNGLRESETMINMAXPROC) (GLenum target);
+#endif
+
+#ifndef GL_VERSION_1_3
+#define GL_VERSION_1_3 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glActiveTexture (GLenum texture);
+GLAPI void APIENTRY glSampleCoverage (GLclampf value, GLboolean invert);
+GLAPI void APIENTRY glCompressedTexImage3D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data);
+GLAPI void APIENTRY glCompressedTexImage2D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data);
+GLAPI void APIENTRY glCompressedTexImage1D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *data);
+GLAPI void APIENTRY glCompressedTexSubImage3D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data);
+GLAPI void APIENTRY glCompressedTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data);
+GLAPI void APIENTRY glCompressedTexSubImage1D (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data);
+GLAPI void APIENTRY glGetCompressedTexImage (GLenum target, GLint level, GLvoid *img);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLACTIVETEXTUREPROC) (GLenum texture);
+typedef void (APIENTRYP PFNGLSAMPLECOVERAGEPROC) (GLclampf value, GLboolean invert);
+typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data);
+typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data);
+typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *data);
+typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data);
+typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data);
+typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data);
+typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEPROC) (GLenum target, GLint level, GLvoid *img);
+#endif
+
+#ifndef GL_VERSION_1_3_DEPRECATED
+#define GL_VERSION_1_3_DEPRECATED 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glClientActiveTexture (GLenum texture);
+GLAPI void APIENTRY glMultiTexCoord1d (GLenum target, GLdouble s);
+GLAPI void APIENTRY glMultiTexCoord1dv (GLenum target, const GLdouble *v);
+GLAPI void APIENTRY glMultiTexCoord1f (GLenum target, GLfloat s);
+GLAPI void APIENTRY glMultiTexCoord1fv (GLenum target, const GLfloat *v);
+GLAPI void APIENTRY glMultiTexCoord1i (GLenum target, GLint s);
+GLAPI void APIENTRY glMultiTexCoord1iv (GLenum target, const GLint *v);
+GLAPI void APIENTRY glMultiTexCoord1s (GLenum target, GLshort s);
+GLAPI void APIENTRY glMultiTexCoord1sv (GLenum target, const GLshort *v);
+GLAPI void APIENTRY glMultiTexCoord2d (GLenum target, GLdouble s, GLdouble t);
+GLAPI void APIENTRY glMultiTexCoord2dv (GLenum target, const GLdouble *v);
+GLAPI void APIENTRY glMultiTexCoord2f (GLenum target, GLfloat s, GLfloat t);
+GLAPI void APIENTRY glMultiTexCoord2fv (GLenum target, const GLfloat *v);
+GLAPI void APIENTRY glMultiTexCoord2i (GLenum target, GLint s, GLint t);
+GLAPI void APIENTRY glMultiTexCoord2iv (GLenum target, const GLint *v);
+GLAPI void APIENTRY glMultiTexCoord2s (GLenum target, GLshort s, GLshort t);
+GLAPI void APIENTRY glMultiTexCoord2sv (GLenum target, const GLshort *v);
+GLAPI void APIENTRY glMultiTexCoord3d (GLenum target, GLdouble s, GLdouble t, GLdouble r);
+GLAPI void APIENTRY glMultiTexCoord3dv (GLenum target, const GLdouble *v);
+GLAPI void APIENTRY glMultiTexCoord3f (GLenum target, GLfloat s, GLfloat t, GLfloat r);
+GLAPI void APIENTRY glMultiTexCoord3fv (GLenum target, const GLfloat *v);
+GLAPI void APIENTRY glMultiTexCoord3i (GLenum target, GLint s, GLint t, GLint r);
+GLAPI void APIENTRY glMultiTexCoord3iv (GLenum target, const GLint *v);
+GLAPI void APIENTRY glMultiTexCoord3s (GLenum target, GLshort s, GLshort t, GLshort r);
+GLAPI void APIENTRY glMultiTexCoord3sv (GLenum target, const GLshort *v);
+GLAPI void APIENTRY glMultiTexCoord4d (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q);
+GLAPI void APIENTRY glMultiTexCoord4dv (GLenum target, const GLdouble *v);
+GLAPI void APIENTRY glMultiTexCoord4f (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q);
+GLAPI void APIENTRY glMultiTexCoord4fv (GLenum target, const GLfloat *v);
+GLAPI void APIENTRY glMultiTexCoord4i (GLenum target, GLint s, GLint t, GLint r, GLint q);
+GLAPI void APIENTRY glMultiTexCoord4iv (GLenum target, const GLint *v);
+GLAPI void APIENTRY glMultiTexCoord4s (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q);
+GLAPI void APIENTRY glMultiTexCoord4sv (GLenum target, const GLshort *v);
+GLAPI void APIENTRY glLoadTransposeMatrixf (const GLfloat *m);
+GLAPI void APIENTRY glLoadTransposeMatrixd (const GLdouble *m);
+GLAPI void APIENTRY glMultTransposeMatrixf (const GLfloat *m);
+GLAPI void APIENTRY glMultTransposeMatrixd (const GLdouble *m);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREPROC) (GLenum texture);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1DPROC) (GLenum target, GLdouble s);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1DVPROC) (GLenum target, const GLdouble *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1FPROC) (GLenum target, GLfloat s);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1FVPROC) (GLenum target, const GLfloat *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1IPROC) (GLenum target, GLint s);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1IVPROC) (GLenum target, const GLint *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1SPROC) (GLenum target, GLshort s);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1SVPROC) (GLenum target, const GLshort *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2DPROC) (GLenum target, GLdouble s, GLdouble t);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2DVPROC) (GLenum target, const GLdouble *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2FPROC) (GLenum target, GLfloat s, GLfloat t);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2FVPROC) (GLenum target, const GLfloat *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2IPROC) (GLenum target, GLint s, GLint t);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2IVPROC) (GLenum target, const GLint *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2SPROC) (GLenum target, GLshort s, GLshort t);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2SVPROC) (GLenum target, const GLshort *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3DPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3DVPROC) (GLenum target, const GLdouble *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3FPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3FVPROC) (GLenum target, const GLfloat *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3IPROC) (GLenum target, GLint s, GLint t, GLint r);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3IVPROC) (GLenum target, const GLint *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3SPROC) (GLenum target, GLshort s, GLshort t, GLshort r);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3SVPROC) (GLenum target, const GLshort *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4DPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4DVPROC) (GLenum target, const GLdouble *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4FPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4FVPROC) (GLenum target, const GLfloat *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4IPROC) (GLenum target, GLint s, GLint t, GLint r, GLint q);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4IVPROC) (GLenum target, const GLint *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4SPROC) (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4SVPROC) (GLenum target, const GLshort *v);
+typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXFPROC) (const GLfloat *m);
+typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXDPROC) (const GLdouble *m);
+typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXFPROC) (const GLfloat *m);
+typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXDPROC) (const GLdouble *m);
+#endif
+
+#ifndef GL_VERSION_1_4
+#define GL_VERSION_1_4 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBlendFuncSeparate (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
+GLAPI void APIENTRY glMultiDrawArrays (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount);
+GLAPI void APIENTRY glMultiDrawElements (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount);
+GLAPI void APIENTRY glPointParameterf (GLenum pname, GLfloat param);
+GLAPI void APIENTRY glPointParameterfv (GLenum pname, const GLfloat *params);
+GLAPI void APIENTRY glPointParameteri (GLenum pname, GLint param);
+GLAPI void APIENTRY glPointParameteriv (GLenum pname, const GLint *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
+typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSPROC) (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount);
+typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSPROC) (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount);
+typedef void (APIENTRYP PFNGLPOINTPARAMETERFPROC) (GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLPOINTPARAMETERFVPROC) (GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLPOINTPARAMETERIPROC) (GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLPOINTPARAMETERIVPROC) (GLenum pname, const GLint *params);
+#endif
+
+#ifndef GL_VERSION_1_4_DEPRECATED
+#define GL_VERSION_1_4_DEPRECATED 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glFogCoordf (GLfloat coord);
+GLAPI void APIENTRY glFogCoordfv (const GLfloat *coord);
+GLAPI void APIENTRY glFogCoordd (GLdouble coord);
+GLAPI void APIENTRY glFogCoorddv (const GLdouble *coord);
+GLAPI void APIENTRY glFogCoordPointer (GLenum type, GLsizei stride, const GLvoid *pointer);
+GLAPI void APIENTRY glSecondaryColor3b (GLbyte red, GLbyte green, GLbyte blue);
+GLAPI void APIENTRY glSecondaryColor3bv (const GLbyte *v);
+GLAPI void APIENTRY glSecondaryColor3d (GLdouble red, GLdouble green, GLdouble blue);
+GLAPI void APIENTRY glSecondaryColor3dv (const GLdouble *v);
+GLAPI void APIENTRY glSecondaryColor3f (GLfloat red, GLfloat green, GLfloat blue);
+GLAPI void APIENTRY glSecondaryColor3fv (const GLfloat *v);
+GLAPI void APIENTRY glSecondaryColor3i (GLint red, GLint green, GLint blue);
+GLAPI void APIENTRY glSecondaryColor3iv (const GLint *v);
+GLAPI void APIENTRY glSecondaryColor3s (GLshort red, GLshort green, GLshort blue);
+GLAPI void APIENTRY glSecondaryColor3sv (const GLshort *v);
+GLAPI void APIENTRY glSecondaryColor3ub (GLubyte red, GLubyte green, GLubyte blue);
+GLAPI void APIENTRY glSecondaryColor3ubv (const GLubyte *v);
+GLAPI void APIENTRY glSecondaryColor3ui (GLuint red, GLuint green, GLuint blue);
+GLAPI void APIENTRY glSecondaryColor3uiv (const GLuint *v);
+GLAPI void APIENTRY glSecondaryColor3us (GLushort red, GLushort green, GLushort blue);
+GLAPI void APIENTRY glSecondaryColor3usv (const GLushort *v);
+GLAPI void APIENTRY glSecondaryColorPointer (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+GLAPI void APIENTRY glWindowPos2d (GLdouble x, GLdouble y);
+GLAPI void APIENTRY glWindowPos2dv (const GLdouble *v);
+GLAPI void APIENTRY glWindowPos2f (GLfloat x, GLfloat y);
+GLAPI void APIENTRY glWindowPos2fv (const GLfloat *v);
+GLAPI void APIENTRY glWindowPos2i (GLint x, GLint y);
+GLAPI void APIENTRY glWindowPos2iv (const GLint *v);
+GLAPI void APIENTRY glWindowPos2s (GLshort x, GLshort y);
+GLAPI void APIENTRY glWindowPos2sv (const GLshort *v);
+GLAPI void APIENTRY glWindowPos3d (GLdouble x, GLdouble y, GLdouble z);
+GLAPI void APIENTRY glWindowPos3dv (const GLdouble *v);
+GLAPI void APIENTRY glWindowPos3f (GLfloat x, GLfloat y, GLfloat z);
+GLAPI void APIENTRY glWindowPos3fv (const GLfloat *v);
+GLAPI void APIENTRY glWindowPos3i (GLint x, GLint y, GLint z);
+GLAPI void APIENTRY glWindowPos3iv (const GLint *v);
+GLAPI void APIENTRY glWindowPos3s (GLshort x, GLshort y, GLshort z);
+GLAPI void APIENTRY glWindowPos3sv (const GLshort *v);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLFOGCOORDFPROC) (GLfloat coord);
+typedef void (APIENTRYP PFNGLFOGCOORDFVPROC) (const GLfloat *coord);
+typedef void (APIENTRYP PFNGLFOGCOORDDPROC) (GLdouble coord);
+typedef void (APIENTRYP PFNGLFOGCOORDDVPROC) (const GLdouble *coord);
+typedef void (APIENTRYP PFNGLFOGCOORDPOINTERPROC) (GLenum type, GLsizei stride, const GLvoid *pointer);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BPROC) (GLbyte red, GLbyte green, GLbyte blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVPROC) (const GLbyte *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DPROC) (GLdouble red, GLdouble green, GLdouble blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DVPROC) (const GLdouble *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FPROC) (GLfloat red, GLfloat green, GLfloat blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FVPROC) (const GLfloat *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IPROC) (GLint red, GLint green, GLint blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IVPROC) (const GLint *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SPROC) (GLshort red, GLshort green, GLshort blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SVPROC) (const GLshort *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBPROC) (GLubyte red, GLubyte green, GLubyte blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBVPROC) (const GLubyte *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIPROC) (GLuint red, GLuint green, GLuint blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIVPROC) (const GLuint *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USPROC) (GLushort red, GLushort green, GLushort blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USVPROC) (const GLushort *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERPROC) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+typedef void (APIENTRYP PFNGLWINDOWPOS2DPROC) (GLdouble x, GLdouble y);
+typedef void (APIENTRYP PFNGLWINDOWPOS2DVPROC) (const GLdouble *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS2FPROC) (GLfloat x, GLfloat y);
+typedef void (APIENTRYP PFNGLWINDOWPOS2FVPROC) (const GLfloat *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS2IPROC) (GLint x, GLint y);
+typedef void (APIENTRYP PFNGLWINDOWPOS2IVPROC) (const GLint *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS2SPROC) (GLshort x, GLshort y);
+typedef void (APIENTRYP PFNGLWINDOWPOS2SVPROC) (const GLshort *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS3DPROC) (GLdouble x, GLdouble y, GLdouble z);
+typedef void (APIENTRYP PFNGLWINDOWPOS3DVPROC) (const GLdouble *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS3FPROC) (GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLWINDOWPOS3FVPROC) (const GLfloat *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS3IPROC) (GLint x, GLint y, GLint z);
+typedef void (APIENTRYP PFNGLWINDOWPOS3IVPROC) (const GLint *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS3SPROC) (GLshort x, GLshort y, GLshort z);
+typedef void (APIENTRYP PFNGLWINDOWPOS3SVPROC) (const GLshort *v);
+#endif
+
+#ifndef GL_VERSION_1_5
+#define GL_VERSION_1_5 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glGenQueries (GLsizei n, GLuint *ids);
+GLAPI void APIENTRY glDeleteQueries (GLsizei n, const GLuint *ids);
+GLAPI GLboolean APIENTRY glIsQuery (GLuint id);
+GLAPI void APIENTRY glBeginQuery (GLenum target, GLuint id);
+GLAPI void APIENTRY glEndQuery (GLenum target);
+GLAPI void APIENTRY glGetQueryiv (GLenum target, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetQueryObjectiv (GLuint id, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetQueryObjectuiv (GLuint id, GLenum pname, GLuint *params);
+GLAPI void APIENTRY glBindBuffer (GLenum target, GLuint buffer);
+GLAPI void APIENTRY glDeleteBuffers (GLsizei n, const GLuint *buffers);
+GLAPI void APIENTRY glGenBuffers (GLsizei n, GLuint *buffers);
+GLAPI GLboolean APIENTRY glIsBuffer (GLuint buffer);
+GLAPI void APIENTRY glBufferData (GLenum target, GLsizeiptr size, const GLvoid *data, GLenum usage);
+GLAPI void APIENTRY glBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid *data);
+GLAPI void APIENTRY glGetBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, GLvoid *data);
+GLAPI GLvoid* APIENTRY glMapBuffer (GLenum target, GLenum access);
+GLAPI GLboolean APIENTRY glUnmapBuffer (GLenum target);
+GLAPI void APIENTRY glGetBufferParameteriv (GLenum target, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetBufferPointerv (GLenum target, GLenum pname, GLvoid* *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLGENQUERIESPROC) (GLsizei n, GLuint *ids);
+typedef void (APIENTRYP PFNGLDELETEQUERIESPROC) (GLsizei n, const GLuint *ids);
+typedef GLboolean (APIENTRYP PFNGLISQUERYPROC) (GLuint id);
+typedef void (APIENTRYP PFNGLBEGINQUERYPROC) (GLenum target, GLuint id);
+typedef void (APIENTRYP PFNGLENDQUERYPROC) (GLenum target);
+typedef void (APIENTRYP PFNGLGETQUERYIVPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETQUERYOBJECTIVPROC) (GLuint id, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVPROC) (GLuint id, GLenum pname, GLuint *params);
+typedef void (APIENTRYP PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer);
+typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers);
+typedef void (APIENTRYP PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers);
+typedef GLboolean (APIENTRYP PFNGLISBUFFERPROC) (GLuint buffer);
+typedef void (APIENTRYP PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const GLvoid *data, GLenum usage);
+typedef void (APIENTRYP PFNGLBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid *data);
+typedef void (APIENTRYP PFNGLGETBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, GLvoid *data);
+typedef GLvoid* (APIENTRYP PFNGLMAPBUFFERPROC) (GLenum target, GLenum access);
+typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERPROC) (GLenum target);
+typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVPROC) (GLenum target, GLenum pname, GLvoid* *params);
+#endif
+
+#ifndef GL_VERSION_2_0
+#define GL_VERSION_2_0 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBlendEquationSeparate (GLenum modeRGB, GLenum modeAlpha);
+GLAPI void APIENTRY glDrawBuffers (GLsizei n, const GLenum *bufs);
+GLAPI void APIENTRY glStencilOpSeparate (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass);
+GLAPI void APIENTRY glStencilFuncSeparate (GLenum face, GLenum func, GLint ref, GLuint mask);
+GLAPI void APIENTRY glStencilMaskSeparate (GLenum face, GLuint mask);
+GLAPI void APIENTRY glAttachShader (GLuint program, GLuint shader);
+GLAPI void APIENTRY glBindAttribLocation (GLuint program, GLuint index, const GLchar *name);
+GLAPI void APIENTRY glCompileShader (GLuint shader);
+GLAPI GLuint APIENTRY glCreateProgram (void);
+GLAPI GLuint APIENTRY glCreateShader (GLenum type);
+GLAPI void APIENTRY glDeleteProgram (GLuint program);
+GLAPI void APIENTRY glDeleteShader (GLuint shader);
+GLAPI void APIENTRY glDetachShader (GLuint program, GLuint shader);
+GLAPI void APIENTRY glDisableVertexAttribArray (GLuint index);
+GLAPI void APIENTRY glEnableVertexAttribArray (GLuint index);
+GLAPI void APIENTRY glGetActiveAttrib (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name);
+GLAPI void APIENTRY glGetActiveUniform (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name);
+GLAPI void APIENTRY glGetAttachedShaders (GLuint program, GLsizei maxCount, GLsizei *count, GLuint *obj);
+GLAPI GLint APIENTRY glGetAttribLocation (GLuint program, const GLchar *name);
+GLAPI void APIENTRY glGetProgramiv (GLuint program, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetProgramInfoLog (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
+GLAPI void APIENTRY glGetShaderiv (GLuint shader, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetShaderInfoLog (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
+GLAPI void APIENTRY glGetShaderSource (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source);
+GLAPI GLint APIENTRY glGetUniformLocation (GLuint program, const GLchar *name);
+GLAPI void APIENTRY glGetUniformfv (GLuint program, GLint location, GLfloat *params);
+GLAPI void APIENTRY glGetUniformiv (GLuint program, GLint location, GLint *params);
+GLAPI void APIENTRY glGetVertexAttribdv (GLuint index, GLenum pname, GLdouble *params);
+GLAPI void APIENTRY glGetVertexAttribfv (GLuint index, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetVertexAttribiv (GLuint index, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetVertexAttribPointerv (GLuint index, GLenum pname, GLvoid* *pointer);
+GLAPI GLboolean APIENTRY glIsProgram (GLuint program);
+GLAPI GLboolean APIENTRY glIsShader (GLuint shader);
+GLAPI void APIENTRY glLinkProgram (GLuint program);
+GLAPI void APIENTRY glShaderSource (GLuint shader, GLsizei count, const GLchar* *string, const GLint *length);
+GLAPI void APIENTRY glUseProgram (GLuint program);
+GLAPI void APIENTRY glUniform1f (GLint location, GLfloat v0);
+GLAPI void APIENTRY glUniform2f (GLint location, GLfloat v0, GLfloat v1);
+GLAPI void APIENTRY glUniform3f (GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
+GLAPI void APIENTRY glUniform4f (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
+GLAPI void APIENTRY glUniform1i (GLint location, GLint v0);
+GLAPI void APIENTRY glUniform2i (GLint location, GLint v0, GLint v1);
+GLAPI void APIENTRY glUniform3i (GLint location, GLint v0, GLint v1, GLint v2);
+GLAPI void APIENTRY glUniform4i (GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
+GLAPI void APIENTRY glUniform1fv (GLint location, GLsizei count, const GLfloat *value);
+GLAPI void APIENTRY glUniform2fv (GLint location, GLsizei count, const GLfloat *value);
+GLAPI void APIENTRY glUniform3fv (GLint location, GLsizei count, const GLfloat *value);
+GLAPI void APIENTRY glUniform4fv (GLint location, GLsizei count, const GLfloat *value);
+GLAPI void APIENTRY glUniform1iv (GLint location, GLsizei count, const GLint *value);
+GLAPI void APIENTRY glUniform2iv (GLint location, GLsizei count, const GLint *value);
+GLAPI void APIENTRY glUniform3iv (GLint location, GLsizei count, const GLint *value);
+GLAPI void APIENTRY glUniform4iv (GLint location, GLsizei count, const GLint *value);
+GLAPI void APIENTRY glUniformMatrix2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GLAPI void APIENTRY glUniformMatrix3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GLAPI void APIENTRY glUniformMatrix4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GLAPI void APIENTRY glValidateProgram (GLuint program);
+GLAPI void APIENTRY glVertexAttrib1d (GLuint index, GLdouble x);
+GLAPI void APIENTRY glVertexAttrib1dv (GLuint index, const GLdouble *v);
+GLAPI void APIENTRY glVertexAttrib1f (GLuint index, GLfloat x);
+GLAPI void APIENTRY glVertexAttrib1fv (GLuint index, const GLfloat *v);
+GLAPI void APIENTRY glVertexAttrib1s (GLuint index, GLshort x);
+GLAPI void APIENTRY glVertexAttrib1sv (GLuint index, const GLshort *v);
+GLAPI void APIENTRY glVertexAttrib2d (GLuint index, GLdouble x, GLdouble y);
+GLAPI void APIENTRY glVertexAttrib2dv (GLuint index, const GLdouble *v);
+GLAPI void APIENTRY glVertexAttrib2f (GLuint index, GLfloat x, GLfloat y);
+GLAPI void APIENTRY glVertexAttrib2fv (GLuint index, const GLfloat *v);
+GLAPI void APIENTRY glVertexAttrib2s (GLuint index, GLshort x, GLshort y);
+GLAPI void APIENTRY glVertexAttrib2sv (GLuint index, const GLshort *v);
+GLAPI void APIENTRY glVertexAttrib3d (GLuint index, GLdouble x, GLdouble y, GLdouble z);
+GLAPI void APIENTRY glVertexAttrib3dv (GLuint index, const GLdouble *v);
+GLAPI void APIENTRY glVertexAttrib3f (GLuint index, GLfloat x, GLfloat y, GLfloat z);
+GLAPI void APIENTRY glVertexAttrib3fv (GLuint index, const GLfloat *v);
+GLAPI void APIENTRY glVertexAttrib3s (GLuint index, GLshort x, GLshort y, GLshort z);
+GLAPI void APIENTRY glVertexAttrib3sv (GLuint index, const GLshort *v);
+GLAPI void APIENTRY glVertexAttrib4Nbv (GLuint index, const GLbyte *v);
+GLAPI void APIENTRY glVertexAttrib4Niv (GLuint index, const GLint *v);
+GLAPI void APIENTRY glVertexAttrib4Nsv (GLuint index, const GLshort *v);
+GLAPI void APIENTRY glVertexAttrib4Nub (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w);
+GLAPI void APIENTRY glVertexAttrib4Nubv (GLuint index, const GLubyte *v);
+GLAPI void APIENTRY glVertexAttrib4Nuiv (GLuint index, const GLuint *v);
+GLAPI void APIENTRY glVertexAttrib4Nusv (GLuint index, const GLushort *v);
+GLAPI void APIENTRY glVertexAttrib4bv (GLuint index, const GLbyte *v);
+GLAPI void APIENTRY glVertexAttrib4d (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+GLAPI void APIENTRY glVertexAttrib4dv (GLuint index, const GLdouble *v);
+GLAPI void APIENTRY glVertexAttrib4f (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+GLAPI void APIENTRY glVertexAttrib4fv (GLuint index, const GLfloat *v);
+GLAPI void APIENTRY glVertexAttrib4iv (GLuint index, const GLint *v);
+GLAPI void APIENTRY glVertexAttrib4s (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w);
+GLAPI void APIENTRY glVertexAttrib4sv (GLuint index, const GLshort *v);
+GLAPI void APIENTRY glVertexAttrib4ubv (GLuint index, const GLubyte *v);
+GLAPI void APIENTRY glVertexAttrib4uiv (GLuint index, const GLuint *v);
+GLAPI void APIENTRY glVertexAttrib4usv (GLuint index, const GLushort *v);
+GLAPI void APIENTRY glVertexAttribPointer (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC) (GLenum modeRGB, GLenum modeAlpha);
+typedef void (APIENTRYP PFNGLDRAWBUFFERSPROC) (GLsizei n, const GLenum *bufs);
+typedef void (APIENTRYP PFNGLSTENCILOPSEPARATEPROC) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass);
+typedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEPROC) (GLenum face, GLenum func, GLint ref, GLuint mask);
+typedef void (APIENTRYP PFNGLSTENCILMASKSEPARATEPROC) (GLenum face, GLuint mask);
+typedef void (APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader);
+typedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONPROC) (GLuint program, GLuint index, const GLchar *name);
+typedef void (APIENTRYP PFNGLCOMPILESHADERPROC) (GLuint shader);
+typedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC) (void);
+typedef GLuint (APIENTRYP PFNGLCREATESHADERPROC) (GLenum type);
+typedef void (APIENTRYP PFNGLDELETEPROGRAMPROC) (GLuint program);
+typedef void (APIENTRYP PFNGLDELETESHADERPROC) (GLuint shader);
+typedef void (APIENTRYP PFNGLDETACHSHADERPROC) (GLuint program, GLuint shader);
+typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC) (GLuint index);
+typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index);
+typedef void (APIENTRYP PFNGLGETACTIVEATTRIBPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name);
+typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name);
+typedef void (APIENTRYP PFNGLGETATTACHEDSHADERSPROC) (GLuint program, GLsizei maxCount, GLsizei *count, GLuint *obj);
+typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const GLchar *name);
+typedef void (APIENTRYP PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
+typedef void (APIENTRYP PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
+typedef void (APIENTRYP PFNGLGETSHADERSOURCEPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source);
+typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const GLchar *name);
+typedef void (APIENTRYP PFNGLGETUNIFORMFVPROC) (GLuint program, GLint location, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETUNIFORMIVPROC) (GLuint program, GLint location, GLint *params);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVPROC) (GLuint index, GLenum pname, GLdouble *params);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVPROC) (GLuint index, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVPROC) (GLuint index, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC) (GLuint index, GLenum pname, GLvoid* *pointer);
+typedef GLboolean (APIENTRYP PFNGLISPROGRAMPROC) (GLuint program);
+typedef GLboolean (APIENTRYP PFNGLISSHADERPROC) (GLuint shader);
+typedef void (APIENTRYP PFNGLLINKPROGRAMPROC) (GLuint program);
+typedef void (APIENTRYP PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const GLchar* *string, const GLint *length);
+typedef void (APIENTRYP PFNGLUSEPROGRAMPROC) (GLuint program);
+typedef void (APIENTRYP PFNGLUNIFORM1FPROC) (GLint location, GLfloat v0);
+typedef void (APIENTRYP PFNGLUNIFORM2FPROC) (GLint location, GLfloat v0, GLfloat v1);
+typedef void (APIENTRYP PFNGLUNIFORM3FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
+typedef void (APIENTRYP PFNGLUNIFORM4FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
+typedef void (APIENTRYP PFNGLUNIFORM1IPROC) (GLint location, GLint v0);
+typedef void (APIENTRYP PFNGLUNIFORM2IPROC) (GLint location, GLint v0, GLint v1);
+typedef void (APIENTRYP PFNGLUNIFORM3IPROC) (GLint location, GLint v0, GLint v1, GLint v2);
+typedef void (APIENTRYP PFNGLUNIFORM4IPROC) (GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
+typedef void (APIENTRYP PFNGLUNIFORM1FVPROC) (GLint location, GLsizei count, const GLfloat *value);
+typedef void (APIENTRYP PFNGLUNIFORM2FVPROC) (GLint location, GLsizei count, const GLfloat *value);
+typedef void (APIENTRYP PFNGLUNIFORM3FVPROC) (GLint location, GLsizei count, const GLfloat *value);
+typedef void (APIENTRYP PFNGLUNIFORM4FVPROC) (GLint location, GLsizei count, const GLfloat *value);
+typedef void (APIENTRYP PFNGLUNIFORM1IVPROC) (GLint location, GLsizei count, const GLint *value);
+typedef void (APIENTRYP PFNGLUNIFORM2IVPROC) (GLint location, GLsizei count, const GLint *value);
+typedef void (APIENTRYP PFNGLUNIFORM3IVPROC) (GLint location, GLsizei count, const GLint *value);
+typedef void (APIENTRYP PFNGLUNIFORM4IVPROC) (GLint location, GLsizei count, const GLint *value);
+typedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLVALIDATEPROGRAMPROC) (GLuint program);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1DPROC) (GLuint index, GLdouble x);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVPROC) (GLuint index, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1FPROC) (GLuint index, GLfloat x);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVPROC) (GLuint index, const GLfloat *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1SPROC) (GLuint index, GLshort x);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVPROC) (GLuint index, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2DPROC) (GLuint index, GLdouble x, GLdouble y);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVPROC) (GLuint index, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2FPROC) (GLuint index, GLfloat x, GLfloat y);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVPROC) (GLuint index, const GLfloat *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2SPROC) (GLuint index, GLshort x, GLshort y);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVPROC) (GLuint index, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVPROC) (GLuint index, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVPROC) (GLuint index, const GLfloat *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3SPROC) (GLuint index, GLshort x, GLshort y, GLshort z);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVPROC) (GLuint index, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVPROC) (GLuint index, const GLbyte *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVPROC) (GLuint index, const GLint *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVPROC) (GLuint index, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVPROC) (GLuint index, const GLubyte *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVPROC) (GLuint index, const GLuint *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVPROC) (GLuint index, const GLushort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4BVPROC) (GLuint index, const GLbyte *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVPROC) (GLuint index, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVPROC) (GLuint index, const GLfloat *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4IVPROC) (GLuint index, const GLint *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4SPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVPROC) (GLuint index, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVPROC) (GLuint index, const GLubyte *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVPROC) (GLuint index, const GLuint *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4USVPROC) (GLuint index, const GLushort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer);
+#endif
+
+#ifndef GL_VERSION_2_1
+#define GL_VERSION_2_1 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glUniformMatrix2x3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GLAPI void APIENTRY glUniformMatrix3x2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GLAPI void APIENTRY glUniformMatrix2x4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GLAPI void APIENTRY glUniformMatrix4x2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GLAPI void APIENTRY glUniformMatrix3x4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GLAPI void APIENTRY glUniformMatrix4x3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+#endif
+
+#ifndef GL_VERSION_3_0
+#define GL_VERSION_3_0 1
+/* OpenGL 3.0 also reuses entry points from these extensions: */
+/* ARB_framebuffer_object */
+/* ARB_map_buffer_range */
+/* ARB_vertex_array_object */
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glColorMaski (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a);
+GLAPI void APIENTRY glGetBooleani_v (GLenum target, GLuint index, GLboolean *data);
+GLAPI void APIENTRY glGetIntegeri_v (GLenum target, GLuint index, GLint *data);
+GLAPI void APIENTRY glEnablei (GLenum target, GLuint index);
+GLAPI void APIENTRY glDisablei (GLenum target, GLuint index);
+GLAPI GLboolean APIENTRY glIsEnabledi (GLenum target, GLuint index);
+GLAPI void APIENTRY glBeginTransformFeedback (GLenum primitiveMode);
+GLAPI void APIENTRY glEndTransformFeedback (void);
+GLAPI void APIENTRY glBindBufferRange (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size);
+GLAPI void APIENTRY glBindBufferBase (GLenum target, GLuint index, GLuint buffer);
+GLAPI void APIENTRY glTransformFeedbackVaryings (GLuint program, GLsizei count, const GLchar* *varyings, GLenum bufferMode);
+GLAPI void APIENTRY glGetTransformFeedbackVarying (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name);
+GLAPI void APIENTRY glClampColor (GLenum target, GLenum clamp);
+GLAPI void APIENTRY glBeginConditionalRender (GLuint id, GLenum mode);
+GLAPI void APIENTRY glEndConditionalRender (void);
+GLAPI void APIENTRY glVertexAttribIPointer (GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+GLAPI void APIENTRY glGetVertexAttribIiv (GLuint index, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetVertexAttribIuiv (GLuint index, GLenum pname, GLuint *params);
+GLAPI void APIENTRY glVertexAttribI1i (GLuint index, GLint x);
+GLAPI void APIENTRY glVertexAttribI2i (GLuint index, GLint x, GLint y);
+GLAPI void APIENTRY glVertexAttribI3i (GLuint index, GLint x, GLint y, GLint z);
+GLAPI void APIENTRY glVertexAttribI4i (GLuint index, GLint x, GLint y, GLint z, GLint w);
+GLAPI void APIENTRY glVertexAttribI1ui (GLuint index, GLuint x);
+GLAPI void APIENTRY glVertexAttribI2ui (GLuint index, GLuint x, GLuint y);
+GLAPI void APIENTRY glVertexAttribI3ui (GLuint index, GLuint x, GLuint y, GLuint z);
+GLAPI void APIENTRY glVertexAttribI4ui (GLuint index, GLuint x, GLuint y, GLuint z, GLuint w);
+GLAPI void APIENTRY glVertexAttribI1iv (GLuint index, const GLint *v);
+GLAPI void APIENTRY glVertexAttribI2iv (GLuint index, const GLint *v);
+GLAPI void APIENTRY glVertexAttribI3iv (GLuint index, const GLint *v);
+GLAPI void APIENTRY glVertexAttribI4iv (GLuint index, const GLint *v);
+GLAPI void APIENTRY glVertexAttribI1uiv (GLuint index, const GLuint *v);
+GLAPI void APIENTRY glVertexAttribI2uiv (GLuint index, const GLuint *v);
+GLAPI void APIENTRY glVertexAttribI3uiv (GLuint index, const GLuint *v);
+GLAPI void APIENTRY glVertexAttribI4uiv (GLuint index, const GLuint *v);
+GLAPI void APIENTRY glVertexAttribI4bv (GLuint index, const GLbyte *v);
+GLAPI void APIENTRY glVertexAttribI4sv (GLuint index, const GLshort *v);
+GLAPI void APIENTRY glVertexAttribI4ubv (GLuint index, const GLubyte *v);
+GLAPI void APIENTRY glVertexAttribI4usv (GLuint index, const GLushort *v);
+GLAPI void APIENTRY glGetUniformuiv (GLuint program, GLint location, GLuint *params);
+GLAPI void APIENTRY glBindFragDataLocation (GLuint program, GLuint color, const GLchar *name);
+GLAPI GLint APIENTRY glGetFragDataLocation (GLuint program, const GLchar *name);
+GLAPI void APIENTRY glUniform1ui (GLint location, GLuint v0);
+GLAPI void APIENTRY glUniform2ui (GLint location, GLuint v0, GLuint v1);
+GLAPI void APIENTRY glUniform3ui (GLint location, GLuint v0, GLuint v1, GLuint v2);
+GLAPI void APIENTRY glUniform4ui (GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3);
+GLAPI void APIENTRY glUniform1uiv (GLint location, GLsizei count, const GLuint *value);
+GLAPI void APIENTRY glUniform2uiv (GLint location, GLsizei count, const GLuint *value);
+GLAPI void APIENTRY glUniform3uiv (GLint location, GLsizei count, const GLuint *value);
+GLAPI void APIENTRY glUniform4uiv (GLint location, GLsizei count, const GLuint *value);
+GLAPI void APIENTRY glTexParameterIiv (GLenum target, GLenum pname, const GLint *params);
+GLAPI void APIENTRY glTexParameterIuiv (GLenum target, GLenum pname, const GLuint *params);
+GLAPI void APIENTRY glGetTexParameterIiv (GLenum target, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetTexParameterIuiv (GLenum target, GLenum pname, GLuint *params);
+GLAPI void APIENTRY glClearBufferiv (GLenum buffer, GLint drawbuffer, const GLint *value);
+GLAPI void APIENTRY glClearBufferuiv (GLenum buffer, GLint drawbuffer, const GLuint *value);
+GLAPI void APIENTRY glClearBufferfv (GLenum buffer, GLint drawbuffer, const GLfloat *value);
+GLAPI void APIENTRY glClearBufferfi (GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil);
+GLAPI const GLubyte * APIENTRY glGetStringi (GLenum name, GLuint index);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCOLORMASKIPROC) (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a);
+typedef void (APIENTRYP PFNGLGETBOOLEANI_VPROC) (GLenum target, GLuint index, GLboolean *data);
+typedef void (APIENTRYP PFNGLGETINTEGERI_VPROC) (GLenum target, GLuint index, GLint *data);
+typedef void (APIENTRYP PFNGLENABLEIPROC) (GLenum target, GLuint index);
+typedef void (APIENTRYP PFNGLDISABLEIPROC) (GLenum target, GLuint index);
+typedef GLboolean (APIENTRYP PFNGLISENABLEDIPROC) (GLenum target, GLuint index);
+typedef void (APIENTRYP PFNGLBEGINTRANSFORMFEEDBACKPROC) (GLenum primitiveMode);
+typedef void (APIENTRYP PFNGLENDTRANSFORMFEEDBACKPROC) (void);
+typedef void (APIENTRYP PFNGLBINDBUFFERRANGEPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size);
+typedef void (APIENTRYP PFNGLBINDBUFFERBASEPROC) (GLenum target, GLuint index, GLuint buffer);
+typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKVARYINGSPROC) (GLuint program, GLsizei count, const GLchar* *varyings, GLenum bufferMode);
+typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKVARYINGPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name);
+typedef void (APIENTRYP PFNGLCLAMPCOLORPROC) (GLenum target, GLenum clamp);
+typedef void (APIENTRYP PFNGLBEGINCONDITIONALRENDERPROC) (GLuint id, GLenum mode);
+typedef void (APIENTRYP PFNGLENDCONDITIONALRENDERPROC) (void);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBIPOINTERPROC) (GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIIVPROC) (GLuint index, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIUIVPROC) (GLuint index, GLenum pname, GLuint *params);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI1IPROC) (GLuint index, GLint x);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI2IPROC) (GLuint index, GLint x, GLint y);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI3IPROC) (GLuint index, GLint x, GLint y, GLint z);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI4IPROC) (GLuint index, GLint x, GLint y, GLint z, GLint w);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIPROC) (GLuint index, GLuint x);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIPROC) (GLuint index, GLuint x, GLuint y);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIPROC) (GLuint index, GLuint x, GLuint y, GLuint z);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIPROC) (GLuint index, GLuint x, GLuint y, GLuint z, GLuint w);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI1IVPROC) (GLuint index, const GLint *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI2IVPROC) (GLuint index, const GLint *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI3IVPROC) (GLuint index, const GLint *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI4IVPROC) (GLuint index, const GLint *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIVPROC) (GLuint index, const GLuint *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIVPROC) (GLuint index, const GLuint *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIVPROC) (GLuint index, const GLuint *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIVPROC) (GLuint index, const GLuint *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI4BVPROC) (GLuint index, const GLbyte *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI4SVPROC) (GLuint index, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UBVPROC) (GLuint index, const GLubyte *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI4USVPROC) (GLuint index, const GLushort *v);
+typedef void (APIENTRYP PFNGLGETUNIFORMUIVPROC) (GLuint program, GLint location, GLuint *params);
+typedef void (APIENTRYP PFNGLBINDFRAGDATALOCATIONPROC) (GLuint program, GLuint color, const GLchar *name);
+typedef GLint (APIENTRYP PFNGLGETFRAGDATALOCATIONPROC) (GLuint program, const GLchar *name);
+typedef void (APIENTRYP PFNGLUNIFORM1UIPROC) (GLint location, GLuint v0);
+typedef void (APIENTRYP PFNGLUNIFORM2UIPROC) (GLint location, GLuint v0, GLuint v1);
+typedef void (APIENTRYP PFNGLUNIFORM3UIPROC) (GLint location, GLuint v0, GLuint v1, GLuint v2);
+typedef void (APIENTRYP PFNGLUNIFORM4UIPROC) (GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3);
+typedef void (APIENTRYP PFNGLUNIFORM1UIVPROC) (GLint location, GLsizei count, const GLuint *value);
+typedef void (APIENTRYP PFNGLUNIFORM2UIVPROC) (GLint location, GLsizei count, const GLuint *value);
+typedef void (APIENTRYP PFNGLUNIFORM3UIVPROC) (GLint location, GLsizei count, const GLuint *value);
+typedef void (APIENTRYP PFNGLUNIFORM4UIVPROC) (GLint location, GLsizei count, const GLuint *value);
+typedef void (APIENTRYP PFNGLTEXPARAMETERIIVPROC) (GLenum target, GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLTEXPARAMETERIUIVPROC) (GLenum target, GLenum pname, const GLuint *params);
+typedef void (APIENTRYP PFNGLGETTEXPARAMETERIIVPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETTEXPARAMETERIUIVPROC) (GLenum target, GLenum pname, GLuint *params);
+typedef void (APIENTRYP PFNGLCLEARBUFFERIVPROC) (GLenum buffer, GLint drawbuffer, const GLint *value);
+typedef void (APIENTRYP PFNGLCLEARBUFFERUIVPROC) (GLenum buffer, GLint drawbuffer, const GLuint *value);
+typedef void (APIENTRYP PFNGLCLEARBUFFERFVPROC) (GLenum buffer, GLint drawbuffer, const GLfloat *value);
+typedef void (APIENTRYP PFNGLCLEARBUFFERFIPROC) (GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil);
+typedef const GLubyte * (APIENTRYP PFNGLGETSTRINGIPROC) (GLenum name, GLuint index);
+#endif
+
+#ifndef GL_VERSION_3_1
+#define GL_VERSION_3_1 1
+/* OpenGL 3.1 also reuses entry points from these extensions: */
+/* ARB_copy_buffer */
+/* ARB_uniform_buffer_object */
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glDrawArraysInstanced (GLenum mode, GLint first, GLsizei count, GLsizei primcount);
+GLAPI void APIENTRY glDrawElementsInstanced (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount);
+GLAPI void APIENTRY glTexBuffer (GLenum target, GLenum internalformat, GLuint buffer);
+GLAPI void APIENTRY glPrimitiveRestartIndex (GLuint index);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDPROC) (GLenum mode, GLint first, GLsizei count, GLsizei primcount);
+typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDPROC) (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount);
+typedef void (APIENTRYP PFNGLTEXBUFFERPROC) (GLenum target, GLenum internalformat, GLuint buffer);
+typedef void (APIENTRYP PFNGLPRIMITIVERESTARTINDEXPROC) (GLuint index);
+#endif
+
+#ifndef GL_VERSION_3_2
+#define GL_VERSION_3_2 1
+/* OpenGL 3.2 also reuses entry points from these extensions: */
+/* ARB_draw_elements_base_vertex */
+/* ARB_provoking_vertex */
+/* ARB_sync */
+/* ARB_texture_multisample */
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glGetInteger64i_v (GLenum target, GLuint index, GLint64 *data);
+GLAPI void APIENTRY glGetBufferParameteri64v (GLenum target, GLenum pname, GLint64 *params);
+GLAPI void APIENTRY glFramebufferTexture (GLenum target, GLenum attachment, GLuint texture, GLint level);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLGETINTEGER64I_VPROC) (GLenum target, GLuint index, GLint64 *data);
+typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERI64VPROC) (GLenum target, GLenum pname, GLint64 *params);
+typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level);
+#endif
+
+#ifndef GL_VERSION_3_3
+#define GL_VERSION_3_3 1
+/* OpenGL 3.3 also reuses entry points from these extensions: */
+/* ARB_blend_func_extended */
+/* ARB_sampler_objects */
+/* ARB_explicit_attrib_location, but it has none */
+/* ARB_occlusion_query2 (no entry points) */
+/* ARB_shader_bit_encoding (no entry points) */
+/* ARB_texture_rgb10_a2ui (no entry points) */
+/* ARB_texture_swizzle (no entry points) */
+/* ARB_timer_query */
+/* ARB_vertex_type_2_10_10_10_rev */
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glVertexAttribDivisor (GLuint index, GLuint divisor);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLVERTEXATTRIBDIVISORPROC) (GLuint index, GLuint divisor);
+#endif
+
+#ifndef GL_VERSION_4_0
+#define GL_VERSION_4_0 1
+/* OpenGL 4.0 also reuses entry points from these extensions: */
+/* ARB_texture_query_lod (no entry points) */
+/* ARB_draw_indirect */
+/* ARB_gpu_shader5 (no entry points) */
+/* ARB_gpu_shader_fp64 */
+/* ARB_shader_subroutine */
+/* ARB_tessellation_shader */
+/* ARB_texture_buffer_object_rgb32 (no entry points) */
+/* ARB_texture_cube_map_array (no entry points) */
+/* ARB_texture_gather (no entry points) */
+/* ARB_transform_feedback2 */
+/* ARB_transform_feedback3 */
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glMinSampleShading (GLclampf value);
+GLAPI void APIENTRY glBlendEquationi (GLuint buf, GLenum mode);
+GLAPI void APIENTRY glBlendEquationSeparatei (GLuint buf, GLenum modeRGB, GLenum modeAlpha);
+GLAPI void APIENTRY glBlendFunci (GLuint buf, GLenum src, GLenum dst);
+GLAPI void APIENTRY glBlendFuncSeparatei (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLMINSAMPLESHADINGPROC) (GLclampf value);
+typedef void (APIENTRYP PFNGLBLENDEQUATIONIPROC) (GLuint buf, GLenum mode);
+typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEIPROC) (GLuint buf, GLenum modeRGB, GLenum modeAlpha);
+typedef void (APIENTRYP PFNGLBLENDFUNCIPROC) (GLuint buf, GLenum src, GLenum dst);
+typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEIPROC) (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
+#endif
+
+#ifndef GL_VERSION_4_1
+#define GL_VERSION_4_1 1
+/* OpenGL 4.1 also reuses entry points from these extensions: */
+/* ARB_ES2_compatibility */
+/* ARB_get_program_binary */
+/* ARB_separate_shader_objects */
+/* ARB_shader_precision (no entry points) */
+/* ARB_vertex_attrib_64bit */
+/* ARB_viewport_array */
+#endif
+
+#ifndef GL_ARB_multitexture
+#define GL_ARB_multitexture 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glActiveTextureARB (GLenum texture);
+GLAPI void APIENTRY glClientActiveTextureARB (GLenum texture);
+GLAPI void APIENTRY glMultiTexCoord1dARB (GLenum target, GLdouble s);
+GLAPI void APIENTRY glMultiTexCoord1dvARB (GLenum target, const GLdouble *v);
+GLAPI void APIENTRY glMultiTexCoord1fARB (GLenum target, GLfloat s);
+GLAPI void APIENTRY glMultiTexCoord1fvARB (GLenum target, const GLfloat *v);
+GLAPI void APIENTRY glMultiTexCoord1iARB (GLenum target, GLint s);
+GLAPI void APIENTRY glMultiTexCoord1ivARB (GLenum target, const GLint *v);
+GLAPI void APIENTRY glMultiTexCoord1sARB (GLenum target, GLshort s);
+GLAPI void APIENTRY glMultiTexCoord1svARB (GLenum target, const GLshort *v);
+GLAPI void APIENTRY glMultiTexCoord2dARB (GLenum target, GLdouble s, GLdouble t);
+GLAPI void APIENTRY glMultiTexCoord2dvARB (GLenum target, const GLdouble *v);
+GLAPI void APIENTRY glMultiTexCoord2fARB (GLenum target, GLfloat s, GLfloat t);
+GLAPI void APIENTRY glMultiTexCoord2fvARB (GLenum target, const GLfloat *v);
+GLAPI void APIENTRY glMultiTexCoord2iARB (GLenum target, GLint s, GLint t);
+GLAPI void APIENTRY glMultiTexCoord2ivARB (GLenum target, const GLint *v);
+GLAPI void APIENTRY glMultiTexCoord2sARB (GLenum target, GLshort s, GLshort t);
+GLAPI void APIENTRY glMultiTexCoord2svARB (GLenum target, const GLshort *v);
+GLAPI void APIENTRY glMultiTexCoord3dARB (GLenum target, GLdouble s, GLdouble t, GLdouble r);
+GLAPI void APIENTRY glMultiTexCoord3dvARB (GLenum target, const GLdouble *v);
+GLAPI void APIENTRY glMultiTexCoord3fARB (GLenum target, GLfloat s, GLfloat t, GLfloat r);
+GLAPI void APIENTRY glMultiTexCoord3fvARB (GLenum target, const GLfloat *v);
+GLAPI void APIENTRY glMultiTexCoord3iARB (GLenum target, GLint s, GLint t, GLint r);
+GLAPI void APIENTRY glMultiTexCoord3ivARB (GLenum target, const GLint *v);
+GLAPI void APIENTRY glMultiTexCoord3sARB (GLenum target, GLshort s, GLshort t, GLshort r);
+GLAPI void APIENTRY glMultiTexCoord3svARB (GLenum target, const GLshort *v);
+GLAPI void APIENTRY glMultiTexCoord4dARB (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q);
+GLAPI void APIENTRY glMultiTexCoord4dvARB (GLenum target, const GLdouble *v);
+GLAPI void APIENTRY glMultiTexCoord4fARB (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q);
+GLAPI void APIENTRY glMultiTexCoord4fvARB (GLenum target, const GLfloat *v);
+GLAPI void APIENTRY glMultiTexCoord4iARB (GLenum target, GLint s, GLint t, GLint r, GLint q);
+GLAPI void APIENTRY glMultiTexCoord4ivARB (GLenum target, const GLint *v);
+GLAPI void APIENTRY glMultiTexCoord4sARB (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q);
+GLAPI void APIENTRY glMultiTexCoord4svARB (GLenum target, const GLshort *v);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLACTIVETEXTUREARBPROC) (GLenum texture);
+typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREARBPROC) (GLenum texture);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1DARBPROC) (GLenum target, GLdouble s);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1DVARBPROC) (GLenum target, const GLdouble *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1FARBPROC) (GLenum target, GLfloat s);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1FVARBPROC) (GLenum target, const GLfloat *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1IARBPROC) (GLenum target, GLint s);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1IVARBPROC) (GLenum target, const GLint *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1SARBPROC) (GLenum target, GLshort s);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1SVARBPROC) (GLenum target, const GLshort *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2DARBPROC) (GLenum target, GLdouble s, GLdouble t);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2DVARBPROC) (GLenum target, const GLdouble *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2FARBPROC) (GLenum target, GLfloat s, GLfloat t);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2FVARBPROC) (GLenum target, const GLfloat *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2IARBPROC) (GLenum target, GLint s, GLint t);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2IVARBPROC) (GLenum target, const GLint *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2SARBPROC) (GLenum target, GLshort s, GLshort t);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2SVARBPROC) (GLenum target, const GLshort *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3DARBPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3DVARBPROC) (GLenum target, const GLdouble *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3FARBPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3FVARBPROC) (GLenum target, const GLfloat *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3IARBPROC) (GLenum target, GLint s, GLint t, GLint r);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3IVARBPROC) (GLenum target, const GLint *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3SARBPROC) (GLenum target, GLshort s, GLshort t, GLshort r);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3SVARBPROC) (GLenum target, const GLshort *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4DARBPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4DVARBPROC) (GLenum target, const GLdouble *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4FARBPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4FVARBPROC) (GLenum target, const GLfloat *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4IARBPROC) (GLenum target, GLint s, GLint t, GLint r, GLint q);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4IVARBPROC) (GLenum target, const GLint *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4SARBPROC) (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4SVARBPROC) (GLenum target, const GLshort *v);
+#endif
+
+#ifndef GL_ARB_transpose_matrix
+#define GL_ARB_transpose_matrix 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glLoadTransposeMatrixfARB (const GLfloat *m);
+GLAPI void APIENTRY glLoadTransposeMatrixdARB (const GLdouble *m);
+GLAPI void APIENTRY glMultTransposeMatrixfARB (const GLfloat *m);
+GLAPI void APIENTRY glMultTransposeMatrixdARB (const GLdouble *m);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXFARBPROC) (const GLfloat *m);
+typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXDARBPROC) (const GLdouble *m);
+typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXFARBPROC) (const GLfloat *m);
+typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXDARBPROC) (const GLdouble *m);
+#endif
+
+#ifndef GL_ARB_multisample
+#define GL_ARB_multisample 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glSampleCoverageARB (GLclampf value, GLboolean invert);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLSAMPLECOVERAGEARBPROC) (GLclampf value, GLboolean invert);
+#endif
+
+#ifndef GL_ARB_texture_env_add
+#define GL_ARB_texture_env_add 1
+#endif
+
+#ifndef GL_ARB_texture_cube_map
+#define GL_ARB_texture_cube_map 1
+#endif
+
+#ifndef GL_ARB_texture_compression
+#define GL_ARB_texture_compression 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glCompressedTexImage3DARB (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data);
+GLAPI void APIENTRY glCompressedTexImage2DARB (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data);
+GLAPI void APIENTRY glCompressedTexImage1DARB (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *data);
+GLAPI void APIENTRY glCompressedTexSubImage3DARB (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data);
+GLAPI void APIENTRY glCompressedTexSubImage2DARB (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data);
+GLAPI void APIENTRY glCompressedTexSubImage1DARB (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data);
+GLAPI void APIENTRY glGetCompressedTexImageARB (GLenum target, GLint level, GLvoid *img);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data);
+typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data);
+typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *data);
+typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DARBPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data);
+typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DARBPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data);
+typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DARBPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data);
+typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEARBPROC) (GLenum target, GLint level, GLvoid *img);
+#endif
+
+#ifndef GL_ARB_texture_border_clamp
+#define GL_ARB_texture_border_clamp 1
+#endif
+
+#ifndef GL_ARB_point_parameters
+#define GL_ARB_point_parameters 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glPointParameterfARB (GLenum pname, GLfloat param);
+GLAPI void APIENTRY glPointParameterfvARB (GLenum pname, const GLfloat *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPOINTPARAMETERFARBPROC) (GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLPOINTPARAMETERFVARBPROC) (GLenum pname, const GLfloat *params);
+#endif
+
+#ifndef GL_ARB_vertex_blend
+#define GL_ARB_vertex_blend 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glWeightbvARB (GLint size, const GLbyte *weights);
+GLAPI void APIENTRY glWeightsvARB (GLint size, const GLshort *weights);
+GLAPI void APIENTRY glWeightivARB (GLint size, const GLint *weights);
+GLAPI void APIENTRY glWeightfvARB (GLint size, const GLfloat *weights);
+GLAPI void APIENTRY glWeightdvARB (GLint size, const GLdouble *weights);
+GLAPI void APIENTRY glWeightubvARB (GLint size, const GLubyte *weights);
+GLAPI void APIENTRY glWeightusvARB (GLint size, const GLushort *weights);
+GLAPI void APIENTRY glWeightuivARB (GLint size, const GLuint *weights);
+GLAPI void APIENTRY glWeightPointerARB (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+GLAPI void APIENTRY glVertexBlendARB (GLint count);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLWEIGHTBVARBPROC) (GLint size, const GLbyte *weights);
+typedef void (APIENTRYP PFNGLWEIGHTSVARBPROC) (GLint size, const GLshort *weights);
+typedef void (APIENTRYP PFNGLWEIGHTIVARBPROC) (GLint size, const GLint *weights);
+typedef void (APIENTRYP PFNGLWEIGHTFVARBPROC) (GLint size, const GLfloat *weights);
+typedef void (APIENTRYP PFNGLWEIGHTDVARBPROC) (GLint size, const GLdouble *weights);
+typedef void (APIENTRYP PFNGLWEIGHTUBVARBPROC) (GLint size, const GLubyte *weights);
+typedef void (APIENTRYP PFNGLWEIGHTUSVARBPROC) (GLint size, const GLushort *weights);
+typedef void (APIENTRYP PFNGLWEIGHTUIVARBPROC) (GLint size, const GLuint *weights);
+typedef void (APIENTRYP PFNGLWEIGHTPOINTERARBPROC) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+typedef void (APIENTRYP PFNGLVERTEXBLENDARBPROC) (GLint count);
+#endif
+
+#ifndef GL_ARB_matrix_palette
+#define GL_ARB_matrix_palette 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glCurrentPaletteMatrixARB (GLint index);
+GLAPI void APIENTRY glMatrixIndexubvARB (GLint size, const GLubyte *indices);
+GLAPI void APIENTRY glMatrixIndexusvARB (GLint size, const GLushort *indices);
+GLAPI void APIENTRY glMatrixIndexuivARB (GLint size, const GLuint *indices);
+GLAPI void APIENTRY glMatrixIndexPointerARB (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCURRENTPALETTEMATRIXARBPROC) (GLint index);
+typedef void (APIENTRYP PFNGLMATRIXINDEXUBVARBPROC) (GLint size, const GLubyte *indices);
+typedef void (APIENTRYP PFNGLMATRIXINDEXUSVARBPROC) (GLint size, const GLushort *indices);
+typedef void (APIENTRYP PFNGLMATRIXINDEXUIVARBPROC) (GLint size, const GLuint *indices);
+typedef void (APIENTRYP PFNGLMATRIXINDEXPOINTERARBPROC) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+#endif
+
+#ifndef GL_ARB_texture_env_combine
+#define GL_ARB_texture_env_combine 1
+#endif
+
+#ifndef GL_ARB_texture_env_crossbar
+#define GL_ARB_texture_env_crossbar 1
+#endif
+
+#ifndef GL_ARB_texture_env_dot3
+#define GL_ARB_texture_env_dot3 1
+#endif
+
+#ifndef GL_ARB_texture_mirrored_repeat
+#define GL_ARB_texture_mirrored_repeat 1
+#endif
+
+#ifndef GL_ARB_depth_texture
+#define GL_ARB_depth_texture 1
+#endif
+
+#ifndef GL_ARB_shadow
+#define GL_ARB_shadow 1
+#endif
+
+#ifndef GL_ARB_shadow_ambient
+#define GL_ARB_shadow_ambient 1
+#endif
+
+#ifndef GL_ARB_window_pos
+#define GL_ARB_window_pos 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glWindowPos2dARB (GLdouble x, GLdouble y);
+GLAPI void APIENTRY glWindowPos2dvARB (const GLdouble *v);
+GLAPI void APIENTRY glWindowPos2fARB (GLfloat x, GLfloat y);
+GLAPI void APIENTRY glWindowPos2fvARB (const GLfloat *v);
+GLAPI void APIENTRY glWindowPos2iARB (GLint x, GLint y);
+GLAPI void APIENTRY glWindowPos2ivARB (const GLint *v);
+GLAPI void APIENTRY glWindowPos2sARB (GLshort x, GLshort y);
+GLAPI void APIENTRY glWindowPos2svARB (const GLshort *v);
+GLAPI void APIENTRY glWindowPos3dARB (GLdouble x, GLdouble y, GLdouble z);
+GLAPI void APIENTRY glWindowPos3dvARB (const GLdouble *v);
+GLAPI void APIENTRY glWindowPos3fARB (GLfloat x, GLfloat y, GLfloat z);
+GLAPI void APIENTRY glWindowPos3fvARB (const GLfloat *v);
+GLAPI void APIENTRY glWindowPos3iARB (GLint x, GLint y, GLint z);
+GLAPI void APIENTRY glWindowPos3ivARB (const GLint *v);
+GLAPI void APIENTRY glWindowPos3sARB (GLshort x, GLshort y, GLshort z);
+GLAPI void APIENTRY glWindowPos3svARB (const GLshort *v);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLWINDOWPOS2DARBPROC) (GLdouble x, GLdouble y);
+typedef void (APIENTRYP PFNGLWINDOWPOS2DVARBPROC) (const GLdouble *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS2FARBPROC) (GLfloat x, GLfloat y);
+typedef void (APIENTRYP PFNGLWINDOWPOS2FVARBPROC) (const GLfloat *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS2IARBPROC) (GLint x, GLint y);
+typedef void (APIENTRYP PFNGLWINDOWPOS2IVARBPROC) (const GLint *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS2SARBPROC) (GLshort x, GLshort y);
+typedef void (APIENTRYP PFNGLWINDOWPOS2SVARBPROC) (const GLshort *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS3DARBPROC) (GLdouble x, GLdouble y, GLdouble z);
+typedef void (APIENTRYP PFNGLWINDOWPOS3DVARBPROC) (const GLdouble *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS3FARBPROC) (GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLWINDOWPOS3FVARBPROC) (const GLfloat *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS3IARBPROC) (GLint x, GLint y, GLint z);
+typedef void (APIENTRYP PFNGLWINDOWPOS3IVARBPROC) (const GLint *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS3SARBPROC) (GLshort x, GLshort y, GLshort z);
+typedef void (APIENTRYP PFNGLWINDOWPOS3SVARBPROC) (const GLshort *v);
+#endif
+
+#ifndef GL_ARB_vertex_program
+#define GL_ARB_vertex_program 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glVertexAttrib1dARB (GLuint index, GLdouble x);
+GLAPI void APIENTRY glVertexAttrib1dvARB (GLuint index, const GLdouble *v);
+GLAPI void APIENTRY glVertexAttrib1fARB (GLuint index, GLfloat x);
+GLAPI void APIENTRY glVertexAttrib1fvARB (GLuint index, const GLfloat *v);
+GLAPI void APIENTRY glVertexAttrib1sARB (GLuint index, GLshort x);
+GLAPI void APIENTRY glVertexAttrib1svARB (GLuint index, const GLshort *v);
+GLAPI void APIENTRY glVertexAttrib2dARB (GLuint index, GLdouble x, GLdouble y);
+GLAPI void APIENTRY glVertexAttrib2dvARB (GLuint index, const GLdouble *v);
+GLAPI void APIENTRY glVertexAttrib2fARB (GLuint index, GLfloat x, GLfloat y);
+GLAPI void APIENTRY glVertexAttrib2fvARB (GLuint index, const GLfloat *v);
+GLAPI void APIENTRY glVertexAttrib2sARB (GLuint index, GLshort x, GLshort y);
+GLAPI void APIENTRY glVertexAttrib2svARB (GLuint index, const GLshort *v);
+GLAPI void APIENTRY glVertexAttrib3dARB (GLuint index, GLdouble x, GLdouble y, GLdouble z);
+GLAPI void APIENTRY glVertexAttrib3dvARB (GLuint index, const GLdouble *v);
+GLAPI void APIENTRY glVertexAttrib3fARB (GLuint index, GLfloat x, GLfloat y, GLfloat z);
+GLAPI void APIENTRY glVertexAttrib3fvARB (GLuint index, const GLfloat *v);
+GLAPI void APIENTRY glVertexAttrib3sARB (GLuint index, GLshort x, GLshort y, GLshort z);
+GLAPI void APIENTRY glVertexAttrib3svARB (GLuint index, const GLshort *v);
+GLAPI void APIENTRY glVertexAttrib4NbvARB (GLuint index, const GLbyte *v);
+GLAPI void APIENTRY glVertexAttrib4NivARB (GLuint index, const GLint *v);
+GLAPI void APIENTRY glVertexAttrib4NsvARB (GLuint index, const GLshort *v);
+GLAPI void APIENTRY glVertexAttrib4NubARB (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w);
+GLAPI void APIENTRY glVertexAttrib4NubvARB (GLuint index, const GLubyte *v);
+GLAPI void APIENTRY glVertexAttrib4NuivARB (GLuint index, const GLuint *v);
+GLAPI void APIENTRY glVertexAttrib4NusvARB (GLuint index, const GLushort *v);
+GLAPI void APIENTRY glVertexAttrib4bvARB (GLuint index, const GLbyte *v);
+GLAPI void APIENTRY glVertexAttrib4dARB (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+GLAPI void APIENTRY glVertexAttrib4dvARB (GLuint index, const GLdouble *v);
+GLAPI void APIENTRY glVertexAttrib4fARB (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+GLAPI void APIENTRY glVertexAttrib4fvARB (GLuint index, const GLfloat *v);
+GLAPI void APIENTRY glVertexAttrib4ivARB (GLuint index, const GLint *v);
+GLAPI void APIENTRY glVertexAttrib4sARB (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w);
+GLAPI void APIENTRY glVertexAttrib4svARB (GLuint index, const GLshort *v);
+GLAPI void APIENTRY glVertexAttrib4ubvARB (GLuint index, const GLubyte *v);
+GLAPI void APIENTRY glVertexAttrib4uivARB (GLuint index, const GLuint *v);
+GLAPI void APIENTRY glVertexAttrib4usvARB (GLuint index, const GLushort *v);
+GLAPI void APIENTRY glVertexAttribPointerARB (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer);
+GLAPI void APIENTRY glEnableVertexAttribArrayARB (GLuint index);
+GLAPI void APIENTRY glDisableVertexAttribArrayARB (GLuint index);
+GLAPI void APIENTRY glProgramStringARB (GLenum target, GLenum format, GLsizei len, const GLvoid *string);
+GLAPI void APIENTRY glBindProgramARB (GLenum target, GLuint program);
+GLAPI void APIENTRY glDeleteProgramsARB (GLsizei n, const GLuint *programs);
+GLAPI void APIENTRY glGenProgramsARB (GLsizei n, GLuint *programs);
+GLAPI void APIENTRY glProgramEnvParameter4dARB (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+GLAPI void APIENTRY glProgramEnvParameter4dvARB (GLenum target, GLuint index, const GLdouble *params);
+GLAPI void APIENTRY glProgramEnvParameter4fARB (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+GLAPI void APIENTRY glProgramEnvParameter4fvARB (GLenum target, GLuint index, const GLfloat *params);
+GLAPI void APIENTRY glProgramLocalParameter4dARB (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+GLAPI void APIENTRY glProgramLocalParameter4dvARB (GLenum target, GLuint index, const GLdouble *params);
+GLAPI void APIENTRY glProgramLocalParameter4fARB (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+GLAPI void APIENTRY glProgramLocalParameter4fvARB (GLenum target, GLuint index, const GLfloat *params);
+GLAPI void APIENTRY glGetProgramEnvParameterdvARB (GLenum target, GLuint index, GLdouble *params);
+GLAPI void APIENTRY glGetProgramEnvParameterfvARB (GLenum target, GLuint index, GLfloat *params);
+GLAPI void APIENTRY glGetProgramLocalParameterdvARB (GLenum target, GLuint index, GLdouble *params);
+GLAPI void APIENTRY glGetProgramLocalParameterfvARB (GLenum target, GLuint index, GLfloat *params);
+GLAPI void APIENTRY glGetProgramivARB (GLenum target, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetProgramStringARB (GLenum target, GLenum pname, GLvoid *string);
+GLAPI void APIENTRY glGetVertexAttribdvARB (GLuint index, GLenum pname, GLdouble *params);
+GLAPI void APIENTRY glGetVertexAttribfvARB (GLuint index, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetVertexAttribivARB (GLuint index, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetVertexAttribPointervARB (GLuint index, GLenum pname, GLvoid* *pointer);
+GLAPI GLboolean APIENTRY glIsProgramARB (GLuint program);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1DARBPROC) (GLuint index, GLdouble x);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVARBPROC) (GLuint index, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1FARBPROC) (GLuint index, GLfloat x);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVARBPROC) (GLuint index, const GLfloat *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1SARBPROC) (GLuint index, GLshort x);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVARBPROC) (GLuint index, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2DARBPROC) (GLuint index, GLdouble x, GLdouble y);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVARBPROC) (GLuint index, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2FARBPROC) (GLuint index, GLfloat x, GLfloat y);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVARBPROC) (GLuint index, const GLfloat *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2SARBPROC) (GLuint index, GLshort x, GLshort y);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVARBPROC) (GLuint index, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3DARBPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVARBPROC) (GLuint index, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3FARBPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVARBPROC) (GLuint index, const GLfloat *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3SARBPROC) (GLuint index, GLshort x, GLshort y, GLshort z);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVARBPROC) (GLuint index, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVARBPROC) (GLuint index, const GLbyte *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVARBPROC) (GLuint index, const GLint *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVARBPROC) (GLuint index, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBARBPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVARBPROC) (GLuint index, const GLubyte *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVARBPROC) (GLuint index, const GLuint *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVARBPROC) (GLuint index, const GLushort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4BVARBPROC) (GLuint index, const GLbyte *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4DARBPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVARBPROC) (GLuint index, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4FARBPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVARBPROC) (GLuint index, const GLfloat *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4IVARBPROC) (GLuint index, const GLint *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4SARBPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVARBPROC) (GLuint index, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVARBPROC) (GLuint index, const GLubyte *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVARBPROC) (GLuint index, const GLuint *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4USVARBPROC) (GLuint index, const GLushort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERARBPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer);
+typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYARBPROC) (GLuint index);
+typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYARBPROC) (GLuint index);
+typedef void (APIENTRYP PFNGLPROGRAMSTRINGARBPROC) (GLenum target, GLenum format, GLsizei len, const GLvoid *string);
+typedef void (APIENTRYP PFNGLBINDPROGRAMARBPROC) (GLenum target, GLuint program);
+typedef void (APIENTRYP PFNGLDELETEPROGRAMSARBPROC) (GLsizei n, const GLuint *programs);
+typedef void (APIENTRYP PFNGLGENPROGRAMSARBPROC) (GLsizei n, GLuint *programs);
+typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4DARBPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4DVARBPROC) (GLenum target, GLuint index, const GLdouble *params);
+typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4FARBPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4FVARBPROC) (GLenum target, GLuint index, const GLfloat *params);
+typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4DARBPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4DVARBPROC) (GLenum target, GLuint index, const GLdouble *params);
+typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4FARBPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4FVARBPROC) (GLenum target, GLuint index, const GLfloat *params);
+typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERDVARBPROC) (GLenum target, GLuint index, GLdouble *params);
+typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERFVARBPROC) (GLenum target, GLuint index, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERDVARBPROC) (GLenum target, GLuint index, GLdouble *params);
+typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERFVARBPROC) (GLenum target, GLuint index, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETPROGRAMIVARBPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETPROGRAMSTRINGARBPROC) (GLenum target, GLenum pname, GLvoid *string);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVARBPROC) (GLuint index, GLenum pname, GLdouble *params);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVARBPROC) (GLuint index, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVARBPROC) (GLuint index, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVARBPROC) (GLuint index, GLenum pname, GLvoid* *pointer);
+typedef GLboolean (APIENTRYP PFNGLISPROGRAMARBPROC) (GLuint program);
+#endif
+
+#ifndef GL_ARB_fragment_program
+#define GL_ARB_fragment_program 1
+/* All ARB_fragment_program entry points are shared with ARB_vertex_program. */
+#endif
+
+#ifndef GL_ARB_vertex_buffer_object
+#define GL_ARB_vertex_buffer_object 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBindBufferARB (GLenum target, GLuint buffer);
+GLAPI void APIENTRY glDeleteBuffersARB (GLsizei n, const GLuint *buffers);
+GLAPI void APIENTRY glGenBuffersARB (GLsizei n, GLuint *buffers);
+GLAPI GLboolean APIENTRY glIsBufferARB (GLuint buffer);
+GLAPI void APIENTRY glBufferDataARB (GLenum target, GLsizeiptrARB size, const GLvoid *data, GLenum usage);
+GLAPI void APIENTRY glBufferSubDataARB (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const GLvoid *data);
+GLAPI void APIENTRY glGetBufferSubDataARB (GLenum target, GLintptrARB offset, GLsizeiptrARB size, GLvoid *data);
+GLAPI GLvoid* APIENTRY glMapBufferARB (GLenum target, GLenum access);
+GLAPI GLboolean APIENTRY glUnmapBufferARB (GLenum target);
+GLAPI void APIENTRY glGetBufferParameterivARB (GLenum target, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetBufferPointervARB (GLenum target, GLenum pname, GLvoid* *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBINDBUFFERARBPROC) (GLenum target, GLuint buffer);
+typedef void (APIENTRYP PFNGLDELETEBUFFERSARBPROC) (GLsizei n, const GLuint *buffers);
+typedef void (APIENTRYP PFNGLGENBUFFERSARBPROC) (GLsizei n, GLuint *buffers);
+typedef GLboolean (APIENTRYP PFNGLISBUFFERARBPROC) (GLuint buffer);
+typedef void (APIENTRYP PFNGLBUFFERDATAARBPROC) (GLenum target, GLsizeiptrARB size, const GLvoid *data, GLenum usage);
+typedef void (APIENTRYP PFNGLBUFFERSUBDATAARBPROC) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const GLvoid *data);
+typedef void (APIENTRYP PFNGLGETBUFFERSUBDATAARBPROC) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, GLvoid *data);
+typedef GLvoid* (APIENTRYP PFNGLMAPBUFFERARBPROC) (GLenum target, GLenum access);
+typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERARBPROC) (GLenum target);
+typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVARBPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVARBPROC) (GLenum target, GLenum pname, GLvoid* *params);
+#endif
+
+#ifndef GL_ARB_occlusion_query
+#define GL_ARB_occlusion_query 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glGenQueriesARB (GLsizei n, GLuint *ids);
+GLAPI void APIENTRY glDeleteQueriesARB (GLsizei n, const GLuint *ids);
+GLAPI GLboolean APIENTRY glIsQueryARB (GLuint id);
+GLAPI void APIENTRY glBeginQueryARB (GLenum target, GLuint id);
+GLAPI void APIENTRY glEndQueryARB (GLenum target);
+GLAPI void APIENTRY glGetQueryivARB (GLenum target, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetQueryObjectivARB (GLuint id, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetQueryObjectuivARB (GLuint id, GLenum pname, GLuint *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLGENQUERIESARBPROC) (GLsizei n, GLuint *ids);
+typedef void (APIENTRYP PFNGLDELETEQUERIESARBPROC) (GLsizei n, const GLuint *ids);
+typedef GLboolean (APIENTRYP PFNGLISQUERYARBPROC) (GLuint id);
+typedef void (APIENTRYP PFNGLBEGINQUERYARBPROC) (GLenum target, GLuint id);
+typedef void (APIENTRYP PFNGLENDQUERYARBPROC) (GLenum target);
+typedef void (APIENTRYP PFNGLGETQUERYIVARBPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETQUERYOBJECTIVARBPROC) (GLuint id, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVARBPROC) (GLuint id, GLenum pname, GLuint *params);
+#endif
+
+#ifndef GL_ARB_shader_objects
+#define GL_ARB_shader_objects 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glDeleteObjectARB (GLhandleARB obj);
+GLAPI GLhandleARB APIENTRY glGetHandleARB (GLenum pname);
+GLAPI void APIENTRY glDetachObjectARB (GLhandleARB containerObj, GLhandleARB attachedObj);
+GLAPI GLhandleARB APIENTRY glCreateShaderObjectARB (GLenum shaderType);
+GLAPI void APIENTRY glShaderSourceARB (GLhandleARB shaderObj, GLsizei count, const GLcharARB* *string, const GLint *length);
+GLAPI void APIENTRY glCompileShaderARB (GLhandleARB shaderObj);
+GLAPI GLhandleARB APIENTRY glCreateProgramObjectARB (void);
+GLAPI void APIENTRY glAttachObjectARB (GLhandleARB containerObj, GLhandleARB obj);
+GLAPI void APIENTRY glLinkProgramARB (GLhandleARB programObj);
+GLAPI void APIENTRY glUseProgramObjectARB (GLhandleARB programObj);
+GLAPI void APIENTRY glValidateProgramARB (GLhandleARB programObj);
+GLAPI void APIENTRY glUniform1fARB (GLint location, GLfloat v0);
+GLAPI void APIENTRY glUniform2fARB (GLint location, GLfloat v0, GLfloat v1);
+GLAPI void APIENTRY glUniform3fARB (GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
+GLAPI void APIENTRY glUniform4fARB (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
+GLAPI void APIENTRY glUniform1iARB (GLint location, GLint v0);
+GLAPI void APIENTRY glUniform2iARB (GLint location, GLint v0, GLint v1);
+GLAPI void APIENTRY glUniform3iARB (GLint location, GLint v0, GLint v1, GLint v2);
+GLAPI void APIENTRY glUniform4iARB (GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
+GLAPI void APIENTRY glUniform1fvARB (GLint location, GLsizei count, const GLfloat *value);
+GLAPI void APIENTRY glUniform2fvARB (GLint location, GLsizei count, const GLfloat *value);
+GLAPI void APIENTRY glUniform3fvARB (GLint location, GLsizei count, const GLfloat *value);
+GLAPI void APIENTRY glUniform4fvARB (GLint location, GLsizei count, const GLfloat *value);
+GLAPI void APIENTRY glUniform1ivARB (GLint location, GLsizei count, const GLint *value);
+GLAPI void APIENTRY glUniform2ivARB (GLint location, GLsizei count, const GLint *value);
+GLAPI void APIENTRY glUniform3ivARB (GLint location, GLsizei count, const GLint *value);
+GLAPI void APIENTRY glUniform4ivARB (GLint location, GLsizei count, const GLint *value);
+GLAPI void APIENTRY glUniformMatrix2fvARB (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GLAPI void APIENTRY glUniformMatrix3fvARB (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GLAPI void APIENTRY glUniformMatrix4fvARB (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GLAPI void APIENTRY glGetObjectParameterfvARB (GLhandleARB obj, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetObjectParameterivARB (GLhandleARB obj, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetInfoLogARB (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog);
+GLAPI void APIENTRY glGetAttachedObjectsARB (GLhandleARB containerObj, GLsizei maxCount, GLsizei *count, GLhandleARB *obj);
+GLAPI GLint APIENTRY glGetUniformLocationARB (GLhandleARB programObj, const GLcharARB *name);
+GLAPI void APIENTRY glGetActiveUniformARB (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name);
+GLAPI void APIENTRY glGetUniformfvARB (GLhandleARB programObj, GLint location, GLfloat *params);
+GLAPI void APIENTRY glGetUniformivARB (GLhandleARB programObj, GLint location, GLint *params);
+GLAPI void APIENTRY glGetShaderSourceARB (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *source);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLDELETEOBJECTARBPROC) (GLhandleARB obj);
+typedef GLhandleARB (APIENTRYP PFNGLGETHANDLEARBPROC) (GLenum pname);
+typedef void (APIENTRYP PFNGLDETACHOBJECTARBPROC) (GLhandleARB containerObj, GLhandleARB attachedObj);
+typedef GLhandleARB (APIENTRYP PFNGLCREATESHADEROBJECTARBPROC) (GLenum shaderType);
+typedef void (APIENTRYP PFNGLSHADERSOURCEARBPROC) (GLhandleARB shaderObj, GLsizei count, const GLcharARB* *string, const GLint *length);
+typedef void (APIENTRYP PFNGLCOMPILESHADERARBPROC) (GLhandleARB shaderObj);
+typedef GLhandleARB (APIENTRYP PFNGLCREATEPROGRAMOBJECTARBPROC) (void);
+typedef void (APIENTRYP PFNGLATTACHOBJECTARBPROC) (GLhandleARB containerObj, GLhandleARB obj);
+typedef void (APIENTRYP PFNGLLINKPROGRAMARBPROC) (GLhandleARB programObj);
+typedef void (APIENTRYP PFNGLUSEPROGRAMOBJECTARBPROC) (GLhandleARB programObj);
+typedef void (APIENTRYP PFNGLVALIDATEPROGRAMARBPROC) (GLhandleARB programObj);
+typedef void (APIENTRYP PFNGLUNIFORM1FARBPROC) (GLint location, GLfloat v0);
+typedef void (APIENTRYP PFNGLUNIFORM2FARBPROC) (GLint location, GLfloat v0, GLfloat v1);
+typedef void (APIENTRYP PFNGLUNIFORM3FARBPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
+typedef void (APIENTRYP PFNGLUNIFORM4FARBPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
+typedef void (APIENTRYP PFNGLUNIFORM1IARBPROC) (GLint location, GLint v0);
+typedef void (APIENTRYP PFNGLUNIFORM2IARBPROC) (GLint location, GLint v0, GLint v1);
+typedef void (APIENTRYP PFNGLUNIFORM3IARBPROC) (GLint location, GLint v0, GLint v1, GLint v2);
+typedef void (APIENTRYP PFNGLUNIFORM4IARBPROC) (GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
+typedef void (APIENTRYP PFNGLUNIFORM1FVARBPROC) (GLint location, GLsizei count, const GLfloat *value);
+typedef void (APIENTRYP PFNGLUNIFORM2FVARBPROC) (GLint location, GLsizei count, const GLfloat *value);
+typedef void (APIENTRYP PFNGLUNIFORM3FVARBPROC) (GLint location, GLsizei count, const GLfloat *value);
+typedef void (APIENTRYP PFNGLUNIFORM4FVARBPROC) (GLint location, GLsizei count, const GLfloat *value);
+typedef void (APIENTRYP PFNGLUNIFORM1IVARBPROC) (GLint location, GLsizei count, const GLint *value);
+typedef void (APIENTRYP PFNGLUNIFORM2IVARBPROC) (GLint location, GLsizei count, const GLint *value);
+typedef void (APIENTRYP PFNGLUNIFORM3IVARBPROC) (GLint location, GLsizei count, const GLint *value);
+typedef void (APIENTRYP PFNGLUNIFORM4IVARBPROC) (GLint location, GLsizei count, const GLint *value);
+typedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLGETOBJECTPARAMETERFVARBPROC) (GLhandleARB obj, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETOBJECTPARAMETERIVARBPROC) (GLhandleARB obj, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETINFOLOGARBPROC) (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog);
+typedef void (APIENTRYP PFNGLGETATTACHEDOBJECTSARBPROC) (GLhandleARB containerObj, GLsizei maxCount, GLsizei *count, GLhandleARB *obj);
+typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONARBPROC) (GLhandleARB programObj, const GLcharARB *name);
+typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMARBPROC) (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name);
+typedef void (APIENTRYP PFNGLGETUNIFORMFVARBPROC) (GLhandleARB programObj, GLint location, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETUNIFORMIVARBPROC) (GLhandleARB programObj, GLint location, GLint *params);
+typedef void (APIENTRYP PFNGLGETSHADERSOURCEARBPROC) (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *source);
+#endif
+
+#ifndef GL_ARB_vertex_shader
+#define GL_ARB_vertex_shader 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBindAttribLocationARB (GLhandleARB programObj, GLuint index, const GLcharARB *name);
+GLAPI void APIENTRY glGetActiveAttribARB (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name);
+GLAPI GLint APIENTRY glGetAttribLocationARB (GLhandleARB programObj, const GLcharARB *name);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONARBPROC) (GLhandleARB programObj, GLuint index, const GLcharARB *name);
+typedef void (APIENTRYP PFNGLGETACTIVEATTRIBARBPROC) (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name);
+typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONARBPROC) (GLhandleARB programObj, const GLcharARB *name);
+#endif
+
+#ifndef GL_ARB_fragment_shader
+#define GL_ARB_fragment_shader 1
+#endif
+
+#ifndef GL_ARB_shading_language_100
+#define GL_ARB_shading_language_100 1
+#endif
+
+#ifndef GL_ARB_texture_non_power_of_two
+#define GL_ARB_texture_non_power_of_two 1
+#endif
+
+#ifndef GL_ARB_point_sprite
+#define GL_ARB_point_sprite 1
+#endif
+
+#ifndef GL_ARB_fragment_program_shadow
+#define GL_ARB_fragment_program_shadow 1
+#endif
+
+#ifndef GL_ARB_draw_buffers
+#define GL_ARB_draw_buffers 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glDrawBuffersARB (GLsizei n, const GLenum *bufs);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLDRAWBUFFERSARBPROC) (GLsizei n, const GLenum *bufs);
+#endif
+
+#ifndef GL_ARB_texture_rectangle
+#define GL_ARB_texture_rectangle 1
+#endif
+
+#ifndef GL_ARB_color_buffer_float
+#define GL_ARB_color_buffer_float 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glClampColorARB (GLenum target, GLenum clamp);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCLAMPCOLORARBPROC) (GLenum target, GLenum clamp);
+#endif
+
+#ifndef GL_ARB_half_float_pixel
+#define GL_ARB_half_float_pixel 1
+#endif
+
+#ifndef GL_ARB_texture_float
+#define GL_ARB_texture_float 1
+#endif
+
+#ifndef GL_ARB_pixel_buffer_object
+#define GL_ARB_pixel_buffer_object 1
+#endif
+
+#ifndef GL_ARB_depth_buffer_float
+#define GL_ARB_depth_buffer_float 1
+#endif
+
+#ifndef GL_ARB_draw_instanced
+#define GL_ARB_draw_instanced 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glDrawArraysInstancedARB (GLenum mode, GLint first, GLsizei count, GLsizei primcount);
+GLAPI void APIENTRY glDrawElementsInstancedARB (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDARBPROC) (GLenum mode, GLint first, GLsizei count, GLsizei primcount);
+typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDARBPROC) (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount);
+#endif
+
+#ifndef GL_ARB_framebuffer_object
+#define GL_ARB_framebuffer_object 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI GLboolean APIENTRY glIsRenderbuffer (GLuint renderbuffer);
+GLAPI void APIENTRY glBindRenderbuffer (GLenum target, GLuint renderbuffer);
+GLAPI void APIENTRY glDeleteRenderbuffers (GLsizei n, const GLuint *renderbuffers);
+GLAPI void APIENTRY glGenRenderbuffers (GLsizei n, GLuint *renderbuffers);
+GLAPI void APIENTRY glRenderbufferStorage (GLenum target, GLenum internalformat, GLsizei width, GLsizei height);
+GLAPI void APIENTRY glGetRenderbufferParameteriv (GLenum target, GLenum pname, GLint *params);
+GLAPI GLboolean APIENTRY glIsFramebuffer (GLuint framebuffer);
+GLAPI void APIENTRY glBindFramebuffer (GLenum target, GLuint framebuffer);
+GLAPI void APIENTRY glDeleteFramebuffers (GLsizei n, const GLuint *framebuffers);
+GLAPI void APIENTRY glGenFramebuffers (GLsizei n, GLuint *framebuffers);
+GLAPI GLenum APIENTRY glCheckFramebufferStatus (GLenum target);
+GLAPI void APIENTRY glFramebufferTexture1D (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
+GLAPI void APIENTRY glFramebufferTexture2D (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
+GLAPI void APIENTRY glFramebufferTexture3D (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset);
+GLAPI void APIENTRY glFramebufferRenderbuffer (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
+GLAPI void APIENTRY glGetFramebufferAttachmentParameteriv (GLenum target, GLenum attachment, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGenerateMipmap (GLenum target);
+GLAPI void APIENTRY glBlitFramebuffer (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
+GLAPI void APIENTRY glRenderbufferStorageMultisample (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
+GLAPI void APIENTRY glFramebufferTextureLayer (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef GLboolean (APIENTRYP PFNGLISRENDERBUFFERPROC) (GLuint renderbuffer);
+typedef void (APIENTRYP PFNGLBINDRENDERBUFFERPROC) (GLenum target, GLuint renderbuffer);
+typedef void (APIENTRYP PFNGLDELETERENDERBUFFERSPROC) (GLsizei n, const GLuint *renderbuffers);
+typedef void (APIENTRYP PFNGLGENRENDERBUFFERSPROC) (GLsizei n, GLuint *renderbuffers);
+typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height);
+typedef void (APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
+typedef GLboolean (APIENTRYP PFNGLISFRAMEBUFFERPROC) (GLuint framebuffer);
+typedef void (APIENTRYP PFNGLBINDFRAMEBUFFERPROC) (GLenum target, GLuint framebuffer);
+typedef void (APIENTRYP PFNGLDELETEFRAMEBUFFERSPROC) (GLsizei n, const GLuint *framebuffers);
+typedef void (APIENTRYP PFNGLGENFRAMEBUFFERSPROC) (GLsizei n, GLuint *framebuffers);
+typedef GLenum (APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSPROC) (GLenum target);
+typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE1DPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
+typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
+typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset);
+typedef void (APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFERPROC) (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
+typedef void (APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC) (GLenum target, GLenum attachment, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGENERATEMIPMAPPROC) (GLenum target);
+typedef void (APIENTRYP PFNGLBLITFRAMEBUFFERPROC) (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
+typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
+typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYERPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer);
+#endif
+
+#ifndef GL_ARB_framebuffer_sRGB
+#define GL_ARB_framebuffer_sRGB 1
+#endif
+
+#ifndef GL_ARB_geometry_shader4
+#define GL_ARB_geometry_shader4 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glProgramParameteriARB (GLuint program, GLenum pname, GLint value);
+GLAPI void APIENTRY glFramebufferTextureARB (GLenum target, GLenum attachment, GLuint texture, GLint level);
+GLAPI void APIENTRY glFramebufferTextureLayerARB (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer);
+GLAPI void APIENTRY glFramebufferTextureFaceARB (GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPROGRAMPARAMETERIARBPROC) (GLuint program, GLenum pname, GLint value);
+typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREARBPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level);
+typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYERARBPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer);
+typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREFACEARBPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face);
+#endif
+
+#ifndef GL_ARB_half_float_vertex
+#define GL_ARB_half_float_vertex 1
+#endif
+
+#ifndef GL_ARB_instanced_arrays
+#define GL_ARB_instanced_arrays 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glVertexAttribDivisorARB (GLuint index, GLuint divisor);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLVERTEXATTRIBDIVISORARBPROC) (GLuint index, GLuint divisor);
+#endif
+
+#ifndef GL_ARB_map_buffer_range
+#define GL_ARB_map_buffer_range 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI GLvoid* APIENTRY glMapBufferRange (GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access);
+GLAPI void APIENTRY glFlushMappedBufferRange (GLenum target, GLintptr offset, GLsizeiptr length);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef GLvoid* (APIENTRYP PFNGLMAPBUFFERRANGEPROC) (GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access);
+typedef void (APIENTRYP PFNGLFLUSHMAPPEDBUFFERRANGEPROC) (GLenum target, GLintptr offset, GLsizeiptr length);
+#endif
+
+#ifndef GL_ARB_texture_buffer_object
+#define GL_ARB_texture_buffer_object 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glTexBufferARB (GLenum target, GLenum internalformat, GLuint buffer);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLTEXBUFFERARBPROC) (GLenum target, GLenum internalformat, GLuint buffer);
+#endif
+
+#ifndef GL_ARB_texture_compression_rgtc
+#define GL_ARB_texture_compression_rgtc 1
+#endif
+
+#ifndef GL_ARB_texture_rg
+#define GL_ARB_texture_rg 1
+#endif
+
+#ifndef GL_ARB_vertex_array_object
+#define GL_ARB_vertex_array_object 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBindVertexArray (GLuint array);
+GLAPI void APIENTRY glDeleteVertexArrays (GLsizei n, const GLuint *arrays);
+GLAPI void APIENTRY glGenVertexArrays (GLsizei n, GLuint *arrays);
+GLAPI GLboolean APIENTRY glIsVertexArray (GLuint array);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBINDVERTEXARRAYPROC) (GLuint array);
+typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSPROC) (GLsizei n, const GLuint *arrays);
+typedef void (APIENTRYP PFNGLGENVERTEXARRAYSPROC) (GLsizei n, GLuint *arrays);
+typedef GLboolean (APIENTRYP PFNGLISVERTEXARRAYPROC) (GLuint array);
+#endif
+
+#ifndef GL_ARB_uniform_buffer_object
+#define GL_ARB_uniform_buffer_object 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glGetUniformIndices (GLuint program, GLsizei uniformCount, const GLchar* *uniformNames, GLuint *uniformIndices);
+GLAPI void APIENTRY glGetActiveUniformsiv (GLuint program, GLsizei uniformCount, const GLuint *uniformIndices, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetActiveUniformName (GLuint program, GLuint uniformIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformName);
+GLAPI GLuint APIENTRY glGetUniformBlockIndex (GLuint program, const GLchar *uniformBlockName);
+GLAPI void APIENTRY glGetActiveUniformBlockiv (GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetActiveUniformBlockName (GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformBlockName);
+GLAPI void APIENTRY glUniformBlockBinding (GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLGETUNIFORMINDICESPROC) (GLuint program, GLsizei uniformCount, const GLchar* *uniformNames, GLuint *uniformIndices);
+typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMSIVPROC) (GLuint program, GLsizei uniformCount, const GLuint *uniformIndices, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMNAMEPROC) (GLuint program, GLuint uniformIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformName);
+typedef GLuint (APIENTRYP PFNGLGETUNIFORMBLOCKINDEXPROC) (GLuint program, const GLchar *uniformBlockName);
+typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKIVPROC) (GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC) (GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformBlockName);
+typedef void (APIENTRYP PFNGLUNIFORMBLOCKBINDINGPROC) (GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding);
+#endif
+
+#ifndef GL_ARB_compatibility
+#define GL_ARB_compatibility 1
+#endif
+
+#ifndef GL_ARB_copy_buffer
+#define GL_ARB_copy_buffer 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glCopyBufferSubData (GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCOPYBUFFERSUBDATAPROC) (GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size);
+#endif
+
+#ifndef GL_ARB_shader_texture_lod
+#define GL_ARB_shader_texture_lod 1
+#endif
+
+#ifndef GL_ARB_depth_clamp
+#define GL_ARB_depth_clamp 1
+#endif
+
+#ifndef GL_ARB_draw_elements_base_vertex
+#define GL_ARB_draw_elements_base_vertex 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glDrawElementsBaseVertex (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLint basevertex);
+GLAPI void APIENTRY glDrawRangeElementsBaseVertex (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices, GLint basevertex);
+GLAPI void APIENTRY glDrawElementsInstancedBaseVertex (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount, GLint basevertex);
+GLAPI void APIENTRY glMultiDrawElementsBaseVertex (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount, const GLint *basevertex);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLDRAWELEMENTSBASEVERTEXPROC) (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLint basevertex);
+typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices, GLint basevertex);
+typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC) (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount, GLint basevertex);
+typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC) (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount, const GLint *basevertex);
+#endif
+
+#ifndef GL_ARB_fragment_coord_conventions
+#define GL_ARB_fragment_coord_conventions 1
+#endif
+
+#ifndef GL_ARB_provoking_vertex
+#define GL_ARB_provoking_vertex 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glProvokingVertex (GLenum mode);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPROVOKINGVERTEXPROC) (GLenum mode);
+#endif
+
+#ifndef GL_ARB_seamless_cube_map
+#define GL_ARB_seamless_cube_map 1
+#endif
+
+#ifndef GL_ARB_sync
+#define GL_ARB_sync 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI GLsync APIENTRY glFenceSync (GLenum condition, GLbitfield flags);
+GLAPI GLboolean APIENTRY glIsSync (GLsync sync);
+GLAPI void APIENTRY glDeleteSync (GLsync sync);
+GLAPI GLenum APIENTRY glClientWaitSync (GLsync sync, GLbitfield flags, GLuint64 timeout);
+GLAPI void APIENTRY glWaitSync (GLsync sync, GLbitfield flags, GLuint64 timeout);
+GLAPI void APIENTRY glGetInteger64v (GLenum pname, GLint64 *params);
+GLAPI void APIENTRY glGetSynciv (GLsync sync, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef GLsync (APIENTRYP PFNGLFENCESYNCPROC) (GLenum condition, GLbitfield flags);
+typedef GLboolean (APIENTRYP PFNGLISSYNCPROC) (GLsync sync);
+typedef void (APIENTRYP PFNGLDELETESYNCPROC) (GLsync sync);
+typedef GLenum (APIENTRYP PFNGLCLIENTWAITSYNCPROC) (GLsync sync, GLbitfield flags, GLuint64 timeout);
+typedef void (APIENTRYP PFNGLWAITSYNCPROC) (GLsync sync, GLbitfield flags, GLuint64 timeout);
+typedef void (APIENTRYP PFNGLGETINTEGER64VPROC) (GLenum pname, GLint64 *params);
+typedef void (APIENTRYP PFNGLGETSYNCIVPROC) (GLsync sync, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values);
+#endif
+
+#ifndef GL_ARB_texture_multisample
+#define GL_ARB_texture_multisample 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glTexImage2DMultisample (GLenum target, GLsizei samples, GLint internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations);
+GLAPI void APIENTRY glTexImage3DMultisample (GLenum target, GLsizei samples, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations);
+GLAPI void APIENTRY glGetMultisamplefv (GLenum pname, GLuint index, GLfloat *val);
+GLAPI void APIENTRY glSampleMaski (GLuint index, GLbitfield mask);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLTEXIMAGE2DMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLint internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations);
+typedef void (APIENTRYP PFNGLTEXIMAGE3DMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations);
+typedef void (APIENTRYP PFNGLGETMULTISAMPLEFVPROC) (GLenum pname, GLuint index, GLfloat *val);
+typedef void (APIENTRYP PFNGLSAMPLEMASKIPROC) (GLuint index, GLbitfield mask);
+#endif
+
+#ifndef GL_ARB_vertex_array_bgra
+#define GL_ARB_vertex_array_bgra 1
+#endif
+
+#ifndef GL_ARB_draw_buffers_blend
+#define GL_ARB_draw_buffers_blend 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBlendEquationiARB (GLuint buf, GLenum mode);
+GLAPI void APIENTRY glBlendEquationSeparateiARB (GLuint buf, GLenum modeRGB, GLenum modeAlpha);
+GLAPI void APIENTRY glBlendFunciARB (GLuint buf, GLenum src, GLenum dst);
+GLAPI void APIENTRY glBlendFuncSeparateiARB (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBLENDEQUATIONIARBPROC) (GLuint buf, GLenum mode);
+typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEIARBPROC) (GLuint buf, GLenum modeRGB, GLenum modeAlpha);
+typedef void (APIENTRYP PFNGLBLENDFUNCIARBPROC) (GLuint buf, GLenum src, GLenum dst);
+typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEIARBPROC) (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
+#endif
+
+#ifndef GL_ARB_sample_shading
+#define GL_ARB_sample_shading 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glMinSampleShadingARB (GLclampf value);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLMINSAMPLESHADINGARBPROC) (GLclampf value);
+#endif
+
+#ifndef GL_ARB_texture_cube_map_array
+#define GL_ARB_texture_cube_map_array 1
+#endif
+
+#ifndef GL_ARB_texture_gather
+#define GL_ARB_texture_gather 1
+#endif
+
+#ifndef GL_ARB_texture_query_lod
+#define GL_ARB_texture_query_lod 1
+#endif
+
+#ifndef GL_ARB_shading_language_include
+#define GL_ARB_shading_language_include 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glNamedStringARB (GLenum type, GLint namelen, const GLchar *name, GLint stringlen, const GLchar *string);
+GLAPI void APIENTRY glDeleteNamedStringARB (GLint namelen, const GLchar *name);
+GLAPI void APIENTRY glCompileShaderIncludeARB (GLuint shader, GLsizei count, const GLchar* *path, const GLint *length);
+GLAPI GLboolean APIENTRY glIsNamedStringARB (GLint namelen, const GLchar *name);
+GLAPI void APIENTRY glGetNamedStringARB (GLint namelen, const GLchar *name, GLsizei bufSize, GLint *stringlen, GLchar *string);
+GLAPI void APIENTRY glGetNamedStringivARB (GLint namelen, const GLchar *name, GLenum pname, GLint *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLNAMEDSTRINGARBPROC) (GLenum type, GLint namelen, const GLchar *name, GLint stringlen, const GLchar *string);
+typedef void (APIENTRYP PFNGLDELETENAMEDSTRINGARBPROC) (GLint namelen, const GLchar *name);
+typedef void (APIENTRYP PFNGLCOMPILESHADERINCLUDEARBPROC) (GLuint shader, GLsizei count, const GLchar* *path, const GLint *length);
+typedef GLboolean (APIENTRYP PFNGLISNAMEDSTRINGARBPROC) (GLint namelen, const GLchar *name);
+typedef void (APIENTRYP PFNGLGETNAMEDSTRINGARBPROC) (GLint namelen, const GLchar *name, GLsizei bufSize, GLint *stringlen, GLchar *string);
+typedef void (APIENTRYP PFNGLGETNAMEDSTRINGIVARBPROC) (GLint namelen, const GLchar *name, GLenum pname, GLint *params);
+#endif
+
+#ifndef GL_ARB_texture_compression_bptc
+#define GL_ARB_texture_compression_bptc 1
+#endif
+
+#ifndef GL_ARB_blend_func_extended
+#define GL_ARB_blend_func_extended 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBindFragDataLocationIndexed (GLuint program, GLuint colorNumber, GLuint index, const GLchar *name);
+GLAPI GLint APIENTRY glGetFragDataIndex (GLuint program, const GLchar *name);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBINDFRAGDATALOCATIONINDEXEDPROC) (GLuint program, GLuint colorNumber, GLuint index, const GLchar *name);
+typedef GLint (APIENTRYP PFNGLGETFRAGDATAINDEXPROC) (GLuint program, const GLchar *name);
+#endif
+
+#ifndef GL_ARB_explicit_attrib_location
+#define GL_ARB_explicit_attrib_location 1
+#endif
+
+#ifndef GL_ARB_occlusion_query2
+#define GL_ARB_occlusion_query2 1
+#endif
+
+#ifndef GL_ARB_sampler_objects
+#define GL_ARB_sampler_objects 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glGenSamplers (GLsizei count, GLuint *samplers);
+GLAPI void APIENTRY glDeleteSamplers (GLsizei count, const GLuint *samplers);
+GLAPI GLboolean APIENTRY glIsSampler (GLuint sampler);
+GLAPI void APIENTRY glBindSampler (GLuint unit, GLuint sampler);
+GLAPI void APIENTRY glSamplerParameteri (GLuint sampler, GLenum pname, GLint param);
+GLAPI void APIENTRY glSamplerParameteriv (GLuint sampler, GLenum pname, const GLint *param);
+GLAPI void APIENTRY glSamplerParameterf (GLuint sampler, GLenum pname, GLfloat param);
+GLAPI void APIENTRY glSamplerParameterfv (GLuint sampler, GLenum pname, const GLfloat *param);
+GLAPI void APIENTRY glSamplerParameterIiv (GLuint sampler, GLenum pname, const GLint *param);
+GLAPI void APIENTRY glSamplerParameterIuiv (GLuint sampler, GLenum pname, const GLuint *param);
+GLAPI void APIENTRY glGetSamplerParameteriv (GLuint sampler, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetSamplerParameterIiv (GLuint sampler, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetSamplerParameterfv (GLuint sampler, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetSamplerParameterIuiv (GLuint sampler, GLenum pname, GLuint *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLGENSAMPLERSPROC) (GLsizei count, GLuint *samplers);
+typedef void (APIENTRYP PFNGLDELETESAMPLERSPROC) (GLsizei count, const GLuint *samplers);
+typedef GLboolean (APIENTRYP PFNGLISSAMPLERPROC) (GLuint sampler);
+typedef void (APIENTRYP PFNGLBINDSAMPLERPROC) (GLuint unit, GLuint sampler);
+typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIPROC) (GLuint sampler, GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIVPROC) (GLuint sampler, GLenum pname, const GLint *param);
+typedef void (APIENTRYP PFNGLSAMPLERPARAMETERFPROC) (GLuint sampler, GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLSAMPLERPARAMETERFVPROC) (GLuint sampler, GLenum pname, const GLfloat *param);
+typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIIVPROC) (GLuint sampler, GLenum pname, const GLint *param);
+typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIUIVPROC) (GLuint sampler, GLenum pname, const GLuint *param);
+typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIVPROC) (GLuint sampler, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIIVPROC) (GLuint sampler, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERFVPROC) (GLuint sampler, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIUIVPROC) (GLuint sampler, GLenum pname, GLuint *params);
+#endif
+
+#ifndef GL_ARB_texture_rgb10_a2ui
+#define GL_ARB_texture_rgb10_a2ui 1
+#endif
+
+#ifndef GL_ARB_texture_swizzle
+#define GL_ARB_texture_swizzle 1
+#endif
+
+#ifndef GL_ARB_timer_query
+#define GL_ARB_timer_query 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glQueryCounter (GLuint id, GLenum target);
+GLAPI void APIENTRY glGetQueryObjecti64v (GLuint id, GLenum pname, GLint64 *params);
+GLAPI void APIENTRY glGetQueryObjectui64v (GLuint id, GLenum pname, GLuint64 *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLQUERYCOUNTERPROC) (GLuint id, GLenum target);
+typedef void (APIENTRYP PFNGLGETQUERYOBJECTI64VPROC) (GLuint id, GLenum pname, GLint64 *params);
+typedef void (APIENTRYP PFNGLGETQUERYOBJECTUI64VPROC) (GLuint id, GLenum pname, GLuint64 *params);
+#endif
+
+#ifndef GL_ARB_vertex_type_2_10_10_10_rev
+#define GL_ARB_vertex_type_2_10_10_10_rev 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glVertexP2ui (GLenum type, GLuint value);
+GLAPI void APIENTRY glVertexP2uiv (GLenum type, const GLuint *value);
+GLAPI void APIENTRY glVertexP3ui (GLenum type, GLuint value);
+GLAPI void APIENTRY glVertexP3uiv (GLenum type, const GLuint *value);
+GLAPI void APIENTRY glVertexP4ui (GLenum type, GLuint value);
+GLAPI void APIENTRY glVertexP4uiv (GLenum type, const GLuint *value);
+GLAPI void APIENTRY glTexCoordP1ui (GLenum type, GLuint coords);
+GLAPI void APIENTRY glTexCoordP1uiv (GLenum type, const GLuint *coords);
+GLAPI void APIENTRY glTexCoordP2ui (GLenum type, GLuint coords);
+GLAPI void APIENTRY glTexCoordP2uiv (GLenum type, const GLuint *coords);
+GLAPI void APIENTRY glTexCoordP3ui (GLenum type, GLuint coords);
+GLAPI void APIENTRY glTexCoordP3uiv (GLenum type, const GLuint *coords);
+GLAPI void APIENTRY glTexCoordP4ui (GLenum type, GLuint coords);
+GLAPI void APIENTRY glTexCoordP4uiv (GLenum type, const GLuint *coords);
+GLAPI void APIENTRY glMultiTexCoordP1ui (GLenum texture, GLenum type, GLuint coords);
+GLAPI void APIENTRY glMultiTexCoordP1uiv (GLenum texture, GLenum type, const GLuint *coords);
+GLAPI void APIENTRY glMultiTexCoordP2ui (GLenum texture, GLenum type, GLuint coords);
+GLAPI void APIENTRY glMultiTexCoordP2uiv (GLenum texture, GLenum type, const GLuint *coords);
+GLAPI void APIENTRY glMultiTexCoordP3ui (GLenum texture, GLenum type, GLuint coords);
+GLAPI void APIENTRY glMultiTexCoordP3uiv (GLenum texture, GLenum type, const GLuint *coords);
+GLAPI void APIENTRY glMultiTexCoordP4ui (GLenum texture, GLenum type, GLuint coords);
+GLAPI void APIENTRY glMultiTexCoordP4uiv (GLenum texture, GLenum type, const GLuint *coords);
+GLAPI void APIENTRY glNormalP3ui (GLenum type, GLuint coords);
+GLAPI void APIENTRY glNormalP3uiv (GLenum type, const GLuint *coords);
+GLAPI void APIENTRY glColorP3ui (GLenum type, GLuint color);
+GLAPI void APIENTRY glColorP3uiv (GLenum type, const GLuint *color);
+GLAPI void APIENTRY glColorP4ui (GLenum type, GLuint color);
+GLAPI void APIENTRY glColorP4uiv (GLenum type, const GLuint *color);
+GLAPI void APIENTRY glSecondaryColorP3ui (GLenum type, GLuint color);
+GLAPI void APIENTRY glSecondaryColorP3uiv (GLenum type, const GLuint *color);
+GLAPI void APIENTRY glVertexAttribP1ui (GLuint index, GLenum type, GLboolean normalized, GLuint value);
+GLAPI void APIENTRY glVertexAttribP1uiv (GLuint index, GLenum type, GLboolean normalized, const GLuint *value);
+GLAPI void APIENTRY glVertexAttribP2ui (GLuint index, GLenum type, GLboolean normalized, GLuint value);
+GLAPI void APIENTRY glVertexAttribP2uiv (GLuint index, GLenum type, GLboolean normalized, const GLuint *value);
+GLAPI void APIENTRY glVertexAttribP3ui (GLuint index, GLenum type, GLboolean normalized, GLuint value);
+GLAPI void APIENTRY glVertexAttribP3uiv (GLuint index, GLenum type, GLboolean normalized, const GLuint *value);
+GLAPI void APIENTRY glVertexAttribP4ui (GLuint index, GLenum type, GLboolean normalized, GLuint value);
+GLAPI void APIENTRY glVertexAttribP4uiv (GLuint index, GLenum type, GLboolean normalized, const GLuint *value);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLVERTEXP2UIPROC) (GLenum type, GLuint value);
+typedef void (APIENTRYP PFNGLVERTEXP2UIVPROC) (GLenum type, const GLuint *value);
+typedef void (APIENTRYP PFNGLVERTEXP3UIPROC) (GLenum type, GLuint value);
+typedef void (APIENTRYP PFNGLVERTEXP3UIVPROC) (GLenum type, const GLuint *value);
+typedef void (APIENTRYP PFNGLVERTEXP4UIPROC) (GLenum type, GLuint value);
+typedef void (APIENTRYP PFNGLVERTEXP4UIVPROC) (GLenum type, const GLuint *value);
+typedef void (APIENTRYP PFNGLTEXCOORDP1UIPROC) (GLenum type, GLuint coords);
+typedef void (APIENTRYP PFNGLTEXCOORDP1UIVPROC) (GLenum type, const GLuint *coords);
+typedef void (APIENTRYP PFNGLTEXCOORDP2UIPROC) (GLenum type, GLuint coords);
+typedef void (APIENTRYP PFNGLTEXCOORDP2UIVPROC) (GLenum type, const GLuint *coords);
+typedef void (APIENTRYP PFNGLTEXCOORDP3UIPROC) (GLenum type, GLuint coords);
+typedef void (APIENTRYP PFNGLTEXCOORDP3UIVPROC) (GLenum type, const GLuint *coords);
+typedef void (APIENTRYP PFNGLTEXCOORDP4UIPROC) (GLenum type, GLuint coords);
+typedef void (APIENTRYP PFNGLTEXCOORDP4UIVPROC) (GLenum type, const GLuint *coords);
+typedef void (APIENTRYP PFNGLMULTITEXCOORDP1UIPROC) (GLenum texture, GLenum type, GLuint coords);
+typedef void (APIENTRYP PFNGLMULTITEXCOORDP1UIVPROC) (GLenum texture, GLenum type, const GLuint *coords);
+typedef void (APIENTRYP PFNGLMULTITEXCOORDP2UIPROC) (GLenum texture, GLenum type, GLuint coords);
+typedef void (APIENTRYP PFNGLMULTITEXCOORDP2UIVPROC) (GLenum texture, GLenum type, const GLuint *coords);
+typedef void (APIENTRYP PFNGLMULTITEXCOORDP3UIPROC) (GLenum texture, GLenum type, GLuint coords);
+typedef void (APIENTRYP PFNGLMULTITEXCOORDP3UIVPROC) (GLenum texture, GLenum type, const GLuint *coords);
+typedef void (APIENTRYP PFNGLMULTITEXCOORDP4UIPROC) (GLenum texture, GLenum type, GLuint coords);
+typedef void (APIENTRYP PFNGLMULTITEXCOORDP4UIVPROC) (GLenum texture, GLenum type, const GLuint *coords);
+typedef void (APIENTRYP PFNGLNORMALP3UIPROC) (GLenum type, GLuint coords);
+typedef void (APIENTRYP PFNGLNORMALP3UIVPROC) (GLenum type, const GLuint *coords);
+typedef void (APIENTRYP PFNGLCOLORP3UIPROC) (GLenum type, GLuint color);
+typedef void (APIENTRYP PFNGLCOLORP3UIVPROC) (GLenum type, const GLuint *color);
+typedef void (APIENTRYP PFNGLCOLORP4UIPROC) (GLenum type, GLuint color);
+typedef void (APIENTRYP PFNGLCOLORP4UIVPROC) (GLenum type, const GLuint *color);
+typedef void (APIENTRYP PFNGLSECONDARYCOLORP3UIPROC) (GLenum type, GLuint color);
+typedef void (APIENTRYP PFNGLSECONDARYCOLORP3UIVPROC) (GLenum type, const GLuint *color);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBP1UIPROC) (GLuint index, GLenum type, GLboolean normalized, GLuint value);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBP1UIVPROC) (GLuint index, GLenum type, GLboolean normalized, const GLuint *value);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBP2UIPROC) (GLuint index, GLenum type, GLboolean normalized, GLuint value);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBP2UIVPROC) (GLuint index, GLenum type, GLboolean normalized, const GLuint *value);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBP3UIPROC) (GLuint index, GLenum type, GLboolean normalized, GLuint value);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBP3UIVPROC) (GLuint index, GLenum type, GLboolean normalized, const GLuint *value);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBP4UIPROC) (GLuint index, GLenum type, GLboolean normalized, GLuint value);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBP4UIVPROC) (GLuint index, GLenum type, GLboolean normalized, const GLuint *value);
+#endif
+
+#ifndef GL_ARB_draw_indirect
+#define GL_ARB_draw_indirect 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glDrawArraysIndirect (GLenum mode, const GLvoid *indirect);
+GLAPI void APIENTRY glDrawElementsIndirect (GLenum mode, GLenum type, const GLvoid *indirect);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLDRAWARRAYSINDIRECTPROC) (GLenum mode, const GLvoid *indirect);
+typedef void (APIENTRYP PFNGLDRAWELEMENTSINDIRECTPROC) (GLenum mode, GLenum type, const GLvoid *indirect);
+#endif
+
+#ifndef GL_ARB_gpu_shader5
+#define GL_ARB_gpu_shader5 1
+#endif
+
+#ifndef GL_ARB_gpu_shader_fp64
+#define GL_ARB_gpu_shader_fp64 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glUniform1d (GLint location, GLdouble x);
+GLAPI void APIENTRY glUniform2d (GLint location, GLdouble x, GLdouble y);
+GLAPI void APIENTRY glUniform3d (GLint location, GLdouble x, GLdouble y, GLdouble z);
+GLAPI void APIENTRY glUniform4d (GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+GLAPI void APIENTRY glUniform1dv (GLint location, GLsizei count, const GLdouble *value);
+GLAPI void APIENTRY glUniform2dv (GLint location, GLsizei count, const GLdouble *value);
+GLAPI void APIENTRY glUniform3dv (GLint location, GLsizei count, const GLdouble *value);
+GLAPI void APIENTRY glUniform4dv (GLint location, GLsizei count, const GLdouble *value);
+GLAPI void APIENTRY glUniformMatrix2dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+GLAPI void APIENTRY glUniformMatrix3dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+GLAPI void APIENTRY glUniformMatrix4dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+GLAPI void APIENTRY glUniformMatrix2x3dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+GLAPI void APIENTRY glUniformMatrix2x4dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+GLAPI void APIENTRY glUniformMatrix3x2dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+GLAPI void APIENTRY glUniformMatrix3x4dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+GLAPI void APIENTRY glUniformMatrix4x2dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+GLAPI void APIENTRY glUniformMatrix4x3dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+GLAPI void APIENTRY glGetUniformdv (GLuint program, GLint location, GLdouble *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLUNIFORM1DPROC) (GLint location, GLdouble x);
+typedef void (APIENTRYP PFNGLUNIFORM2DPROC) (GLint location, GLdouble x, GLdouble y);
+typedef void (APIENTRYP PFNGLUNIFORM3DPROC) (GLint location, GLdouble x, GLdouble y, GLdouble z);
+typedef void (APIENTRYP PFNGLUNIFORM4DPROC) (GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+typedef void (APIENTRYP PFNGLUNIFORM1DVPROC) (GLint location, GLsizei count, const GLdouble *value);
+typedef void (APIENTRYP PFNGLUNIFORM2DVPROC) (GLint location, GLsizei count, const GLdouble *value);
+typedef void (APIENTRYP PFNGLUNIFORM3DVPROC) (GLint location, GLsizei count, const GLdouble *value);
+typedef void (APIENTRYP PFNGLUNIFORM4DVPROC) (GLint location, GLsizei count, const GLdouble *value);
+typedef void (APIENTRYP PFNGLUNIFORMMATRIX2DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+typedef void (APIENTRYP PFNGLUNIFORMMATRIX3DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+typedef void (APIENTRYP PFNGLUNIFORMMATRIX4DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X3DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X4DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X2DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X4DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X2DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X3DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+typedef void (APIENTRYP PFNGLGETUNIFORMDVPROC) (GLuint program, GLint location, GLdouble *params);
+#endif
+
+#ifndef GL_ARB_shader_subroutine
+#define GL_ARB_shader_subroutine 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI GLint APIENTRY glGetSubroutineUniformLocation (GLuint program, GLenum shadertype, const GLchar *name);
+GLAPI GLuint APIENTRY glGetSubroutineIndex (GLuint program, GLenum shadertype, const GLchar *name);
+GLAPI void APIENTRY glGetActiveSubroutineUniformiv (GLuint program, GLenum shadertype, GLuint index, GLenum pname, GLint *values);
+GLAPI void APIENTRY glGetActiveSubroutineUniformName (GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei *length, GLchar *name);
+GLAPI void APIENTRY glGetActiveSubroutineName (GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei *length, GLchar *name);
+GLAPI void APIENTRY glUniformSubroutinesuiv (GLenum shadertype, GLsizei count, const GLuint *indices);
+GLAPI void APIENTRY glGetUniformSubroutineuiv (GLenum shadertype, GLint location, GLuint *params);
+GLAPI void APIENTRY glGetProgramStageiv (GLuint program, GLenum shadertype, GLenum pname, GLint *values);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef GLint (APIENTRYP PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC) (GLuint program, GLenum shadertype, const GLchar *name);
+typedef GLuint (APIENTRYP PFNGLGETSUBROUTINEINDEXPROC) (GLuint program, GLenum shadertype, const GLchar *name);
+typedef void (APIENTRYP PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC) (GLuint program, GLenum shadertype, GLuint index, GLenum pname, GLint *values);
+typedef void (APIENTRYP PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC) (GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei *length, GLchar *name);
+typedef void (APIENTRYP PFNGLGETACTIVESUBROUTINENAMEPROC) (GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei *length, GLchar *name);
+typedef void (APIENTRYP PFNGLUNIFORMSUBROUTINESUIVPROC) (GLenum shadertype, GLsizei count, const GLuint *indices);
+typedef void (APIENTRYP PFNGLGETUNIFORMSUBROUTINEUIVPROC) (GLenum shadertype, GLint location, GLuint *params);
+typedef void (APIENTRYP PFNGLGETPROGRAMSTAGEIVPROC) (GLuint program, GLenum shadertype, GLenum pname, GLint *values);
+#endif
+
+#ifndef GL_ARB_tessellation_shader
+#define GL_ARB_tessellation_shader 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glPatchParameteri (GLenum pname, GLint value);
+GLAPI void APIENTRY glPatchParameterfv (GLenum pname, const GLfloat *values);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPATCHPARAMETERIPROC) (GLenum pname, GLint value);
+typedef void (APIENTRYP PFNGLPATCHPARAMETERFVPROC) (GLenum pname, const GLfloat *values);
+#endif
+
+#ifndef GL_ARB_texture_buffer_object_rgb32
+#define GL_ARB_texture_buffer_object_rgb32 1
+#endif
+
+#ifndef GL_ARB_transform_feedback2
+#define GL_ARB_transform_feedback2 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBindTransformFeedback (GLenum target, GLuint id);
+GLAPI void APIENTRY glDeleteTransformFeedbacks (GLsizei n, const GLuint *ids);
+GLAPI void APIENTRY glGenTransformFeedbacks (GLsizei n, GLuint *ids);
+GLAPI GLboolean APIENTRY glIsTransformFeedback (GLuint id);
+GLAPI void APIENTRY glPauseTransformFeedback (void);
+GLAPI void APIENTRY glResumeTransformFeedback (void);
+GLAPI void APIENTRY glDrawTransformFeedback (GLenum mode, GLuint id);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBINDTRANSFORMFEEDBACKPROC) (GLenum target, GLuint id);
+typedef void (APIENTRYP PFNGLDELETETRANSFORMFEEDBACKSPROC) (GLsizei n, const GLuint *ids);
+typedef void (APIENTRYP PFNGLGENTRANSFORMFEEDBACKSPROC) (GLsizei n, GLuint *ids);
+typedef GLboolean (APIENTRYP PFNGLISTRANSFORMFEEDBACKPROC) (GLuint id);
+typedef void (APIENTRYP PFNGLPAUSETRANSFORMFEEDBACKPROC) (void);
+typedef void (APIENTRYP PFNGLRESUMETRANSFORMFEEDBACKPROC) (void);
+typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKPROC) (GLenum mode, GLuint id);
+#endif
+
+#ifndef GL_ARB_transform_feedback3
+#define GL_ARB_transform_feedback3 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glDrawTransformFeedbackStream (GLenum mode, GLuint id, GLuint stream);
+GLAPI void APIENTRY glBeginQueryIndexed (GLenum target, GLuint index, GLuint id);
+GLAPI void APIENTRY glEndQueryIndexed (GLenum target, GLuint index);
+GLAPI void APIENTRY glGetQueryIndexediv (GLenum target, GLuint index, GLenum pname, GLint *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC) (GLenum mode, GLuint id, GLuint stream);
+typedef void (APIENTRYP PFNGLBEGINQUERYINDEXEDPROC) (GLenum target, GLuint index, GLuint id);
+typedef void (APIENTRYP PFNGLENDQUERYINDEXEDPROC) (GLenum target, GLuint index);
+typedef void (APIENTRYP PFNGLGETQUERYINDEXEDIVPROC) (GLenum target, GLuint index, GLenum pname, GLint *params);
+#endif
+
+#ifndef GL_ARB_ES2_compatibility
+#define GL_ARB_ES2_compatibility 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glReleaseShaderCompiler (void);
+GLAPI void APIENTRY glShaderBinary (GLsizei count, const GLuint *shaders, GLenum binaryformat, const GLvoid *binary, GLsizei length);
+GLAPI void APIENTRY glGetShaderPrecisionFormat (GLenum shadertype, GLenum precisiontype, GLint *range, GLint *precision);
+GLAPI void APIENTRY glDepthRangef (GLclampf n, GLclampf f);
+GLAPI void APIENTRY glClearDepthf (GLclampf d);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLRELEASESHADERCOMPILERPROC) (void);
+typedef void (APIENTRYP PFNGLSHADERBINARYPROC) (GLsizei count, const GLuint *shaders, GLenum binaryformat, const GLvoid *binary, GLsizei length);
+typedef void (APIENTRYP PFNGLGETSHADERPRECISIONFORMATPROC) (GLenum shadertype, GLenum precisiontype, GLint *range, GLint *precision);
+typedef void (APIENTRYP PFNGLDEPTHRANGEFPROC) (GLclampf n, GLclampf f);
+typedef void (APIENTRYP PFNGLCLEARDEPTHFPROC) (GLclampf d);
+#endif
+
+#ifndef GL_ARB_get_program_binary
+#define GL_ARB_get_program_binary 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glGetProgramBinary (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, GLvoid *binary);
+GLAPI void APIENTRY glProgramBinary (GLuint program, GLenum binaryFormat, const GLvoid *binary, GLsizei length);
+GLAPI void APIENTRY glProgramParameteri (GLuint program, GLenum pname, GLint value);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLGETPROGRAMBINARYPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, GLvoid *binary);
+typedef void (APIENTRYP PFNGLPROGRAMBINARYPROC) (GLuint program, GLenum binaryFormat, const GLvoid *binary, GLsizei length);
+typedef void (APIENTRYP PFNGLPROGRAMPARAMETERIPROC) (GLuint program, GLenum pname, GLint value);
+#endif
+
+#ifndef GL_ARB_separate_shader_objects
+#define GL_ARB_separate_shader_objects 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glUseProgramStages (GLuint pipeline, GLbitfield stages, GLuint program);
+GLAPI void APIENTRY glActiveShaderProgram (GLuint pipeline, GLuint program);
+GLAPI GLuint APIENTRY glCreateShaderProgramv (GLenum type, GLsizei count, const GLchar* *strings);
+GLAPI void APIENTRY glBindProgramPipeline (GLuint pipeline);
+GLAPI void APIENTRY glDeleteProgramPipelines (GLsizei n, const GLuint *pipelines);
+GLAPI void APIENTRY glGenProgramPipelines (GLsizei n, GLuint *pipelines);
+GLAPI GLboolean APIENTRY glIsProgramPipeline (GLuint pipeline);
+GLAPI void APIENTRY glGetProgramPipelineiv (GLuint pipeline, GLenum pname, GLint *params);
+GLAPI void APIENTRY glProgramUniform1i (GLuint program, GLint location, GLint v0);
+GLAPI void APIENTRY glProgramUniform1iv (GLuint program, GLint location, GLsizei count, const GLint *value);
+GLAPI void APIENTRY glProgramUniform1f (GLuint program, GLint location, GLfloat v0);
+GLAPI void APIENTRY glProgramUniform1fv (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+GLAPI void APIENTRY glProgramUniform1d (GLuint program, GLint location, GLdouble v0);
+GLAPI void APIENTRY glProgramUniform1dv (GLuint program, GLint location, GLsizei count, const GLdouble *value);
+GLAPI void APIENTRY glProgramUniform1ui (GLuint program, GLint location, GLuint v0);
+GLAPI void APIENTRY glProgramUniform1uiv (GLuint program, GLint location, GLsizei count, const GLuint *value);
+GLAPI void APIENTRY glProgramUniform2i (GLuint program, GLint location, GLint v0, GLint v1);
+GLAPI void APIENTRY glProgramUniform2iv (GLuint program, GLint location, GLsizei count, const GLint *value);
+GLAPI void APIENTRY glProgramUniform2f (GLuint program, GLint location, GLfloat v0, GLfloat v1);
+GLAPI void APIENTRY glProgramUniform2fv (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+GLAPI void APIENTRY glProgramUniform2d (GLuint program, GLint location, GLdouble v0, GLdouble v1);
+GLAPI void APIENTRY glProgramUniform2dv (GLuint program, GLint location, GLsizei count, const GLdouble *value);
+GLAPI void APIENTRY glProgramUniform2ui (GLuint program, GLint location, GLuint v0, GLuint v1);
+GLAPI void APIENTRY glProgramUniform2uiv (GLuint program, GLint location, GLsizei count, const GLuint *value);
+GLAPI void APIENTRY glProgramUniform3i (GLuint program, GLint location, GLint v0, GLint v1, GLint v2);
+GLAPI void APIENTRY glProgramUniform3iv (GLuint program, GLint location, GLsizei count, const GLint *value);
+GLAPI void APIENTRY glProgramUniform3f (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
+GLAPI void APIENTRY glProgramUniform3fv (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+GLAPI void APIENTRY glProgramUniform3d (GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2);
+GLAPI void APIENTRY glProgramUniform3dv (GLuint program, GLint location, GLsizei count, const GLdouble *value);
+GLAPI void APIENTRY glProgramUniform3ui (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2);
+GLAPI void APIENTRY glProgramUniform3uiv (GLuint program, GLint location, GLsizei count, const GLuint *value);
+GLAPI void APIENTRY glProgramUniform4i (GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
+GLAPI void APIENTRY glProgramUniform4iv (GLuint program, GLint location, GLsizei count, const GLint *value);
+GLAPI void APIENTRY glProgramUniform4f (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
+GLAPI void APIENTRY glProgramUniform4fv (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+GLAPI void APIENTRY glProgramUniform4d (GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2, GLdouble v3);
+GLAPI void APIENTRY glProgramUniform4dv (GLuint program, GLint location, GLsizei count, const GLdouble *value);
+GLAPI void APIENTRY glProgramUniform4ui (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3);
+GLAPI void APIENTRY glProgramUniform4uiv (GLuint program, GLint location, GLsizei count, const GLuint *value);
+GLAPI void APIENTRY glProgramUniformMatrix2fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GLAPI void APIENTRY glProgramUniformMatrix3fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GLAPI void APIENTRY glProgramUniformMatrix4fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GLAPI void APIENTRY glProgramUniformMatrix2dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+GLAPI void APIENTRY glProgramUniformMatrix3dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+GLAPI void APIENTRY glProgramUniformMatrix4dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+GLAPI void APIENTRY glProgramUniformMatrix2x3fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GLAPI void APIENTRY glProgramUniformMatrix3x2fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GLAPI void APIENTRY glProgramUniformMatrix2x4fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GLAPI void APIENTRY glProgramUniformMatrix4x2fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GLAPI void APIENTRY glProgramUniformMatrix3x4fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GLAPI void APIENTRY glProgramUniformMatrix4x3fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GLAPI void APIENTRY glProgramUniformMatrix2x3dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+GLAPI void APIENTRY glProgramUniformMatrix3x2dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+GLAPI void APIENTRY glProgramUniformMatrix2x4dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+GLAPI void APIENTRY glProgramUniformMatrix4x2dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+GLAPI void APIENTRY glProgramUniformMatrix3x4dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+GLAPI void APIENTRY glProgramUniformMatrix4x3dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+GLAPI void APIENTRY glValidateProgramPipeline (GLuint pipeline);
+GLAPI void APIENTRY glGetProgramPipelineInfoLog (GLuint pipeline, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLUSEPROGRAMSTAGESPROC) (GLuint pipeline, GLbitfield stages, GLuint program);
+typedef void (APIENTRYP PFNGLACTIVESHADERPROGRAMPROC) (GLuint pipeline, GLuint program);
+typedef GLuint (APIENTRYP PFNGLCREATESHADERPROGRAMVPROC) (GLenum type, GLsizei count, const GLchar* *strings);
+typedef void (APIENTRYP PFNGLBINDPROGRAMPIPELINEPROC) (GLuint pipeline);
+typedef void (APIENTRYP PFNGLDELETEPROGRAMPIPELINESPROC) (GLsizei n, const GLuint *pipelines);
+typedef void (APIENTRYP PFNGLGENPROGRAMPIPELINESPROC) (GLsizei n, GLuint *pipelines);
+typedef GLboolean (APIENTRYP PFNGLISPROGRAMPIPELINEPROC) (GLuint pipeline);
+typedef void (APIENTRYP PFNGLGETPROGRAMPIPELINEIVPROC) (GLuint pipeline, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1IPROC) (GLuint program, GLint location, GLint v0);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1IVPROC) (GLuint program, GLint location, GLsizei count, const GLint *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1FPROC) (GLuint program, GLint location, GLfloat v0);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1FVPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1DPROC) (GLuint program, GLint location, GLdouble v0);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1DVPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UIPROC) (GLuint program, GLint location, GLuint v0);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UIVPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2IPROC) (GLuint program, GLint location, GLint v0, GLint v1);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2IVPROC) (GLuint program, GLint location, GLsizei count, const GLint *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2FPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2FVPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2DPROC) (GLuint program, GLint location, GLdouble v0, GLdouble v1);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2DVPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UIPROC) (GLuint program, GLint location, GLuint v0, GLuint v1);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UIVPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3IPROC) (GLuint program, GLint location, GLint v0, GLint v1, GLint v2);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3IVPROC) (GLuint program, GLint location, GLsizei count, const GLint *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3FPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3FVPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3DPROC) (GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3DVPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UIPROC) (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UIVPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4IPROC) (GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4IVPROC) (GLuint program, GLint location, GLsizei count, const GLint *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4FPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4FVPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4DPROC) (GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2, GLdouble v3);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4DVPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UIPROC) (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UIVPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+typedef void (APIENTRYP PFNGLVALIDATEPROGRAMPIPELINEPROC) (GLuint pipeline);
+typedef void (APIENTRYP PFNGLGETPROGRAMPIPELINEINFOLOGPROC) (GLuint pipeline, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
+#endif
+
+#ifndef GL_ARB_vertex_attrib_64bit
+#define GL_ARB_vertex_attrib_64bit 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glVertexAttribL1d (GLuint index, GLdouble x);
+GLAPI void APIENTRY glVertexAttribL2d (GLuint index, GLdouble x, GLdouble y);
+GLAPI void APIENTRY glVertexAttribL3d (GLuint index, GLdouble x, GLdouble y, GLdouble z);
+GLAPI void APIENTRY glVertexAttribL4d (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+GLAPI void APIENTRY glVertexAttribL1dv (GLuint index, const GLdouble *v);
+GLAPI void APIENTRY glVertexAttribL2dv (GLuint index, const GLdouble *v);
+GLAPI void APIENTRY glVertexAttribL3dv (GLuint index, const GLdouble *v);
+GLAPI void APIENTRY glVertexAttribL4dv (GLuint index, const GLdouble *v);
+GLAPI void APIENTRY glVertexAttribLPointer (GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+GLAPI void APIENTRY glGetVertexAttribLdv (GLuint index, GLenum pname, GLdouble *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL1DPROC) (GLuint index, GLdouble x);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL2DPROC) (GLuint index, GLdouble x, GLdouble y);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL3DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL4DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL1DVPROC) (GLuint index, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL2DVPROC) (GLuint index, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL3DVPROC) (GLuint index, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL4DVPROC) (GLuint index, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBLPOINTERPROC) (GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBLDVPROC) (GLuint index, GLenum pname, GLdouble *params);
+#endif
+
+#ifndef GL_ARB_viewport_array
+#define GL_ARB_viewport_array 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glViewportArrayv (GLuint first, GLsizei count, const GLfloat *v);
+GLAPI void APIENTRY glViewportIndexedf (GLuint index, GLfloat x, GLfloat y, GLfloat w, GLfloat h);
+GLAPI void APIENTRY glViewportIndexedfv (GLuint index, const GLfloat *v);
+GLAPI void APIENTRY glScissorArrayv (GLuint first, GLsizei count, const GLint *v);
+GLAPI void APIENTRY glScissorIndexed (GLuint index, GLint left, GLint bottom, GLsizei width, GLsizei height);
+GLAPI void APIENTRY glScissorIndexedv (GLuint index, const GLint *v);
+GLAPI void APIENTRY glDepthRangeArrayv (GLuint first, GLsizei count, const GLclampd *v);
+GLAPI void APIENTRY glDepthRangeIndexed (GLuint index, GLclampd n, GLclampd f);
+GLAPI void APIENTRY glGetFloati_v (GLenum target, GLuint index, GLfloat *data);
+GLAPI void APIENTRY glGetDoublei_v (GLenum target, GLuint index, GLdouble *data);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLVIEWPORTARRAYVPROC) (GLuint first, GLsizei count, const GLfloat *v);
+typedef void (APIENTRYP PFNGLVIEWPORTINDEXEDFPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat w, GLfloat h);
+typedef void (APIENTRYP PFNGLVIEWPORTINDEXEDFVPROC) (GLuint index, const GLfloat *v);
+typedef void (APIENTRYP PFNGLSCISSORARRAYVPROC) (GLuint first, GLsizei count, const GLint *v);
+typedef void (APIENTRYP PFNGLSCISSORINDEXEDPROC) (GLuint index, GLint left, GLint bottom, GLsizei width, GLsizei height);
+typedef void (APIENTRYP PFNGLSCISSORINDEXEDVPROC) (GLuint index, const GLint *v);
+typedef void (APIENTRYP PFNGLDEPTHRANGEARRAYVPROC) (GLuint first, GLsizei count, const GLclampd *v);
+typedef void (APIENTRYP PFNGLDEPTHRANGEINDEXEDPROC) (GLuint index, GLclampd n, GLclampd f);
+typedef void (APIENTRYP PFNGLGETFLOATI_VPROC) (GLenum target, GLuint index, GLfloat *data);
+typedef void (APIENTRYP PFNGLGETDOUBLEI_VPROC) (GLenum target, GLuint index, GLdouble *data);
+#endif
+
+#ifndef GL_ARB_cl_event
+#define GL_ARB_cl_event 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI GLsync APIENTRY glCreateSyncFromCLeventARB (struct _cl_context * context, struct _cl_event * event, GLbitfield flags);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef GLsync (APIENTRYP PFNGLCREATESYNCFROMCLEVENTARBPROC) (struct _cl_context * context, struct _cl_event * event, GLbitfield flags);
+#endif
+
+#ifndef GL_ARB_debug_output
+#define GL_ARB_debug_output 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glDebugMessageControlARB (GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled);
+GLAPI void APIENTRY glDebugMessageInsertARB (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf);
+GLAPI void APIENTRY glDebugMessageCallbackARB (GLDEBUGPROCARB callback, const GLvoid *userParam);
+GLAPI GLuint APIENTRY glGetDebugMessageLogARB (GLuint count, GLsizei bufsize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLDEBUGMESSAGECONTROLARBPROC) (GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled);
+typedef void (APIENTRYP PFNGLDEBUGMESSAGEINSERTARBPROC) (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf);
+typedef void (APIENTRYP PFNGLDEBUGMESSAGECALLBACKARBPROC) (GLDEBUGPROCARB callback, const GLvoid *userParam);
+typedef GLuint (APIENTRYP PFNGLGETDEBUGMESSAGELOGARBPROC) (GLuint count, GLsizei bufsize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog);
+#endif
+
+#ifndef GL_ARB_robustness
+#define GL_ARB_robustness 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI GLenum APIENTRY glGetGraphicsResetStatusARB (void);
+GLAPI void APIENTRY glGetnMapdvARB (GLenum target, GLenum query, GLsizei bufSize, GLdouble *v);
+GLAPI void APIENTRY glGetnMapfvARB (GLenum target, GLenum query, GLsizei bufSize, GLfloat *v);
+GLAPI void APIENTRY glGetnMapivARB (GLenum target, GLenum query, GLsizei bufSize, GLint *v);
+GLAPI void APIENTRY glGetnPixelMapfvARB (GLenum map, GLsizei bufSize, GLfloat *values);
+GLAPI void APIENTRY glGetnPixelMapuivARB (GLenum map, GLsizei bufSize, GLuint *values);
+GLAPI void APIENTRY glGetnPixelMapusvARB (GLenum map, GLsizei bufSize, GLushort *values);
+GLAPI void APIENTRY glGetnPolygonStippleARB (GLsizei bufSize, GLubyte *pattern);
+GLAPI void APIENTRY glGetnColorTableARB (GLenum target, GLenum format, GLenum type, GLsizei bufSize, GLvoid *table);
+GLAPI void APIENTRY glGetnConvolutionFilterARB (GLenum target, GLenum format, GLenum type, GLsizei bufSize, GLvoid *image);
+GLAPI void APIENTRY glGetnSeparableFilterARB (GLenum target, GLenum format, GLenum type, GLsizei rowBufSize, GLvoid *row, GLsizei columnBufSize, GLvoid *column, GLvoid *span);
+GLAPI void APIENTRY glGetnHistogramARB (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, GLvoid *values);
+GLAPI void APIENTRY glGetnMinmaxARB (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, GLvoid *values);
+GLAPI void APIENTRY glGetnTexImageARB (GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, GLvoid *img);
+GLAPI void APIENTRY glReadnPixelsARB (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, GLvoid *data);
+GLAPI void APIENTRY glGetnCompressedTexImageARB (GLenum target, GLint lod, GLsizei bufSize, GLvoid *img);
+GLAPI void APIENTRY glGetnUniformfvARB (GLuint program, GLint location, GLsizei bufSize, GLfloat *params);
+GLAPI void APIENTRY glGetnUniformivARB (GLuint program, GLint location, GLsizei bufSize, GLint *params);
+GLAPI void APIENTRY glGetnUniformuivARB (GLuint program, GLint location, GLsizei bufSize, GLuint *params);
+GLAPI void APIENTRY glGetnUniformdvARB (GLuint program, GLint location, GLsizei bufSize, GLdouble *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef GLenum (APIENTRYP PFNGLGETGRAPHICSRESETSTATUSARBPROC) (void);
+typedef void (APIENTRYP PFNGLGETNMAPDVARBPROC) (GLenum target, GLenum query, GLsizei bufSize, GLdouble *v);
+typedef void (APIENTRYP PFNGLGETNMAPFVARBPROC) (GLenum target, GLenum query, GLsizei bufSize, GLfloat *v);
+typedef void (APIENTRYP PFNGLGETNMAPIVARBPROC) (GLenum target, GLenum query, GLsizei bufSize, GLint *v);
+typedef void (APIENTRYP PFNGLGETNPIXELMAPFVARBPROC) (GLenum map, GLsizei bufSize, GLfloat *values);
+typedef void (APIENTRYP PFNGLGETNPIXELMAPUIVARBPROC) (GLenum map, GLsizei bufSize, GLuint *values);
+typedef void (APIENTRYP PFNGLGETNPIXELMAPUSVARBPROC) (GLenum map, GLsizei bufSize, GLushort *values);
+typedef void (APIENTRYP PFNGLGETNPOLYGONSTIPPLEARBPROC) (GLsizei bufSize, GLubyte *pattern);
+typedef void (APIENTRYP PFNGLGETNCOLORTABLEARBPROC) (GLenum target, GLenum format, GLenum type, GLsizei bufSize, GLvoid *table);
+typedef void (APIENTRYP PFNGLGETNCONVOLUTIONFILTERARBPROC) (GLenum target, GLenum format, GLenum type, GLsizei bufSize, GLvoid *image);
+typedef void (APIENTRYP PFNGLGETNSEPARABLEFILTERARBPROC) (GLenum target, GLenum format, GLenum type, GLsizei rowBufSize, GLvoid *row, GLsizei columnBufSize, GLvoid *column, GLvoid *span);
+typedef void (APIENTRYP PFNGLGETNHISTOGRAMARBPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, GLvoid *values);
+typedef void (APIENTRYP PFNGLGETNMINMAXARBPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, GLvoid *values);
+typedef void (APIENTRYP PFNGLGETNTEXIMAGEARBPROC) (GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, GLvoid *img);
+typedef void (APIENTRYP PFNGLREADNPIXELSARBPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, GLvoid *data);
+typedef void (APIENTRYP PFNGLGETNCOMPRESSEDTEXIMAGEARBPROC) (GLenum target, GLint lod, GLsizei bufSize, GLvoid *img);
+typedef void (APIENTRYP PFNGLGETNUNIFORMFVARBPROC) (GLuint program, GLint location, GLsizei bufSize, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETNUNIFORMIVARBPROC) (GLuint program, GLint location, GLsizei bufSize, GLint *params);
+typedef void (APIENTRYP PFNGLGETNUNIFORMUIVARBPROC) (GLuint program, GLint location, GLsizei bufSize, GLuint *params);
+typedef void (APIENTRYP PFNGLGETNUNIFORMDVARBPROC) (GLuint program, GLint location, GLsizei bufSize, GLdouble *params);
+#endif
+
+#ifndef GL_ARB_shader_stencil_export
+#define GL_ARB_shader_stencil_export 1
+#endif
+
+#ifndef GL_EXT_abgr
+#define GL_EXT_abgr 1
+#endif
+
+#ifndef GL_EXT_blend_color
+#define GL_EXT_blend_color 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBlendColorEXT (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBLENDCOLOREXTPROC) (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+#endif
+
+#ifndef GL_EXT_polygon_offset
+#define GL_EXT_polygon_offset 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glPolygonOffsetEXT (GLfloat factor, GLfloat bias);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPOLYGONOFFSETEXTPROC) (GLfloat factor, GLfloat bias);
+#endif
+
+#ifndef GL_EXT_texture
+#define GL_EXT_texture 1
+#endif
+
+#ifndef GL_EXT_texture3D
+#define GL_EXT_texture3D 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glTexImage3DEXT (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+GLAPI void APIENTRY glTexSubImage3DEXT (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLTEXIMAGE3DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+typedef void (APIENTRYP PFNGLTEXSUBIMAGE3DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels);
+#endif
+
+#ifndef GL_SGIS_texture_filter4
+#define GL_SGIS_texture_filter4 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glGetTexFilterFuncSGIS (GLenum target, GLenum filter, GLfloat *weights);
+GLAPI void APIENTRY glTexFilterFuncSGIS (GLenum target, GLenum filter, GLsizei n, const GLfloat *weights);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLGETTEXFILTERFUNCSGISPROC) (GLenum target, GLenum filter, GLfloat *weights);
+typedef void (APIENTRYP PFNGLTEXFILTERFUNCSGISPROC) (GLenum target, GLenum filter, GLsizei n, const GLfloat *weights);
+#endif
+
+#ifndef GL_EXT_subtexture
+#define GL_EXT_subtexture 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glTexSubImage1DEXT (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels);
+GLAPI void APIENTRY glTexSubImage2DEXT (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLTEXSUBIMAGE1DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels);
+typedef void (APIENTRYP PFNGLTEXSUBIMAGE2DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+#endif
+
+#ifndef GL_EXT_copy_texture
+#define GL_EXT_copy_texture 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glCopyTexImage1DEXT (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border);
+GLAPI void APIENTRY glCopyTexImage2DEXT (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
+GLAPI void APIENTRY glCopyTexSubImage1DEXT (GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);
+GLAPI void APIENTRY glCopyTexSubImage2DEXT (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+GLAPI void APIENTRY glCopyTexSubImage3DEXT (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCOPYTEXIMAGE1DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border);
+typedef void (APIENTRYP PFNGLCOPYTEXIMAGE2DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
+typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE1DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);
+typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE2DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+#endif
+
+#ifndef GL_EXT_histogram
+#define GL_EXT_histogram 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glGetHistogramEXT (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values);
+GLAPI void APIENTRY glGetHistogramParameterfvEXT (GLenum target, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetHistogramParameterivEXT (GLenum target, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetMinmaxEXT (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values);
+GLAPI void APIENTRY glGetMinmaxParameterfvEXT (GLenum target, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetMinmaxParameterivEXT (GLenum target, GLenum pname, GLint *params);
+GLAPI void APIENTRY glHistogramEXT (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink);
+GLAPI void APIENTRY glMinmaxEXT (GLenum target, GLenum internalformat, GLboolean sink);
+GLAPI void APIENTRY glResetHistogramEXT (GLenum target);
+GLAPI void APIENTRY glResetMinmaxEXT (GLenum target);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLGETHISTOGRAMEXTPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values);
+typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETMINMAXEXTPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values);
+typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLHISTOGRAMEXTPROC) (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink);
+typedef void (APIENTRYP PFNGLMINMAXEXTPROC) (GLenum target, GLenum internalformat, GLboolean sink);
+typedef void (APIENTRYP PFNGLRESETHISTOGRAMEXTPROC) (GLenum target);
+typedef void (APIENTRYP PFNGLRESETMINMAXEXTPROC) (GLenum target);
+#endif
+
+#ifndef GL_EXT_convolution
+#define GL_EXT_convolution 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glConvolutionFilter1DEXT (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *image);
+GLAPI void APIENTRY glConvolutionFilter2DEXT (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *image);
+GLAPI void APIENTRY glConvolutionParameterfEXT (GLenum target, GLenum pname, GLfloat params);
+GLAPI void APIENTRY glConvolutionParameterfvEXT (GLenum target, GLenum pname, const GLfloat *params);
+GLAPI void APIENTRY glConvolutionParameteriEXT (GLenum target, GLenum pname, GLint params);
+GLAPI void APIENTRY glConvolutionParameterivEXT (GLenum target, GLenum pname, const GLint *params);
+GLAPI void APIENTRY glCopyConvolutionFilter1DEXT (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);
+GLAPI void APIENTRY glCopyConvolutionFilter2DEXT (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height);
+GLAPI void APIENTRY glGetConvolutionFilterEXT (GLenum target, GLenum format, GLenum type, GLvoid *image);
+GLAPI void APIENTRY glGetConvolutionParameterfvEXT (GLenum target, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetConvolutionParameterivEXT (GLenum target, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetSeparableFilterEXT (GLenum target, GLenum format, GLenum type, GLvoid *row, GLvoid *column, GLvoid *span);
+GLAPI void APIENTRY glSeparableFilter2DEXT (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *row, const GLvoid *column);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER1DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *image);
+typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *image);
+typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFEXTPROC) (GLenum target, GLenum pname, GLfloat params);
+typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFVEXTPROC) (GLenum target, GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIEXTPROC) (GLenum target, GLenum pname, GLint params);
+typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIVEXTPROC) (GLenum target, GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER1DEXTPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);
+typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height);
+typedef void (APIENTRYP PFNGLGETCONVOLUTIONFILTEREXTPROC) (GLenum target, GLenum format, GLenum type, GLvoid *image);
+typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETSEPARABLEFILTEREXTPROC) (GLenum target, GLenum format, GLenum type, GLvoid *row, GLvoid *column, GLvoid *span);
+typedef void (APIENTRYP PFNGLSEPARABLEFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *row, const GLvoid *column);
+#endif
+
+#ifndef GL_SGI_color_matrix
+#define GL_SGI_color_matrix 1
+#endif
+
+#ifndef GL_SGI_color_table
+#define GL_SGI_color_table 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glColorTableSGI (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *table);
+GLAPI void APIENTRY glColorTableParameterfvSGI (GLenum target, GLenum pname, const GLfloat *params);
+GLAPI void APIENTRY glColorTableParameterivSGI (GLenum target, GLenum pname, const GLint *params);
+GLAPI void APIENTRY glCopyColorTableSGI (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);
+GLAPI void APIENTRY glGetColorTableSGI (GLenum target, GLenum format, GLenum type, GLvoid *table);
+GLAPI void APIENTRY glGetColorTableParameterfvSGI (GLenum target, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetColorTableParameterivSGI (GLenum target, GLenum pname, GLint *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCOLORTABLESGIPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *table);
+typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERFVSGIPROC) (GLenum target, GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERIVSGIPROC) (GLenum target, GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLCOPYCOLORTABLESGIPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);
+typedef void (APIENTRYP PFNGLGETCOLORTABLESGIPROC) (GLenum target, GLenum format, GLenum type, GLvoid *table);
+typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVSGIPROC) (GLenum target, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVSGIPROC) (GLenum target, GLenum pname, GLint *params);
+#endif
+
+#ifndef GL_SGIX_pixel_texture
+#define GL_SGIX_pixel_texture 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glPixelTexGenSGIX (GLenum mode);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPIXELTEXGENSGIXPROC) (GLenum mode);
+#endif
+
+#ifndef GL_SGIS_pixel_texture
+#define GL_SGIS_pixel_texture 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glPixelTexGenParameteriSGIS (GLenum pname, GLint param);
+GLAPI void APIENTRY glPixelTexGenParameterivSGIS (GLenum pname, const GLint *params);
+GLAPI void APIENTRY glPixelTexGenParameterfSGIS (GLenum pname, GLfloat param);
+GLAPI void APIENTRY glPixelTexGenParameterfvSGIS (GLenum pname, const GLfloat *params);
+GLAPI void APIENTRY glGetPixelTexGenParameterivSGIS (GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetPixelTexGenParameterfvSGIS (GLenum pname, GLfloat *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERISGISPROC) (GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERIVSGISPROC) (GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERFSGISPROC) (GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERFVSGISPROC) (GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLGETPIXELTEXGENPARAMETERIVSGISPROC) (GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETPIXELTEXGENPARAMETERFVSGISPROC) (GLenum pname, GLfloat *params);
+#endif
+
+#ifndef GL_SGIS_texture4D
+#define GL_SGIS_texture4D 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glTexImage4DSGIS (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+GLAPI void APIENTRY glTexSubImage4DSGIS (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint woffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLenum format, GLenum type, const GLvoid *pixels);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLTEXIMAGE4DSGISPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+typedef void (APIENTRYP PFNGLTEXSUBIMAGE4DSGISPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint woffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLenum format, GLenum type, const GLvoid *pixels);
+#endif
+
+#ifndef GL_SGI_texture_color_table
+#define GL_SGI_texture_color_table 1
+#endif
+
+#ifndef GL_EXT_cmyka
+#define GL_EXT_cmyka 1
+#endif
+
+#ifndef GL_EXT_texture_object
+#define GL_EXT_texture_object 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI GLboolean APIENTRY glAreTexturesResidentEXT (GLsizei n, const GLuint *textures, GLboolean *residences);
+GLAPI void APIENTRY glBindTextureEXT (GLenum target, GLuint texture);
+GLAPI void APIENTRY glDeleteTexturesEXT (GLsizei n, const GLuint *textures);
+GLAPI void APIENTRY glGenTexturesEXT (GLsizei n, GLuint *textures);
+GLAPI GLboolean APIENTRY glIsTextureEXT (GLuint texture);
+GLAPI void APIENTRY glPrioritizeTexturesEXT (GLsizei n, const GLuint *textures, const GLclampf *priorities);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef GLboolean (APIENTRYP PFNGLARETEXTURESRESIDENTEXTPROC) (GLsizei n, const GLuint *textures, GLboolean *residences);
+typedef void (APIENTRYP PFNGLBINDTEXTUREEXTPROC) (GLenum target, GLuint texture);
+typedef void (APIENTRYP PFNGLDELETETEXTURESEXTPROC) (GLsizei n, const GLuint *textures);
+typedef void (APIENTRYP PFNGLGENTEXTURESEXTPROC) (GLsizei n, GLuint *textures);
+typedef GLboolean (APIENTRYP PFNGLISTEXTUREEXTPROC) (GLuint texture);
+typedef void (APIENTRYP PFNGLPRIORITIZETEXTURESEXTPROC) (GLsizei n, const GLuint *textures, const GLclampf *priorities);
+#endif
+
+#ifndef GL_SGIS_detail_texture
+#define GL_SGIS_detail_texture 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glDetailTexFuncSGIS (GLenum target, GLsizei n, const GLfloat *points);
+GLAPI void APIENTRY glGetDetailTexFuncSGIS (GLenum target, GLfloat *points);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLDETAILTEXFUNCSGISPROC) (GLenum target, GLsizei n, const GLfloat *points);
+typedef void (APIENTRYP PFNGLGETDETAILTEXFUNCSGISPROC) (GLenum target, GLfloat *points);
+#endif
+
+#ifndef GL_SGIS_sharpen_texture
+#define GL_SGIS_sharpen_texture 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glSharpenTexFuncSGIS (GLenum target, GLsizei n, const GLfloat *points);
+GLAPI void APIENTRY glGetSharpenTexFuncSGIS (GLenum target, GLfloat *points);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLSHARPENTEXFUNCSGISPROC) (GLenum target, GLsizei n, const GLfloat *points);
+typedef void (APIENTRYP PFNGLGETSHARPENTEXFUNCSGISPROC) (GLenum target, GLfloat *points);
+#endif
+
+#ifndef GL_EXT_packed_pixels
+#define GL_EXT_packed_pixels 1
+#endif
+
+#ifndef GL_SGIS_texture_lod
+#define GL_SGIS_texture_lod 1
+#endif
+
+#ifndef GL_SGIS_multisample
+#define GL_SGIS_multisample 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glSampleMaskSGIS (GLclampf value, GLboolean invert);
+GLAPI void APIENTRY glSamplePatternSGIS (GLenum pattern);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLSAMPLEMASKSGISPROC) (GLclampf value, GLboolean invert);
+typedef void (APIENTRYP PFNGLSAMPLEPATTERNSGISPROC) (GLenum pattern);
+#endif
+
+#ifndef GL_EXT_rescale_normal
+#define GL_EXT_rescale_normal 1
+#endif
+
+#ifndef GL_EXT_vertex_array
+#define GL_EXT_vertex_array 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glArrayElementEXT (GLint i);
+GLAPI void APIENTRY glColorPointerEXT (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
+GLAPI void APIENTRY glDrawArraysEXT (GLenum mode, GLint first, GLsizei count);
+GLAPI void APIENTRY glEdgeFlagPointerEXT (GLsizei stride, GLsizei count, const GLboolean *pointer);
+GLAPI void APIENTRY glGetPointervEXT (GLenum pname, GLvoid* *params);
+GLAPI void APIENTRY glIndexPointerEXT (GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
+GLAPI void APIENTRY glNormalPointerEXT (GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
+GLAPI void APIENTRY glTexCoordPointerEXT (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
+GLAPI void APIENTRY glVertexPointerEXT (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLARRAYELEMENTEXTPROC) (GLint i);
+typedef void (APIENTRYP PFNGLCOLORPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
+typedef void (APIENTRYP PFNGLDRAWARRAYSEXTPROC) (GLenum mode, GLint first, GLsizei count);
+typedef void (APIENTRYP PFNGLEDGEFLAGPOINTEREXTPROC) (GLsizei stride, GLsizei count, const GLboolean *pointer);
+typedef void (APIENTRYP PFNGLGETPOINTERVEXTPROC) (GLenum pname, GLvoid* *params);
+typedef void (APIENTRYP PFNGLINDEXPOINTEREXTPROC) (GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
+typedef void (APIENTRYP PFNGLNORMALPOINTEREXTPROC) (GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
+typedef void (APIENTRYP PFNGLTEXCOORDPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
+typedef void (APIENTRYP PFNGLVERTEXPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
+#endif
+
+#ifndef GL_EXT_misc_attribute
+#define GL_EXT_misc_attribute 1
+#endif
+
+#ifndef GL_SGIS_generate_mipmap
+#define GL_SGIS_generate_mipmap 1
+#endif
+
+#ifndef GL_SGIX_clipmap
+#define GL_SGIX_clipmap 1
+#endif
+
+#ifndef GL_SGIX_shadow
+#define GL_SGIX_shadow 1
+#endif
+
+#ifndef GL_SGIS_texture_edge_clamp
+#define GL_SGIS_texture_edge_clamp 1
+#endif
+
+#ifndef GL_SGIS_texture_border_clamp
+#define GL_SGIS_texture_border_clamp 1
+#endif
+
+#ifndef GL_EXT_blend_minmax
+#define GL_EXT_blend_minmax 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBlendEquationEXT (GLenum mode);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBLENDEQUATIONEXTPROC) (GLenum mode);
+#endif
+
+#ifndef GL_EXT_blend_subtract
+#define GL_EXT_blend_subtract 1
+#endif
+
+#ifndef GL_EXT_blend_logic_op
+#define GL_EXT_blend_logic_op 1
+#endif
+
+#ifndef GL_SGIX_interlace
+#define GL_SGIX_interlace 1
+#endif
+
+#ifndef GL_SGIX_pixel_tiles
+#define GL_SGIX_pixel_tiles 1
+#endif
+
+#ifndef GL_SGIX_texture_select
+#define GL_SGIX_texture_select 1
+#endif
+
+#ifndef GL_SGIX_sprite
+#define GL_SGIX_sprite 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glSpriteParameterfSGIX (GLenum pname, GLfloat param);
+GLAPI void APIENTRY glSpriteParameterfvSGIX (GLenum pname, const GLfloat *params);
+GLAPI void APIENTRY glSpriteParameteriSGIX (GLenum pname, GLint param);
+GLAPI void APIENTRY glSpriteParameterivSGIX (GLenum pname, const GLint *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLSPRITEPARAMETERFSGIXPROC) (GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLSPRITEPARAMETERFVSGIXPROC) (GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLSPRITEPARAMETERISGIXPROC) (GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLSPRITEPARAMETERIVSGIXPROC) (GLenum pname, const GLint *params);
+#endif
+
+#ifndef GL_SGIX_texture_multi_buffer
+#define GL_SGIX_texture_multi_buffer 1
+#endif
+
+#ifndef GL_EXT_point_parameters
+#define GL_EXT_point_parameters 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glPointParameterfEXT (GLenum pname, GLfloat param);
+GLAPI void APIENTRY glPointParameterfvEXT (GLenum pname, const GLfloat *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPOINTPARAMETERFEXTPROC) (GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLPOINTPARAMETERFVEXTPROC) (GLenum pname, const GLfloat *params);
+#endif
+
+#ifndef GL_SGIS_point_parameters
+#define GL_SGIS_point_parameters 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glPointParameterfSGIS (GLenum pname, GLfloat param);
+GLAPI void APIENTRY glPointParameterfvSGIS (GLenum pname, const GLfloat *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPOINTPARAMETERFSGISPROC) (GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLPOINTPARAMETERFVSGISPROC) (GLenum pname, const GLfloat *params);
+#endif
+
+#ifndef GL_SGIX_instruments
+#define GL_SGIX_instruments 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI GLint APIENTRY glGetInstrumentsSGIX (void);
+GLAPI void APIENTRY glInstrumentsBufferSGIX (GLsizei size, GLint *buffer);
+GLAPI GLint APIENTRY glPollInstrumentsSGIX (GLint *marker_p);
+GLAPI void APIENTRY glReadInstrumentsSGIX (GLint marker);
+GLAPI void APIENTRY glStartInstrumentsSGIX (void);
+GLAPI void APIENTRY glStopInstrumentsSGIX (GLint marker);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef GLint (APIENTRYP PFNGLGETINSTRUMENTSSGIXPROC) (void);
+typedef void (APIENTRYP PFNGLINSTRUMENTSBUFFERSGIXPROC) (GLsizei size, GLint *buffer);
+typedef GLint (APIENTRYP PFNGLPOLLINSTRUMENTSSGIXPROC) (GLint *marker_p);
+typedef void (APIENTRYP PFNGLREADINSTRUMENTSSGIXPROC) (GLint marker);
+typedef void (APIENTRYP PFNGLSTARTINSTRUMENTSSGIXPROC) (void);
+typedef void (APIENTRYP PFNGLSTOPINSTRUMENTSSGIXPROC) (GLint marker);
+#endif
+
+#ifndef GL_SGIX_texture_scale_bias
+#define GL_SGIX_texture_scale_bias 1
+#endif
+
+#ifndef GL_SGIX_framezoom
+#define GL_SGIX_framezoom 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glFrameZoomSGIX (GLint factor);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLFRAMEZOOMSGIXPROC) (GLint factor);
+#endif
+
+#ifndef GL_SGIX_tag_sample_buffer
+#define GL_SGIX_tag_sample_buffer 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glTagSampleBufferSGIX (void);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLTAGSAMPLEBUFFERSGIXPROC) (void);
+#endif
+
+#ifndef GL_SGIX_polynomial_ffd
+#define GL_SGIX_polynomial_ffd 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glDeformationMap3dSGIX (GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, GLdouble w1, GLdouble w2, GLint wstride, GLint worder, const GLdouble *points);
+GLAPI void APIENTRY glDeformationMap3fSGIX (GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, GLfloat w1, GLfloat w2, GLint wstride, GLint worder, const GLfloat *points);
+GLAPI void APIENTRY glDeformSGIX (GLbitfield mask);
+GLAPI void APIENTRY glLoadIdentityDeformationMapSGIX (GLbitfield mask);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLDEFORMATIONMAP3DSGIXPROC) (GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, GLdouble w1, GLdouble w2, GLint wstride, GLint worder, const GLdouble *points);
+typedef void (APIENTRYP PFNGLDEFORMATIONMAP3FSGIXPROC) (GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, GLfloat w1, GLfloat w2, GLint wstride, GLint worder, const GLfloat *points);
+typedef void (APIENTRYP PFNGLDEFORMSGIXPROC) (GLbitfield mask);
+typedef void (APIENTRYP PFNGLLOADIDENTITYDEFORMATIONMAPSGIXPROC) (GLbitfield mask);
+#endif
+
+#ifndef GL_SGIX_reference_plane
+#define GL_SGIX_reference_plane 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glReferencePlaneSGIX (const GLdouble *equation);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLREFERENCEPLANESGIXPROC) (const GLdouble *equation);
+#endif
+
+#ifndef GL_SGIX_flush_raster
+#define GL_SGIX_flush_raster 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glFlushRasterSGIX (void);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLFLUSHRASTERSGIXPROC) (void);
+#endif
+
+#ifndef GL_SGIX_depth_texture
+#define GL_SGIX_depth_texture 1
+#endif
+
+#ifndef GL_SGIS_fog_function
+#define GL_SGIS_fog_function 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glFogFuncSGIS (GLsizei n, const GLfloat *points);
+GLAPI void APIENTRY glGetFogFuncSGIS (GLfloat *points);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLFOGFUNCSGISPROC) (GLsizei n, const GLfloat *points);
+typedef void (APIENTRYP PFNGLGETFOGFUNCSGISPROC) (GLfloat *points);
+#endif
+
+#ifndef GL_SGIX_fog_offset
+#define GL_SGIX_fog_offset 1
+#endif
+
+#ifndef GL_HP_image_transform
+#define GL_HP_image_transform 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glImageTransformParameteriHP (GLenum target, GLenum pname, GLint param);
+GLAPI void APIENTRY glImageTransformParameterfHP (GLenum target, GLenum pname, GLfloat param);
+GLAPI void APIENTRY glImageTransformParameterivHP (GLenum target, GLenum pname, const GLint *params);
+GLAPI void APIENTRY glImageTransformParameterfvHP (GLenum target, GLenum pname, const GLfloat *params);
+GLAPI void APIENTRY glGetImageTransformParameterivHP (GLenum target, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetImageTransformParameterfvHP (GLenum target, GLenum pname, GLfloat *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERIHPPROC) (GLenum target, GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERFHPPROC) (GLenum target, GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERIVHPPROC) (GLenum target, GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERFVHPPROC) (GLenum target, GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLGETIMAGETRANSFORMPARAMETERIVHPPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETIMAGETRANSFORMPARAMETERFVHPPROC) (GLenum target, GLenum pname, GLfloat *params);
+#endif
+
+#ifndef GL_HP_convolution_border_modes
+#define GL_HP_convolution_border_modes 1
+#endif
+
+#ifndef GL_SGIX_texture_add_env
+#define GL_SGIX_texture_add_env 1
+#endif
+
+#ifndef GL_EXT_color_subtable
+#define GL_EXT_color_subtable 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glColorSubTableEXT (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const GLvoid *data);
+GLAPI void APIENTRY glCopyColorSubTableEXT (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCOLORSUBTABLEEXTPROC) (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const GLvoid *data);
+typedef void (APIENTRYP PFNGLCOPYCOLORSUBTABLEEXTPROC) (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width);
+#endif
+
+#ifndef GL_PGI_vertex_hints
+#define GL_PGI_vertex_hints 1
+#endif
+
+#ifndef GL_PGI_misc_hints
+#define GL_PGI_misc_hints 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glHintPGI (GLenum target, GLint mode);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLHINTPGIPROC) (GLenum target, GLint mode);
+#endif
+
+#ifndef GL_EXT_paletted_texture
+#define GL_EXT_paletted_texture 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glColorTableEXT (GLenum target, GLenum internalFormat, GLsizei width, GLenum format, GLenum type, const GLvoid *table);
+GLAPI void APIENTRY glGetColorTableEXT (GLenum target, GLenum format, GLenum type, GLvoid *data);
+GLAPI void APIENTRY glGetColorTableParameterivEXT (GLenum target, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetColorTableParameterfvEXT (GLenum target, GLenum pname, GLfloat *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCOLORTABLEEXTPROC) (GLenum target, GLenum internalFormat, GLsizei width, GLenum format, GLenum type, const GLvoid *table);
+typedef void (APIENTRYP PFNGLGETCOLORTABLEEXTPROC) (GLenum target, GLenum format, GLenum type, GLvoid *data);
+typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params);
+#endif
+
+#ifndef GL_EXT_clip_volume_hint
+#define GL_EXT_clip_volume_hint 1
+#endif
+
+#ifndef GL_SGIX_list_priority
+#define GL_SGIX_list_priority 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glGetListParameterfvSGIX (GLuint list, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetListParameterivSGIX (GLuint list, GLenum pname, GLint *params);
+GLAPI void APIENTRY glListParameterfSGIX (GLuint list, GLenum pname, GLfloat param);
+GLAPI void APIENTRY glListParameterfvSGIX (GLuint list, GLenum pname, const GLfloat *params);
+GLAPI void APIENTRY glListParameteriSGIX (GLuint list, GLenum pname, GLint param);
+GLAPI void APIENTRY glListParameterivSGIX (GLuint list, GLenum pname, const GLint *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLGETLISTPARAMETERFVSGIXPROC) (GLuint list, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETLISTPARAMETERIVSGIXPROC) (GLuint list, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLLISTPARAMETERFSGIXPROC) (GLuint list, GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLLISTPARAMETERFVSGIXPROC) (GLuint list, GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLLISTPARAMETERISGIXPROC) (GLuint list, GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLLISTPARAMETERIVSGIXPROC) (GLuint list, GLenum pname, const GLint *params);
+#endif
+
+#ifndef GL_SGIX_ir_instrument1
+#define GL_SGIX_ir_instrument1 1
+#endif
+
+#ifndef GL_SGIX_calligraphic_fragment
+#define GL_SGIX_calligraphic_fragment 1
+#endif
+
+#ifndef GL_SGIX_texture_lod_bias
+#define GL_SGIX_texture_lod_bias 1
+#endif
+
+#ifndef GL_SGIX_shadow_ambient
+#define GL_SGIX_shadow_ambient 1
+#endif
+
+#ifndef GL_EXT_index_texture
+#define GL_EXT_index_texture 1
+#endif
+
+#ifndef GL_EXT_index_material
+#define GL_EXT_index_material 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glIndexMaterialEXT (GLenum face, GLenum mode);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLINDEXMATERIALEXTPROC) (GLenum face, GLenum mode);
+#endif
+
+#ifndef GL_EXT_index_func
+#define GL_EXT_index_func 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glIndexFuncEXT (GLenum func, GLclampf ref);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLINDEXFUNCEXTPROC) (GLenum func, GLclampf ref);
+#endif
+
+#ifndef GL_EXT_index_array_formats
+#define GL_EXT_index_array_formats 1
+#endif
+
+#ifndef GL_EXT_compiled_vertex_array
+#define GL_EXT_compiled_vertex_array 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glLockArraysEXT (GLint first, GLsizei count);
+GLAPI void APIENTRY glUnlockArraysEXT (void);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLLOCKARRAYSEXTPROC) (GLint first, GLsizei count);
+typedef void (APIENTRYP PFNGLUNLOCKARRAYSEXTPROC) (void);
+#endif
+
+#ifndef GL_EXT_cull_vertex
+#define GL_EXT_cull_vertex 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glCullParameterdvEXT (GLenum pname, GLdouble *params);
+GLAPI void APIENTRY glCullParameterfvEXT (GLenum pname, GLfloat *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCULLPARAMETERDVEXTPROC) (GLenum pname, GLdouble *params);
+typedef void (APIENTRYP PFNGLCULLPARAMETERFVEXTPROC) (GLenum pname, GLfloat *params);
+#endif
+
+#ifndef GL_SGIX_ycrcb
+#define GL_SGIX_ycrcb 1
+#endif
+
+#ifndef GL_SGIX_fragment_lighting
+#define GL_SGIX_fragment_lighting 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glFragmentColorMaterialSGIX (GLenum face, GLenum mode);
+GLAPI void APIENTRY glFragmentLightfSGIX (GLenum light, GLenum pname, GLfloat param);
+GLAPI void APIENTRY glFragmentLightfvSGIX (GLenum light, GLenum pname, const GLfloat *params);
+GLAPI void APIENTRY glFragmentLightiSGIX (GLenum light, GLenum pname, GLint param);
+GLAPI void APIENTRY glFragmentLightivSGIX (GLenum light, GLenum pname, const GLint *params);
+GLAPI void APIENTRY glFragmentLightModelfSGIX (GLenum pname, GLfloat param);
+GLAPI void APIENTRY glFragmentLightModelfvSGIX (GLenum pname, const GLfloat *params);
+GLAPI void APIENTRY glFragmentLightModeliSGIX (GLenum pname, GLint param);
+GLAPI void APIENTRY glFragmentLightModelivSGIX (GLenum pname, const GLint *params);
+GLAPI void APIENTRY glFragmentMaterialfSGIX (GLenum face, GLenum pname, GLfloat param);
+GLAPI void APIENTRY glFragmentMaterialfvSGIX (GLenum face, GLenum pname, const GLfloat *params);
+GLAPI void APIENTRY glFragmentMaterialiSGIX (GLenum face, GLenum pname, GLint param);
+GLAPI void APIENTRY glFragmentMaterialivSGIX (GLenum face, GLenum pname, const GLint *params);
+GLAPI void APIENTRY glGetFragmentLightfvSGIX (GLenum light, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetFragmentLightivSGIX (GLenum light, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetFragmentMaterialfvSGIX (GLenum face, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetFragmentMaterialivSGIX (GLenum face, GLenum pname, GLint *params);
+GLAPI void APIENTRY glLightEnviSGIX (GLenum pname, GLint param);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLFRAGMENTCOLORMATERIALSGIXPROC) (GLenum face, GLenum mode);
+typedef void (APIENTRYP PFNGLFRAGMENTLIGHTFSGIXPROC) (GLenum light, GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLFRAGMENTLIGHTFVSGIXPROC) (GLenum light, GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLFRAGMENTLIGHTISGIXPROC) (GLenum light, GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLFRAGMENTLIGHTIVSGIXPROC) (GLenum light, GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELFSGIXPROC) (GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELFVSGIXPROC) (GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELISGIXPROC) (GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELIVSGIXPROC) (GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLFRAGMENTMATERIALFSGIXPROC) (GLenum face, GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLFRAGMENTMATERIALFVSGIXPROC) (GLenum face, GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLFRAGMENTMATERIALISGIXPROC) (GLenum face, GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLFRAGMENTMATERIALIVSGIXPROC) (GLenum face, GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLGETFRAGMENTLIGHTFVSGIXPROC) (GLenum light, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETFRAGMENTLIGHTIVSGIXPROC) (GLenum light, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETFRAGMENTMATERIALFVSGIXPROC) (GLenum face, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETFRAGMENTMATERIALIVSGIXPROC) (GLenum face, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLLIGHTENVISGIXPROC) (GLenum pname, GLint param);
+#endif
+
+#ifndef GL_IBM_rasterpos_clip
+#define GL_IBM_rasterpos_clip 1
+#endif
+
+#ifndef GL_HP_texture_lighting
+#define GL_HP_texture_lighting 1
+#endif
+
+#ifndef GL_EXT_draw_range_elements
+#define GL_EXT_draw_range_elements 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glDrawRangeElementsEXT (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSEXTPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices);
+#endif
+
+#ifndef GL_WIN_phong_shading
+#define GL_WIN_phong_shading 1
+#endif
+
+#ifndef GL_WIN_specular_fog
+#define GL_WIN_specular_fog 1
+#endif
+
+#ifndef GL_EXT_light_texture
+#define GL_EXT_light_texture 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glApplyTextureEXT (GLenum mode);
+GLAPI void APIENTRY glTextureLightEXT (GLenum pname);
+GLAPI void APIENTRY glTextureMaterialEXT (GLenum face, GLenum mode);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLAPPLYTEXTUREEXTPROC) (GLenum mode);
+typedef void (APIENTRYP PFNGLTEXTURELIGHTEXTPROC) (GLenum pname);
+typedef void (APIENTRYP PFNGLTEXTUREMATERIALEXTPROC) (GLenum face, GLenum mode);
+#endif
+
+#ifndef GL_SGIX_blend_alpha_minmax
+#define GL_SGIX_blend_alpha_minmax 1
+#endif
+
+#ifndef GL_EXT_bgra
+#define GL_EXT_bgra 1
+#endif
+
+#ifndef GL_SGIX_async
+#define GL_SGIX_async 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glAsyncMarkerSGIX (GLuint marker);
+GLAPI GLint APIENTRY glFinishAsyncSGIX (GLuint *markerp);
+GLAPI GLint APIENTRY glPollAsyncSGIX (GLuint *markerp);
+GLAPI GLuint APIENTRY glGenAsyncMarkersSGIX (GLsizei range);
+GLAPI void APIENTRY glDeleteAsyncMarkersSGIX (GLuint marker, GLsizei range);
+GLAPI GLboolean APIENTRY glIsAsyncMarkerSGIX (GLuint marker);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLASYNCMARKERSGIXPROC) (GLuint marker);
+typedef GLint (APIENTRYP PFNGLFINISHASYNCSGIXPROC) (GLuint *markerp);
+typedef GLint (APIENTRYP PFNGLPOLLASYNCSGIXPROC) (GLuint *markerp);
+typedef GLuint (APIENTRYP PFNGLGENASYNCMARKERSSGIXPROC) (GLsizei range);
+typedef void (APIENTRYP PFNGLDELETEASYNCMARKERSSGIXPROC) (GLuint marker, GLsizei range);
+typedef GLboolean (APIENTRYP PFNGLISASYNCMARKERSGIXPROC) (GLuint marker);
+#endif
+
+#ifndef GL_SGIX_async_pixel
+#define GL_SGIX_async_pixel 1
+#endif
+
+#ifndef GL_SGIX_async_histogram
+#define GL_SGIX_async_histogram 1
+#endif
+
+#ifndef GL_INTEL_parallel_arrays
+#define GL_INTEL_parallel_arrays 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glVertexPointervINTEL (GLint size, GLenum type, const GLvoid* *pointer);
+GLAPI void APIENTRY glNormalPointervINTEL (GLenum type, const GLvoid* *pointer);
+GLAPI void APIENTRY glColorPointervINTEL (GLint size, GLenum type, const GLvoid* *pointer);
+GLAPI void APIENTRY glTexCoordPointervINTEL (GLint size, GLenum type, const GLvoid* *pointer);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLVERTEXPOINTERVINTELPROC) (GLint size, GLenum type, const GLvoid* *pointer);
+typedef void (APIENTRYP PFNGLNORMALPOINTERVINTELPROC) (GLenum type, const GLvoid* *pointer);
+typedef void (APIENTRYP PFNGLCOLORPOINTERVINTELPROC) (GLint size, GLenum type, const GLvoid* *pointer);
+typedef void (APIENTRYP PFNGLTEXCOORDPOINTERVINTELPROC) (GLint size, GLenum type, const GLvoid* *pointer);
+#endif
+
+#ifndef GL_HP_occlusion_test
+#define GL_HP_occlusion_test 1
+#endif
+
+#ifndef GL_EXT_pixel_transform
+#define GL_EXT_pixel_transform 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glPixelTransformParameteriEXT (GLenum target, GLenum pname, GLint param);
+GLAPI void APIENTRY glPixelTransformParameterfEXT (GLenum target, GLenum pname, GLfloat param);
+GLAPI void APIENTRY glPixelTransformParameterivEXT (GLenum target, GLenum pname, const GLint *params);
+GLAPI void APIENTRY glPixelTransformParameterfvEXT (GLenum target, GLenum pname, const GLfloat *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERIEXTPROC) (GLenum target, GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERFEXTPROC) (GLenum target, GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERIVEXTPROC) (GLenum target, GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERFVEXTPROC) (GLenum target, GLenum pname, const GLfloat *params);
+#endif
+
+#ifndef GL_EXT_pixel_transform_color_table
+#define GL_EXT_pixel_transform_color_table 1
+#endif
+
+#ifndef GL_EXT_shared_texture_palette
+#define GL_EXT_shared_texture_palette 1
+#endif
+
+#ifndef GL_EXT_separate_specular_color
+#define GL_EXT_separate_specular_color 1
+#endif
+
+#ifndef GL_EXT_secondary_color
+#define GL_EXT_secondary_color 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glSecondaryColor3bEXT (GLbyte red, GLbyte green, GLbyte blue);
+GLAPI void APIENTRY glSecondaryColor3bvEXT (const GLbyte *v);
+GLAPI void APIENTRY glSecondaryColor3dEXT (GLdouble red, GLdouble green, GLdouble blue);
+GLAPI void APIENTRY glSecondaryColor3dvEXT (const GLdouble *v);
+GLAPI void APIENTRY glSecondaryColor3fEXT (GLfloat red, GLfloat green, GLfloat blue);
+GLAPI void APIENTRY glSecondaryColor3fvEXT (const GLfloat *v);
+GLAPI void APIENTRY glSecondaryColor3iEXT (GLint red, GLint green, GLint blue);
+GLAPI void APIENTRY glSecondaryColor3ivEXT (const GLint *v);
+GLAPI void APIENTRY glSecondaryColor3sEXT (GLshort red, GLshort green, GLshort blue);
+GLAPI void APIENTRY glSecondaryColor3svEXT (const GLshort *v);
+GLAPI void APIENTRY glSecondaryColor3ubEXT (GLubyte red, GLubyte green, GLubyte blue);
+GLAPI void APIENTRY glSecondaryColor3ubvEXT (const GLubyte *v);
+GLAPI void APIENTRY glSecondaryColor3uiEXT (GLuint red, GLuint green, GLuint blue);
+GLAPI void APIENTRY glSecondaryColor3uivEXT (const GLuint *v);
+GLAPI void APIENTRY glSecondaryColor3usEXT (GLushort red, GLushort green, GLushort blue);
+GLAPI void APIENTRY glSecondaryColor3usvEXT (const GLushort *v);
+GLAPI void APIENTRY glSecondaryColorPointerEXT (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BEXTPROC) (GLbyte red, GLbyte green, GLbyte blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVEXTPROC) (const GLbyte *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DEXTPROC) (GLdouble red, GLdouble green, GLdouble blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DVEXTPROC) (const GLdouble *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FEXTPROC) (GLfloat red, GLfloat green, GLfloat blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FVEXTPROC) (const GLfloat *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IEXTPROC) (GLint red, GLint green, GLint blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IVEXTPROC) (const GLint *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SEXTPROC) (GLshort red, GLshort green, GLshort blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SVEXTPROC) (const GLshort *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBEXTPROC) (GLubyte red, GLubyte green, GLubyte blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBVEXTPROC) (const GLubyte *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIEXTPROC) (GLuint red, GLuint green, GLuint blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIVEXTPROC) (const GLuint *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USEXTPROC) (GLushort red, GLushort green, GLushort blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USVEXTPROC) (const GLushort *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+#endif
+
+#ifndef GL_EXT_texture_perturb_normal
+#define GL_EXT_texture_perturb_normal 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glTextureNormalEXT (GLenum mode);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLTEXTURENORMALEXTPROC) (GLenum mode);
+#endif
+
+#ifndef GL_EXT_multi_draw_arrays
+#define GL_EXT_multi_draw_arrays 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glMultiDrawArraysEXT (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount);
+GLAPI void APIENTRY glMultiDrawElementsEXT (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSEXTPROC) (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount);
+typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSEXTPROC) (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount);
+#endif
+
+#ifndef GL_EXT_fog_coord
+#define GL_EXT_fog_coord 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glFogCoordfEXT (GLfloat coord);
+GLAPI void APIENTRY glFogCoordfvEXT (const GLfloat *coord);
+GLAPI void APIENTRY glFogCoorddEXT (GLdouble coord);
+GLAPI void APIENTRY glFogCoorddvEXT (const GLdouble *coord);
+GLAPI void APIENTRY glFogCoordPointerEXT (GLenum type, GLsizei stride, const GLvoid *pointer);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLFOGCOORDFEXTPROC) (GLfloat coord);
+typedef void (APIENTRYP PFNGLFOGCOORDFVEXTPROC) (const GLfloat *coord);
+typedef void (APIENTRYP PFNGLFOGCOORDDEXTPROC) (GLdouble coord);
+typedef void (APIENTRYP PFNGLFOGCOORDDVEXTPROC) (const GLdouble *coord);
+typedef void (APIENTRYP PFNGLFOGCOORDPOINTEREXTPROC) (GLenum type, GLsizei stride, const GLvoid *pointer);
+#endif
+
+#ifndef GL_REND_screen_coordinates
+#define GL_REND_screen_coordinates 1
+#endif
+
+#ifndef GL_EXT_coordinate_frame
+#define GL_EXT_coordinate_frame 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glTangent3bEXT (GLbyte tx, GLbyte ty, GLbyte tz);
+GLAPI void APIENTRY glTangent3bvEXT (const GLbyte *v);
+GLAPI void APIENTRY glTangent3dEXT (GLdouble tx, GLdouble ty, GLdouble tz);
+GLAPI void APIENTRY glTangent3dvEXT (const GLdouble *v);
+GLAPI void APIENTRY glTangent3fEXT (GLfloat tx, GLfloat ty, GLfloat tz);
+GLAPI void APIENTRY glTangent3fvEXT (const GLfloat *v);
+GLAPI void APIENTRY glTangent3iEXT (GLint tx, GLint ty, GLint tz);
+GLAPI void APIENTRY glTangent3ivEXT (const GLint *v);
+GLAPI void APIENTRY glTangent3sEXT (GLshort tx, GLshort ty, GLshort tz);
+GLAPI void APIENTRY glTangent3svEXT (const GLshort *v);
+GLAPI void APIENTRY glBinormal3bEXT (GLbyte bx, GLbyte by, GLbyte bz);
+GLAPI void APIENTRY glBinormal3bvEXT (const GLbyte *v);
+GLAPI void APIENTRY glBinormal3dEXT (GLdouble bx, GLdouble by, GLdouble bz);
+GLAPI void APIENTRY glBinormal3dvEXT (const GLdouble *v);
+GLAPI void APIENTRY glBinormal3fEXT (GLfloat bx, GLfloat by, GLfloat bz);
+GLAPI void APIENTRY glBinormal3fvEXT (const GLfloat *v);
+GLAPI void APIENTRY glBinormal3iEXT (GLint bx, GLint by, GLint bz);
+GLAPI void APIENTRY glBinormal3ivEXT (const GLint *v);
+GLAPI void APIENTRY glBinormal3sEXT (GLshort bx, GLshort by, GLshort bz);
+GLAPI void APIENTRY glBinormal3svEXT (const GLshort *v);
+GLAPI void APIENTRY glTangentPointerEXT (GLenum type, GLsizei stride, const GLvoid *pointer);
+GLAPI void APIENTRY glBinormalPointerEXT (GLenum type, GLsizei stride, const GLvoid *pointer);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLTANGENT3BEXTPROC) (GLbyte tx, GLbyte ty, GLbyte tz);
+typedef void (APIENTRYP PFNGLTANGENT3BVEXTPROC) (const GLbyte *v);
+typedef void (APIENTRYP PFNGLTANGENT3DEXTPROC) (GLdouble tx, GLdouble ty, GLdouble tz);
+typedef void (APIENTRYP PFNGLTANGENT3DVEXTPROC) (const GLdouble *v);
+typedef void (APIENTRYP PFNGLTANGENT3FEXTPROC) (GLfloat tx, GLfloat ty, GLfloat tz);
+typedef void (APIENTRYP PFNGLTANGENT3FVEXTPROC) (const GLfloat *v);
+typedef void (APIENTRYP PFNGLTANGENT3IEXTPROC) (GLint tx, GLint ty, GLint tz);
+typedef void (APIENTRYP PFNGLTANGENT3IVEXTPROC) (const GLint *v);
+typedef void (APIENTRYP PFNGLTANGENT3SEXTPROC) (GLshort tx, GLshort ty, GLshort tz);
+typedef void (APIENTRYP PFNGLTANGENT3SVEXTPROC) (const GLshort *v);
+typedef void (APIENTRYP PFNGLBINORMAL3BEXTPROC) (GLbyte bx, GLbyte by, GLbyte bz);
+typedef void (APIENTRYP PFNGLBINORMAL3BVEXTPROC) (const GLbyte *v);
+typedef void (APIENTRYP PFNGLBINORMAL3DEXTPROC) (GLdouble bx, GLdouble by, GLdouble bz);
+typedef void (APIENTRYP PFNGLBINORMAL3DVEXTPROC) (const GLdouble *v);
+typedef void (APIENTRYP PFNGLBINORMAL3FEXTPROC) (GLfloat bx, GLfloat by, GLfloat bz);
+typedef void (APIENTRYP PFNGLBINORMAL3FVEXTPROC) (const GLfloat *v);
+typedef void (APIENTRYP PFNGLBINORMAL3IEXTPROC) (GLint bx, GLint by, GLint bz);
+typedef void (APIENTRYP PFNGLBINORMAL3IVEXTPROC) (const GLint *v);
+typedef void (APIENTRYP PFNGLBINORMAL3SEXTPROC) (GLshort bx, GLshort by, GLshort bz);
+typedef void (APIENTRYP PFNGLBINORMAL3SVEXTPROC) (const GLshort *v);
+typedef void (APIENTRYP PFNGLTANGENTPOINTEREXTPROC) (GLenum type, GLsizei stride, const GLvoid *pointer);
+typedef void (APIENTRYP PFNGLBINORMALPOINTEREXTPROC) (GLenum type, GLsizei stride, const GLvoid *pointer);
+#endif
+
+#ifndef GL_EXT_texture_env_combine
+#define GL_EXT_texture_env_combine 1
+#endif
+
+#ifndef GL_APPLE_specular_vector
+#define GL_APPLE_specular_vector 1
+#endif
+
+#ifndef GL_APPLE_transform_hint
+#define GL_APPLE_transform_hint 1
+#endif
+
+#ifndef GL_SGIX_fog_scale
+#define GL_SGIX_fog_scale 1
+#endif
+
+#ifndef GL_SUNX_constant_data
+#define GL_SUNX_constant_data 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glFinishTextureSUNX (void);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLFINISHTEXTURESUNXPROC) (void);
+#endif
+
+#ifndef GL_SUN_global_alpha
+#define GL_SUN_global_alpha 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glGlobalAlphaFactorbSUN (GLbyte factor);
+GLAPI void APIENTRY glGlobalAlphaFactorsSUN (GLshort factor);
+GLAPI void APIENTRY glGlobalAlphaFactoriSUN (GLint factor);
+GLAPI void APIENTRY glGlobalAlphaFactorfSUN (GLfloat factor);
+GLAPI void APIENTRY glGlobalAlphaFactordSUN (GLdouble factor);
+GLAPI void APIENTRY glGlobalAlphaFactorubSUN (GLubyte factor);
+GLAPI void APIENTRY glGlobalAlphaFactorusSUN (GLushort factor);
+GLAPI void APIENTRY glGlobalAlphaFactoruiSUN (GLuint factor);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORBSUNPROC) (GLbyte factor);
+typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORSSUNPROC) (GLshort factor);
+typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORISUNPROC) (GLint factor);
+typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORFSUNPROC) (GLfloat factor);
+typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORDSUNPROC) (GLdouble factor);
+typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUBSUNPROC) (GLubyte factor);
+typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUSSUNPROC) (GLushort factor);
+typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUISUNPROC) (GLuint factor);
+#endif
+
+#ifndef GL_SUN_triangle_list
+#define GL_SUN_triangle_list 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glReplacementCodeuiSUN (GLuint code);
+GLAPI void APIENTRY glReplacementCodeusSUN (GLushort code);
+GLAPI void APIENTRY glReplacementCodeubSUN (GLubyte code);
+GLAPI void APIENTRY glReplacementCodeuivSUN (const GLuint *code);
+GLAPI void APIENTRY glReplacementCodeusvSUN (const GLushort *code);
+GLAPI void APIENTRY glReplacementCodeubvSUN (const GLubyte *code);
+GLAPI void APIENTRY glReplacementCodePointerSUN (GLenum type, GLsizei stride, const GLvoid* *pointer);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUISUNPROC) (GLuint code);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUSSUNPROC) (GLushort code);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUBSUNPROC) (GLubyte code);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVSUNPROC) (const GLuint *code);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUSVSUNPROC) (const GLushort *code);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUBVSUNPROC) (const GLubyte *code);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEPOINTERSUNPROC) (GLenum type, GLsizei stride, const GLvoid* *pointer);
+#endif
+
+#ifndef GL_SUN_vertex
+#define GL_SUN_vertex 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glColor4ubVertex2fSUN (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y);
+GLAPI void APIENTRY glColor4ubVertex2fvSUN (const GLubyte *c, const GLfloat *v);
+GLAPI void APIENTRY glColor4ubVertex3fSUN (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z);
+GLAPI void APIENTRY glColor4ubVertex3fvSUN (const GLubyte *c, const GLfloat *v);
+GLAPI void APIENTRY glColor3fVertex3fSUN (GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z);
+GLAPI void APIENTRY glColor3fVertex3fvSUN (const GLfloat *c, const GLfloat *v);
+GLAPI void APIENTRY glNormal3fVertex3fSUN (GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+GLAPI void APIENTRY glNormal3fVertex3fvSUN (const GLfloat *n, const GLfloat *v);
+GLAPI void APIENTRY glColor4fNormal3fVertex3fSUN (GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+GLAPI void APIENTRY glColor4fNormal3fVertex3fvSUN (const GLfloat *c, const GLfloat *n, const GLfloat *v);
+GLAPI void APIENTRY glTexCoord2fVertex3fSUN (GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z);
+GLAPI void APIENTRY glTexCoord2fVertex3fvSUN (const GLfloat *tc, const GLfloat *v);
+GLAPI void APIENTRY glTexCoord4fVertex4fSUN (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+GLAPI void APIENTRY glTexCoord4fVertex4fvSUN (const GLfloat *tc, const GLfloat *v);
+GLAPI void APIENTRY glTexCoord2fColor4ubVertex3fSUN (GLfloat s, GLfloat t, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z);
+GLAPI void APIENTRY glTexCoord2fColor4ubVertex3fvSUN (const GLfloat *tc, const GLubyte *c, const GLfloat *v);
+GLAPI void APIENTRY glTexCoord2fColor3fVertex3fSUN (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z);
+GLAPI void APIENTRY glTexCoord2fColor3fVertex3fvSUN (const GLfloat *tc, const GLfloat *c, const GLfloat *v);
+GLAPI void APIENTRY glTexCoord2fNormal3fVertex3fSUN (GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+GLAPI void APIENTRY glTexCoord2fNormal3fVertex3fvSUN (const GLfloat *tc, const GLfloat *n, const GLfloat *v);
+GLAPI void APIENTRY glTexCoord2fColor4fNormal3fVertex3fSUN (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+GLAPI void APIENTRY glTexCoord2fColor4fNormal3fVertex3fvSUN (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v);
+GLAPI void APIENTRY glTexCoord4fColor4fNormal3fVertex4fSUN (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+GLAPI void APIENTRY glTexCoord4fColor4fNormal3fVertex4fvSUN (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v);
+GLAPI void APIENTRY glReplacementCodeuiVertex3fSUN (GLuint rc, GLfloat x, GLfloat y, GLfloat z);
+GLAPI void APIENTRY glReplacementCodeuiVertex3fvSUN (const GLuint *rc, const GLfloat *v);
+GLAPI void APIENTRY glReplacementCodeuiColor4ubVertex3fSUN (GLuint rc, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z);
+GLAPI void APIENTRY glReplacementCodeuiColor4ubVertex3fvSUN (const GLuint *rc, const GLubyte *c, const GLfloat *v);
+GLAPI void APIENTRY glReplacementCodeuiColor3fVertex3fSUN (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z);
+GLAPI void APIENTRY glReplacementCodeuiColor3fVertex3fvSUN (const GLuint *rc, const GLfloat *c, const GLfloat *v);
+GLAPI void APIENTRY glReplacementCodeuiNormal3fVertex3fSUN (GLuint rc, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+GLAPI void APIENTRY glReplacementCodeuiNormal3fVertex3fvSUN (const GLuint *rc, const GLfloat *n, const GLfloat *v);
+GLAPI void APIENTRY glReplacementCodeuiColor4fNormal3fVertex3fSUN (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+GLAPI void APIENTRY glReplacementCodeuiColor4fNormal3fVertex3fvSUN (const GLuint *rc, const GLfloat *c, const GLfloat *n, const GLfloat *v);
+GLAPI void APIENTRY glReplacementCodeuiTexCoord2fVertex3fSUN (GLuint rc, GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z);
+GLAPI void APIENTRY glReplacementCodeuiTexCoord2fVertex3fvSUN (const GLuint *rc, const GLfloat *tc, const GLfloat *v);
+GLAPI void APIENTRY glReplacementCodeuiTexCoord2fNormal3fVertex3fSUN (GLuint rc, GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+GLAPI void APIENTRY glReplacementCodeuiTexCoord2fNormal3fVertex3fvSUN (const GLuint *rc, const GLfloat *tc, const GLfloat *n, const GLfloat *v);
+GLAPI void APIENTRY glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fSUN (GLuint rc, GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+GLAPI void APIENTRY glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fvSUN (const GLuint *rc, const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX2FSUNPROC) (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y);
+typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX2FVSUNPROC) (const GLubyte *c, const GLfloat *v);
+typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX3FSUNPROC) (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX3FVSUNPROC) (const GLubyte *c, const GLfloat *v);
+typedef void (APIENTRYP PFNGLCOLOR3FVERTEX3FSUNPROC) (GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLCOLOR3FVERTEX3FVSUNPROC) (const GLfloat *c, const GLfloat *v);
+typedef void (APIENTRYP PFNGLNORMAL3FVERTEX3FSUNPROC) (GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *n, const GLfloat *v);
+typedef void (APIENTRYP PFNGLCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *c, const GLfloat *n, const GLfloat *v);
+typedef void (APIENTRYP PFNGLTEXCOORD2FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLTEXCOORD2FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *v);
+typedef void (APIENTRYP PFNGLTEXCOORD4FVERTEX4FSUNPROC) (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+typedef void (APIENTRYP PFNGLTEXCOORD4FVERTEX4FVSUNPROC) (const GLfloat *tc, const GLfloat *v);
+typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4UBVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4UBVERTEX3FVSUNPROC) (const GLfloat *tc, const GLubyte *c, const GLfloat *v);
+typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *v);
+typedef void (APIENTRYP PFNGLTEXCOORD2FNORMAL3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLTEXCOORD2FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *n, const GLfloat *v);
+typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v);
+typedef void (APIENTRYP PFNGLTEXCOORD4FCOLOR4FNORMAL3FVERTEX4FSUNPROC) (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+typedef void (APIENTRYP PFNGLTEXCOORD4FCOLOR4FNORMAL3FVERTEX4FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVERTEX3FSUNPROC) (GLuint rc, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *v);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4UBVERTEX3FSUNPROC) (GLuint rc, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4UBVERTEX3FVSUNPROC) (const GLuint *rc, const GLubyte *c, const GLfloat *v);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR3FVERTEX3FSUNPROC) (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *c, const GLfloat *v);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUINORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUINORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *n, const GLfloat *v);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *c, const GLfloat *n, const GLfloat *v);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *v);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *n, const GLfloat *v);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v);
+#endif
+
+#ifndef GL_EXT_blend_func_separate
+#define GL_EXT_blend_func_separate 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBlendFuncSeparateEXT (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEEXTPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
+#endif
+
+#ifndef GL_INGR_blend_func_separate
+#define GL_INGR_blend_func_separate 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBlendFuncSeparateINGR (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEINGRPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
+#endif
+
+#ifndef GL_INGR_color_clamp
+#define GL_INGR_color_clamp 1
+#endif
+
+#ifndef GL_INGR_interlace_read
+#define GL_INGR_interlace_read 1
+#endif
+
+#ifndef GL_EXT_stencil_wrap
+#define GL_EXT_stencil_wrap 1
+#endif
+
+#ifndef GL_EXT_422_pixels
+#define GL_EXT_422_pixels 1
+#endif
+
+#ifndef GL_NV_texgen_reflection
+#define GL_NV_texgen_reflection 1
+#endif
+
+#ifndef GL_SUN_convolution_border_modes
+#define GL_SUN_convolution_border_modes 1
+#endif
+
+#ifndef GL_EXT_texture_env_add
+#define GL_EXT_texture_env_add 1
+#endif
+
+#ifndef GL_EXT_texture_lod_bias
+#define GL_EXT_texture_lod_bias 1
+#endif
+
+#ifndef GL_EXT_texture_filter_anisotropic
+#define GL_EXT_texture_filter_anisotropic 1
+#endif
+
+#ifndef GL_EXT_vertex_weighting
+#define GL_EXT_vertex_weighting 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glVertexWeightfEXT (GLfloat weight);
+GLAPI void APIENTRY glVertexWeightfvEXT (const GLfloat *weight);
+GLAPI void APIENTRY glVertexWeightPointerEXT (GLsizei size, GLenum type, GLsizei stride, const GLvoid *pointer);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLVERTEXWEIGHTFEXTPROC) (GLfloat weight);
+typedef void (APIENTRYP PFNGLVERTEXWEIGHTFVEXTPROC) (const GLfloat *weight);
+typedef void (APIENTRYP PFNGLVERTEXWEIGHTPOINTEREXTPROC) (GLsizei size, GLenum type, GLsizei stride, const GLvoid *pointer);
+#endif
+
+#ifndef GL_NV_light_max_exponent
+#define GL_NV_light_max_exponent 1
+#endif
+
+#ifndef GL_NV_vertex_array_range
+#define GL_NV_vertex_array_range 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glFlushVertexArrayRangeNV (void);
+GLAPI void APIENTRY glVertexArrayRangeNV (GLsizei length, const GLvoid *pointer);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLFLUSHVERTEXARRAYRANGENVPROC) (void);
+typedef void (APIENTRYP PFNGLVERTEXARRAYRANGENVPROC) (GLsizei length, const GLvoid *pointer);
+#endif
+
+#ifndef GL_NV_register_combiners
+#define GL_NV_register_combiners 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glCombinerParameterfvNV (GLenum pname, const GLfloat *params);
+GLAPI void APIENTRY glCombinerParameterfNV (GLenum pname, GLfloat param);
+GLAPI void APIENTRY glCombinerParameterivNV (GLenum pname, const GLint *params);
+GLAPI void APIENTRY glCombinerParameteriNV (GLenum pname, GLint param);
+GLAPI void APIENTRY glCombinerInputNV (GLenum stage, GLenum portion, GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage);
+GLAPI void APIENTRY glCombinerOutputNV (GLenum stage, GLenum portion, GLenum abOutput, GLenum cdOutput, GLenum sumOutput, GLenum scale, GLenum bias, GLboolean abDotProduct, GLboolean cdDotProduct, GLboolean muxSum);
+GLAPI void APIENTRY glFinalCombinerInputNV (GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage);
+GLAPI void APIENTRY glGetCombinerInputParameterfvNV (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetCombinerInputParameterivNV (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetCombinerOutputParameterfvNV (GLenum stage, GLenum portion, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetCombinerOutputParameterivNV (GLenum stage, GLenum portion, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetFinalCombinerInputParameterfvNV (GLenum variable, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetFinalCombinerInputParameterivNV (GLenum variable, GLenum pname, GLint *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCOMBINERPARAMETERFVNVPROC) (GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLCOMBINERPARAMETERFNVPROC) (GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLCOMBINERPARAMETERIVNVPROC) (GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLCOMBINERPARAMETERINVPROC) (GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLCOMBINERINPUTNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage);
+typedef void (APIENTRYP PFNGLCOMBINEROUTPUTNVPROC) (GLenum stage, GLenum portion, GLenum abOutput, GLenum cdOutput, GLenum sumOutput, GLenum scale, GLenum bias, GLboolean abDotProduct, GLboolean cdDotProduct, GLboolean muxSum);
+typedef void (APIENTRYP PFNGLFINALCOMBINERINPUTNVPROC) (GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage);
+typedef void (APIENTRYP PFNGLGETCOMBINERINPUTPARAMETERFVNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETCOMBINERINPUTPARAMETERIVNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETCOMBINEROUTPUTPARAMETERFVNVPROC) (GLenum stage, GLenum portion, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETCOMBINEROUTPUTPARAMETERIVNVPROC) (GLenum stage, GLenum portion, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETFINALCOMBINERINPUTPARAMETERFVNVPROC) (GLenum variable, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETFINALCOMBINERINPUTPARAMETERIVNVPROC) (GLenum variable, GLenum pname, GLint *params);
+#endif
+
+#ifndef GL_NV_fog_distance
+#define GL_NV_fog_distance 1
+#endif
+
+#ifndef GL_NV_texgen_emboss
+#define GL_NV_texgen_emboss 1
+#endif
+
+#ifndef GL_NV_blend_square
+#define GL_NV_blend_square 1
+#endif
+
+#ifndef GL_NV_texture_env_combine4
+#define GL_NV_texture_env_combine4 1
+#endif
+
+#ifndef GL_MESA_resize_buffers
+#define GL_MESA_resize_buffers 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glResizeBuffersMESA (void);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLRESIZEBUFFERSMESAPROC) (void);
+#endif
+
+#ifndef GL_MESA_window_pos
+#define GL_MESA_window_pos 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glWindowPos2dMESA (GLdouble x, GLdouble y);
+GLAPI void APIENTRY glWindowPos2dvMESA (const GLdouble *v);
+GLAPI void APIENTRY glWindowPos2fMESA (GLfloat x, GLfloat y);
+GLAPI void APIENTRY glWindowPos2fvMESA (const GLfloat *v);
+GLAPI void APIENTRY glWindowPos2iMESA (GLint x, GLint y);
+GLAPI void APIENTRY glWindowPos2ivMESA (const GLint *v);
+GLAPI void APIENTRY glWindowPos2sMESA (GLshort x, GLshort y);
+GLAPI void APIENTRY glWindowPos2svMESA (const GLshort *v);
+GLAPI void APIENTRY glWindowPos3dMESA (GLdouble x, GLdouble y, GLdouble z);
+GLAPI void APIENTRY glWindowPos3dvMESA (const GLdouble *v);
+GLAPI void APIENTRY glWindowPos3fMESA (GLfloat x, GLfloat y, GLfloat z);
+GLAPI void APIENTRY glWindowPos3fvMESA (const GLfloat *v);
+GLAPI void APIENTRY glWindowPos3iMESA (GLint x, GLint y, GLint z);
+GLAPI void APIENTRY glWindowPos3ivMESA (const GLint *v);
+GLAPI void APIENTRY glWindowPos3sMESA (GLshort x, GLshort y, GLshort z);
+GLAPI void APIENTRY glWindowPos3svMESA (const GLshort *v);
+GLAPI void APIENTRY glWindowPos4dMESA (GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+GLAPI void APIENTRY glWindowPos4dvMESA (const GLdouble *v);
+GLAPI void APIENTRY glWindowPos4fMESA (GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+GLAPI void APIENTRY glWindowPos4fvMESA (const GLfloat *v);
+GLAPI void APIENTRY glWindowPos4iMESA (GLint x, GLint y, GLint z, GLint w);
+GLAPI void APIENTRY glWindowPos4ivMESA (const GLint *v);
+GLAPI void APIENTRY glWindowPos4sMESA (GLshort x, GLshort y, GLshort z, GLshort w);
+GLAPI void APIENTRY glWindowPos4svMESA (const GLshort *v);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLWINDOWPOS2DMESAPROC) (GLdouble x, GLdouble y);
+typedef void (APIENTRYP PFNGLWINDOWPOS2DVMESAPROC) (const GLdouble *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS2FMESAPROC) (GLfloat x, GLfloat y);
+typedef void (APIENTRYP PFNGLWINDOWPOS2FVMESAPROC) (const GLfloat *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS2IMESAPROC) (GLint x, GLint y);
+typedef void (APIENTRYP PFNGLWINDOWPOS2IVMESAPROC) (const GLint *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS2SMESAPROC) (GLshort x, GLshort y);
+typedef void (APIENTRYP PFNGLWINDOWPOS2SVMESAPROC) (const GLshort *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS3DMESAPROC) (GLdouble x, GLdouble y, GLdouble z);
+typedef void (APIENTRYP PFNGLWINDOWPOS3DVMESAPROC) (const GLdouble *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS3FMESAPROC) (GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLWINDOWPOS3FVMESAPROC) (const GLfloat *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS3IMESAPROC) (GLint x, GLint y, GLint z);
+typedef void (APIENTRYP PFNGLWINDOWPOS3IVMESAPROC) (const GLint *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS3SMESAPROC) (GLshort x, GLshort y, GLshort z);
+typedef void (APIENTRYP PFNGLWINDOWPOS3SVMESAPROC) (const GLshort *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS4DMESAPROC) (GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+typedef void (APIENTRYP PFNGLWINDOWPOS4DVMESAPROC) (const GLdouble *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS4FMESAPROC) (GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+typedef void (APIENTRYP PFNGLWINDOWPOS4FVMESAPROC) (const GLfloat *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS4IMESAPROC) (GLint x, GLint y, GLint z, GLint w);
+typedef void (APIENTRYP PFNGLWINDOWPOS4IVMESAPROC) (const GLint *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS4SMESAPROC) (GLshort x, GLshort y, GLshort z, GLshort w);
+typedef void (APIENTRYP PFNGLWINDOWPOS4SVMESAPROC) (const GLshort *v);
+#endif
+
+#ifndef GL_IBM_cull_vertex
+#define GL_IBM_cull_vertex 1
+#endif
+
+#ifndef GL_IBM_multimode_draw_arrays
+#define GL_IBM_multimode_draw_arrays 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glMultiModeDrawArraysIBM (const GLenum *mode, const GLint *first, const GLsizei *count, GLsizei primcount, GLint modestride);
+GLAPI void APIENTRY glMultiModeDrawElementsIBM (const GLenum *mode, const GLsizei *count, GLenum type, const GLvoid* const *indices, GLsizei primcount, GLint modestride);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLMULTIMODEDRAWARRAYSIBMPROC) (const GLenum *mode, const GLint *first, const GLsizei *count, GLsizei primcount, GLint modestride);
+typedef void (APIENTRYP PFNGLMULTIMODEDRAWELEMENTSIBMPROC) (const GLenum *mode, const GLsizei *count, GLenum type, const GLvoid* const *indices, GLsizei primcount, GLint modestride);
+#endif
+
+#ifndef GL_IBM_vertex_array_lists
+#define GL_IBM_vertex_array_lists 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glColorPointerListIBM (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+GLAPI void APIENTRY glSecondaryColorPointerListIBM (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+GLAPI void APIENTRY glEdgeFlagPointerListIBM (GLint stride, const GLboolean* *pointer, GLint ptrstride);
+GLAPI void APIENTRY glFogCoordPointerListIBM (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+GLAPI void APIENTRY glIndexPointerListIBM (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+GLAPI void APIENTRY glNormalPointerListIBM (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+GLAPI void APIENTRY glTexCoordPointerListIBM (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+GLAPI void APIENTRY glVertexPointerListIBM (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCOLORPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+typedef void (APIENTRYP PFNGLEDGEFLAGPOINTERLISTIBMPROC) (GLint stride, const GLboolean* *pointer, GLint ptrstride);
+typedef void (APIENTRYP PFNGLFOGCOORDPOINTERLISTIBMPROC) (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+typedef void (APIENTRYP PFNGLINDEXPOINTERLISTIBMPROC) (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+typedef void (APIENTRYP PFNGLNORMALPOINTERLISTIBMPROC) (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+typedef void (APIENTRYP PFNGLTEXCOORDPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+typedef void (APIENTRYP PFNGLVERTEXPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+#endif
+
+#ifndef GL_SGIX_subsample
+#define GL_SGIX_subsample 1
+#endif
+
+#ifndef GL_SGIX_ycrcba
+#define GL_SGIX_ycrcba 1
+#endif
+
+#ifndef GL_SGIX_ycrcb_subsample
+#define GL_SGIX_ycrcb_subsample 1
+#endif
+
+#ifndef GL_SGIX_depth_pass_instrument
+#define GL_SGIX_depth_pass_instrument 1
+#endif
+
+#ifndef GL_3DFX_texture_compression_FXT1
+#define GL_3DFX_texture_compression_FXT1 1
+#endif
+
+#ifndef GL_3DFX_multisample
+#define GL_3DFX_multisample 1
+#endif
+
+#ifndef GL_3DFX_tbuffer
+#define GL_3DFX_tbuffer 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glTbufferMask3DFX (GLuint mask);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLTBUFFERMASK3DFXPROC) (GLuint mask);
+#endif
+
+#ifndef GL_EXT_multisample
+#define GL_EXT_multisample 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glSampleMaskEXT (GLclampf value, GLboolean invert);
+GLAPI void APIENTRY glSamplePatternEXT (GLenum pattern);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLSAMPLEMASKEXTPROC) (GLclampf value, GLboolean invert);
+typedef void (APIENTRYP PFNGLSAMPLEPATTERNEXTPROC) (GLenum pattern);
+#endif
+
+#ifndef GL_SGIX_vertex_preclip
+#define GL_SGIX_vertex_preclip 1
+#endif
+
+#ifndef GL_SGIX_convolution_accuracy
+#define GL_SGIX_convolution_accuracy 1
+#endif
+
+#ifndef GL_SGIX_resample
+#define GL_SGIX_resample 1
+#endif
+
+#ifndef GL_SGIS_point_line_texgen
+#define GL_SGIS_point_line_texgen 1
+#endif
+
+#ifndef GL_SGIS_texture_color_mask
+#define GL_SGIS_texture_color_mask 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glTextureColorMaskSGIS (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLTEXTURECOLORMASKSGISPROC) (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
+#endif
+
+#ifndef GL_SGIX_igloo_interface
+#define GL_SGIX_igloo_interface 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glIglooInterfaceSGIX (GLenum pname, const GLvoid *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLIGLOOINTERFACESGIXPROC) (GLenum pname, const GLvoid *params);
+#endif
+
+#ifndef GL_EXT_texture_env_dot3
+#define GL_EXT_texture_env_dot3 1
+#endif
+
+#ifndef GL_ATI_texture_mirror_once
+#define GL_ATI_texture_mirror_once 1
+#endif
+
+#ifndef GL_NV_fence
+#define GL_NV_fence 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glDeleteFencesNV (GLsizei n, const GLuint *fences);
+GLAPI void APIENTRY glGenFencesNV (GLsizei n, GLuint *fences);
+GLAPI GLboolean APIENTRY glIsFenceNV (GLuint fence);
+GLAPI GLboolean APIENTRY glTestFenceNV (GLuint fence);
+GLAPI void APIENTRY glGetFenceivNV (GLuint fence, GLenum pname, GLint *params);
+GLAPI void APIENTRY glFinishFenceNV (GLuint fence);
+GLAPI void APIENTRY glSetFenceNV (GLuint fence, GLenum condition);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLDELETEFENCESNVPROC) (GLsizei n, const GLuint *fences);
+typedef void (APIENTRYP PFNGLGENFENCESNVPROC) (GLsizei n, GLuint *fences);
+typedef GLboolean (APIENTRYP PFNGLISFENCENVPROC) (GLuint fence);
+typedef GLboolean (APIENTRYP PFNGLTESTFENCENVPROC) (GLuint fence);
+typedef void (APIENTRYP PFNGLGETFENCEIVNVPROC) (GLuint fence, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLFINISHFENCENVPROC) (GLuint fence);
+typedef void (APIENTRYP PFNGLSETFENCENVPROC) (GLuint fence, GLenum condition);
+#endif
+
+#ifndef GL_NV_evaluators
+#define GL_NV_evaluators 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glMapControlPointsNV (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLint uorder, GLint vorder, GLboolean packed, const GLvoid *points);
+GLAPI void APIENTRY glMapParameterivNV (GLenum target, GLenum pname, const GLint *params);
+GLAPI void APIENTRY glMapParameterfvNV (GLenum target, GLenum pname, const GLfloat *params);
+GLAPI void APIENTRY glGetMapControlPointsNV (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLboolean packed, GLvoid *points);
+GLAPI void APIENTRY glGetMapParameterivNV (GLenum target, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetMapParameterfvNV (GLenum target, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetMapAttribParameterivNV (GLenum target, GLuint index, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetMapAttribParameterfvNV (GLenum target, GLuint index, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glEvalMapsNV (GLenum target, GLenum mode);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLMAPCONTROLPOINTSNVPROC) (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLint uorder, GLint vorder, GLboolean packed, const GLvoid *points);
+typedef void (APIENTRYP PFNGLMAPPARAMETERIVNVPROC) (GLenum target, GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLMAPPARAMETERFVNVPROC) (GLenum target, GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLGETMAPCONTROLPOINTSNVPROC) (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLboolean packed, GLvoid *points);
+typedef void (APIENTRYP PFNGLGETMAPPARAMETERIVNVPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETMAPPARAMETERFVNVPROC) (GLenum target, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETMAPATTRIBPARAMETERIVNVPROC) (GLenum target, GLuint index, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETMAPATTRIBPARAMETERFVNVPROC) (GLenum target, GLuint index, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLEVALMAPSNVPROC) (GLenum target, GLenum mode);
+#endif
+
+#ifndef GL_NV_packed_depth_stencil
+#define GL_NV_packed_depth_stencil 1
+#endif
+
+#ifndef GL_NV_register_combiners2
+#define GL_NV_register_combiners2 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glCombinerStageParameterfvNV (GLenum stage, GLenum pname, const GLfloat *params);
+GLAPI void APIENTRY glGetCombinerStageParameterfvNV (GLenum stage, GLenum pname, GLfloat *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCOMBINERSTAGEPARAMETERFVNVPROC) (GLenum stage, GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLGETCOMBINERSTAGEPARAMETERFVNVPROC) (GLenum stage, GLenum pname, GLfloat *params);
+#endif
+
+#ifndef GL_NV_texture_compression_vtc
+#define GL_NV_texture_compression_vtc 1
+#endif
+
+#ifndef GL_NV_texture_rectangle
+#define GL_NV_texture_rectangle 1
+#endif
+
+#ifndef GL_NV_texture_shader
+#define GL_NV_texture_shader 1
+#endif
+
+#ifndef GL_NV_texture_shader2
+#define GL_NV_texture_shader2 1
+#endif
+
+#ifndef GL_NV_vertex_array_range2
+#define GL_NV_vertex_array_range2 1
+#endif
+
+#ifndef GL_NV_vertex_program
+#define GL_NV_vertex_program 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI GLboolean APIENTRY glAreProgramsResidentNV (GLsizei n, const GLuint *programs, GLboolean *residences);
+GLAPI void APIENTRY glBindProgramNV (GLenum target, GLuint id);
+GLAPI void APIENTRY glDeleteProgramsNV (GLsizei n, const GLuint *programs);
+GLAPI void APIENTRY glExecuteProgramNV (GLenum target, GLuint id, const GLfloat *params);
+GLAPI void APIENTRY glGenProgramsNV (GLsizei n, GLuint *programs);
+GLAPI void APIENTRY glGetProgramParameterdvNV (GLenum target, GLuint index, GLenum pname, GLdouble *params);
+GLAPI void APIENTRY glGetProgramParameterfvNV (GLenum target, GLuint index, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetProgramivNV (GLuint id, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetProgramStringNV (GLuint id, GLenum pname, GLubyte *program);
+GLAPI void APIENTRY glGetTrackMatrixivNV (GLenum target, GLuint address, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetVertexAttribdvNV (GLuint index, GLenum pname, GLdouble *params);
+GLAPI void APIENTRY glGetVertexAttribfvNV (GLuint index, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetVertexAttribivNV (GLuint index, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetVertexAttribPointervNV (GLuint index, GLenum pname, GLvoid* *pointer);
+GLAPI GLboolean APIENTRY glIsProgramNV (GLuint id);
+GLAPI void APIENTRY glLoadProgramNV (GLenum target, GLuint id, GLsizei len, const GLubyte *program);
+GLAPI void APIENTRY glProgramParameter4dNV (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+GLAPI void APIENTRY glProgramParameter4dvNV (GLenum target, GLuint index, const GLdouble *v);
+GLAPI void APIENTRY glProgramParameter4fNV (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+GLAPI void APIENTRY glProgramParameter4fvNV (GLenum target, GLuint index, const GLfloat *v);
+GLAPI void APIENTRY glProgramParameters4dvNV (GLenum target, GLuint index, GLuint count, const GLdouble *v);
+GLAPI void APIENTRY glProgramParameters4fvNV (GLenum target, GLuint index, GLuint count, const GLfloat *v);
+GLAPI void APIENTRY glRequestResidentProgramsNV (GLsizei n, const GLuint *programs);
+GLAPI void APIENTRY glTrackMatrixNV (GLenum target, GLuint address, GLenum matrix, GLenum transform);
+GLAPI void APIENTRY glVertexAttribPointerNV (GLuint index, GLint fsize, GLenum type, GLsizei stride, const GLvoid *pointer);
+GLAPI void APIENTRY glVertexAttrib1dNV (GLuint index, GLdouble x);
+GLAPI void APIENTRY glVertexAttrib1dvNV (GLuint index, const GLdouble *v);
+GLAPI void APIENTRY glVertexAttrib1fNV (GLuint index, GLfloat x);
+GLAPI void APIENTRY glVertexAttrib1fvNV (GLuint index, const GLfloat *v);
+GLAPI void APIENTRY glVertexAttrib1sNV (GLuint index, GLshort x);
+GLAPI void APIENTRY glVertexAttrib1svNV (GLuint index, const GLshort *v);
+GLAPI void APIENTRY glVertexAttrib2dNV (GLuint index, GLdouble x, GLdouble y);
+GLAPI void APIENTRY glVertexAttrib2dvNV (GLuint index, const GLdouble *v);
+GLAPI void APIENTRY glVertexAttrib2fNV (GLuint index, GLfloat x, GLfloat y);
+GLAPI void APIENTRY glVertexAttrib2fvNV (GLuint index, const GLfloat *v);
+GLAPI void APIENTRY glVertexAttrib2sNV (GLuint index, GLshort x, GLshort y);
+GLAPI void APIENTRY glVertexAttrib2svNV (GLuint index, const GLshort *v);
+GLAPI void APIENTRY glVertexAttrib3dNV (GLuint index, GLdouble x, GLdouble y, GLdouble z);
+GLAPI void APIENTRY glVertexAttrib3dvNV (GLuint index, const GLdouble *v);
+GLAPI void APIENTRY glVertexAttrib3fNV (GLuint index, GLfloat x, GLfloat y, GLfloat z);
+GLAPI void APIENTRY glVertexAttrib3fvNV (GLuint index, const GLfloat *v);
+GLAPI void APIENTRY glVertexAttrib3sNV (GLuint index, GLshort x, GLshort y, GLshort z);
+GLAPI void APIENTRY glVertexAttrib3svNV (GLuint index, const GLshort *v);
+GLAPI void APIENTRY glVertexAttrib4dNV (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+GLAPI void APIENTRY glVertexAttrib4dvNV (GLuint index, const GLdouble *v);
+GLAPI void APIENTRY glVertexAttrib4fNV (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+GLAPI void APIENTRY glVertexAttrib4fvNV (GLuint index, const GLfloat *v);
+GLAPI void APIENTRY glVertexAttrib4sNV (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w);
+GLAPI void APIENTRY glVertexAttrib4svNV (GLuint index, const GLshort *v);
+GLAPI void APIENTRY glVertexAttrib4ubNV (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w);
+GLAPI void APIENTRY glVertexAttrib4ubvNV (GLuint index, const GLubyte *v);
+GLAPI void APIENTRY glVertexAttribs1dvNV (GLuint index, GLsizei count, const GLdouble *v);
+GLAPI void APIENTRY glVertexAttribs1fvNV (GLuint index, GLsizei count, const GLfloat *v);
+GLAPI void APIENTRY glVertexAttribs1svNV (GLuint index, GLsizei count, const GLshort *v);
+GLAPI void APIENTRY glVertexAttribs2dvNV (GLuint index, GLsizei count, const GLdouble *v);
+GLAPI void APIENTRY glVertexAttribs2fvNV (GLuint index, GLsizei count, const GLfloat *v);
+GLAPI void APIENTRY glVertexAttribs2svNV (GLuint index, GLsizei count, const GLshort *v);
+GLAPI void APIENTRY glVertexAttribs3dvNV (GLuint index, GLsizei count, const GLdouble *v);
+GLAPI void APIENTRY glVertexAttribs3fvNV (GLuint index, GLsizei count, const GLfloat *v);
+GLAPI void APIENTRY glVertexAttribs3svNV (GLuint index, GLsizei count, const GLshort *v);
+GLAPI void APIENTRY glVertexAttribs4dvNV (GLuint index, GLsizei count, const GLdouble *v);
+GLAPI void APIENTRY glVertexAttribs4fvNV (GLuint index, GLsizei count, const GLfloat *v);
+GLAPI void APIENTRY glVertexAttribs4svNV (GLuint index, GLsizei count, const GLshort *v);
+GLAPI void APIENTRY glVertexAttribs4ubvNV (GLuint index, GLsizei count, const GLubyte *v);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef GLboolean (APIENTRYP PFNGLAREPROGRAMSRESIDENTNVPROC) (GLsizei n, const GLuint *programs, GLboolean *residences);
+typedef void (APIENTRYP PFNGLBINDPROGRAMNVPROC) (GLenum target, GLuint id);
+typedef void (APIENTRYP PFNGLDELETEPROGRAMSNVPROC) (GLsizei n, const GLuint *programs);
+typedef void (APIENTRYP PFNGLEXECUTEPROGRAMNVPROC) (GLenum target, GLuint id, const GLfloat *params);
+typedef void (APIENTRYP PFNGLGENPROGRAMSNVPROC) (GLsizei n, GLuint *programs);
+typedef void (APIENTRYP PFNGLGETPROGRAMPARAMETERDVNVPROC) (GLenum target, GLuint index, GLenum pname, GLdouble *params);
+typedef void (APIENTRYP PFNGLGETPROGRAMPARAMETERFVNVPROC) (GLenum target, GLuint index, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETPROGRAMIVNVPROC) (GLuint id, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETPROGRAMSTRINGNVPROC) (GLuint id, GLenum pname, GLubyte *program);
+typedef void (APIENTRYP PFNGLGETTRACKMATRIXIVNVPROC) (GLenum target, GLuint address, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVNVPROC) (GLuint index, GLenum pname, GLdouble *params);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVNVPROC) (GLuint index, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVNVPROC) (GLuint index, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVNVPROC) (GLuint index, GLenum pname, GLvoid* *pointer);
+typedef GLboolean (APIENTRYP PFNGLISPROGRAMNVPROC) (GLuint id);
+typedef void (APIENTRYP PFNGLLOADPROGRAMNVPROC) (GLenum target, GLuint id, GLsizei len, const GLubyte *program);
+typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4DNVPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4DVNVPROC) (GLenum target, GLuint index, const GLdouble *v);
+typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4FNVPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4FVNVPROC) (GLenum target, GLuint index, const GLfloat *v);
+typedef void (APIENTRYP PFNGLPROGRAMPARAMETERS4DVNVPROC) (GLenum target, GLuint index, GLuint count, const GLdouble *v);
+typedef void (APIENTRYP PFNGLPROGRAMPARAMETERS4FVNVPROC) (GLenum target, GLuint index, GLuint count, const GLfloat *v);
+typedef void (APIENTRYP PFNGLREQUESTRESIDENTPROGRAMSNVPROC) (GLsizei n, const GLuint *programs);
+typedef void (APIENTRYP PFNGLTRACKMATRIXNVPROC) (GLenum target, GLuint address, GLenum matrix, GLenum transform);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERNVPROC) (GLuint index, GLint fsize, GLenum type, GLsizei stride, const GLvoid *pointer);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1DNVPROC) (GLuint index, GLdouble x);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVNVPROC) (GLuint index, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1FNVPROC) (GLuint index, GLfloat x);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVNVPROC) (GLuint index, const GLfloat *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1SNVPROC) (GLuint index, GLshort x);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVNVPROC) (GLuint index, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2DNVPROC) (GLuint index, GLdouble x, GLdouble y);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVNVPROC) (GLuint index, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2FNVPROC) (GLuint index, GLfloat x, GLfloat y);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVNVPROC) (GLuint index, const GLfloat *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2SNVPROC) (GLuint index, GLshort x, GLshort y);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVNVPROC) (GLuint index, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3DNVPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVNVPROC) (GLuint index, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3FNVPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVNVPROC) (GLuint index, const GLfloat *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3SNVPROC) (GLuint index, GLshort x, GLshort y, GLshort z);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVNVPROC) (GLuint index, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4DNVPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVNVPROC) (GLuint index, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4FNVPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVNVPROC) (GLuint index, const GLfloat *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4SNVPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVNVPROC) (GLuint index, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBNVPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVNVPROC) (GLuint index, const GLubyte *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS1DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS1FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS1SVNVPROC) (GLuint index, GLsizei count, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS2DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS2FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS2SVNVPROC) (GLuint index, GLsizei count, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS3DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS3FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS3SVNVPROC) (GLuint index, GLsizei count, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS4DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS4FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS4SVNVPROC) (GLuint index, GLsizei count, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS4UBVNVPROC) (GLuint index, GLsizei count, const GLubyte *v);
+#endif
+
+#ifndef GL_SGIX_texture_coordinate_clamp
+#define GL_SGIX_texture_coordinate_clamp 1
+#endif
+
+#ifndef GL_SGIX_scalebias_hint
+#define GL_SGIX_scalebias_hint 1
+#endif
+
+#ifndef GL_OML_interlace
+#define GL_OML_interlace 1
+#endif
+
+#ifndef GL_OML_subsample
+#define GL_OML_subsample 1
+#endif
+
+#ifndef GL_OML_resample
+#define GL_OML_resample 1
+#endif
+
+#ifndef GL_NV_copy_depth_to_color
+#define GL_NV_copy_depth_to_color 1
+#endif
+
+#ifndef GL_ATI_envmap_bumpmap
+#define GL_ATI_envmap_bumpmap 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glTexBumpParameterivATI (GLenum pname, const GLint *param);
+GLAPI void APIENTRY glTexBumpParameterfvATI (GLenum pname, const GLfloat *param);
+GLAPI void APIENTRY glGetTexBumpParameterivATI (GLenum pname, GLint *param);
+GLAPI void APIENTRY glGetTexBumpParameterfvATI (GLenum pname, GLfloat *param);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLTEXBUMPPARAMETERIVATIPROC) (GLenum pname, const GLint *param);
+typedef void (APIENTRYP PFNGLTEXBUMPPARAMETERFVATIPROC) (GLenum pname, const GLfloat *param);
+typedef void (APIENTRYP PFNGLGETTEXBUMPPARAMETERIVATIPROC) (GLenum pname, GLint *param);
+typedef void (APIENTRYP PFNGLGETTEXBUMPPARAMETERFVATIPROC) (GLenum pname, GLfloat *param);
+#endif
+
+#ifndef GL_ATI_fragment_shader
+#define GL_ATI_fragment_shader 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI GLuint APIENTRY glGenFragmentShadersATI (GLuint range);
+GLAPI void APIENTRY glBindFragmentShaderATI (GLuint id);
+GLAPI void APIENTRY glDeleteFragmentShaderATI (GLuint id);
+GLAPI void APIENTRY glBeginFragmentShaderATI (void);
+GLAPI void APIENTRY glEndFragmentShaderATI (void);
+GLAPI void APIENTRY glPassTexCoordATI (GLuint dst, GLuint coord, GLenum swizzle);
+GLAPI void APIENTRY glSampleMapATI (GLuint dst, GLuint interp, GLenum swizzle);
+GLAPI void APIENTRY glColorFragmentOp1ATI (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod);
+GLAPI void APIENTRY glColorFragmentOp2ATI (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod);
+GLAPI void APIENTRY glColorFragmentOp3ATI (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod);
+GLAPI void APIENTRY glAlphaFragmentOp1ATI (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod);
+GLAPI void APIENTRY glAlphaFragmentOp2ATI (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod);
+GLAPI void APIENTRY glAlphaFragmentOp3ATI (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod);
+GLAPI void APIENTRY glSetFragmentShaderConstantATI (GLuint dst, const GLfloat *value);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef GLuint (APIENTRYP PFNGLGENFRAGMENTSHADERSATIPROC) (GLuint range);
+typedef void (APIENTRYP PFNGLBINDFRAGMENTSHADERATIPROC) (GLuint id);
+typedef void (APIENTRYP PFNGLDELETEFRAGMENTSHADERATIPROC) (GLuint id);
+typedef void (APIENTRYP PFNGLBEGINFRAGMENTSHADERATIPROC) (void);
+typedef void (APIENTRYP PFNGLENDFRAGMENTSHADERATIPROC) (void);
+typedef void (APIENTRYP PFNGLPASSTEXCOORDATIPROC) (GLuint dst, GLuint coord, GLenum swizzle);
+typedef void (APIENTRYP PFNGLSAMPLEMAPATIPROC) (GLuint dst, GLuint interp, GLenum swizzle);
+typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP1ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod);
+typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP2ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod);
+typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP3ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod);
+typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP1ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod);
+typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP2ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod);
+typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP3ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod);
+typedef void (APIENTRYP PFNGLSETFRAGMENTSHADERCONSTANTATIPROC) (GLuint dst, const GLfloat *value);
+#endif
+
+#ifndef GL_ATI_pn_triangles
+#define GL_ATI_pn_triangles 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glPNTrianglesiATI (GLenum pname, GLint param);
+GLAPI void APIENTRY glPNTrianglesfATI (GLenum pname, GLfloat param);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPNTRIANGLESIATIPROC) (GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLPNTRIANGLESFATIPROC) (GLenum pname, GLfloat param);
+#endif
+
+#ifndef GL_ATI_vertex_array_object
+#define GL_ATI_vertex_array_object 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI GLuint APIENTRY glNewObjectBufferATI (GLsizei size, const GLvoid *pointer, GLenum usage);
+GLAPI GLboolean APIENTRY glIsObjectBufferATI (GLuint buffer);
+GLAPI void APIENTRY glUpdateObjectBufferATI (GLuint buffer, GLuint offset, GLsizei size, const GLvoid *pointer, GLenum preserve);
+GLAPI void APIENTRY glGetObjectBufferfvATI (GLuint buffer, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetObjectBufferivATI (GLuint buffer, GLenum pname, GLint *params);
+GLAPI void APIENTRY glFreeObjectBufferATI (GLuint buffer);
+GLAPI void APIENTRY glArrayObjectATI (GLenum array, GLint size, GLenum type, GLsizei stride, GLuint buffer, GLuint offset);
+GLAPI void APIENTRY glGetArrayObjectfvATI (GLenum array, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetArrayObjectivATI (GLenum array, GLenum pname, GLint *params);
+GLAPI void APIENTRY glVariantArrayObjectATI (GLuint id, GLenum type, GLsizei stride, GLuint buffer, GLuint offset);
+GLAPI void APIENTRY glGetVariantArrayObjectfvATI (GLuint id, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetVariantArrayObjectivATI (GLuint id, GLenum pname, GLint *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef GLuint (APIENTRYP PFNGLNEWOBJECTBUFFERATIPROC) (GLsizei size, const GLvoid *pointer, GLenum usage);
+typedef GLboolean (APIENTRYP PFNGLISOBJECTBUFFERATIPROC) (GLuint buffer);
+typedef void (APIENTRYP PFNGLUPDATEOBJECTBUFFERATIPROC) (GLuint buffer, GLuint offset, GLsizei size, const GLvoid *pointer, GLenum preserve);
+typedef void (APIENTRYP PFNGLGETOBJECTBUFFERFVATIPROC) (GLuint buffer, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETOBJECTBUFFERIVATIPROC) (GLuint buffer, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLFREEOBJECTBUFFERATIPROC) (GLuint buffer);
+typedef void (APIENTRYP PFNGLARRAYOBJECTATIPROC) (GLenum array, GLint size, GLenum type, GLsizei stride, GLuint buffer, GLuint offset);
+typedef void (APIENTRYP PFNGLGETARRAYOBJECTFVATIPROC) (GLenum array, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETARRAYOBJECTIVATIPROC) (GLenum array, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLVARIANTARRAYOBJECTATIPROC) (GLuint id, GLenum type, GLsizei stride, GLuint buffer, GLuint offset);
+typedef void (APIENTRYP PFNGLGETVARIANTARRAYOBJECTFVATIPROC) (GLuint id, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETVARIANTARRAYOBJECTIVATIPROC) (GLuint id, GLenum pname, GLint *params);
+#endif
+
+#ifndef GL_EXT_vertex_shader
+#define GL_EXT_vertex_shader 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBeginVertexShaderEXT (void);
+GLAPI void APIENTRY glEndVertexShaderEXT (void);
+GLAPI void APIENTRY glBindVertexShaderEXT (GLuint id);
+GLAPI GLuint APIENTRY glGenVertexShadersEXT (GLuint range);
+GLAPI void APIENTRY glDeleteVertexShaderEXT (GLuint id);
+GLAPI void APIENTRY glShaderOp1EXT (GLenum op, GLuint res, GLuint arg1);
+GLAPI void APIENTRY glShaderOp2EXT (GLenum op, GLuint res, GLuint arg1, GLuint arg2);
+GLAPI void APIENTRY glShaderOp3EXT (GLenum op, GLuint res, GLuint arg1, GLuint arg2, GLuint arg3);
+GLAPI void APIENTRY glSwizzleEXT (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW);
+GLAPI void APIENTRY glWriteMaskEXT (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW);
+GLAPI void APIENTRY glInsertComponentEXT (GLuint res, GLuint src, GLuint num);
+GLAPI void APIENTRY glExtractComponentEXT (GLuint res, GLuint src, GLuint num);
+GLAPI GLuint APIENTRY glGenSymbolsEXT (GLenum datatype, GLenum storagetype, GLenum range, GLuint components);
+GLAPI void APIENTRY glSetInvariantEXT (GLuint id, GLenum type, const GLvoid *addr);
+GLAPI void APIENTRY glSetLocalConstantEXT (GLuint id, GLenum type, const GLvoid *addr);
+GLAPI void APIENTRY glVariantbvEXT (GLuint id, const GLbyte *addr);
+GLAPI void APIENTRY glVariantsvEXT (GLuint id, const GLshort *addr);
+GLAPI void APIENTRY glVariantivEXT (GLuint id, const GLint *addr);
+GLAPI void APIENTRY glVariantfvEXT (GLuint id, const GLfloat *addr);
+GLAPI void APIENTRY glVariantdvEXT (GLuint id, const GLdouble *addr);
+GLAPI void APIENTRY glVariantubvEXT (GLuint id, const GLubyte *addr);
+GLAPI void APIENTRY glVariantusvEXT (GLuint id, const GLushort *addr);
+GLAPI void APIENTRY glVariantuivEXT (GLuint id, const GLuint *addr);
+GLAPI void APIENTRY glVariantPointerEXT (GLuint id, GLenum type, GLuint stride, const GLvoid *addr);
+GLAPI void APIENTRY glEnableVariantClientStateEXT (GLuint id);
+GLAPI void APIENTRY glDisableVariantClientStateEXT (GLuint id);
+GLAPI GLuint APIENTRY glBindLightParameterEXT (GLenum light, GLenum value);
+GLAPI GLuint APIENTRY glBindMaterialParameterEXT (GLenum face, GLenum value);
+GLAPI GLuint APIENTRY glBindTexGenParameterEXT (GLenum unit, GLenum coord, GLenum value);
+GLAPI GLuint APIENTRY glBindTextureUnitParameterEXT (GLenum unit, GLenum value);
+GLAPI GLuint APIENTRY glBindParameterEXT (GLenum value);
+GLAPI GLboolean APIENTRY glIsVariantEnabledEXT (GLuint id, GLenum cap);
+GLAPI void APIENTRY glGetVariantBooleanvEXT (GLuint id, GLenum value, GLboolean *data);
+GLAPI void APIENTRY glGetVariantIntegervEXT (GLuint id, GLenum value, GLint *data);
+GLAPI void APIENTRY glGetVariantFloatvEXT (GLuint id, GLenum value, GLfloat *data);
+GLAPI void APIENTRY glGetVariantPointervEXT (GLuint id, GLenum value, GLvoid* *data);
+GLAPI void APIENTRY glGetInvariantBooleanvEXT (GLuint id, GLenum value, GLboolean *data);
+GLAPI void APIENTRY glGetInvariantIntegervEXT (GLuint id, GLenum value, GLint *data);
+GLAPI void APIENTRY glGetInvariantFloatvEXT (GLuint id, GLenum value, GLfloat *data);
+GLAPI void APIENTRY glGetLocalConstantBooleanvEXT (GLuint id, GLenum value, GLboolean *data);
+GLAPI void APIENTRY glGetLocalConstantIntegervEXT (GLuint id, GLenum value, GLint *data);
+GLAPI void APIENTRY glGetLocalConstantFloatvEXT (GLuint id, GLenum value, GLfloat *data);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBEGINVERTEXSHADEREXTPROC) (void);
+typedef void (APIENTRYP PFNGLENDVERTEXSHADEREXTPROC) (void);
+typedef void (APIENTRYP PFNGLBINDVERTEXSHADEREXTPROC) (GLuint id);
+typedef GLuint (APIENTRYP PFNGLGENVERTEXSHADERSEXTPROC) (GLuint range);
+typedef void (APIENTRYP PFNGLDELETEVERTEXSHADEREXTPROC) (GLuint id);
+typedef void (APIENTRYP PFNGLSHADEROP1EXTPROC) (GLenum op, GLuint res, GLuint arg1);
+typedef void (APIENTRYP PFNGLSHADEROP2EXTPROC) (GLenum op, GLuint res, GLuint arg1, GLuint arg2);
+typedef void (APIENTRYP PFNGLSHADEROP3EXTPROC) (GLenum op, GLuint res, GLuint arg1, GLuint arg2, GLuint arg3);
+typedef void (APIENTRYP PFNGLSWIZZLEEXTPROC) (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW);
+typedef void (APIENTRYP PFNGLWRITEMASKEXTPROC) (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW);
+typedef void (APIENTRYP PFNGLINSERTCOMPONENTEXTPROC) (GLuint res, GLuint src, GLuint num);
+typedef void (APIENTRYP PFNGLEXTRACTCOMPONENTEXTPROC) (GLuint res, GLuint src, GLuint num);
+typedef GLuint (APIENTRYP PFNGLGENSYMBOLSEXTPROC) (GLenum datatype, GLenum storagetype, GLenum range, GLuint components);
+typedef void (APIENTRYP PFNGLSETINVARIANTEXTPROC) (GLuint id, GLenum type, const GLvoid *addr);
+typedef void (APIENTRYP PFNGLSETLOCALCONSTANTEXTPROC) (GLuint id, GLenum type, const GLvoid *addr);
+typedef void (APIENTRYP PFNGLVARIANTBVEXTPROC) (GLuint id, const GLbyte *addr);
+typedef void (APIENTRYP PFNGLVARIANTSVEXTPROC) (GLuint id, const GLshort *addr);
+typedef void (APIENTRYP PFNGLVARIANTIVEXTPROC) (GLuint id, const GLint *addr);
+typedef void (APIENTRYP PFNGLVARIANTFVEXTPROC) (GLuint id, const GLfloat *addr);
+typedef void (APIENTRYP PFNGLVARIANTDVEXTPROC) (GLuint id, const GLdouble *addr);
+typedef void (APIENTRYP PFNGLVARIANTUBVEXTPROC) (GLuint id, const GLubyte *addr);
+typedef void (APIENTRYP PFNGLVARIANTUSVEXTPROC) (GLuint id, const GLushort *addr);
+typedef void (APIENTRYP PFNGLVARIANTUIVEXTPROC) (GLuint id, const GLuint *addr);
+typedef void (APIENTRYP PFNGLVARIANTPOINTEREXTPROC) (GLuint id, GLenum type, GLuint stride, const GLvoid *addr);
+typedef void (APIENTRYP PFNGLENABLEVARIANTCLIENTSTATEEXTPROC) (GLuint id);
+typedef void (APIENTRYP PFNGLDISABLEVARIANTCLIENTSTATEEXTPROC) (GLuint id);
+typedef GLuint (APIENTRYP PFNGLBINDLIGHTPARAMETEREXTPROC) (GLenum light, GLenum value);
+typedef GLuint (APIENTRYP PFNGLBINDMATERIALPARAMETEREXTPROC) (GLenum face, GLenum value);
+typedef GLuint (APIENTRYP PFNGLBINDTEXGENPARAMETEREXTPROC) (GLenum unit, GLenum coord, GLenum value);
+typedef GLuint (APIENTRYP PFNGLBINDTEXTUREUNITPARAMETEREXTPROC) (GLenum unit, GLenum value);
+typedef GLuint (APIENTRYP PFNGLBINDPARAMETEREXTPROC) (GLenum value);
+typedef GLboolean (APIENTRYP PFNGLISVARIANTENABLEDEXTPROC) (GLuint id, GLenum cap);
+typedef void (APIENTRYP PFNGLGETVARIANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data);
+typedef void (APIENTRYP PFNGLGETVARIANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data);
+typedef void (APIENTRYP PFNGLGETVARIANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data);
+typedef void (APIENTRYP PFNGLGETVARIANTPOINTERVEXTPROC) (GLuint id, GLenum value, GLvoid* *data);
+typedef void (APIENTRYP PFNGLGETINVARIANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data);
+typedef void (APIENTRYP PFNGLGETINVARIANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data);
+typedef void (APIENTRYP PFNGLGETINVARIANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data);
+typedef void (APIENTRYP PFNGLGETLOCALCONSTANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data);
+typedef void (APIENTRYP PFNGLGETLOCALCONSTANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data);
+typedef void (APIENTRYP PFNGLGETLOCALCONSTANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data);
+#endif
+
+#ifndef GL_ATI_vertex_streams
+#define GL_ATI_vertex_streams 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glVertexStream1sATI (GLenum stream, GLshort x);
+GLAPI void APIENTRY glVertexStream1svATI (GLenum stream, const GLshort *coords);
+GLAPI void APIENTRY glVertexStream1iATI (GLenum stream, GLint x);
+GLAPI void APIENTRY glVertexStream1ivATI (GLenum stream, const GLint *coords);
+GLAPI void APIENTRY glVertexStream1fATI (GLenum stream, GLfloat x);
+GLAPI void APIENTRY glVertexStream1fvATI (GLenum stream, const GLfloat *coords);
+GLAPI void APIENTRY glVertexStream1dATI (GLenum stream, GLdouble x);
+GLAPI void APIENTRY glVertexStream1dvATI (GLenum stream, const GLdouble *coords);
+GLAPI void APIENTRY glVertexStream2sATI (GLenum stream, GLshort x, GLshort y);
+GLAPI void APIENTRY glVertexStream2svATI (GLenum stream, const GLshort *coords);
+GLAPI void APIENTRY glVertexStream2iATI (GLenum stream, GLint x, GLint y);
+GLAPI void APIENTRY glVertexStream2ivATI (GLenum stream, const GLint *coords);
+GLAPI void APIENTRY glVertexStream2fATI (GLenum stream, GLfloat x, GLfloat y);
+GLAPI void APIENTRY glVertexStream2fvATI (GLenum stream, const GLfloat *coords);
+GLAPI void APIENTRY glVertexStream2dATI (GLenum stream, GLdouble x, GLdouble y);
+GLAPI void APIENTRY glVertexStream2dvATI (GLenum stream, const GLdouble *coords);
+GLAPI void APIENTRY glVertexStream3sATI (GLenum stream, GLshort x, GLshort y, GLshort z);
+GLAPI void APIENTRY glVertexStream3svATI (GLenum stream, const GLshort *coords);
+GLAPI void APIENTRY glVertexStream3iATI (GLenum stream, GLint x, GLint y, GLint z);
+GLAPI void APIENTRY glVertexStream3ivATI (GLenum stream, const GLint *coords);
+GLAPI void APIENTRY glVertexStream3fATI (GLenum stream, GLfloat x, GLfloat y, GLfloat z);
+GLAPI void APIENTRY glVertexStream3fvATI (GLenum stream, const GLfloat *coords);
+GLAPI void APIENTRY glVertexStream3dATI (GLenum stream, GLdouble x, GLdouble y, GLdouble z);
+GLAPI void APIENTRY glVertexStream3dvATI (GLenum stream, const GLdouble *coords);
+GLAPI void APIENTRY glVertexStream4sATI (GLenum stream, GLshort x, GLshort y, GLshort z, GLshort w);
+GLAPI void APIENTRY glVertexStream4svATI (GLenum stream, const GLshort *coords);
+GLAPI void APIENTRY glVertexStream4iATI (GLenum stream, GLint x, GLint y, GLint z, GLint w);
+GLAPI void APIENTRY glVertexStream4ivATI (GLenum stream, const GLint *coords);
+GLAPI void APIENTRY glVertexStream4fATI (GLenum stream, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+GLAPI void APIENTRY glVertexStream4fvATI (GLenum stream, const GLfloat *coords);
+GLAPI void APIENTRY glVertexStream4dATI (GLenum stream, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+GLAPI void APIENTRY glVertexStream4dvATI (GLenum stream, const GLdouble *coords);
+GLAPI void APIENTRY glNormalStream3bATI (GLenum stream, GLbyte nx, GLbyte ny, GLbyte nz);
+GLAPI void APIENTRY glNormalStream3bvATI (GLenum stream, const GLbyte *coords);
+GLAPI void APIENTRY glNormalStream3sATI (GLenum stream, GLshort nx, GLshort ny, GLshort nz);
+GLAPI void APIENTRY glNormalStream3svATI (GLenum stream, const GLshort *coords);
+GLAPI void APIENTRY glNormalStream3iATI (GLenum stream, GLint nx, GLint ny, GLint nz);
+GLAPI void APIENTRY glNormalStream3ivATI (GLenum stream, const GLint *coords);
+GLAPI void APIENTRY glNormalStream3fATI (GLenum stream, GLfloat nx, GLfloat ny, GLfloat nz);
+GLAPI void APIENTRY glNormalStream3fvATI (GLenum stream, const GLfloat *coords);
+GLAPI void APIENTRY glNormalStream3dATI (GLenum stream, GLdouble nx, GLdouble ny, GLdouble nz);
+GLAPI void APIENTRY glNormalStream3dvATI (GLenum stream, const GLdouble *coords);
+GLAPI void APIENTRY glClientActiveVertexStreamATI (GLenum stream);
+GLAPI void APIENTRY glVertexBlendEnviATI (GLenum pname, GLint param);
+GLAPI void APIENTRY glVertexBlendEnvfATI (GLenum pname, GLfloat param);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLVERTEXSTREAM1SATIPROC) (GLenum stream, GLshort x);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM1SVATIPROC) (GLenum stream, const GLshort *coords);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM1IATIPROC) (GLenum stream, GLint x);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM1IVATIPROC) (GLenum stream, const GLint *coords);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM1FATIPROC) (GLenum stream, GLfloat x);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM1FVATIPROC) (GLenum stream, const GLfloat *coords);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM1DATIPROC) (GLenum stream, GLdouble x);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM1DVATIPROC) (GLenum stream, const GLdouble *coords);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM2SATIPROC) (GLenum stream, GLshort x, GLshort y);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM2SVATIPROC) (GLenum stream, const GLshort *coords);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM2IATIPROC) (GLenum stream, GLint x, GLint y);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM2IVATIPROC) (GLenum stream, const GLint *coords);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM2FATIPROC) (GLenum stream, GLfloat x, GLfloat y);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM2FVATIPROC) (GLenum stream, const GLfloat *coords);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM2DATIPROC) (GLenum stream, GLdouble x, GLdouble y);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM2DVATIPROC) (GLenum stream, const GLdouble *coords);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM3SATIPROC) (GLenum stream, GLshort x, GLshort y, GLshort z);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM3SVATIPROC) (GLenum stream, const GLshort *coords);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM3IATIPROC) (GLenum stream, GLint x, GLint y, GLint z);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM3IVATIPROC) (GLenum stream, const GLint *coords);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM3FATIPROC) (GLenum stream, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM3FVATIPROC) (GLenum stream, const GLfloat *coords);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM3DATIPROC) (GLenum stream, GLdouble x, GLdouble y, GLdouble z);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM3DVATIPROC) (GLenum stream, const GLdouble *coords);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM4SATIPROC) (GLenum stream, GLshort x, GLshort y, GLshort z, GLshort w);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM4SVATIPROC) (GLenum stream, const GLshort *coords);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM4IATIPROC) (GLenum stream, GLint x, GLint y, GLint z, GLint w);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM4IVATIPROC) (GLenum stream, const GLint *coords);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM4FATIPROC) (GLenum stream, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM4FVATIPROC) (GLenum stream, const GLfloat *coords);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM4DATIPROC) (GLenum stream, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM4DVATIPROC) (GLenum stream, const GLdouble *coords);
+typedef void (APIENTRYP PFNGLNORMALSTREAM3BATIPROC) (GLenum stream, GLbyte nx, GLbyte ny, GLbyte nz);
+typedef void (APIENTRYP PFNGLNORMALSTREAM3BVATIPROC) (GLenum stream, const GLbyte *coords);
+typedef void (APIENTRYP PFNGLNORMALSTREAM3SATIPROC) (GLenum stream, GLshort nx, GLshort ny, GLshort nz);
+typedef void (APIENTRYP PFNGLNORMALSTREAM3SVATIPROC) (GLenum stream, const GLshort *coords);
+typedef void (APIENTRYP PFNGLNORMALSTREAM3IATIPROC) (GLenum stream, GLint nx, GLint ny, GLint nz);
+typedef void (APIENTRYP PFNGLNORMALSTREAM3IVATIPROC) (GLenum stream, const GLint *coords);
+typedef void (APIENTRYP PFNGLNORMALSTREAM3FATIPROC) (GLenum stream, GLfloat nx, GLfloat ny, GLfloat nz);
+typedef void (APIENTRYP PFNGLNORMALSTREAM3FVATIPROC) (GLenum stream, const GLfloat *coords);
+typedef void (APIENTRYP PFNGLNORMALSTREAM3DATIPROC) (GLenum stream, GLdouble nx, GLdouble ny, GLdouble nz);
+typedef void (APIENTRYP PFNGLNORMALSTREAM3DVATIPROC) (GLenum stream, const GLdouble *coords);
+typedef void (APIENTRYP PFNGLCLIENTACTIVEVERTEXSTREAMATIPROC) (GLenum stream);
+typedef void (APIENTRYP PFNGLVERTEXBLENDENVIATIPROC) (GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLVERTEXBLENDENVFATIPROC) (GLenum pname, GLfloat param);
+#endif
+
+#ifndef GL_ATI_element_array
+#define GL_ATI_element_array 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glElementPointerATI (GLenum type, const GLvoid *pointer);
+GLAPI void APIENTRY glDrawElementArrayATI (GLenum mode, GLsizei count);
+GLAPI void APIENTRY glDrawRangeElementArrayATI (GLenum mode, GLuint start, GLuint end, GLsizei count);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLELEMENTPOINTERATIPROC) (GLenum type, const GLvoid *pointer);
+typedef void (APIENTRYP PFNGLDRAWELEMENTARRAYATIPROC) (GLenum mode, GLsizei count);
+typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTARRAYATIPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count);
+#endif
+
+#ifndef GL_SUN_mesh_array
+#define GL_SUN_mesh_array 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glDrawMeshArraysSUN (GLenum mode, GLint first, GLsizei count, GLsizei width);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLDRAWMESHARRAYSSUNPROC) (GLenum mode, GLint first, GLsizei count, GLsizei width);
+#endif
+
+#ifndef GL_SUN_slice_accum
+#define GL_SUN_slice_accum 1
+#endif
+
+#ifndef GL_NV_multisample_filter_hint
+#define GL_NV_multisample_filter_hint 1
+#endif
+
+#ifndef GL_NV_depth_clamp
+#define GL_NV_depth_clamp 1
+#endif
+
+#ifndef GL_NV_occlusion_query
+#define GL_NV_occlusion_query 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glGenOcclusionQueriesNV (GLsizei n, GLuint *ids);
+GLAPI void APIENTRY glDeleteOcclusionQueriesNV (GLsizei n, const GLuint *ids);
+GLAPI GLboolean APIENTRY glIsOcclusionQueryNV (GLuint id);
+GLAPI void APIENTRY glBeginOcclusionQueryNV (GLuint id);
+GLAPI void APIENTRY glEndOcclusionQueryNV (void);
+GLAPI void APIENTRY glGetOcclusionQueryivNV (GLuint id, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetOcclusionQueryuivNV (GLuint id, GLenum pname, GLuint *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLGENOCCLUSIONQUERIESNVPROC) (GLsizei n, GLuint *ids);
+typedef void (APIENTRYP PFNGLDELETEOCCLUSIONQUERIESNVPROC) (GLsizei n, const GLuint *ids);
+typedef GLboolean (APIENTRYP PFNGLISOCCLUSIONQUERYNVPROC) (GLuint id);
+typedef void (APIENTRYP PFNGLBEGINOCCLUSIONQUERYNVPROC) (GLuint id);
+typedef void (APIENTRYP PFNGLENDOCCLUSIONQUERYNVPROC) (void);
+typedef void (APIENTRYP PFNGLGETOCCLUSIONQUERYIVNVPROC) (GLuint id, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETOCCLUSIONQUERYUIVNVPROC) (GLuint id, GLenum pname, GLuint *params);
+#endif
+
+#ifndef GL_NV_point_sprite
+#define GL_NV_point_sprite 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glPointParameteriNV (GLenum pname, GLint param);
+GLAPI void APIENTRY glPointParameterivNV (GLenum pname, const GLint *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPOINTPARAMETERINVPROC) (GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLPOINTPARAMETERIVNVPROC) (GLenum pname, const GLint *params);
+#endif
+
+#ifndef GL_NV_texture_shader3
+#define GL_NV_texture_shader3 1
+#endif
+
+#ifndef GL_NV_vertex_program1_1
+#define GL_NV_vertex_program1_1 1
+#endif
+
+#ifndef GL_EXT_shadow_funcs
+#define GL_EXT_shadow_funcs 1
+#endif
+
+#ifndef GL_EXT_stencil_two_side
+#define GL_EXT_stencil_two_side 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glActiveStencilFaceEXT (GLenum face);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLACTIVESTENCILFACEEXTPROC) (GLenum face);
+#endif
+
+#ifndef GL_ATI_text_fragment_shader
+#define GL_ATI_text_fragment_shader 1
+#endif
+
+#ifndef GL_APPLE_client_storage
+#define GL_APPLE_client_storage 1
+#endif
+
+#ifndef GL_APPLE_element_array
+#define GL_APPLE_element_array 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glElementPointerAPPLE (GLenum type, const GLvoid *pointer);
+GLAPI void APIENTRY glDrawElementArrayAPPLE (GLenum mode, GLint first, GLsizei count);
+GLAPI void APIENTRY glDrawRangeElementArrayAPPLE (GLenum mode, GLuint start, GLuint end, GLint first, GLsizei count);
+GLAPI void APIENTRY glMultiDrawElementArrayAPPLE (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount);
+GLAPI void APIENTRY glMultiDrawRangeElementArrayAPPLE (GLenum mode, GLuint start, GLuint end, const GLint *first, const GLsizei *count, GLsizei primcount);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLELEMENTPOINTERAPPLEPROC) (GLenum type, const GLvoid *pointer);
+typedef void (APIENTRYP PFNGLDRAWELEMENTARRAYAPPLEPROC) (GLenum mode, GLint first, GLsizei count);
+typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTARRAYAPPLEPROC) (GLenum mode, GLuint start, GLuint end, GLint first, GLsizei count);
+typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTARRAYAPPLEPROC) (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount);
+typedef void (APIENTRYP PFNGLMULTIDRAWRANGEELEMENTARRAYAPPLEPROC) (GLenum mode, GLuint start, GLuint end, const GLint *first, const GLsizei *count, GLsizei primcount);
+#endif
+
+#ifndef GL_APPLE_fence
+#define GL_APPLE_fence 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glGenFencesAPPLE (GLsizei n, GLuint *fences);
+GLAPI void APIENTRY glDeleteFencesAPPLE (GLsizei n, const GLuint *fences);
+GLAPI void APIENTRY glSetFenceAPPLE (GLuint fence);
+GLAPI GLboolean APIENTRY glIsFenceAPPLE (GLuint fence);
+GLAPI GLboolean APIENTRY glTestFenceAPPLE (GLuint fence);
+GLAPI void APIENTRY glFinishFenceAPPLE (GLuint fence);
+GLAPI GLboolean APIENTRY glTestObjectAPPLE (GLenum object, GLuint name);
+GLAPI void APIENTRY glFinishObjectAPPLE (GLenum object, GLint name);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLGENFENCESAPPLEPROC) (GLsizei n, GLuint *fences);
+typedef void (APIENTRYP PFNGLDELETEFENCESAPPLEPROC) (GLsizei n, const GLuint *fences);
+typedef void (APIENTRYP PFNGLSETFENCEAPPLEPROC) (GLuint fence);
+typedef GLboolean (APIENTRYP PFNGLISFENCEAPPLEPROC) (GLuint fence);
+typedef GLboolean (APIENTRYP PFNGLTESTFENCEAPPLEPROC) (GLuint fence);
+typedef void (APIENTRYP PFNGLFINISHFENCEAPPLEPROC) (GLuint fence);
+typedef GLboolean (APIENTRYP PFNGLTESTOBJECTAPPLEPROC) (GLenum object, GLuint name);
+typedef void (APIENTRYP PFNGLFINISHOBJECTAPPLEPROC) (GLenum object, GLint name);
+#endif
+
+#ifndef GL_APPLE_vertex_array_object
+#define GL_APPLE_vertex_array_object 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBindVertexArrayAPPLE (GLuint array);
+GLAPI void APIENTRY glDeleteVertexArraysAPPLE (GLsizei n, const GLuint *arrays);
+GLAPI void APIENTRY glGenVertexArraysAPPLE (GLsizei n, GLuint *arrays);
+GLAPI GLboolean APIENTRY glIsVertexArrayAPPLE (GLuint array);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBINDVERTEXARRAYAPPLEPROC) (GLuint array);
+typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSAPPLEPROC) (GLsizei n, const GLuint *arrays);
+typedef void (APIENTRYP PFNGLGENVERTEXARRAYSAPPLEPROC) (GLsizei n, GLuint *arrays);
+typedef GLboolean (APIENTRYP PFNGLISVERTEXARRAYAPPLEPROC) (GLuint array);
+#endif
+
+#ifndef GL_APPLE_vertex_array_range
+#define GL_APPLE_vertex_array_range 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glVertexArrayRangeAPPLE (GLsizei length, GLvoid *pointer);
+GLAPI void APIENTRY glFlushVertexArrayRangeAPPLE (GLsizei length, GLvoid *pointer);
+GLAPI void APIENTRY glVertexArrayParameteriAPPLE (GLenum pname, GLint param);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLVERTEXARRAYRANGEAPPLEPROC) (GLsizei length, GLvoid *pointer);
+typedef void (APIENTRYP PFNGLFLUSHVERTEXARRAYRANGEAPPLEPROC) (GLsizei length, GLvoid *pointer);
+typedef void (APIENTRYP PFNGLVERTEXARRAYPARAMETERIAPPLEPROC) (GLenum pname, GLint param);
+#endif
+
+#ifndef GL_APPLE_ycbcr_422
+#define GL_APPLE_ycbcr_422 1
+#endif
+
+#ifndef GL_S3_s3tc
+#define GL_S3_s3tc 1
+#endif
+
+#ifndef GL_ATI_draw_buffers
+#define GL_ATI_draw_buffers 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glDrawBuffersATI (GLsizei n, const GLenum *bufs);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLDRAWBUFFERSATIPROC) (GLsizei n, const GLenum *bufs);
+#endif
+
+#ifndef GL_ATI_pixel_format_float
+#define GL_ATI_pixel_format_float 1
+/* This is really a WGL extension, but defines some associated GL enums.
+ * ATI does not export "GL_ATI_pixel_format_float" in the GL_EXTENSIONS string.
+ */
+#endif
+
+#ifndef GL_ATI_texture_env_combine3
+#define GL_ATI_texture_env_combine3 1
+#endif
+
+#ifndef GL_ATI_texture_float
+#define GL_ATI_texture_float 1
+#endif
+
+#ifndef GL_NV_float_buffer
+#define GL_NV_float_buffer 1
+#endif
+
+#ifndef GL_NV_fragment_program
+#define GL_NV_fragment_program 1
+/* Some NV_fragment_program entry points are shared with ARB_vertex_program. */
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glProgramNamedParameter4fNV (GLuint id, GLsizei len, const GLubyte *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+GLAPI void APIENTRY glProgramNamedParameter4dNV (GLuint id, GLsizei len, const GLubyte *name, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+GLAPI void APIENTRY glProgramNamedParameter4fvNV (GLuint id, GLsizei len, const GLubyte *name, const GLfloat *v);
+GLAPI void APIENTRY glProgramNamedParameter4dvNV (GLuint id, GLsizei len, const GLubyte *name, const GLdouble *v);
+GLAPI void APIENTRY glGetProgramNamedParameterfvNV (GLuint id, GLsizei len, const GLubyte *name, GLfloat *params);
+GLAPI void APIENTRY glGetProgramNamedParameterdvNV (GLuint id, GLsizei len, const GLubyte *name, GLdouble *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4FNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4DNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4FVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, const GLfloat *v);
+typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4DVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, const GLdouble *v);
+typedef void (APIENTRYP PFNGLGETPROGRAMNAMEDPARAMETERFVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETPROGRAMNAMEDPARAMETERDVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLdouble *params);
+#endif
+
+#ifndef GL_NV_half_float
+#define GL_NV_half_float 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glVertex2hNV (GLhalfNV x, GLhalfNV y);
+GLAPI void APIENTRY glVertex2hvNV (const GLhalfNV *v);
+GLAPI void APIENTRY glVertex3hNV (GLhalfNV x, GLhalfNV y, GLhalfNV z);
+GLAPI void APIENTRY glVertex3hvNV (const GLhalfNV *v);
+GLAPI void APIENTRY glVertex4hNV (GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w);
+GLAPI void APIENTRY glVertex4hvNV (const GLhalfNV *v);
+GLAPI void APIENTRY glNormal3hNV (GLhalfNV nx, GLhalfNV ny, GLhalfNV nz);
+GLAPI void APIENTRY glNormal3hvNV (const GLhalfNV *v);
+GLAPI void APIENTRY glColor3hNV (GLhalfNV red, GLhalfNV green, GLhalfNV blue);
+GLAPI void APIENTRY glColor3hvNV (const GLhalfNV *v);
+GLAPI void APIENTRY glColor4hNV (GLhalfNV red, GLhalfNV green, GLhalfNV blue, GLhalfNV alpha);
+GLAPI void APIENTRY glColor4hvNV (const GLhalfNV *v);
+GLAPI void APIENTRY glTexCoord1hNV (GLhalfNV s);
+GLAPI void APIENTRY glTexCoord1hvNV (const GLhalfNV *v);
+GLAPI void APIENTRY glTexCoord2hNV (GLhalfNV s, GLhalfNV t);
+GLAPI void APIENTRY glTexCoord2hvNV (const GLhalfNV *v);
+GLAPI void APIENTRY glTexCoord3hNV (GLhalfNV s, GLhalfNV t, GLhalfNV r);
+GLAPI void APIENTRY glTexCoord3hvNV (const GLhalfNV *v);
+GLAPI void APIENTRY glTexCoord4hNV (GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q);
+GLAPI void APIENTRY glTexCoord4hvNV (const GLhalfNV *v);
+GLAPI void APIENTRY glMultiTexCoord1hNV (GLenum target, GLhalfNV s);
+GLAPI void APIENTRY glMultiTexCoord1hvNV (GLenum target, const GLhalfNV *v);
+GLAPI void APIENTRY glMultiTexCoord2hNV (GLenum target, GLhalfNV s, GLhalfNV t);
+GLAPI void APIENTRY glMultiTexCoord2hvNV (GLenum target, const GLhalfNV *v);
+GLAPI void APIENTRY glMultiTexCoord3hNV (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r);
+GLAPI void APIENTRY glMultiTexCoord3hvNV (GLenum target, const GLhalfNV *v);
+GLAPI void APIENTRY glMultiTexCoord4hNV (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q);
+GLAPI void APIENTRY glMultiTexCoord4hvNV (GLenum target, const GLhalfNV *v);
+GLAPI void APIENTRY glFogCoordhNV (GLhalfNV fog);
+GLAPI void APIENTRY glFogCoordhvNV (const GLhalfNV *fog);
+GLAPI void APIENTRY glSecondaryColor3hNV (GLhalfNV red, GLhalfNV green, GLhalfNV blue);
+GLAPI void APIENTRY glSecondaryColor3hvNV (const GLhalfNV *v);
+GLAPI void APIENTRY glVertexWeighthNV (GLhalfNV weight);
+GLAPI void APIENTRY glVertexWeighthvNV (const GLhalfNV *weight);
+GLAPI void APIENTRY glVertexAttrib1hNV (GLuint index, GLhalfNV x);
+GLAPI void APIENTRY glVertexAttrib1hvNV (GLuint index, const GLhalfNV *v);
+GLAPI void APIENTRY glVertexAttrib2hNV (GLuint index, GLhalfNV x, GLhalfNV y);
+GLAPI void APIENTRY glVertexAttrib2hvNV (GLuint index, const GLhalfNV *v);
+GLAPI void APIENTRY glVertexAttrib3hNV (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z);
+GLAPI void APIENTRY glVertexAttrib3hvNV (GLuint index, const GLhalfNV *v);
+GLAPI void APIENTRY glVertexAttrib4hNV (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w);
+GLAPI void APIENTRY glVertexAttrib4hvNV (GLuint index, const GLhalfNV *v);
+GLAPI void APIENTRY glVertexAttribs1hvNV (GLuint index, GLsizei n, const GLhalfNV *v);
+GLAPI void APIENTRY glVertexAttribs2hvNV (GLuint index, GLsizei n, const GLhalfNV *v);
+GLAPI void APIENTRY glVertexAttribs3hvNV (GLuint index, GLsizei n, const GLhalfNV *v);
+GLAPI void APIENTRY glVertexAttribs4hvNV (GLuint index, GLsizei n, const GLhalfNV *v);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLVERTEX2HNVPROC) (GLhalfNV x, GLhalfNV y);
+typedef void (APIENTRYP PFNGLVERTEX2HVNVPROC) (const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLVERTEX3HNVPROC) (GLhalfNV x, GLhalfNV y, GLhalfNV z);
+typedef void (APIENTRYP PFNGLVERTEX3HVNVPROC) (const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLVERTEX4HNVPROC) (GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w);
+typedef void (APIENTRYP PFNGLVERTEX4HVNVPROC) (const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLNORMAL3HNVPROC) (GLhalfNV nx, GLhalfNV ny, GLhalfNV nz);
+typedef void (APIENTRYP PFNGLNORMAL3HVNVPROC) (const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLCOLOR3HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue);
+typedef void (APIENTRYP PFNGLCOLOR3HVNVPROC) (const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLCOLOR4HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue, GLhalfNV alpha);
+typedef void (APIENTRYP PFNGLCOLOR4HVNVPROC) (const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLTEXCOORD1HNVPROC) (GLhalfNV s);
+typedef void (APIENTRYP PFNGLTEXCOORD1HVNVPROC) (const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLTEXCOORD2HNVPROC) (GLhalfNV s, GLhalfNV t);
+typedef void (APIENTRYP PFNGLTEXCOORD2HVNVPROC) (const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLTEXCOORD3HNVPROC) (GLhalfNV s, GLhalfNV t, GLhalfNV r);
+typedef void (APIENTRYP PFNGLTEXCOORD3HVNVPROC) (const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLTEXCOORD4HNVPROC) (GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q);
+typedef void (APIENTRYP PFNGLTEXCOORD4HVNVPROC) (const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1HNVPROC) (GLenum target, GLhalfNV s);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1HVNVPROC) (GLenum target, const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2HVNVPROC) (GLenum target, const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3HVNVPROC) (GLenum target, const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4HVNVPROC) (GLenum target, const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLFOGCOORDHNVPROC) (GLhalfNV fog);
+typedef void (APIENTRYP PFNGLFOGCOORDHVNVPROC) (const GLhalfNV *fog);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3HVNVPROC) (const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLVERTEXWEIGHTHNVPROC) (GLhalfNV weight);
+typedef void (APIENTRYP PFNGLVERTEXWEIGHTHVNVPROC) (const GLhalfNV *weight);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1HNVPROC) (GLuint index, GLhalfNV x);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1HVNVPROC) (GLuint index, const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2HVNVPROC) (GLuint index, const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3HVNVPROC) (GLuint index, const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4HVNVPROC) (GLuint index, const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS1HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS2HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS3HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS4HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v);
+#endif
+
+#ifndef GL_NV_pixel_data_range
+#define GL_NV_pixel_data_range 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glPixelDataRangeNV (GLenum target, GLsizei length, GLvoid *pointer);
+GLAPI void APIENTRY glFlushPixelDataRangeNV (GLenum target);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPIXELDATARANGENVPROC) (GLenum target, GLsizei length, GLvoid *pointer);
+typedef void (APIENTRYP PFNGLFLUSHPIXELDATARANGENVPROC) (GLenum target);
+#endif
+
+#ifndef GL_NV_primitive_restart
+#define GL_NV_primitive_restart 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glPrimitiveRestartNV (void);
+GLAPI void APIENTRY glPrimitiveRestartIndexNV (GLuint index);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPRIMITIVERESTARTNVPROC) (void);
+typedef void (APIENTRYP PFNGLPRIMITIVERESTARTINDEXNVPROC) (GLuint index);
+#endif
+
+#ifndef GL_NV_texture_expand_normal
+#define GL_NV_texture_expand_normal 1
+#endif
+
+#ifndef GL_NV_vertex_program2
+#define GL_NV_vertex_program2 1
+#endif
+
+#ifndef GL_ATI_map_object_buffer
+#define GL_ATI_map_object_buffer 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI GLvoid* APIENTRY glMapObjectBufferATI (GLuint buffer);
+GLAPI void APIENTRY glUnmapObjectBufferATI (GLuint buffer);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef GLvoid* (APIENTRYP PFNGLMAPOBJECTBUFFERATIPROC) (GLuint buffer);
+typedef void (APIENTRYP PFNGLUNMAPOBJECTBUFFERATIPROC) (GLuint buffer);
+#endif
+
+#ifndef GL_ATI_separate_stencil
+#define GL_ATI_separate_stencil 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glStencilOpSeparateATI (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass);
+GLAPI void APIENTRY glStencilFuncSeparateATI (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLSTENCILOPSEPARATEATIPROC) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass);
+typedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEATIPROC) (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask);
+#endif
+
+#ifndef GL_ATI_vertex_attrib_array_object
+#define GL_ATI_vertex_attrib_array_object 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glVertexAttribArrayObjectATI (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLuint buffer, GLuint offset);
+GLAPI void APIENTRY glGetVertexAttribArrayObjectfvATI (GLuint index, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetVertexAttribArrayObjectivATI (GLuint index, GLenum pname, GLint *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLVERTEXATTRIBARRAYOBJECTATIPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLuint buffer, GLuint offset);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBARRAYOBJECTFVATIPROC) (GLuint index, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBARRAYOBJECTIVATIPROC) (GLuint index, GLenum pname, GLint *params);
+#endif
+
+#ifndef GL_OES_read_format
+#define GL_OES_read_format 1
+#endif
+
+#ifndef GL_EXT_depth_bounds_test
+#define GL_EXT_depth_bounds_test 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glDepthBoundsEXT (GLclampd zmin, GLclampd zmax);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLDEPTHBOUNDSEXTPROC) (GLclampd zmin, GLclampd zmax);
+#endif
+
+#ifndef GL_EXT_texture_mirror_clamp
+#define GL_EXT_texture_mirror_clamp 1
+#endif
+
+#ifndef GL_EXT_blend_equation_separate
+#define GL_EXT_blend_equation_separate 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBlendEquationSeparateEXT (GLenum modeRGB, GLenum modeAlpha);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEEXTPROC) (GLenum modeRGB, GLenum modeAlpha);
+#endif
+
+#ifndef GL_MESA_pack_invert
+#define GL_MESA_pack_invert 1
+#endif
+
+#ifndef GL_MESA_ycbcr_texture
+#define GL_MESA_ycbcr_texture 1
+#endif
+
+#ifndef GL_EXT_pixel_buffer_object
+#define GL_EXT_pixel_buffer_object 1
+#endif
+
+#ifndef GL_NV_fragment_program_option
+#define GL_NV_fragment_program_option 1
+#endif
+
+#ifndef GL_NV_fragment_program2
+#define GL_NV_fragment_program2 1
+#endif
+
+#ifndef GL_NV_vertex_program2_option
+#define GL_NV_vertex_program2_option 1
+#endif
+
+#ifndef GL_NV_vertex_program3
+#define GL_NV_vertex_program3 1
+#endif
+
+#ifndef GL_EXT_framebuffer_object
+#define GL_EXT_framebuffer_object 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI GLboolean APIENTRY glIsRenderbufferEXT (GLuint renderbuffer);
+GLAPI void APIENTRY glBindRenderbufferEXT (GLenum target, GLuint renderbuffer);
+GLAPI void APIENTRY glDeleteRenderbuffersEXT (GLsizei n, const GLuint *renderbuffers);
+GLAPI void APIENTRY glGenRenderbuffersEXT (GLsizei n, GLuint *renderbuffers);
+GLAPI void APIENTRY glRenderbufferStorageEXT (GLenum target, GLenum internalformat, GLsizei width, GLsizei height);
+GLAPI void APIENTRY glGetRenderbufferParameterivEXT (GLenum target, GLenum pname, GLint *params);
+GLAPI GLboolean APIENTRY glIsFramebufferEXT (GLuint framebuffer);
+GLAPI void APIENTRY glBindFramebufferEXT (GLenum target, GLuint framebuffer);
+GLAPI void APIENTRY glDeleteFramebuffersEXT (GLsizei n, const GLuint *framebuffers);
+GLAPI void APIENTRY glGenFramebuffersEXT (GLsizei n, GLuint *framebuffers);
+GLAPI GLenum APIENTRY glCheckFramebufferStatusEXT (GLenum target);
+GLAPI void APIENTRY glFramebufferTexture1DEXT (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
+GLAPI void APIENTRY glFramebufferTexture2DEXT (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
+GLAPI void APIENTRY glFramebufferTexture3DEXT (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset);
+GLAPI void APIENTRY glFramebufferRenderbufferEXT (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
+GLAPI void APIENTRY glGetFramebufferAttachmentParameterivEXT (GLenum target, GLenum attachment, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGenerateMipmapEXT (GLenum target);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef GLboolean (APIENTRYP PFNGLISRENDERBUFFEREXTPROC) (GLuint renderbuffer);
+typedef void (APIENTRYP PFNGLBINDRENDERBUFFEREXTPROC) (GLenum target, GLuint renderbuffer);
+typedef void (APIENTRYP PFNGLDELETERENDERBUFFERSEXTPROC) (GLsizei n, const GLuint *renderbuffers);
+typedef void (APIENTRYP PFNGLGENRENDERBUFFERSEXTPROC) (GLsizei n, GLuint *renderbuffers);
+typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height);
+typedef void (APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);
+typedef GLboolean (APIENTRYP PFNGLISFRAMEBUFFEREXTPROC) (GLuint framebuffer);
+typedef void (APIENTRYP PFNGLBINDFRAMEBUFFEREXTPROC) (GLenum target, GLuint framebuffer);
+typedef void (APIENTRYP PFNGLDELETEFRAMEBUFFERSEXTPROC) (GLsizei n, const GLuint *framebuffers);
+typedef void (APIENTRYP PFNGLGENFRAMEBUFFERSEXTPROC) (GLsizei n, GLuint *framebuffers);
+typedef GLenum (APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC) (GLenum target);
+typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE1DEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
+typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
+typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset);
+typedef void (APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC) (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
+typedef void (APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC) (GLenum target, GLenum attachment, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGENERATEMIPMAPEXTPROC) (GLenum target);
+#endif
+
+#ifndef GL_GREMEDY_string_marker
+#define GL_GREMEDY_string_marker 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glStringMarkerGREMEDY (GLsizei len, const GLvoid *string);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLSTRINGMARKERGREMEDYPROC) (GLsizei len, const GLvoid *string);
+#endif
+
+#ifndef GL_EXT_packed_depth_stencil
+#define GL_EXT_packed_depth_stencil 1
+#endif
+
+#ifndef GL_EXT_stencil_clear_tag
+#define GL_EXT_stencil_clear_tag 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glStencilClearTagEXT (GLsizei stencilTagBits, GLuint stencilClearTag);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLSTENCILCLEARTAGEXTPROC) (GLsizei stencilTagBits, GLuint stencilClearTag);
+#endif
+
+#ifndef GL_EXT_texture_sRGB
+#define GL_EXT_texture_sRGB 1
+#endif
+
+#ifndef GL_EXT_framebuffer_blit
+#define GL_EXT_framebuffer_blit 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBlitFramebufferEXT (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBLITFRAMEBUFFEREXTPROC) (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
+#endif
+
+#ifndef GL_EXT_framebuffer_multisample
+#define GL_EXT_framebuffer_multisample 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glRenderbufferStorageMultisampleEXT (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
+#endif
+
+#ifndef GL_MESAX_texture_stack
+#define GL_MESAX_texture_stack 1
+#endif
+
+#ifndef GL_EXT_timer_query
+#define GL_EXT_timer_query 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glGetQueryObjecti64vEXT (GLuint id, GLenum pname, GLint64EXT *params);
+GLAPI void APIENTRY glGetQueryObjectui64vEXT (GLuint id, GLenum pname, GLuint64EXT *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLGETQUERYOBJECTI64VEXTPROC) (GLuint id, GLenum pname, GLint64EXT *params);
+typedef void (APIENTRYP PFNGLGETQUERYOBJECTUI64VEXTPROC) (GLuint id, GLenum pname, GLuint64EXT *params);
+#endif
+
+#ifndef GL_EXT_gpu_program_parameters
+#define GL_EXT_gpu_program_parameters 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glProgramEnvParameters4fvEXT (GLenum target, GLuint index, GLsizei count, const GLfloat *params);
+GLAPI void APIENTRY glProgramLocalParameters4fvEXT (GLenum target, GLuint index, GLsizei count, const GLfloat *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERS4FVEXTPROC) (GLenum target, GLuint index, GLsizei count, const GLfloat *params);
+typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERS4FVEXTPROC) (GLenum target, GLuint index, GLsizei count, const GLfloat *params);
+#endif
+
+#ifndef GL_APPLE_flush_buffer_range
+#define GL_APPLE_flush_buffer_range 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBufferParameteriAPPLE (GLenum target, GLenum pname, GLint param);
+GLAPI void APIENTRY glFlushMappedBufferRangeAPPLE (GLenum target, GLintptr offset, GLsizeiptr size);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBUFFERPARAMETERIAPPLEPROC) (GLenum target, GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLFLUSHMAPPEDBUFFERRANGEAPPLEPROC) (GLenum target, GLintptr offset, GLsizeiptr size);
+#endif
+
+#ifndef GL_NV_gpu_program4
+#define GL_NV_gpu_program4 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glProgramLocalParameterI4iNV (GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w);
+GLAPI void APIENTRY glProgramLocalParameterI4ivNV (GLenum target, GLuint index, const GLint *params);
+GLAPI void APIENTRY glProgramLocalParametersI4ivNV (GLenum target, GLuint index, GLsizei count, const GLint *params);
+GLAPI void APIENTRY glProgramLocalParameterI4uiNV (GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w);
+GLAPI void APIENTRY glProgramLocalParameterI4uivNV (GLenum target, GLuint index, const GLuint *params);
+GLAPI void APIENTRY glProgramLocalParametersI4uivNV (GLenum target, GLuint index, GLsizei count, const GLuint *params);
+GLAPI void APIENTRY glProgramEnvParameterI4iNV (GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w);
+GLAPI void APIENTRY glProgramEnvParameterI4ivNV (GLenum target, GLuint index, const GLint *params);
+GLAPI void APIENTRY glProgramEnvParametersI4ivNV (GLenum target, GLuint index, GLsizei count, const GLint *params);
+GLAPI void APIENTRY glProgramEnvParameterI4uiNV (GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w);
+GLAPI void APIENTRY glProgramEnvParameterI4uivNV (GLenum target, GLuint index, const GLuint *params);
+GLAPI void APIENTRY glProgramEnvParametersI4uivNV (GLenum target, GLuint index, GLsizei count, const GLuint *params);
+GLAPI void APIENTRY glGetProgramLocalParameterIivNV (GLenum target, GLuint index, GLint *params);
+GLAPI void APIENTRY glGetProgramLocalParameterIuivNV (GLenum target, GLuint index, GLuint *params);
+GLAPI void APIENTRY glGetProgramEnvParameterIivNV (GLenum target, GLuint index, GLint *params);
+GLAPI void APIENTRY glGetProgramEnvParameterIuivNV (GLenum target, GLuint index, GLuint *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERI4INVPROC) (GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w);
+typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERI4IVNVPROC) (GLenum target, GLuint index, const GLint *params);
+typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERSI4IVNVPROC) (GLenum target, GLuint index, GLsizei count, const GLint *params);
+typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERI4UINVPROC) (GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w);
+typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERI4UIVNVPROC) (GLenum target, GLuint index, const GLuint *params);
+typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERSI4UIVNVPROC) (GLenum target, GLuint index, GLsizei count, const GLuint *params);
+typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERI4INVPROC) (GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w);
+typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERI4IVNVPROC) (GLenum target, GLuint index, const GLint *params);
+typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERSI4IVNVPROC) (GLenum target, GLuint index, GLsizei count, const GLint *params);
+typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERI4UINVPROC) (GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w);
+typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERI4UIVNVPROC) (GLenum target, GLuint index, const GLuint *params);
+typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERSI4UIVNVPROC) (GLenum target, GLuint index, GLsizei count, const GLuint *params);
+typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERIIVNVPROC) (GLenum target, GLuint index, GLint *params);
+typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERIUIVNVPROC) (GLenum target, GLuint index, GLuint *params);
+typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERIIVNVPROC) (GLenum target, GLuint index, GLint *params);
+typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERIUIVNVPROC) (GLenum target, GLuint index, GLuint *params);
+#endif
+
+#ifndef GL_NV_geometry_program4
+#define GL_NV_geometry_program4 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glProgramVertexLimitNV (GLenum target, GLint limit);
+GLAPI void APIENTRY glFramebufferTextureEXT (GLenum target, GLenum attachment, GLuint texture, GLint level);
+GLAPI void APIENTRY glFramebufferTextureLayerEXT (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer);
+GLAPI void APIENTRY glFramebufferTextureFaceEXT (GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPROGRAMVERTEXLIMITNVPROC) (GLenum target, GLint limit);
+typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREEXTPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level);
+typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYEREXTPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer);
+typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREFACEEXTPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face);
+#endif
+
+#ifndef GL_EXT_geometry_shader4
+#define GL_EXT_geometry_shader4 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glProgramParameteriEXT (GLuint program, GLenum pname, GLint value);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPROGRAMPARAMETERIEXTPROC) (GLuint program, GLenum pname, GLint value);
+#endif
+
+#ifndef GL_NV_vertex_program4
+#define GL_NV_vertex_program4 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glVertexAttribI1iEXT (GLuint index, GLint x);
+GLAPI void APIENTRY glVertexAttribI2iEXT (GLuint index, GLint x, GLint y);
+GLAPI void APIENTRY glVertexAttribI3iEXT (GLuint index, GLint x, GLint y, GLint z);
+GLAPI void APIENTRY glVertexAttribI4iEXT (GLuint index, GLint x, GLint y, GLint z, GLint w);
+GLAPI void APIENTRY glVertexAttribI1uiEXT (GLuint index, GLuint x);
+GLAPI void APIENTRY glVertexAttribI2uiEXT (GLuint index, GLuint x, GLuint y);
+GLAPI void APIENTRY glVertexAttribI3uiEXT (GLuint index, GLuint x, GLuint y, GLuint z);
+GLAPI void APIENTRY glVertexAttribI4uiEXT (GLuint index, GLuint x, GLuint y, GLuint z, GLuint w);
+GLAPI void APIENTRY glVertexAttribI1ivEXT (GLuint index, const GLint *v);
+GLAPI void APIENTRY glVertexAttribI2ivEXT (GLuint index, const GLint *v);
+GLAPI void APIENTRY glVertexAttribI3ivEXT (GLuint index, const GLint *v);
+GLAPI void APIENTRY glVertexAttribI4ivEXT (GLuint index, const GLint *v);
+GLAPI void APIENTRY glVertexAttribI1uivEXT (GLuint index, const GLuint *v);
+GLAPI void APIENTRY glVertexAttribI2uivEXT (GLuint index, const GLuint *v);
+GLAPI void APIENTRY glVertexAttribI3uivEXT (GLuint index, const GLuint *v);
+GLAPI void APIENTRY glVertexAttribI4uivEXT (GLuint index, const GLuint *v);
+GLAPI void APIENTRY glVertexAttribI4bvEXT (GLuint index, const GLbyte *v);
+GLAPI void APIENTRY glVertexAttribI4svEXT (GLuint index, const GLshort *v);
+GLAPI void APIENTRY glVertexAttribI4ubvEXT (GLuint index, const GLubyte *v);
+GLAPI void APIENTRY glVertexAttribI4usvEXT (GLuint index, const GLushort *v);
+GLAPI void APIENTRY glVertexAttribIPointerEXT (GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+GLAPI void APIENTRY glGetVertexAttribIivEXT (GLuint index, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetVertexAttribIuivEXT (GLuint index, GLenum pname, GLuint *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI1IEXTPROC) (GLuint index, GLint x);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI2IEXTPROC) (GLuint index, GLint x, GLint y);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI3IEXTPROC) (GLuint index, GLint x, GLint y, GLint z);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI4IEXTPROC) (GLuint index, GLint x, GLint y, GLint z, GLint w);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIEXTPROC) (GLuint index, GLuint x);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIEXTPROC) (GLuint index, GLuint x, GLuint y);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIEXTPROC) (GLuint index, GLuint x, GLuint y, GLuint z);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIEXTPROC) (GLuint index, GLuint x, GLuint y, GLuint z, GLuint w);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI1IVEXTPROC) (GLuint index, const GLint *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI2IVEXTPROC) (GLuint index, const GLint *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI3IVEXTPROC) (GLuint index, const GLint *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI4IVEXTPROC) (GLuint index, const GLint *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIVEXTPROC) (GLuint index, const GLuint *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIVEXTPROC) (GLuint index, const GLuint *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIVEXTPROC) (GLuint index, const GLuint *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIVEXTPROC) (GLuint index, const GLuint *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI4BVEXTPROC) (GLuint index, const GLbyte *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI4SVEXTPROC) (GLuint index, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UBVEXTPROC) (GLuint index, const GLubyte *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBI4USVEXTPROC) (GLuint index, const GLushort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBIPOINTEREXTPROC) (GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIIVEXTPROC) (GLuint index, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIUIVEXTPROC) (GLuint index, GLenum pname, GLuint *params);
+#endif
+
+#ifndef GL_EXT_gpu_shader4
+#define GL_EXT_gpu_shader4 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glGetUniformuivEXT (GLuint program, GLint location, GLuint *params);
+GLAPI void APIENTRY glBindFragDataLocationEXT (GLuint program, GLuint color, const GLchar *name);
+GLAPI GLint APIENTRY glGetFragDataLocationEXT (GLuint program, const GLchar *name);
+GLAPI void APIENTRY glUniform1uiEXT (GLint location, GLuint v0);
+GLAPI void APIENTRY glUniform2uiEXT (GLint location, GLuint v0, GLuint v1);
+GLAPI void APIENTRY glUniform3uiEXT (GLint location, GLuint v0, GLuint v1, GLuint v2);
+GLAPI void APIENTRY glUniform4uiEXT (GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3);
+GLAPI void APIENTRY glUniform1uivEXT (GLint location, GLsizei count, const GLuint *value);
+GLAPI void APIENTRY glUniform2uivEXT (GLint location, GLsizei count, const GLuint *value);
+GLAPI void APIENTRY glUniform3uivEXT (GLint location, GLsizei count, const GLuint *value);
+GLAPI void APIENTRY glUniform4uivEXT (GLint location, GLsizei count, const GLuint *value);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLGETUNIFORMUIVEXTPROC) (GLuint program, GLint location, GLuint *params);
+typedef void (APIENTRYP PFNGLBINDFRAGDATALOCATIONEXTPROC) (GLuint program, GLuint color, const GLchar *name);
+typedef GLint (APIENTRYP PFNGLGETFRAGDATALOCATIONEXTPROC) (GLuint program, const GLchar *name);
+typedef void (APIENTRYP PFNGLUNIFORM1UIEXTPROC) (GLint location, GLuint v0);
+typedef void (APIENTRYP PFNGLUNIFORM2UIEXTPROC) (GLint location, GLuint v0, GLuint v1);
+typedef void (APIENTRYP PFNGLUNIFORM3UIEXTPROC) (GLint location, GLuint v0, GLuint v1, GLuint v2);
+typedef void (APIENTRYP PFNGLUNIFORM4UIEXTPROC) (GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3);
+typedef void (APIENTRYP PFNGLUNIFORM1UIVEXTPROC) (GLint location, GLsizei count, const GLuint *value);
+typedef void (APIENTRYP PFNGLUNIFORM2UIVEXTPROC) (GLint location, GLsizei count, const GLuint *value);
+typedef void (APIENTRYP PFNGLUNIFORM3UIVEXTPROC) (GLint location, GLsizei count, const GLuint *value);
+typedef void (APIENTRYP PFNGLUNIFORM4UIVEXTPROC) (GLint location, GLsizei count, const GLuint *value);
+#endif
+
+#ifndef GL_EXT_draw_instanced
+#define GL_EXT_draw_instanced 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glDrawArraysInstancedEXT (GLenum mode, GLint start, GLsizei count, GLsizei primcount);
+GLAPI void APIENTRY glDrawElementsInstancedEXT (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDEXTPROC) (GLenum mode, GLint start, GLsizei count, GLsizei primcount);
+typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDEXTPROC) (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount);
+#endif
+
+#ifndef GL_EXT_packed_float
+#define GL_EXT_packed_float 1
+#endif
+
+#ifndef GL_EXT_texture_array
+#define GL_EXT_texture_array 1
+#endif
+
+#ifndef GL_EXT_texture_buffer_object
+#define GL_EXT_texture_buffer_object 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glTexBufferEXT (GLenum target, GLenum internalformat, GLuint buffer);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLTEXBUFFEREXTPROC) (GLenum target, GLenum internalformat, GLuint buffer);
+#endif
+
+#ifndef GL_EXT_texture_compression_latc
+#define GL_EXT_texture_compression_latc 1
+#endif
+
+#ifndef GL_EXT_texture_compression_rgtc
+#define GL_EXT_texture_compression_rgtc 1
+#endif
+
+#ifndef GL_EXT_texture_shared_exponent
+#define GL_EXT_texture_shared_exponent 1
+#endif
+
+#ifndef GL_NV_depth_buffer_float
+#define GL_NV_depth_buffer_float 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glDepthRangedNV (GLdouble zNear, GLdouble zFar);
+GLAPI void APIENTRY glClearDepthdNV (GLdouble depth);
+GLAPI void APIENTRY glDepthBoundsdNV (GLdouble zmin, GLdouble zmax);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLDEPTHRANGEDNVPROC) (GLdouble zNear, GLdouble zFar);
+typedef void (APIENTRYP PFNGLCLEARDEPTHDNVPROC) (GLdouble depth);
+typedef void (APIENTRYP PFNGLDEPTHBOUNDSDNVPROC) (GLdouble zmin, GLdouble zmax);
+#endif
+
+#ifndef GL_NV_fragment_program4
+#define GL_NV_fragment_program4 1
+#endif
+
+#ifndef GL_NV_framebuffer_multisample_coverage
+#define GL_NV_framebuffer_multisample_coverage 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glRenderbufferStorageMultisampleCoverageNV (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLECOVERAGENVPROC) (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height);
+#endif
+
+#ifndef GL_EXT_framebuffer_sRGB
+#define GL_EXT_framebuffer_sRGB 1
+#endif
+
+#ifndef GL_NV_geometry_shader4
+#define GL_NV_geometry_shader4 1
+#endif
+
+#ifndef GL_NV_parameter_buffer_object
+#define GL_NV_parameter_buffer_object 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glProgramBufferParametersfvNV (GLenum target, GLuint buffer, GLuint index, GLsizei count, const GLfloat *params);
+GLAPI void APIENTRY glProgramBufferParametersIivNV (GLenum target, GLuint buffer, GLuint index, GLsizei count, const GLint *params);
+GLAPI void APIENTRY glProgramBufferParametersIuivNV (GLenum target, GLuint buffer, GLuint index, GLsizei count, const GLuint *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPROGRAMBUFFERPARAMETERSFVNVPROC) (GLenum target, GLuint buffer, GLuint index, GLsizei count, const GLfloat *params);
+typedef void (APIENTRYP PFNGLPROGRAMBUFFERPARAMETERSIIVNVPROC) (GLenum target, GLuint buffer, GLuint index, GLsizei count, const GLint *params);
+typedef void (APIENTRYP PFNGLPROGRAMBUFFERPARAMETERSIUIVNVPROC) (GLenum target, GLuint buffer, GLuint index, GLsizei count, const GLuint *params);
+#endif
+
+#ifndef GL_EXT_draw_buffers2
+#define GL_EXT_draw_buffers2 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glColorMaskIndexedEXT (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a);
+GLAPI void APIENTRY glGetBooleanIndexedvEXT (GLenum target, GLuint index, GLboolean *data);
+GLAPI void APIENTRY glGetIntegerIndexedvEXT (GLenum target, GLuint index, GLint *data);
+GLAPI void APIENTRY glEnableIndexedEXT (GLenum target, GLuint index);
+GLAPI void APIENTRY glDisableIndexedEXT (GLenum target, GLuint index);
+GLAPI GLboolean APIENTRY glIsEnabledIndexedEXT (GLenum target, GLuint index);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCOLORMASKINDEXEDEXTPROC) (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a);
+typedef void (APIENTRYP PFNGLGETBOOLEANINDEXEDVEXTPROC) (GLenum target, GLuint index, GLboolean *data);
+typedef void (APIENTRYP PFNGLGETINTEGERINDEXEDVEXTPROC) (GLenum target, GLuint index, GLint *data);
+typedef void (APIENTRYP PFNGLENABLEINDEXEDEXTPROC) (GLenum target, GLuint index);
+typedef void (APIENTRYP PFNGLDISABLEINDEXEDEXTPROC) (GLenum target, GLuint index);
+typedef GLboolean (APIENTRYP PFNGLISENABLEDINDEXEDEXTPROC) (GLenum target, GLuint index);
+#endif
+
+#ifndef GL_NV_transform_feedback
+#define GL_NV_transform_feedback 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBeginTransformFeedbackNV (GLenum primitiveMode);
+GLAPI void APIENTRY glEndTransformFeedbackNV (void);
+GLAPI void APIENTRY glTransformFeedbackAttribsNV (GLuint count, const GLint *attribs, GLenum bufferMode);
+GLAPI void APIENTRY glBindBufferRangeNV (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size);
+GLAPI void APIENTRY glBindBufferOffsetNV (GLenum target, GLuint index, GLuint buffer, GLintptr offset);
+GLAPI void APIENTRY glBindBufferBaseNV (GLenum target, GLuint index, GLuint buffer);
+GLAPI void APIENTRY glTransformFeedbackVaryingsNV (GLuint program, GLsizei count, const GLint *locations, GLenum bufferMode);
+GLAPI void APIENTRY glActiveVaryingNV (GLuint program, const GLchar *name);
+GLAPI GLint APIENTRY glGetVaryingLocationNV (GLuint program, const GLchar *name);
+GLAPI void APIENTRY glGetActiveVaryingNV (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name);
+GLAPI void APIENTRY glGetTransformFeedbackVaryingNV (GLuint program, GLuint index, GLint *location);
+GLAPI void APIENTRY glTransformFeedbackStreamAttribsNV (GLsizei count, const GLint *attribs, GLsizei nbuffers, const GLint *bufstreams, GLenum bufferMode);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBEGINTRANSFORMFEEDBACKNVPROC) (GLenum primitiveMode);
+typedef void (APIENTRYP PFNGLENDTRANSFORMFEEDBACKNVPROC) (void);
+typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKATTRIBSNVPROC) (GLuint count, const GLint *attribs, GLenum bufferMode);
+typedef void (APIENTRYP PFNGLBINDBUFFERRANGENVPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size);
+typedef void (APIENTRYP PFNGLBINDBUFFEROFFSETNVPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset);
+typedef void (APIENTRYP PFNGLBINDBUFFERBASENVPROC) (GLenum target, GLuint index, GLuint buffer);
+typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKVARYINGSNVPROC) (GLuint program, GLsizei count, const GLint *locations, GLenum bufferMode);
+typedef void (APIENTRYP PFNGLACTIVEVARYINGNVPROC) (GLuint program, const GLchar *name);
+typedef GLint (APIENTRYP PFNGLGETVARYINGLOCATIONNVPROC) (GLuint program, const GLchar *name);
+typedef void (APIENTRYP PFNGLGETACTIVEVARYINGNVPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name);
+typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKVARYINGNVPROC) (GLuint program, GLuint index, GLint *location);
+typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKSTREAMATTRIBSNVPROC) (GLsizei count, const GLint *attribs, GLsizei nbuffers, const GLint *bufstreams, GLenum bufferMode);
+#endif
+
+#ifndef GL_EXT_bindable_uniform
+#define GL_EXT_bindable_uniform 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glUniformBufferEXT (GLuint program, GLint location, GLuint buffer);
+GLAPI GLint APIENTRY glGetUniformBufferSizeEXT (GLuint program, GLint location);
+GLAPI GLintptr APIENTRY glGetUniformOffsetEXT (GLuint program, GLint location);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLUNIFORMBUFFEREXTPROC) (GLuint program, GLint location, GLuint buffer);
+typedef GLint (APIENTRYP PFNGLGETUNIFORMBUFFERSIZEEXTPROC) (GLuint program, GLint location);
+typedef GLintptr (APIENTRYP PFNGLGETUNIFORMOFFSETEXTPROC) (GLuint program, GLint location);
+#endif
+
+#ifndef GL_EXT_texture_integer
+#define GL_EXT_texture_integer 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glTexParameterIivEXT (GLenum target, GLenum pname, const GLint *params);
+GLAPI void APIENTRY glTexParameterIuivEXT (GLenum target, GLenum pname, const GLuint *params);
+GLAPI void APIENTRY glGetTexParameterIivEXT (GLenum target, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetTexParameterIuivEXT (GLenum target, GLenum pname, GLuint *params);
+GLAPI void APIENTRY glClearColorIiEXT (GLint red, GLint green, GLint blue, GLint alpha);
+GLAPI void APIENTRY glClearColorIuiEXT (GLuint red, GLuint green, GLuint blue, GLuint alpha);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLTEXPARAMETERIIVEXTPROC) (GLenum target, GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLTEXPARAMETERIUIVEXTPROC) (GLenum target, GLenum pname, const GLuint *params);
+typedef void (APIENTRYP PFNGLGETTEXPARAMETERIIVEXTPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETTEXPARAMETERIUIVEXTPROC) (GLenum target, GLenum pname, GLuint *params);
+typedef void (APIENTRYP PFNGLCLEARCOLORIIEXTPROC) (GLint red, GLint green, GLint blue, GLint alpha);
+typedef void (APIENTRYP PFNGLCLEARCOLORIUIEXTPROC) (GLuint red, GLuint green, GLuint blue, GLuint alpha);
+#endif
+
+#ifndef GL_GREMEDY_frame_terminator
+#define GL_GREMEDY_frame_terminator 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glFrameTerminatorGREMEDY (void);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLFRAMETERMINATORGREMEDYPROC) (void);
+#endif
+
+#ifndef GL_NV_conditional_render
+#define GL_NV_conditional_render 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBeginConditionalRenderNV (GLuint id, GLenum mode);
+GLAPI void APIENTRY glEndConditionalRenderNV (void);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBEGINCONDITIONALRENDERNVPROC) (GLuint id, GLenum mode);
+typedef void (APIENTRYP PFNGLENDCONDITIONALRENDERNVPROC) (void);
+#endif
+
+#ifndef GL_NV_present_video
+#define GL_NV_present_video 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glPresentFrameKeyedNV (GLuint video_slot, GLuint64EXT minPresentTime, GLuint beginPresentTimeId, GLuint presentDurationId, GLenum type, GLenum target0, GLuint fill0, GLuint key0, GLenum target1, GLuint fill1, GLuint key1);
+GLAPI void APIENTRY glPresentFrameDualFillNV (GLuint video_slot, GLuint64EXT minPresentTime, GLuint beginPresentTimeId, GLuint presentDurationId, GLenum type, GLenum target0, GLuint fill0, GLenum target1, GLuint fill1, GLenum target2, GLuint fill2, GLenum target3, GLuint fill3);
+GLAPI void APIENTRY glGetVideoivNV (GLuint video_slot, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetVideouivNV (GLuint video_slot, GLenum pname, GLuint *params);
+GLAPI void APIENTRY glGetVideoi64vNV (GLuint video_slot, GLenum pname, GLint64EXT *params);
+GLAPI void APIENTRY glGetVideoui64vNV (GLuint video_slot, GLenum pname, GLuint64EXT *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPRESENTFRAMEKEYEDNVPROC) (GLuint video_slot, GLuint64EXT minPresentTime, GLuint beginPresentTimeId, GLuint presentDurationId, GLenum type, GLenum target0, GLuint fill0, GLuint key0, GLenum target1, GLuint fill1, GLuint key1);
+typedef void (APIENTRYP PFNGLPRESENTFRAMEDUALFILLNVPROC) (GLuint video_slot, GLuint64EXT minPresentTime, GLuint beginPresentTimeId, GLuint presentDurationId, GLenum type, GLenum target0, GLuint fill0, GLenum target1, GLuint fill1, GLenum target2, GLuint fill2, GLenum target3, GLuint fill3);
+typedef void (APIENTRYP PFNGLGETVIDEOIVNVPROC) (GLuint video_slot, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETVIDEOUIVNVPROC) (GLuint video_slot, GLenum pname, GLuint *params);
+typedef void (APIENTRYP PFNGLGETVIDEOI64VNVPROC) (GLuint video_slot, GLenum pname, GLint64EXT *params);
+typedef void (APIENTRYP PFNGLGETVIDEOUI64VNVPROC) (GLuint video_slot, GLenum pname, GLuint64EXT *params);
+#endif
+
+#ifndef GL_EXT_transform_feedback
+#define GL_EXT_transform_feedback 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBeginTransformFeedbackEXT (GLenum primitiveMode);
+GLAPI void APIENTRY glEndTransformFeedbackEXT (void);
+GLAPI void APIENTRY glBindBufferRangeEXT (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size);
+GLAPI void APIENTRY glBindBufferOffsetEXT (GLenum target, GLuint index, GLuint buffer, GLintptr offset);
+GLAPI void APIENTRY glBindBufferBaseEXT (GLenum target, GLuint index, GLuint buffer);
+GLAPI void APIENTRY glTransformFeedbackVaryingsEXT (GLuint program, GLsizei count, const GLchar* *varyings, GLenum bufferMode);
+GLAPI void APIENTRY glGetTransformFeedbackVaryingEXT (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBEGINTRANSFORMFEEDBACKEXTPROC) (GLenum primitiveMode);
+typedef void (APIENTRYP PFNGLENDTRANSFORMFEEDBACKEXTPROC) (void);
+typedef void (APIENTRYP PFNGLBINDBUFFERRANGEEXTPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size);
+typedef void (APIENTRYP PFNGLBINDBUFFEROFFSETEXTPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset);
+typedef void (APIENTRYP PFNGLBINDBUFFERBASEEXTPROC) (GLenum target, GLuint index, GLuint buffer);
+typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKVARYINGSEXTPROC) (GLuint program, GLsizei count, const GLchar* *varyings, GLenum bufferMode);
+typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKVARYINGEXTPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name);
+#endif
+
+#ifndef GL_EXT_direct_state_access
+#define GL_EXT_direct_state_access 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glClientAttribDefaultEXT (GLbitfield mask);
+GLAPI void APIENTRY glPushClientAttribDefaultEXT (GLbitfield mask);
+GLAPI void APIENTRY glMatrixLoadfEXT (GLenum mode, const GLfloat *m);
+GLAPI void APIENTRY glMatrixLoaddEXT (GLenum mode, const GLdouble *m);
+GLAPI void APIENTRY glMatrixMultfEXT (GLenum mode, const GLfloat *m);
+GLAPI void APIENTRY glMatrixMultdEXT (GLenum mode, const GLdouble *m);
+GLAPI void APIENTRY glMatrixLoadIdentityEXT (GLenum mode);
+GLAPI void APIENTRY glMatrixRotatefEXT (GLenum mode, GLfloat angle, GLfloat x, GLfloat y, GLfloat z);
+GLAPI void APIENTRY glMatrixRotatedEXT (GLenum mode, GLdouble angle, GLdouble x, GLdouble y, GLdouble z);
+GLAPI void APIENTRY glMatrixScalefEXT (GLenum mode, GLfloat x, GLfloat y, GLfloat z);
+GLAPI void APIENTRY glMatrixScaledEXT (GLenum mode, GLdouble x, GLdouble y, GLdouble z);
+GLAPI void APIENTRY glMatrixTranslatefEXT (GLenum mode, GLfloat x, GLfloat y, GLfloat z);
+GLAPI void APIENTRY glMatrixTranslatedEXT (GLenum mode, GLdouble x, GLdouble y, GLdouble z);
+GLAPI void APIENTRY glMatrixFrustumEXT (GLenum mode, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+GLAPI void APIENTRY glMatrixOrthoEXT (GLenum mode, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+GLAPI void APIENTRY glMatrixPopEXT (GLenum mode);
+GLAPI void APIENTRY glMatrixPushEXT (GLenum mode);
+GLAPI void APIENTRY glMatrixLoadTransposefEXT (GLenum mode, const GLfloat *m);
+GLAPI void APIENTRY glMatrixLoadTransposedEXT (GLenum mode, const GLdouble *m);
+GLAPI void APIENTRY glMatrixMultTransposefEXT (GLenum mode, const GLfloat *m);
+GLAPI void APIENTRY glMatrixMultTransposedEXT (GLenum mode, const GLdouble *m);
+GLAPI void APIENTRY glTextureParameterfEXT (GLuint texture, GLenum target, GLenum pname, GLfloat param);
+GLAPI void APIENTRY glTextureParameterfvEXT (GLuint texture, GLenum target, GLenum pname, const GLfloat *params);
+GLAPI void APIENTRY glTextureParameteriEXT (GLuint texture, GLenum target, GLenum pname, GLint param);
+GLAPI void APIENTRY glTextureParameterivEXT (GLuint texture, GLenum target, GLenum pname, const GLint *params);
+GLAPI void APIENTRY glTextureImage1DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+GLAPI void APIENTRY glTextureImage2DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+GLAPI void APIENTRY glTextureSubImage1DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels);
+GLAPI void APIENTRY glTextureSubImage2DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+GLAPI void APIENTRY glCopyTextureImage1DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border);
+GLAPI void APIENTRY glCopyTextureImage2DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
+GLAPI void APIENTRY glCopyTextureSubImage1DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);
+GLAPI void APIENTRY glCopyTextureSubImage2DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+GLAPI void APIENTRY glGetTextureImageEXT (GLuint texture, GLenum target, GLint level, GLenum format, GLenum type, GLvoid *pixels);
+GLAPI void APIENTRY glGetTextureParameterfvEXT (GLuint texture, GLenum target, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetTextureParameterivEXT (GLuint texture, GLenum target, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetTextureLevelParameterfvEXT (GLuint texture, GLenum target, GLint level, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetTextureLevelParameterivEXT (GLuint texture, GLenum target, GLint level, GLenum pname, GLint *params);
+GLAPI void APIENTRY glTextureImage3DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+GLAPI void APIENTRY glTextureSubImage3DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels);
+GLAPI void APIENTRY glCopyTextureSubImage3DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+GLAPI void APIENTRY glMultiTexParameterfEXT (GLenum texunit, GLenum target, GLenum pname, GLfloat param);
+GLAPI void APIENTRY glMultiTexParameterfvEXT (GLenum texunit, GLenum target, GLenum pname, const GLfloat *params);
+GLAPI void APIENTRY glMultiTexParameteriEXT (GLenum texunit, GLenum target, GLenum pname, GLint param);
+GLAPI void APIENTRY glMultiTexParameterivEXT (GLenum texunit, GLenum target, GLenum pname, const GLint *params);
+GLAPI void APIENTRY glMultiTexImage1DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+GLAPI void APIENTRY glMultiTexImage2DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+GLAPI void APIENTRY glMultiTexSubImage1DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels);
+GLAPI void APIENTRY glMultiTexSubImage2DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+GLAPI void APIENTRY glCopyMultiTexImage1DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border);
+GLAPI void APIENTRY glCopyMultiTexImage2DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
+GLAPI void APIENTRY glCopyMultiTexSubImage1DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);
+GLAPI void APIENTRY glCopyMultiTexSubImage2DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+GLAPI void APIENTRY glGetMultiTexImageEXT (GLenum texunit, GLenum target, GLint level, GLenum format, GLenum type, GLvoid *pixels);
+GLAPI void APIENTRY glGetMultiTexParameterfvEXT (GLenum texunit, GLenum target, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetMultiTexParameterivEXT (GLenum texunit, GLenum target, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetMultiTexLevelParameterfvEXT (GLenum texunit, GLenum target, GLint level, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetMultiTexLevelParameterivEXT (GLenum texunit, GLenum target, GLint level, GLenum pname, GLint *params);
+GLAPI void APIENTRY glMultiTexImage3DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+GLAPI void APIENTRY glMultiTexSubImage3DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels);
+GLAPI void APIENTRY glCopyMultiTexSubImage3DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+GLAPI void APIENTRY glBindMultiTextureEXT (GLenum texunit, GLenum target, GLuint texture);
+GLAPI void APIENTRY glEnableClientStateIndexedEXT (GLenum array, GLuint index);
+GLAPI void APIENTRY glDisableClientStateIndexedEXT (GLenum array, GLuint index);
+GLAPI void APIENTRY glMultiTexCoordPointerEXT (GLenum texunit, GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+GLAPI void APIENTRY glMultiTexEnvfEXT (GLenum texunit, GLenum target, GLenum pname, GLfloat param);
+GLAPI void APIENTRY glMultiTexEnvfvEXT (GLenum texunit, GLenum target, GLenum pname, const GLfloat *params);
+GLAPI void APIENTRY glMultiTexEnviEXT (GLenum texunit, GLenum target, GLenum pname, GLint param);
+GLAPI void APIENTRY glMultiTexEnvivEXT (GLenum texunit, GLenum target, GLenum pname, const GLint *params);
+GLAPI void APIENTRY glMultiTexGendEXT (GLenum texunit, GLenum coord, GLenum pname, GLdouble param);
+GLAPI void APIENTRY glMultiTexGendvEXT (GLenum texunit, GLenum coord, GLenum pname, const GLdouble *params);
+GLAPI void APIENTRY glMultiTexGenfEXT (GLenum texunit, GLenum coord, GLenum pname, GLfloat param);
+GLAPI void APIENTRY glMultiTexGenfvEXT (GLenum texunit, GLenum coord, GLenum pname, const GLfloat *params);
+GLAPI void APIENTRY glMultiTexGeniEXT (GLenum texunit, GLenum coord, GLenum pname, GLint param);
+GLAPI void APIENTRY glMultiTexGenivEXT (GLenum texunit, GLenum coord, GLenum pname, const GLint *params);
+GLAPI void APIENTRY glGetMultiTexEnvfvEXT (GLenum texunit, GLenum target, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetMultiTexEnvivEXT (GLenum texunit, GLenum target, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetMultiTexGendvEXT (GLenum texunit, GLenum coord, GLenum pname, GLdouble *params);
+GLAPI void APIENTRY glGetMultiTexGenfvEXT (GLenum texunit, GLenum coord, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetMultiTexGenivEXT (GLenum texunit, GLenum coord, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetFloatIndexedvEXT (GLenum target, GLuint index, GLfloat *data);
+GLAPI void APIENTRY glGetDoubleIndexedvEXT (GLenum target, GLuint index, GLdouble *data);
+GLAPI void APIENTRY glGetPointerIndexedvEXT (GLenum target, GLuint index, GLvoid* *data);
+GLAPI void APIENTRY glCompressedTextureImage3DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *bits);
+GLAPI void APIENTRY glCompressedTextureImage2DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *bits);
+GLAPI void APIENTRY glCompressedTextureImage1DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *bits);
+GLAPI void APIENTRY glCompressedTextureSubImage3DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *bits);
+GLAPI void APIENTRY glCompressedTextureSubImage2DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *bits);
+GLAPI void APIENTRY glCompressedTextureSubImage1DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *bits);
+GLAPI void APIENTRY glGetCompressedTextureImageEXT (GLuint texture, GLenum target, GLint lod, GLvoid *img);
+GLAPI void APIENTRY glCompressedMultiTexImage3DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *bits);
+GLAPI void APIENTRY glCompressedMultiTexImage2DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *bits);
+GLAPI void APIENTRY glCompressedMultiTexImage1DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *bits);
+GLAPI void APIENTRY glCompressedMultiTexSubImage3DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *bits);
+GLAPI void APIENTRY glCompressedMultiTexSubImage2DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *bits);
+GLAPI void APIENTRY glCompressedMultiTexSubImage1DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *bits);
+GLAPI void APIENTRY glGetCompressedMultiTexImageEXT (GLenum texunit, GLenum target, GLint lod, GLvoid *img);
+GLAPI void APIENTRY glNamedProgramStringEXT (GLuint program, GLenum target, GLenum format, GLsizei len, const GLvoid *string);
+GLAPI void APIENTRY glNamedProgramLocalParameter4dEXT (GLuint program, GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+GLAPI void APIENTRY glNamedProgramLocalParameter4dvEXT (GLuint program, GLenum target, GLuint index, const GLdouble *params);
+GLAPI void APIENTRY glNamedProgramLocalParameter4fEXT (GLuint program, GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+GLAPI void APIENTRY glNamedProgramLocalParameter4fvEXT (GLuint program, GLenum target, GLuint index, const GLfloat *params);
+GLAPI void APIENTRY glGetNamedProgramLocalParameterdvEXT (GLuint program, GLenum target, GLuint index, GLdouble *params);
+GLAPI void APIENTRY glGetNamedProgramLocalParameterfvEXT (GLuint program, GLenum target, GLuint index, GLfloat *params);
+GLAPI void APIENTRY glGetNamedProgramivEXT (GLuint program, GLenum target, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetNamedProgramStringEXT (GLuint program, GLenum target, GLenum pname, GLvoid *string);
+GLAPI void APIENTRY glNamedProgramLocalParameters4fvEXT (GLuint program, GLenum target, GLuint index, GLsizei count, const GLfloat *params);
+GLAPI void APIENTRY glNamedProgramLocalParameterI4iEXT (GLuint program, GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w);
+GLAPI void APIENTRY glNamedProgramLocalParameterI4ivEXT (GLuint program, GLenum target, GLuint index, const GLint *params);
+GLAPI void APIENTRY glNamedProgramLocalParametersI4ivEXT (GLuint program, GLenum target, GLuint index, GLsizei count, const GLint *params);
+GLAPI void APIENTRY glNamedProgramLocalParameterI4uiEXT (GLuint program, GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w);
+GLAPI void APIENTRY glNamedProgramLocalParameterI4uivEXT (GLuint program, GLenum target, GLuint index, const GLuint *params);
+GLAPI void APIENTRY glNamedProgramLocalParametersI4uivEXT (GLuint program, GLenum target, GLuint index, GLsizei count, const GLuint *params);
+GLAPI void APIENTRY glGetNamedProgramLocalParameterIivEXT (GLuint program, GLenum target, GLuint index, GLint *params);
+GLAPI void APIENTRY glGetNamedProgramLocalParameterIuivEXT (GLuint program, GLenum target, GLuint index, GLuint *params);
+GLAPI void APIENTRY glTextureParameterIivEXT (GLuint texture, GLenum target, GLenum pname, const GLint *params);
+GLAPI void APIENTRY glTextureParameterIuivEXT (GLuint texture, GLenum target, GLenum pname, const GLuint *params);
+GLAPI void APIENTRY glGetTextureParameterIivEXT (GLuint texture, GLenum target, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetTextureParameterIuivEXT (GLuint texture, GLenum target, GLenum pname, GLuint *params);
+GLAPI void APIENTRY glMultiTexParameterIivEXT (GLenum texunit, GLenum target, GLenum pname, const GLint *params);
+GLAPI void APIENTRY glMultiTexParameterIuivEXT (GLenum texunit, GLenum target, GLenum pname, const GLuint *params);
+GLAPI void APIENTRY glGetMultiTexParameterIivEXT (GLenum texunit, GLenum target, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetMultiTexParameterIuivEXT (GLenum texunit, GLenum target, GLenum pname, GLuint *params);
+GLAPI void APIENTRY glProgramUniform1fEXT (GLuint program, GLint location, GLfloat v0);
+GLAPI void APIENTRY glProgramUniform2fEXT (GLuint program, GLint location, GLfloat v0, GLfloat v1);
+GLAPI void APIENTRY glProgramUniform3fEXT (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
+GLAPI void APIENTRY glProgramUniform4fEXT (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
+GLAPI void APIENTRY glProgramUniform1iEXT (GLuint program, GLint location, GLint v0);
+GLAPI void APIENTRY glProgramUniform2iEXT (GLuint program, GLint location, GLint v0, GLint v1);
+GLAPI void APIENTRY glProgramUniform3iEXT (GLuint program, GLint location, GLint v0, GLint v1, GLint v2);
+GLAPI void APIENTRY glProgramUniform4iEXT (GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
+GLAPI void APIENTRY glProgramUniform1fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+GLAPI void APIENTRY glProgramUniform2fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+GLAPI void APIENTRY glProgramUniform3fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+GLAPI void APIENTRY glProgramUniform4fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+GLAPI void APIENTRY glProgramUniform1ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value);
+GLAPI void APIENTRY glProgramUniform2ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value);
+GLAPI void APIENTRY glProgramUniform3ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value);
+GLAPI void APIENTRY glProgramUniform4ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value);
+GLAPI void APIENTRY glProgramUniformMatrix2fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GLAPI void APIENTRY glProgramUniformMatrix3fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GLAPI void APIENTRY glProgramUniformMatrix4fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GLAPI void APIENTRY glProgramUniformMatrix2x3fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GLAPI void APIENTRY glProgramUniformMatrix3x2fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GLAPI void APIENTRY glProgramUniformMatrix2x4fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GLAPI void APIENTRY glProgramUniformMatrix4x2fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GLAPI void APIENTRY glProgramUniformMatrix3x4fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GLAPI void APIENTRY glProgramUniformMatrix4x3fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+GLAPI void APIENTRY glProgramUniform1uiEXT (GLuint program, GLint location, GLuint v0);
+GLAPI void APIENTRY glProgramUniform2uiEXT (GLuint program, GLint location, GLuint v0, GLuint v1);
+GLAPI void APIENTRY glProgramUniform3uiEXT (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2);
+GLAPI void APIENTRY glProgramUniform4uiEXT (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3);
+GLAPI void APIENTRY glProgramUniform1uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value);
+GLAPI void APIENTRY glProgramUniform2uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value);
+GLAPI void APIENTRY glProgramUniform3uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value);
+GLAPI void APIENTRY glProgramUniform4uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value);
+GLAPI void APIENTRY glNamedBufferDataEXT (GLuint buffer, GLsizeiptr size, const GLvoid *data, GLenum usage);
+GLAPI void APIENTRY glNamedBufferSubDataEXT (GLuint buffer, GLintptr offset, GLsizeiptr size, const GLvoid *data);
+GLAPI GLvoid* APIENTRY glMapNamedBufferEXT (GLuint buffer, GLenum access);
+GLAPI GLboolean APIENTRY glUnmapNamedBufferEXT (GLuint buffer);
+GLAPI GLvoid* APIENTRY glMapNamedBufferRangeEXT (GLuint buffer, GLintptr offset, GLsizeiptr length, GLbitfield access);
+GLAPI void APIENTRY glFlushMappedNamedBufferRangeEXT (GLuint buffer, GLintptr offset, GLsizeiptr length);
+GLAPI void APIENTRY glNamedCopyBufferSubDataEXT (GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size);
+GLAPI void APIENTRY glGetNamedBufferParameterivEXT (GLuint buffer, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetNamedBufferPointervEXT (GLuint buffer, GLenum pname, GLvoid* *params);
+GLAPI void APIENTRY glGetNamedBufferSubDataEXT (GLuint buffer, GLintptr offset, GLsizeiptr size, GLvoid *data);
+GLAPI void APIENTRY glTextureBufferEXT (GLuint texture, GLenum target, GLenum internalformat, GLuint buffer);
+GLAPI void APIENTRY glMultiTexBufferEXT (GLenum texunit, GLenum target, GLenum internalformat, GLuint buffer);
+GLAPI void APIENTRY glNamedRenderbufferStorageEXT (GLuint renderbuffer, GLenum internalformat, GLsizei width, GLsizei height);
+GLAPI void APIENTRY glGetNamedRenderbufferParameterivEXT (GLuint renderbuffer, GLenum pname, GLint *params);
+GLAPI GLenum APIENTRY glCheckNamedFramebufferStatusEXT (GLuint framebuffer, GLenum target);
+GLAPI void APIENTRY glNamedFramebufferTexture1DEXT (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
+GLAPI void APIENTRY glNamedFramebufferTexture2DEXT (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
+GLAPI void APIENTRY glNamedFramebufferTexture3DEXT (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset);
+GLAPI void APIENTRY glNamedFramebufferRenderbufferEXT (GLuint framebuffer, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
+GLAPI void APIENTRY glGetNamedFramebufferAttachmentParameterivEXT (GLuint framebuffer, GLenum attachment, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGenerateTextureMipmapEXT (GLuint texture, GLenum target);
+GLAPI void APIENTRY glGenerateMultiTexMipmapEXT (GLenum texunit, GLenum target);
+GLAPI void APIENTRY glFramebufferDrawBufferEXT (GLuint framebuffer, GLenum mode);
+GLAPI void APIENTRY glFramebufferDrawBuffersEXT (GLuint framebuffer, GLsizei n, const GLenum *bufs);
+GLAPI void APIENTRY glFramebufferReadBufferEXT (GLuint framebuffer, GLenum mode);
+GLAPI void APIENTRY glGetFramebufferParameterivEXT (GLuint framebuffer, GLenum pname, GLint *params);
+GLAPI void APIENTRY glNamedRenderbufferStorageMultisampleEXT (GLuint renderbuffer, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
+GLAPI void APIENTRY glNamedRenderbufferStorageMultisampleCoverageEXT (GLuint renderbuffer, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height);
+GLAPI void APIENTRY glNamedFramebufferTextureEXT (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level);
+GLAPI void APIENTRY glNamedFramebufferTextureLayerEXT (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint layer);
+GLAPI void APIENTRY glNamedFramebufferTextureFaceEXT (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLenum face);
+GLAPI void APIENTRY glTextureRenderbufferEXT (GLuint texture, GLenum target, GLuint renderbuffer);
+GLAPI void APIENTRY glMultiTexRenderbufferEXT (GLenum texunit, GLenum target, GLuint renderbuffer);
+GLAPI void APIENTRY glProgramUniform1dEXT (GLuint program, GLint location, GLdouble x);
+GLAPI void APIENTRY glProgramUniform2dEXT (GLuint program, GLint location, GLdouble x, GLdouble y);
+GLAPI void APIENTRY glProgramUniform3dEXT (GLuint program, GLint location, GLdouble x, GLdouble y, GLdouble z);
+GLAPI void APIENTRY glProgramUniform4dEXT (GLuint program, GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+GLAPI void APIENTRY glProgramUniform1dvEXT (GLuint program, GLint location, GLsizei count, const GLdouble *value);
+GLAPI void APIENTRY glProgramUniform2dvEXT (GLuint program, GLint location, GLsizei count, const GLdouble *value);
+GLAPI void APIENTRY glProgramUniform3dvEXT (GLuint program, GLint location, GLsizei count, const GLdouble *value);
+GLAPI void APIENTRY glProgramUniform4dvEXT (GLuint program, GLint location, GLsizei count, const GLdouble *value);
+GLAPI void APIENTRY glProgramUniformMatrix2dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+GLAPI void APIENTRY glProgramUniformMatrix3dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+GLAPI void APIENTRY glProgramUniformMatrix4dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+GLAPI void APIENTRY glProgramUniformMatrix2x3dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+GLAPI void APIENTRY glProgramUniformMatrix2x4dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+GLAPI void APIENTRY glProgramUniformMatrix3x2dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+GLAPI void APIENTRY glProgramUniformMatrix3x4dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+GLAPI void APIENTRY glProgramUniformMatrix4x2dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+GLAPI void APIENTRY glProgramUniformMatrix4x3dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCLIENTATTRIBDEFAULTEXTPROC) (GLbitfield mask);
+typedef void (APIENTRYP PFNGLPUSHCLIENTATTRIBDEFAULTEXTPROC) (GLbitfield mask);
+typedef void (APIENTRYP PFNGLMATRIXLOADFEXTPROC) (GLenum mode, const GLfloat *m);
+typedef void (APIENTRYP PFNGLMATRIXLOADDEXTPROC) (GLenum mode, const GLdouble *m);
+typedef void (APIENTRYP PFNGLMATRIXMULTFEXTPROC) (GLenum mode, const GLfloat *m);
+typedef void (APIENTRYP PFNGLMATRIXMULTDEXTPROC) (GLenum mode, const GLdouble *m);
+typedef void (APIENTRYP PFNGLMATRIXLOADIDENTITYEXTPROC) (GLenum mode);
+typedef void (APIENTRYP PFNGLMATRIXROTATEFEXTPROC) (GLenum mode, GLfloat angle, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLMATRIXROTATEDEXTPROC) (GLenum mode, GLdouble angle, GLdouble x, GLdouble y, GLdouble z);
+typedef void (APIENTRYP PFNGLMATRIXSCALEFEXTPROC) (GLenum mode, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLMATRIXSCALEDEXTPROC) (GLenum mode, GLdouble x, GLdouble y, GLdouble z);
+typedef void (APIENTRYP PFNGLMATRIXTRANSLATEFEXTPROC) (GLenum mode, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLMATRIXTRANSLATEDEXTPROC) (GLenum mode, GLdouble x, GLdouble y, GLdouble z);
+typedef void (APIENTRYP PFNGLMATRIXFRUSTUMEXTPROC) (GLenum mode, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+typedef void (APIENTRYP PFNGLMATRIXORTHOEXTPROC) (GLenum mode, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+typedef void (APIENTRYP PFNGLMATRIXPOPEXTPROC) (GLenum mode);
+typedef void (APIENTRYP PFNGLMATRIXPUSHEXTPROC) (GLenum mode);
+typedef void (APIENTRYP PFNGLMATRIXLOADTRANSPOSEFEXTPROC) (GLenum mode, const GLfloat *m);
+typedef void (APIENTRYP PFNGLMATRIXLOADTRANSPOSEDEXTPROC) (GLenum mode, const GLdouble *m);
+typedef void (APIENTRYP PFNGLMATRIXMULTTRANSPOSEFEXTPROC) (GLenum mode, const GLfloat *m);
+typedef void (APIENTRYP PFNGLMATRIXMULTTRANSPOSEDEXTPROC) (GLenum mode, const GLdouble *m);
+typedef void (APIENTRYP PFNGLTEXTUREPARAMETERFEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLTEXTUREPARAMETERFVEXTPROC) (GLuint texture, GLenum target, GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLTEXTUREIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+typedef void (APIENTRYP PFNGLTEXTUREIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels);
+typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+typedef void (APIENTRYP PFNGLCOPYTEXTUREIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border);
+typedef void (APIENTRYP PFNGLCOPYTEXTUREIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
+typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);
+typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+typedef void (APIENTRYP PFNGLGETTEXTUREIMAGEEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum format, GLenum type, GLvoid *pixels);
+typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERFVEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETTEXTURELEVELPARAMETERFVEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETTEXTURELEVELPARAMETERIVEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLTEXTUREIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels);
+typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+typedef void (APIENTRYP PFNGLMULTITEXPARAMETERFEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLMULTITEXPARAMETERFVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLMULTITEXPARAMETERIEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLMULTITEXPARAMETERIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLMULTITEXIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+typedef void (APIENTRYP PFNGLMULTITEXIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+typedef void (APIENTRYP PFNGLMULTITEXSUBIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels);
+typedef void (APIENTRYP PFNGLMULTITEXSUBIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+typedef void (APIENTRYP PFNGLCOPYMULTITEXIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border);
+typedef void (APIENTRYP PFNGLCOPYMULTITEXIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
+typedef void (APIENTRYP PFNGLCOPYMULTITEXSUBIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);
+typedef void (APIENTRYP PFNGLCOPYMULTITEXSUBIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+typedef void (APIENTRYP PFNGLGETMULTITEXIMAGEEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum format, GLenum type, GLvoid *pixels);
+typedef void (APIENTRYP PFNGLGETMULTITEXPARAMETERFVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETMULTITEXPARAMETERIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETMULTITEXLEVELPARAMETERFVEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETMULTITEXLEVELPARAMETERIVEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLMULTITEXIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+typedef void (APIENTRYP PFNGLMULTITEXSUBIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels);
+typedef void (APIENTRYP PFNGLCOPYMULTITEXSUBIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+typedef void (APIENTRYP PFNGLBINDMULTITEXTUREEXTPROC) (GLenum texunit, GLenum target, GLuint texture);
+typedef void (APIENTRYP PFNGLENABLECLIENTSTATEINDEXEDEXTPROC) (GLenum array, GLuint index);
+typedef void (APIENTRYP PFNGLDISABLECLIENTSTATEINDEXEDEXTPROC) (GLenum array, GLuint index);
+typedef void (APIENTRYP PFNGLMULTITEXCOORDPOINTEREXTPROC) (GLenum texunit, GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+typedef void (APIENTRYP PFNGLMULTITEXENVFEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLMULTITEXENVFVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLMULTITEXENVIEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLMULTITEXENVIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLMULTITEXGENDEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLdouble param);
+typedef void (APIENTRYP PFNGLMULTITEXGENDVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, const GLdouble *params);
+typedef void (APIENTRYP PFNGLMULTITEXGENFEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLMULTITEXGENFVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLMULTITEXGENIEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLMULTITEXGENIVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLGETMULTITEXENVFVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETMULTITEXENVIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETMULTITEXGENDVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLdouble *params);
+typedef void (APIENTRYP PFNGLGETMULTITEXGENFVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETMULTITEXGENIVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETFLOATINDEXEDVEXTPROC) (GLenum target, GLuint index, GLfloat *data);
+typedef void (APIENTRYP PFNGLGETDOUBLEINDEXEDVEXTPROC) (GLenum target, GLuint index, GLdouble *data);
+typedef void (APIENTRYP PFNGLGETPOINTERINDEXEDVEXTPROC) (GLenum target, GLuint index, GLvoid* *data);
+typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTUREIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *bits);
+typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTUREIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *bits);
+typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTUREIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *bits);
+typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *bits);
+typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *bits);
+typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *bits);
+typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXTUREIMAGEEXTPROC) (GLuint texture, GLenum target, GLint lod, GLvoid *img);
+typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *bits);
+typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *bits);
+typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *bits);
+typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXSUBIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *bits);
+typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXSUBIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *bits);
+typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXSUBIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *bits);
+typedef void (APIENTRYP PFNGLGETCOMPRESSEDMULTITEXIMAGEEXTPROC) (GLenum texunit, GLenum target, GLint lod, GLvoid *img);
+typedef void (APIENTRYP PFNGLNAMEDPROGRAMSTRINGEXTPROC) (GLuint program, GLenum target, GLenum format, GLsizei len, const GLvoid *string);
+typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETER4DEXTPROC) (GLuint program, GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETER4DVEXTPROC) (GLuint program, GLenum target, GLuint index, const GLdouble *params);
+typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETER4FEXTPROC) (GLuint program, GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETER4FVEXTPROC) (GLuint program, GLenum target, GLuint index, const GLfloat *params);
+typedef void (APIENTRYP PFNGLGETNAMEDPROGRAMLOCALPARAMETERDVEXTPROC) (GLuint program, GLenum target, GLuint index, GLdouble *params);
+typedef void (APIENTRYP PFNGLGETNAMEDPROGRAMLOCALPARAMETERFVEXTPROC) (GLuint program, GLenum target, GLuint index, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETNAMEDPROGRAMIVEXTPROC) (GLuint program, GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETNAMEDPROGRAMSTRINGEXTPROC) (GLuint program, GLenum target, GLenum pname, GLvoid *string);
+typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERS4FVEXTPROC) (GLuint program, GLenum target, GLuint index, GLsizei count, const GLfloat *params);
+typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERI4IEXTPROC) (GLuint program, GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w);
+typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERI4IVEXTPROC) (GLuint program, GLenum target, GLuint index, const GLint *params);
+typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERSI4IVEXTPROC) (GLuint program, GLenum target, GLuint index, GLsizei count, const GLint *params);
+typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERI4UIEXTPROC) (GLuint program, GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w);
+typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERI4UIVEXTPROC) (GLuint program, GLenum target, GLuint index, const GLuint *params);
+typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERSI4UIVEXTPROC) (GLuint program, GLenum target, GLuint index, GLsizei count, const GLuint *params);
+typedef void (APIENTRYP PFNGLGETNAMEDPROGRAMLOCALPARAMETERIIVEXTPROC) (GLuint program, GLenum target, GLuint index, GLint *params);
+typedef void (APIENTRYP PFNGLGETNAMEDPROGRAMLOCALPARAMETERIUIVEXTPROC) (GLuint program, GLenum target, GLuint index, GLuint *params);
+typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIUIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, const GLuint *params);
+typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIUIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLuint *params);
+typedef void (APIENTRYP PFNGLMULTITEXPARAMETERIIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLMULTITEXPARAMETERIUIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLuint *params);
+typedef void (APIENTRYP PFNGLGETMULTITEXPARAMETERIIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETMULTITEXPARAMETERIUIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLuint *params);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1FEXTPROC) (GLuint program, GLint location, GLfloat v0);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2FEXTPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3FEXTPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4FEXTPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1IEXTPROC) (GLuint program, GLint location, GLint v0);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2IEXTPROC) (GLuint program, GLint location, GLint v0, GLint v1);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3IEXTPROC) (GLuint program, GLint location, GLint v0, GLint v1, GLint v2);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4IEXTPROC) (GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UIEXTPROC) (GLuint program, GLint location, GLuint v0);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UIEXTPROC) (GLuint program, GLint location, GLuint v0, GLuint v1);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UIEXTPROC) (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UIEXTPROC) (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value);
+typedef void (APIENTRYP PFNGLNAMEDBUFFERDATAEXTPROC) (GLuint buffer, GLsizeiptr size, const GLvoid *data, GLenum usage);
+typedef void (APIENTRYP PFNGLNAMEDBUFFERSUBDATAEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, const GLvoid *data);
+typedef GLvoid* (APIENTRYP PFNGLMAPNAMEDBUFFEREXTPROC) (GLuint buffer, GLenum access);
+typedef GLboolean (APIENTRYP PFNGLUNMAPNAMEDBUFFEREXTPROC) (GLuint buffer);
+typedef GLvoid* (APIENTRYP PFNGLMAPNAMEDBUFFERRANGEEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr length, GLbitfield access);
+typedef void (APIENTRYP PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr length);
+typedef void (APIENTRYP PFNGLNAMEDCOPYBUFFERSUBDATAEXTPROC) (GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size);
+typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPARAMETERIVEXTPROC) (GLuint buffer, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPOINTERVEXTPROC) (GLuint buffer, GLenum pname, GLvoid* *params);
+typedef void (APIENTRYP PFNGLGETNAMEDBUFFERSUBDATAEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, GLvoid *data);
+typedef void (APIENTRYP PFNGLTEXTUREBUFFEREXTPROC) (GLuint texture, GLenum target, GLenum internalformat, GLuint buffer);
+typedef void (APIENTRYP PFNGLMULTITEXBUFFEREXTPROC) (GLenum texunit, GLenum target, GLenum internalformat, GLuint buffer);
+typedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEEXTPROC) (GLuint renderbuffer, GLenum internalformat, GLsizei width, GLsizei height);
+typedef void (APIENTRYP PFNGLGETNAMEDRENDERBUFFERPARAMETERIVEXTPROC) (GLuint renderbuffer, GLenum pname, GLint *params);
+typedef GLenum (APIENTRYP PFNGLCHECKNAMEDFRAMEBUFFERSTATUSEXTPROC) (GLuint framebuffer, GLenum target);
+typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTURE1DEXTPROC) (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
+typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTURE2DEXTPROC) (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
+typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTURE3DEXTPROC) (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset);
+typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERRENDERBUFFEREXTPROC) (GLuint framebuffer, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
+typedef void (APIENTRYP PFNGLGETNAMEDFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC) (GLuint framebuffer, GLenum attachment, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGENERATETEXTUREMIPMAPEXTPROC) (GLuint texture, GLenum target);
+typedef void (APIENTRYP PFNGLGENERATEMULTITEXMIPMAPEXTPROC) (GLenum texunit, GLenum target);
+typedef void (APIENTRYP PFNGLFRAMEBUFFERDRAWBUFFEREXTPROC) (GLuint framebuffer, GLenum mode);
+typedef void (APIENTRYP PFNGLFRAMEBUFFERDRAWBUFFERSEXTPROC) (GLuint framebuffer, GLsizei n, const GLenum *bufs);
+typedef void (APIENTRYP PFNGLFRAMEBUFFERREADBUFFEREXTPROC) (GLuint framebuffer, GLenum mode);
+typedef void (APIENTRYP PFNGLGETFRAMEBUFFERPARAMETERIVEXTPROC) (GLuint framebuffer, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC) (GLuint renderbuffer, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
+typedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLECOVERAGEEXTPROC) (GLuint renderbuffer, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height);
+typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTUREEXTPROC) (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level);
+typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTURELAYEREXTPROC) (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint layer);
+typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTUREFACEEXTPROC) (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLenum face);
+typedef void (APIENTRYP PFNGLTEXTURERENDERBUFFEREXTPROC) (GLuint texture, GLenum target, GLuint renderbuffer);
+typedef void (APIENTRYP PFNGLMULTITEXRENDERBUFFEREXTPROC) (GLenum texunit, GLenum target, GLuint renderbuffer);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1DEXTPROC) (GLuint program, GLint location, GLdouble x);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2DEXTPROC) (GLuint program, GLint location, GLdouble x, GLdouble y);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3DEXTPROC) (GLuint program, GLint location, GLdouble x, GLdouble y, GLdouble z);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4DEXTPROC) (GLuint program, GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1DVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2DVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3DVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4DVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value);
+#endif
+
+#ifndef GL_EXT_vertex_array_bgra
+#define GL_EXT_vertex_array_bgra 1
+#endif
+
+#ifndef GL_EXT_texture_swizzle
+#define GL_EXT_texture_swizzle 1
+#endif
+
+#ifndef GL_NV_explicit_multisample
+#define GL_NV_explicit_multisample 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glGetMultisamplefvNV (GLenum pname, GLuint index, GLfloat *val);
+GLAPI void APIENTRY glSampleMaskIndexedNV (GLuint index, GLbitfield mask);
+GLAPI void APIENTRY glTexRenderbufferNV (GLenum target, GLuint renderbuffer);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLGETMULTISAMPLEFVNVPROC) (GLenum pname, GLuint index, GLfloat *val);
+typedef void (APIENTRYP PFNGLSAMPLEMASKINDEXEDNVPROC) (GLuint index, GLbitfield mask);
+typedef void (APIENTRYP PFNGLTEXRENDERBUFFERNVPROC) (GLenum target, GLuint renderbuffer);
+#endif
+
+#ifndef GL_NV_transform_feedback2
+#define GL_NV_transform_feedback2 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBindTransformFeedbackNV (GLenum target, GLuint id);
+GLAPI void APIENTRY glDeleteTransformFeedbacksNV (GLsizei n, const GLuint *ids);
+GLAPI void APIENTRY glGenTransformFeedbacksNV (GLsizei n, GLuint *ids);
+GLAPI GLboolean APIENTRY glIsTransformFeedbackNV (GLuint id);
+GLAPI void APIENTRY glPauseTransformFeedbackNV (void);
+GLAPI void APIENTRY glResumeTransformFeedbackNV (void);
+GLAPI void APIENTRY glDrawTransformFeedbackNV (GLenum mode, GLuint id);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBINDTRANSFORMFEEDBACKNVPROC) (GLenum target, GLuint id);
+typedef void (APIENTRYP PFNGLDELETETRANSFORMFEEDBACKSNVPROC) (GLsizei n, const GLuint *ids);
+typedef void (APIENTRYP PFNGLGENTRANSFORMFEEDBACKSNVPROC) (GLsizei n, GLuint *ids);
+typedef GLboolean (APIENTRYP PFNGLISTRANSFORMFEEDBACKNVPROC) (GLuint id);
+typedef void (APIENTRYP PFNGLPAUSETRANSFORMFEEDBACKNVPROC) (void);
+typedef void (APIENTRYP PFNGLRESUMETRANSFORMFEEDBACKNVPROC) (void);
+typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKNVPROC) (GLenum mode, GLuint id);
+#endif
+
+#ifndef GL_ATI_meminfo
+#define GL_ATI_meminfo 1
+#endif
+
+#ifndef GL_AMD_performance_monitor
+#define GL_AMD_performance_monitor 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glGetPerfMonitorGroupsAMD (GLint *numGroups, GLsizei groupsSize, GLuint *groups);
+GLAPI void APIENTRY glGetPerfMonitorCountersAMD (GLuint group, GLint *numCounters, GLint *maxActiveCounters, GLsizei counterSize, GLuint *counters);
+GLAPI void APIENTRY glGetPerfMonitorGroupStringAMD (GLuint group, GLsizei bufSize, GLsizei *length, GLchar *groupString);
+GLAPI void APIENTRY glGetPerfMonitorCounterStringAMD (GLuint group, GLuint counter, GLsizei bufSize, GLsizei *length, GLchar *counterString);
+GLAPI void APIENTRY glGetPerfMonitorCounterInfoAMD (GLuint group, GLuint counter, GLenum pname, GLvoid *data);
+GLAPI void APIENTRY glGenPerfMonitorsAMD (GLsizei n, GLuint *monitors);
+GLAPI void APIENTRY glDeletePerfMonitorsAMD (GLsizei n, GLuint *monitors);
+GLAPI void APIENTRY glSelectPerfMonitorCountersAMD (GLuint monitor, GLboolean enable, GLuint group, GLint numCounters, GLuint *counterList);
+GLAPI void APIENTRY glBeginPerfMonitorAMD (GLuint monitor);
+GLAPI void APIENTRY glEndPerfMonitorAMD (GLuint monitor);
+GLAPI void APIENTRY glGetPerfMonitorCounterDataAMD (GLuint monitor, GLenum pname, GLsizei dataSize, GLuint *data, GLint *bytesWritten);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLGETPERFMONITORGROUPSAMDPROC) (GLint *numGroups, GLsizei groupsSize, GLuint *groups);
+typedef void (APIENTRYP PFNGLGETPERFMONITORCOUNTERSAMDPROC) (GLuint group, GLint *numCounters, GLint *maxActiveCounters, GLsizei counterSize, GLuint *counters);
+typedef void (APIENTRYP PFNGLGETPERFMONITORGROUPSTRINGAMDPROC) (GLuint group, GLsizei bufSize, GLsizei *length, GLchar *groupString);
+typedef void (APIENTRYP PFNGLGETPERFMONITORCOUNTERSTRINGAMDPROC) (GLuint group, GLuint counter, GLsizei bufSize, GLsizei *length, GLchar *counterString);
+typedef void (APIENTRYP PFNGLGETPERFMONITORCOUNTERINFOAMDPROC) (GLuint group, GLuint counter, GLenum pname, GLvoid *data);
+typedef void (APIENTRYP PFNGLGENPERFMONITORSAMDPROC) (GLsizei n, GLuint *monitors);
+typedef void (APIENTRYP PFNGLDELETEPERFMONITORSAMDPROC) (GLsizei n, GLuint *monitors);
+typedef void (APIENTRYP PFNGLSELECTPERFMONITORCOUNTERSAMDPROC) (GLuint monitor, GLboolean enable, GLuint group, GLint numCounters, GLuint *counterList);
+typedef void (APIENTRYP PFNGLBEGINPERFMONITORAMDPROC) (GLuint monitor);
+typedef void (APIENTRYP PFNGLENDPERFMONITORAMDPROC) (GLuint monitor);
+typedef void (APIENTRYP PFNGLGETPERFMONITORCOUNTERDATAAMDPROC) (GLuint monitor, GLenum pname, GLsizei dataSize, GLuint *data, GLint *bytesWritten);
+#endif
+
+#ifndef GL_AMD_texture_texture4
+#define GL_AMD_texture_texture4 1
+#endif
+
+#ifndef GL_AMD_vertex_shader_tesselator
+#define GL_AMD_vertex_shader_tesselator 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glTessellationFactorAMD (GLfloat factor);
+GLAPI void APIENTRY glTessellationModeAMD (GLenum mode);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLTESSELLATIONFACTORAMDPROC) (GLfloat factor);
+typedef void (APIENTRYP PFNGLTESSELLATIONMODEAMDPROC) (GLenum mode);
+#endif
+
+#ifndef GL_EXT_provoking_vertex
+#define GL_EXT_provoking_vertex 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glProvokingVertexEXT (GLenum mode);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPROVOKINGVERTEXEXTPROC) (GLenum mode);
+#endif
+
+#ifndef GL_EXT_texture_snorm
+#define GL_EXT_texture_snorm 1
+#endif
+
+#ifndef GL_AMD_draw_buffers_blend
+#define GL_AMD_draw_buffers_blend 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBlendFuncIndexedAMD (GLuint buf, GLenum src, GLenum dst);
+GLAPI void APIENTRY glBlendFuncSeparateIndexedAMD (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
+GLAPI void APIENTRY glBlendEquationIndexedAMD (GLuint buf, GLenum mode);
+GLAPI void APIENTRY glBlendEquationSeparateIndexedAMD (GLuint buf, GLenum modeRGB, GLenum modeAlpha);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBLENDFUNCINDEXEDAMDPROC) (GLuint buf, GLenum src, GLenum dst);
+typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEINDEXEDAMDPROC) (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
+typedef void (APIENTRYP PFNGLBLENDEQUATIONINDEXEDAMDPROC) (GLuint buf, GLenum mode);
+typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEINDEXEDAMDPROC) (GLuint buf, GLenum modeRGB, GLenum modeAlpha);
+#endif
+
+#ifndef GL_APPLE_texture_range
+#define GL_APPLE_texture_range 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glTextureRangeAPPLE (GLenum target, GLsizei length, const GLvoid *pointer);
+GLAPI void APIENTRY glGetTexParameterPointervAPPLE (GLenum target, GLenum pname, GLvoid* *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLTEXTURERANGEAPPLEPROC) (GLenum target, GLsizei length, const GLvoid *pointer);
+typedef void (APIENTRYP PFNGLGETTEXPARAMETERPOINTERVAPPLEPROC) (GLenum target, GLenum pname, GLvoid* *params);
+#endif
+
+#ifndef GL_APPLE_float_pixels
+#define GL_APPLE_float_pixels 1
+#endif
+
+#ifndef GL_APPLE_vertex_program_evaluators
+#define GL_APPLE_vertex_program_evaluators 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glEnableVertexAttribAPPLE (GLuint index, GLenum pname);
+GLAPI void APIENTRY glDisableVertexAttribAPPLE (GLuint index, GLenum pname);
+GLAPI GLboolean APIENTRY glIsVertexAttribEnabledAPPLE (GLuint index, GLenum pname);
+GLAPI void APIENTRY glMapVertexAttrib1dAPPLE (GLuint index, GLuint size, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points);
+GLAPI void APIENTRY glMapVertexAttrib1fAPPLE (GLuint index, GLuint size, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points);
+GLAPI void APIENTRY glMapVertexAttrib2dAPPLE (GLuint index, GLuint size, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points);
+GLAPI void APIENTRY glMapVertexAttrib2fAPPLE (GLuint index, GLuint size, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBAPPLEPROC) (GLuint index, GLenum pname);
+typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBAPPLEPROC) (GLuint index, GLenum pname);
+typedef GLboolean (APIENTRYP PFNGLISVERTEXATTRIBENABLEDAPPLEPROC) (GLuint index, GLenum pname);
+typedef void (APIENTRYP PFNGLMAPVERTEXATTRIB1DAPPLEPROC) (GLuint index, GLuint size, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points);
+typedef void (APIENTRYP PFNGLMAPVERTEXATTRIB1FAPPLEPROC) (GLuint index, GLuint size, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points);
+typedef void (APIENTRYP PFNGLMAPVERTEXATTRIB2DAPPLEPROC) (GLuint index, GLuint size, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points);
+typedef void (APIENTRYP PFNGLMAPVERTEXATTRIB2FAPPLEPROC) (GLuint index, GLuint size, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points);
+#endif
+
+#ifndef GL_APPLE_aux_depth_stencil
+#define GL_APPLE_aux_depth_stencil 1
+#endif
+
+#ifndef GL_APPLE_object_purgeable
+#define GL_APPLE_object_purgeable 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI GLenum APIENTRY glObjectPurgeableAPPLE (GLenum objectType, GLuint name, GLenum option);
+GLAPI GLenum APIENTRY glObjectUnpurgeableAPPLE (GLenum objectType, GLuint name, GLenum option);
+GLAPI void APIENTRY glGetObjectParameterivAPPLE (GLenum objectType, GLuint name, GLenum pname, GLint *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef GLenum (APIENTRYP PFNGLOBJECTPURGEABLEAPPLEPROC) (GLenum objectType, GLuint name, GLenum option);
+typedef GLenum (APIENTRYP PFNGLOBJECTUNPURGEABLEAPPLEPROC) (GLenum objectType, GLuint name, GLenum option);
+typedef void (APIENTRYP PFNGLGETOBJECTPARAMETERIVAPPLEPROC) (GLenum objectType, GLuint name, GLenum pname, GLint *params);
+#endif
+
+#ifndef GL_APPLE_row_bytes
+#define GL_APPLE_row_bytes 1
+#endif
+
+#ifndef GL_APPLE_rgb_422
+#define GL_APPLE_rgb_422 1
+#endif
+
+#ifndef GL_NV_video_capture
+#define GL_NV_video_capture 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBeginVideoCaptureNV (GLuint video_capture_slot);
+GLAPI void APIENTRY glBindVideoCaptureStreamBufferNV (GLuint video_capture_slot, GLuint stream, GLenum frame_region, GLintptrARB offset);
+GLAPI void APIENTRY glBindVideoCaptureStreamTextureNV (GLuint video_capture_slot, GLuint stream, GLenum frame_region, GLenum target, GLuint texture);
+GLAPI void APIENTRY glEndVideoCaptureNV (GLuint video_capture_slot);
+GLAPI void APIENTRY glGetVideoCaptureivNV (GLuint video_capture_slot, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetVideoCaptureStreamivNV (GLuint video_capture_slot, GLuint stream, GLenum pname, GLint *params);
+GLAPI void APIENTRY glGetVideoCaptureStreamfvNV (GLuint video_capture_slot, GLuint stream, GLenum pname, GLfloat *params);
+GLAPI void APIENTRY glGetVideoCaptureStreamdvNV (GLuint video_capture_slot, GLuint stream, GLenum pname, GLdouble *params);
+GLAPI GLenum APIENTRY glVideoCaptureNV (GLuint video_capture_slot, GLuint *sequence_num, GLuint64EXT *capture_time);
+GLAPI void APIENTRY glVideoCaptureStreamParameterivNV (GLuint video_capture_slot, GLuint stream, GLenum pname, const GLint *params);
+GLAPI void APIENTRY glVideoCaptureStreamParameterfvNV (GLuint video_capture_slot, GLuint stream, GLenum pname, const GLfloat *params);
+GLAPI void APIENTRY glVideoCaptureStreamParameterdvNV (GLuint video_capture_slot, GLuint stream, GLenum pname, const GLdouble *params);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBEGINVIDEOCAPTURENVPROC) (GLuint video_capture_slot);
+typedef void (APIENTRYP PFNGLBINDVIDEOCAPTURESTREAMBUFFERNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum frame_region, GLintptrARB offset);
+typedef void (APIENTRYP PFNGLBINDVIDEOCAPTURESTREAMTEXTURENVPROC) (GLuint video_capture_slot, GLuint stream, GLenum frame_region, GLenum target, GLuint texture);
+typedef void (APIENTRYP PFNGLENDVIDEOCAPTURENVPROC) (GLuint video_capture_slot);
+typedef void (APIENTRYP PFNGLGETVIDEOCAPTUREIVNVPROC) (GLuint video_capture_slot, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETVIDEOCAPTURESTREAMIVNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETVIDEOCAPTURESTREAMFVNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETVIDEOCAPTURESTREAMDVNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum pname, GLdouble *params);
+typedef GLenum (APIENTRYP PFNGLVIDEOCAPTURENVPROC) (GLuint video_capture_slot, GLuint *sequence_num, GLuint64EXT *capture_time);
+typedef void (APIENTRYP PFNGLVIDEOCAPTURESTREAMPARAMETERIVNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLVIDEOCAPTURESTREAMPARAMETERFVNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLVIDEOCAPTURESTREAMPARAMETERDVNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum pname, const GLdouble *params);
+#endif
+
+#ifndef GL_NV_copy_image
+#define GL_NV_copy_image 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glCopyImageSubDataNV (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCOPYIMAGESUBDATANVPROC) (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth);
+#endif
+
+#ifndef GL_EXT_separate_shader_objects
+#define GL_EXT_separate_shader_objects 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glUseShaderProgramEXT (GLenum type, GLuint program);
+GLAPI void APIENTRY glActiveProgramEXT (GLuint program);
+GLAPI GLuint APIENTRY glCreateShaderProgramEXT (GLenum type, const GLchar *string);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLUSESHADERPROGRAMEXTPROC) (GLenum type, GLuint program);
+typedef void (APIENTRYP PFNGLACTIVEPROGRAMEXTPROC) (GLuint program);
+typedef GLuint (APIENTRYP PFNGLCREATESHADERPROGRAMEXTPROC) (GLenum type, const GLchar *string);
+#endif
+
+#ifndef GL_NV_parameter_buffer_object2
+#define GL_NV_parameter_buffer_object2 1
+#endif
+
+#ifndef GL_NV_shader_buffer_load
+#define GL_NV_shader_buffer_load 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glMakeBufferResidentNV (GLenum target, GLenum access);
+GLAPI void APIENTRY glMakeBufferNonResidentNV (GLenum target);
+GLAPI GLboolean APIENTRY glIsBufferResidentNV (GLenum target);
+GLAPI void APIENTRY glMakeNamedBufferResidentNV (GLuint buffer, GLenum access);
+GLAPI void APIENTRY glMakeNamedBufferNonResidentNV (GLuint buffer);
+GLAPI GLboolean APIENTRY glIsNamedBufferResidentNV (GLuint buffer);
+GLAPI void APIENTRY glGetBufferParameterui64vNV (GLenum target, GLenum pname, GLuint64EXT *params);
+GLAPI void APIENTRY glGetNamedBufferParameterui64vNV (GLuint buffer, GLenum pname, GLuint64EXT *params);
+GLAPI void APIENTRY glGetIntegerui64vNV (GLenum value, GLuint64EXT *result);
+GLAPI void APIENTRY glUniformui64NV (GLint location, GLuint64EXT value);
+GLAPI void APIENTRY glUniformui64vNV (GLint location, GLsizei count, const GLuint64EXT *value);
+GLAPI void APIENTRY glGetUniformui64vNV (GLuint program, GLint location, GLuint64EXT *params);
+GLAPI void APIENTRY glProgramUniformui64NV (GLuint program, GLint location, GLuint64EXT value);
+GLAPI void APIENTRY glProgramUniformui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLMAKEBUFFERRESIDENTNVPROC) (GLenum target, GLenum access);
+typedef void (APIENTRYP PFNGLMAKEBUFFERNONRESIDENTNVPROC) (GLenum target);
+typedef GLboolean (APIENTRYP PFNGLISBUFFERRESIDENTNVPROC) (GLenum target);
+typedef void (APIENTRYP PFNGLMAKENAMEDBUFFERRESIDENTNVPROC) (GLuint buffer, GLenum access);
+typedef void (APIENTRYP PFNGLMAKENAMEDBUFFERNONRESIDENTNVPROC) (GLuint buffer);
+typedef GLboolean (APIENTRYP PFNGLISNAMEDBUFFERRESIDENTNVPROC) (GLuint buffer);
+typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERUI64VNVPROC) (GLenum target, GLenum pname, GLuint64EXT *params);
+typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPARAMETERUI64VNVPROC) (GLuint buffer, GLenum pname, GLuint64EXT *params);
+typedef void (APIENTRYP PFNGLGETINTEGERUI64VNVPROC) (GLenum value, GLuint64EXT *result);
+typedef void (APIENTRYP PFNGLUNIFORMUI64NVPROC) (GLint location, GLuint64EXT value);
+typedef void (APIENTRYP PFNGLUNIFORMUI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value);
+typedef void (APIENTRYP PFNGLGETUNIFORMUI64VNVPROC) (GLuint program, GLint location, GLuint64EXT *params);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMUI64NVPROC) (GLuint program, GLint location, GLuint64EXT value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORMUI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value);
+#endif
+
+#ifndef GL_NV_vertex_buffer_unified_memory
+#define GL_NV_vertex_buffer_unified_memory 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBufferAddressRangeNV (GLenum pname, GLuint index, GLuint64EXT address, GLsizeiptr length);
+GLAPI void APIENTRY glVertexFormatNV (GLint size, GLenum type, GLsizei stride);
+GLAPI void APIENTRY glNormalFormatNV (GLenum type, GLsizei stride);
+GLAPI void APIENTRY glColorFormatNV (GLint size, GLenum type, GLsizei stride);
+GLAPI void APIENTRY glIndexFormatNV (GLenum type, GLsizei stride);
+GLAPI void APIENTRY glTexCoordFormatNV (GLint size, GLenum type, GLsizei stride);
+GLAPI void APIENTRY glEdgeFlagFormatNV (GLsizei stride);
+GLAPI void APIENTRY glSecondaryColorFormatNV (GLint size, GLenum type, GLsizei stride);
+GLAPI void APIENTRY glFogCoordFormatNV (GLenum type, GLsizei stride);
+GLAPI void APIENTRY glVertexAttribFormatNV (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride);
+GLAPI void APIENTRY glVertexAttribIFormatNV (GLuint index, GLint size, GLenum type, GLsizei stride);
+GLAPI void APIENTRY glGetIntegerui64i_vNV (GLenum value, GLuint index, GLuint64EXT *result);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBUFFERADDRESSRANGENVPROC) (GLenum pname, GLuint index, GLuint64EXT address, GLsizeiptr length);
+typedef void (APIENTRYP PFNGLVERTEXFORMATNVPROC) (GLint size, GLenum type, GLsizei stride);
+typedef void (APIENTRYP PFNGLNORMALFORMATNVPROC) (GLenum type, GLsizei stride);
+typedef void (APIENTRYP PFNGLCOLORFORMATNVPROC) (GLint size, GLenum type, GLsizei stride);
+typedef void (APIENTRYP PFNGLINDEXFORMATNVPROC) (GLenum type, GLsizei stride);
+typedef void (APIENTRYP PFNGLTEXCOORDFORMATNVPROC) (GLint size, GLenum type, GLsizei stride);
+typedef void (APIENTRYP PFNGLEDGEFLAGFORMATNVPROC) (GLsizei stride);
+typedef void (APIENTRYP PFNGLSECONDARYCOLORFORMATNVPROC) (GLint size, GLenum type, GLsizei stride);
+typedef void (APIENTRYP PFNGLFOGCOORDFORMATNVPROC) (GLenum type, GLsizei stride);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBFORMATNVPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBIFORMATNVPROC) (GLuint index, GLint size, GLenum type, GLsizei stride);
+typedef void (APIENTRYP PFNGLGETINTEGERUI64I_VNVPROC) (GLenum value, GLuint index, GLuint64EXT *result);
+#endif
+
+#ifndef GL_NV_texture_barrier
+#define GL_NV_texture_barrier 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glTextureBarrierNV (void);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLTEXTUREBARRIERNVPROC) (void);
+#endif
+
+#ifndef GL_AMD_shader_stencil_export
+#define GL_AMD_shader_stencil_export 1
+#endif
+
+#ifndef GL_AMD_seamless_cubemap_per_texture
+#define GL_AMD_seamless_cubemap_per_texture 1
+#endif
+
+#ifndef GL_AMD_conservative_depth
+#define GL_AMD_conservative_depth 1
+#endif
+
+#ifndef GL_EXT_shader_image_load_store
+#define GL_EXT_shader_image_load_store 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBindImageTextureEXT (GLuint index, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLint format);
+GLAPI void APIENTRY glMemoryBarrierEXT (GLbitfield barriers);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBINDIMAGETEXTUREEXTPROC) (GLuint index, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLint format);
+typedef void (APIENTRYP PFNGLMEMORYBARRIEREXTPROC) (GLbitfield barriers);
+#endif
+
+#ifndef GL_EXT_vertex_attrib_64bit
+#define GL_EXT_vertex_attrib_64bit 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glVertexAttribL1dEXT (GLuint index, GLdouble x);
+GLAPI void APIENTRY glVertexAttribL2dEXT (GLuint index, GLdouble x, GLdouble y);
+GLAPI void APIENTRY glVertexAttribL3dEXT (GLuint index, GLdouble x, GLdouble y, GLdouble z);
+GLAPI void APIENTRY glVertexAttribL4dEXT (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+GLAPI void APIENTRY glVertexAttribL1dvEXT (GLuint index, const GLdouble *v);
+GLAPI void APIENTRY glVertexAttribL2dvEXT (GLuint index, const GLdouble *v);
+GLAPI void APIENTRY glVertexAttribL3dvEXT (GLuint index, const GLdouble *v);
+GLAPI void APIENTRY glVertexAttribL4dvEXT (GLuint index, const GLdouble *v);
+GLAPI void APIENTRY glVertexAttribLPointerEXT (GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+GLAPI void APIENTRY glGetVertexAttribLdvEXT (GLuint index, GLenum pname, GLdouble *params);
+GLAPI void APIENTRY glVertexArrayVertexAttribLOffsetEXT (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL1DEXTPROC) (GLuint index, GLdouble x);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL2DEXTPROC) (GLuint index, GLdouble x, GLdouble y);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL3DEXTPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL4DEXTPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL1DVEXTPROC) (GLuint index, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL2DVEXTPROC) (GLuint index, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL3DVEXTPROC) (GLuint index, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL4DVEXTPROC) (GLuint index, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBLPOINTEREXTPROC) (GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBLDVEXTPROC) (GLuint index, GLenum pname, GLdouble *params);
+typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBLOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset);
+#endif
+
+#ifndef GL_NV_gpu_program5
+#define GL_NV_gpu_program5 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glProgramSubroutineParametersuivNV (GLenum target, GLsizei count, const GLuint *params);
+GLAPI void APIENTRY glGetProgramSubroutineParameteruivNV (GLenum target, GLuint index, GLuint *param);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPROGRAMSUBROUTINEPARAMETERSUIVNVPROC) (GLenum target, GLsizei count, const GLuint *params);
+typedef void (APIENTRYP PFNGLGETPROGRAMSUBROUTINEPARAMETERUIVNVPROC) (GLenum target, GLuint index, GLuint *param);
+#endif
+
+#ifndef GL_NV_gpu_shader5
+#define GL_NV_gpu_shader5 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glUniform1i64NV (GLint location, GLint64EXT x);
+GLAPI void APIENTRY glUniform2i64NV (GLint location, GLint64EXT x, GLint64EXT y);
+GLAPI void APIENTRY glUniform3i64NV (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z);
+GLAPI void APIENTRY glUniform4i64NV (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w);
+GLAPI void APIENTRY glUniform1i64vNV (GLint location, GLsizei count, const GLint64EXT *value);
+GLAPI void APIENTRY glUniform2i64vNV (GLint location, GLsizei count, const GLint64EXT *value);
+GLAPI void APIENTRY glUniform3i64vNV (GLint location, GLsizei count, const GLint64EXT *value);
+GLAPI void APIENTRY glUniform4i64vNV (GLint location, GLsizei count, const GLint64EXT *value);
+GLAPI void APIENTRY glUniform1ui64NV (GLint location, GLuint64EXT x);
+GLAPI void APIENTRY glUniform2ui64NV (GLint location, GLuint64EXT x, GLuint64EXT y);
+GLAPI void APIENTRY glUniform3ui64NV (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z);
+GLAPI void APIENTRY glUniform4ui64NV (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w);
+GLAPI void APIENTRY glUniform1ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value);
+GLAPI void APIENTRY glUniform2ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value);
+GLAPI void APIENTRY glUniform3ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value);
+GLAPI void APIENTRY glUniform4ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value);
+GLAPI void APIENTRY glGetUniformi64vNV (GLuint program, GLint location, GLint64EXT *params);
+GLAPI void APIENTRY glProgramUniform1i64NV (GLuint program, GLint location, GLint64EXT x);
+GLAPI void APIENTRY glProgramUniform2i64NV (GLuint program, GLint location, GLint64EXT x, GLint64EXT y);
+GLAPI void APIENTRY glProgramUniform3i64NV (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z);
+GLAPI void APIENTRY glProgramUniform4i64NV (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w);
+GLAPI void APIENTRY glProgramUniform1i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value);
+GLAPI void APIENTRY glProgramUniform2i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value);
+GLAPI void APIENTRY glProgramUniform3i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value);
+GLAPI void APIENTRY glProgramUniform4i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value);
+GLAPI void APIENTRY glProgramUniform1ui64NV (GLuint program, GLint location, GLuint64EXT x);
+GLAPI void APIENTRY glProgramUniform2ui64NV (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y);
+GLAPI void APIENTRY glProgramUniform3ui64NV (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z);
+GLAPI void APIENTRY glProgramUniform4ui64NV (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w);
+GLAPI void APIENTRY glProgramUniform1ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value);
+GLAPI void APIENTRY glProgramUniform2ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value);
+GLAPI void APIENTRY glProgramUniform3ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value);
+GLAPI void APIENTRY glProgramUniform4ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLUNIFORM1I64NVPROC) (GLint location, GLint64EXT x);
+typedef void (APIENTRYP PFNGLUNIFORM2I64NVPROC) (GLint location, GLint64EXT x, GLint64EXT y);
+typedef void (APIENTRYP PFNGLUNIFORM3I64NVPROC) (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z);
+typedef void (APIENTRYP PFNGLUNIFORM4I64NVPROC) (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w);
+typedef void (APIENTRYP PFNGLUNIFORM1I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value);
+typedef void (APIENTRYP PFNGLUNIFORM2I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value);
+typedef void (APIENTRYP PFNGLUNIFORM3I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value);
+typedef void (APIENTRYP PFNGLUNIFORM4I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value);
+typedef void (APIENTRYP PFNGLUNIFORM1UI64NVPROC) (GLint location, GLuint64EXT x);
+typedef void (APIENTRYP PFNGLUNIFORM2UI64NVPROC) (GLint location, GLuint64EXT x, GLuint64EXT y);
+typedef void (APIENTRYP PFNGLUNIFORM3UI64NVPROC) (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z);
+typedef void (APIENTRYP PFNGLUNIFORM4UI64NVPROC) (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w);
+typedef void (APIENTRYP PFNGLUNIFORM1UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value);
+typedef void (APIENTRYP PFNGLUNIFORM2UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value);
+typedef void (APIENTRYP PFNGLUNIFORM3UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value);
+typedef void (APIENTRYP PFNGLUNIFORM4UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value);
+typedef void (APIENTRYP PFNGLGETUNIFORMI64VNVPROC) (GLuint program, GLint location, GLint64EXT *params);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1I64NVPROC) (GLuint program, GLint location, GLint64EXT x);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2I64NVPROC) (GLuint program, GLint location, GLint64EXT x, GLint64EXT y);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3I64NVPROC) (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4I64NVPROC) (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value);
+typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value);
+#endif
+
+#ifndef GL_NV_shader_buffer_store
+#define GL_NV_shader_buffer_store 1
+#endif
+
+#ifndef GL_NV_tessellation_program5
+#define GL_NV_tessellation_program5 1
+#endif
+
+#ifndef GL_NV_vertex_attrib_integer_64bit
+#define GL_NV_vertex_attrib_integer_64bit 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glVertexAttribL1i64NV (GLuint index, GLint64EXT x);
+GLAPI void APIENTRY glVertexAttribL2i64NV (GLuint index, GLint64EXT x, GLint64EXT y);
+GLAPI void APIENTRY glVertexAttribL3i64NV (GLuint index, GLint64EXT x, GLint64EXT y, GLint64EXT z);
+GLAPI void APIENTRY glVertexAttribL4i64NV (GLuint index, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w);
+GLAPI void APIENTRY glVertexAttribL1i64vNV (GLuint index, const GLint64EXT *v);
+GLAPI void APIENTRY glVertexAttribL2i64vNV (GLuint index, const GLint64EXT *v);
+GLAPI void APIENTRY glVertexAttribL3i64vNV (GLuint index, const GLint64EXT *v);
+GLAPI void APIENTRY glVertexAttribL4i64vNV (GLuint index, const GLint64EXT *v);
+GLAPI void APIENTRY glVertexAttribL1ui64NV (GLuint index, GLuint64EXT x);
+GLAPI void APIENTRY glVertexAttribL2ui64NV (GLuint index, GLuint64EXT x, GLuint64EXT y);
+GLAPI void APIENTRY glVertexAttribL3ui64NV (GLuint index, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z);
+GLAPI void APIENTRY glVertexAttribL4ui64NV (GLuint index, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w);
+GLAPI void APIENTRY glVertexAttribL1ui64vNV (GLuint index, const GLuint64EXT *v);
+GLAPI void APIENTRY glVertexAttribL2ui64vNV (GLuint index, const GLuint64EXT *v);
+GLAPI void APIENTRY glVertexAttribL3ui64vNV (GLuint index, const GLuint64EXT *v);
+GLAPI void APIENTRY glVertexAttribL4ui64vNV (GLuint index, const GLuint64EXT *v);
+GLAPI void APIENTRY glGetVertexAttribLi64vNV (GLuint index, GLenum pname, GLint64EXT *params);
+GLAPI void APIENTRY glGetVertexAttribLui64vNV (GLuint index, GLenum pname, GLuint64EXT *params);
+GLAPI void APIENTRY glVertexAttribLFormatNV (GLuint index, GLint size, GLenum type, GLsizei stride);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL1I64NVPROC) (GLuint index, GLint64EXT x);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL2I64NVPROC) (GLuint index, GLint64EXT x, GLint64EXT y);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL3I64NVPROC) (GLuint index, GLint64EXT x, GLint64EXT y, GLint64EXT z);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL4I64NVPROC) (GLuint index, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL1I64VNVPROC) (GLuint index, const GLint64EXT *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL2I64VNVPROC) (GLuint index, const GLint64EXT *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL3I64VNVPROC) (GLuint index, const GLint64EXT *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL4I64VNVPROC) (GLuint index, const GLint64EXT *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL1UI64NVPROC) (GLuint index, GLuint64EXT x);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL2UI64NVPROC) (GLuint index, GLuint64EXT x, GLuint64EXT y);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL3UI64NVPROC) (GLuint index, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL4UI64NVPROC) (GLuint index, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL1UI64VNVPROC) (GLuint index, const GLuint64EXT *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL2UI64VNVPROC) (GLuint index, const GLuint64EXT *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL3UI64VNVPROC) (GLuint index, const GLuint64EXT *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBL4UI64VNVPROC) (GLuint index, const GLuint64EXT *v);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBLI64VNVPROC) (GLuint index, GLenum pname, GLint64EXT *params);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBLUI64VNVPROC) (GLuint index, GLenum pname, GLuint64EXT *params);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBLFORMATNVPROC) (GLuint index, GLint size, GLenum type, GLsizei stride);
+#endif
+
+#ifndef GL_NV_multisample_coverage
+#define GL_NV_multisample_coverage 1
+#endif
+
+#ifndef GL_AMD_name_gen_delete
+#define GL_AMD_name_gen_delete 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glGenNamesAMD (GLenum identifier, GLuint num, GLuint *names);
+GLAPI void APIENTRY glDeleteNamesAMD (GLenum identifier, GLuint num, const GLuint *names);
+GLAPI GLboolean APIENTRY glIsNameAMD (GLenum identifier, GLuint name);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLGENNAMESAMDPROC) (GLenum identifier, GLuint num, GLuint *names);
+typedef void (APIENTRYP PFNGLDELETENAMESAMDPROC) (GLenum identifier, GLuint num, const GLuint *names);
+typedef GLboolean (APIENTRYP PFNGLISNAMEAMDPROC) (GLenum identifier, GLuint name);
+#endif
+
+#ifndef GL_AMD_debug_output
+#define GL_AMD_debug_output 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glDebugMessageEnableAMD (GLenum category, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled);
+GLAPI void APIENTRY glDebugMessageInsertAMD (GLenum category, GLenum severity, GLuint id, GLsizei length, const GLchar *buf);
+GLAPI void APIENTRY glDebugMessageCallbackAMD (GLDEBUGPROCAMD callback, GLvoid *userParam);
+GLAPI GLuint APIENTRY glGetDebugMessageLogAMD (GLuint count, GLsizei bufsize, GLenum *categories, GLuint *severities, GLuint *ids, GLsizei *lengths, GLchar *message);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLDEBUGMESSAGEENABLEAMDPROC) (GLenum category, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled);
+typedef void (APIENTRYP PFNGLDEBUGMESSAGEINSERTAMDPROC) (GLenum category, GLenum severity, GLuint id, GLsizei length, const GLchar *buf);
+typedef void (APIENTRYP PFNGLDEBUGMESSAGECALLBACKAMDPROC) (GLDEBUGPROCAMD callback, GLvoid *userParam);
+typedef GLuint (APIENTRYP PFNGLGETDEBUGMESSAGELOGAMDPROC) (GLuint count, GLsizei bufsize, GLenum *categories, GLuint *severities, GLuint *ids, GLsizei *lengths, GLchar *message);
+#endif
+
+#ifndef GL_NV_vdpau_interop
+#define GL_NV_vdpau_interop 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glVDPAUInitNV (const GLvoid *vdpDevice, const GLvoid *getProcAddress);
+GLAPI void APIENTRY glVDPAUFiniNV (void);
+GLAPI GLvdpauSurfaceNV APIENTRY glVDPAURegisterVideoSurfaceNV (GLvoid *vdpSurface, GLenum target, GLsizei numTextureNames, const GLuint *textureNames);
+GLAPI GLvdpauSurfaceNV APIENTRY glVDPAURegisterOutputSurfaceNV (GLvoid *vdpSurface, GLenum target, GLsizei numTextureNames, const GLuint *textureNames);
+GLAPI void APIENTRY glVDPAUIsSurfaceNV (GLvdpauSurfaceNV surface);
+GLAPI void APIENTRY glVDPAUUnregisterSurfaceNV (GLvdpauSurfaceNV surface);
+GLAPI void APIENTRY glVDPAUGetSurfaceivNV (GLvdpauSurfaceNV surface, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values);
+GLAPI void APIENTRY glVDPAUSurfaceAccessNV (GLvdpauSurfaceNV surface, GLenum access);
+GLAPI void APIENTRY glVDPAUMapSurfacesNV (GLsizei numSurfaces, const GLvdpauSurfaceNV *surfaces);
+GLAPI void APIENTRY glVDPAUUnmapSurfacesNV (GLsizei numSurface, const GLvdpauSurfaceNV *surfaces);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLVDPAUINITNVPROC) (const GLvoid *vdpDevice, const GLvoid *getProcAddress);
+typedef void (APIENTRYP PFNGLVDPAUFININVPROC) (void);
+typedef GLvdpauSurfaceNV (APIENTRYP PFNGLVDPAUREGISTERVIDEOSURFACENVPROC) (GLvoid *vdpSurface, GLenum target, GLsizei numTextureNames, const GLuint *textureNames);
+typedef GLvdpauSurfaceNV (APIENTRYP PFNGLVDPAUREGISTEROUTPUTSURFACENVPROC) (GLvoid *vdpSurface, GLenum target, GLsizei numTextureNames, const GLuint *textureNames);
+typedef void (APIENTRYP PFNGLVDPAUISSURFACENVPROC) (GLvdpauSurfaceNV surface);
+typedef void (APIENTRYP PFNGLVDPAUUNREGISTERSURFACENVPROC) (GLvdpauSurfaceNV surface);
+typedef void (APIENTRYP PFNGLVDPAUGETSURFACEIVNVPROC) (GLvdpauSurfaceNV surface, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values);
+typedef void (APIENTRYP PFNGLVDPAUSURFACEACCESSNVPROC) (GLvdpauSurfaceNV surface, GLenum access);
+typedef void (APIENTRYP PFNGLVDPAUMAPSURFACESNVPROC) (GLsizei numSurfaces, const GLvdpauSurfaceNV *surfaces);
+typedef void (APIENTRYP PFNGLVDPAUUNMAPSURFACESNVPROC) (GLsizei numSurface, const GLvdpauSurfaceNV *surfaces);
+#endif
+
+#ifndef GL_AMD_transform_feedback3_lines_triangles
+#define GL_AMD_transform_feedback3_lines_triangles 1
+#endif
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/src/SFML/Window/glext/glxext.h b/src/SFML/Window/glext/glxext.h
new file mode 100644
index 0000000..3c47dc3
--- /dev/null
+++ b/src/SFML/Window/glext/glxext.h
@@ -0,0 +1,993 @@
+#ifndef __glxext_h_
+#define __glxext_h_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+** Copyright (c) 2007-2010 The Khronos Group Inc.
+**
+** Permission is hereby granted, free of charge, to any person obtaining a
+** copy of this software and/or associated documentation files (the
+** "Materials"), to deal in the Materials without restriction, including
+** without limitation the rights to use, copy, modify, merge, publish,
+** distribute, sublicense, and/or sell copies of the Materials, and to
+** permit persons to whom the Materials are furnished to do so, subject to
+** the following conditions:
+**
+** The above copyright notice and this permission notice shall be included
+** in all copies or substantial portions of the Materials.
+**
+** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
+*/
+
+/* Function declaration macros - to move into glplatform.h */
+
+#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__)
+#define WIN32_LEAN_AND_MEAN 1
+#include <windows.h>
+#endif
+
+#ifndef APIENTRY
+#define APIENTRY
+#endif
+#ifndef APIENTRYP
+#define APIENTRYP APIENTRY *
+#endif
+#ifndef GLAPI
+#define GLAPI extern
+#endif
+
+/*************************************************************/
+
+/* Header file version number, required by OpenGL ABI for Linux */
+/* glxext.h last updated 2010/08/06 */
+/* Current version at http://www.opengl.org/registry/ */
+#define GLX_GLXEXT_VERSION 32
+
+#ifndef GLX_VERSION_1_3
+#define GLX_WINDOW_BIT 0x00000001
+#define GLX_PIXMAP_BIT 0x00000002
+#define GLX_PBUFFER_BIT 0x00000004
+#define GLX_RGBA_BIT 0x00000001
+#define GLX_COLOR_INDEX_BIT 0x00000002
+#define GLX_PBUFFER_CLOBBER_MASK 0x08000000
+#define GLX_FRONT_LEFT_BUFFER_BIT 0x00000001
+#define GLX_FRONT_RIGHT_BUFFER_BIT 0x00000002
+#define GLX_BACK_LEFT_BUFFER_BIT 0x00000004
+#define GLX_BACK_RIGHT_BUFFER_BIT 0x00000008
+#define GLX_AUX_BUFFERS_BIT 0x00000010
+#define GLX_DEPTH_BUFFER_BIT 0x00000020
+#define GLX_STENCIL_BUFFER_BIT 0x00000040
+#define GLX_ACCUM_BUFFER_BIT 0x00000080
+#define GLX_CONFIG_CAVEAT 0x20
+#define GLX_X_VISUAL_TYPE 0x22
+#define GLX_TRANSPARENT_TYPE 0x23
+#define GLX_TRANSPARENT_INDEX_VALUE 0x24
+#define GLX_TRANSPARENT_RED_VALUE 0x25
+#define GLX_TRANSPARENT_GREEN_VALUE 0x26
+#define GLX_TRANSPARENT_BLUE_VALUE 0x27
+#define GLX_TRANSPARENT_ALPHA_VALUE 0x28
+#define GLX_DONT_CARE 0xFFFFFFFF
+#define GLX_NONE 0x8000
+#define GLX_SLOW_CONFIG 0x8001
+#define GLX_TRUE_COLOR 0x8002
+#define GLX_DIRECT_COLOR 0x8003
+#define GLX_PSEUDO_COLOR 0x8004
+#define GLX_STATIC_COLOR 0x8005
+#define GLX_GRAY_SCALE 0x8006
+#define GLX_STATIC_GRAY 0x8007
+#define GLX_TRANSPARENT_RGB 0x8008
+#define GLX_TRANSPARENT_INDEX 0x8009
+#define GLX_VISUAL_ID 0x800B
+#define GLX_SCREEN 0x800C
+#define GLX_NON_CONFORMANT_CONFIG 0x800D
+#define GLX_DRAWABLE_TYPE 0x8010
+#define GLX_RENDER_TYPE 0x8011
+#define GLX_X_RENDERABLE 0x8012
+#define GLX_FBCONFIG_ID 0x8013
+#define GLX_RGBA_TYPE 0x8014
+#define GLX_COLOR_INDEX_TYPE 0x8015
+#define GLX_MAX_PBUFFER_WIDTH 0x8016
+#define GLX_MAX_PBUFFER_HEIGHT 0x8017
+#define GLX_MAX_PBUFFER_PIXELS 0x8018
+#define GLX_PRESERVED_CONTENTS 0x801B
+#define GLX_LARGEST_PBUFFER 0x801C
+#define GLX_WIDTH 0x801D
+#define GLX_HEIGHT 0x801E
+#define GLX_EVENT_MASK 0x801F
+#define GLX_DAMAGED 0x8020
+#define GLX_SAVED 0x8021
+#define GLX_WINDOW 0x8022
+#define GLX_PBUFFER 0x8023
+#define GLX_PBUFFER_HEIGHT 0x8040
+#define GLX_PBUFFER_WIDTH 0x8041
+#endif
+
+#ifndef GLX_VERSION_1_4
+#define GLX_SAMPLE_BUFFERS 100000
+#define GLX_SAMPLES 100001
+#endif
+
+#ifndef GLX_ARB_get_proc_address
+#endif
+
+#ifndef GLX_ARB_multisample
+#define GLX_SAMPLE_BUFFERS_ARB 100000
+#define GLX_SAMPLES_ARB 100001
+#endif
+
+#ifndef GLX_ARB_vertex_buffer_object
+#define GLX_CONTEXT_ALLOW_BUFFER_BYTE_ORDER_MISMATCH_ARB 0x2095
+#endif
+
+#ifndef GLX_ARB_fbconfig_float
+#define GLX_RGBA_FLOAT_TYPE_ARB 0x20B9
+#define GLX_RGBA_FLOAT_BIT_ARB 0x00000004
+#endif
+
+#ifndef GLX_ARB_framebuffer_sRGB
+#define GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB 0x20B2
+#endif
+
+#ifndef GLX_ARB_create_context
+#define GLX_CONTEXT_DEBUG_BIT_ARB 0x00000001
+#define GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x00000002
+#define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091
+#define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092
+#define GLX_CONTEXT_FLAGS_ARB 0x2094
+#endif
+
+#ifndef GLX_ARB_create_context_profile
+#define GLX_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
+#define GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002
+#define GLX_CONTEXT_PROFILE_MASK_ARB 0x9126
+#endif
+
+#ifndef GLX_ARB_create_context_robustness
+#define GLX_CONTEXT_ROBUST_ACCESS_BIT_ARB 0x00000004
+#define GLX_LOSE_CONTEXT_ON_RESET_ARB 0x8252
+#define GLX_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB 0x8256
+#define GLX_NO_RESET_NOTIFICATION_ARB 0x8261
+#endif
+
+#ifndef GLX_SGIS_multisample
+#define GLX_SAMPLE_BUFFERS_SGIS 100000
+#define GLX_SAMPLES_SGIS 100001
+#endif
+
+#ifndef GLX_EXT_visual_info
+#define GLX_X_VISUAL_TYPE_EXT 0x22
+#define GLX_TRANSPARENT_TYPE_EXT 0x23
+#define GLX_TRANSPARENT_INDEX_VALUE_EXT 0x24
+#define GLX_TRANSPARENT_RED_VALUE_EXT 0x25
+#define GLX_TRANSPARENT_GREEN_VALUE_EXT 0x26
+#define GLX_TRANSPARENT_BLUE_VALUE_EXT 0x27
+#define GLX_TRANSPARENT_ALPHA_VALUE_EXT 0x28
+#define GLX_NONE_EXT 0x8000
+#define GLX_TRUE_COLOR_EXT 0x8002
+#define GLX_DIRECT_COLOR_EXT 0x8003
+#define GLX_PSEUDO_COLOR_EXT 0x8004
+#define GLX_STATIC_COLOR_EXT 0x8005
+#define GLX_GRAY_SCALE_EXT 0x8006
+#define GLX_STATIC_GRAY_EXT 0x8007
+#define GLX_TRANSPARENT_RGB_EXT 0x8008
+#define GLX_TRANSPARENT_INDEX_EXT 0x8009
+#endif
+
+#ifndef GLX_SGI_swap_control
+#endif
+
+#ifndef GLX_SGI_video_sync
+#endif
+
+#ifndef GLX_SGI_make_current_read
+#endif
+
+#ifndef GLX_SGIX_video_source
+#endif
+
+#ifndef GLX_EXT_visual_rating
+#define GLX_VISUAL_CAVEAT_EXT 0x20
+#define GLX_SLOW_VISUAL_EXT 0x8001
+#define GLX_NON_CONFORMANT_VISUAL_EXT 0x800D
+/* reuse GLX_NONE_EXT */
+#endif
+
+#ifndef GLX_EXT_import_context
+#define GLX_SHARE_CONTEXT_EXT 0x800A
+#define GLX_VISUAL_ID_EXT 0x800B
+#define GLX_SCREEN_EXT 0x800C
+#endif
+
+#ifndef GLX_SGIX_fbconfig
+#define GLX_WINDOW_BIT_SGIX 0x00000001
+#define GLX_PIXMAP_BIT_SGIX 0x00000002
+#define GLX_RGBA_BIT_SGIX 0x00000001
+#define GLX_COLOR_INDEX_BIT_SGIX 0x00000002
+#define GLX_DRAWABLE_TYPE_SGIX 0x8010
+#define GLX_RENDER_TYPE_SGIX 0x8011
+#define GLX_X_RENDERABLE_SGIX 0x8012
+#define GLX_FBCONFIG_ID_SGIX 0x8013
+#define GLX_RGBA_TYPE_SGIX 0x8014
+#define GLX_COLOR_INDEX_TYPE_SGIX 0x8015
+/* reuse GLX_SCREEN_EXT */
+#endif
+
+#ifndef GLX_SGIX_pbuffer
+#define GLX_PBUFFER_BIT_SGIX 0x00000004
+#define GLX_BUFFER_CLOBBER_MASK_SGIX 0x08000000
+#define GLX_FRONT_LEFT_BUFFER_BIT_SGIX 0x00000001
+#define GLX_FRONT_RIGHT_BUFFER_BIT_SGIX 0x00000002
+#define GLX_BACK_LEFT_BUFFER_BIT_SGIX 0x00000004
+#define GLX_BACK_RIGHT_BUFFER_BIT_SGIX 0x00000008
+#define GLX_AUX_BUFFERS_BIT_SGIX 0x00000010
+#define GLX_DEPTH_BUFFER_BIT_SGIX 0x00000020
+#define GLX_STENCIL_BUFFER_BIT_SGIX 0x00000040
+#define GLX_ACCUM_BUFFER_BIT_SGIX 0x00000080
+#define GLX_SAMPLE_BUFFERS_BIT_SGIX 0x00000100
+#define GLX_MAX_PBUFFER_WIDTH_SGIX 0x8016
+#define GLX_MAX_PBUFFER_HEIGHT_SGIX 0x8017
+#define GLX_MAX_PBUFFER_PIXELS_SGIX 0x8018
+#define GLX_OPTIMAL_PBUFFER_WIDTH_SGIX 0x8019
+#define GLX_OPTIMAL_PBUFFER_HEIGHT_SGIX 0x801A
+#define GLX_PRESERVED_CONTENTS_SGIX 0x801B
+#define GLX_LARGEST_PBUFFER_SGIX 0x801C
+#define GLX_WIDTH_SGIX 0x801D
+#define GLX_HEIGHT_SGIX 0x801E
+#define GLX_EVENT_MASK_SGIX 0x801F
+#define GLX_DAMAGED_SGIX 0x8020
+#define GLX_SAVED_SGIX 0x8021
+#define GLX_WINDOW_SGIX 0x8022
+#define GLX_PBUFFER_SGIX 0x8023
+#endif
+
+#ifndef GLX_SGI_cushion
+#endif
+
+#ifndef GLX_SGIX_video_resize
+#define GLX_SYNC_FRAME_SGIX 0x00000000
+#define GLX_SYNC_SWAP_SGIX 0x00000001
+#endif
+
+#ifndef GLX_SGIX_dmbuffer
+#define GLX_DIGITAL_MEDIA_PBUFFER_SGIX 0x8024
+#endif
+
+#ifndef GLX_SGIX_swap_group
+#endif
+
+#ifndef GLX_SGIX_swap_barrier
+#endif
+
+#ifndef GLX_SGIS_blended_overlay
+#define GLX_BLENDED_RGBA_SGIS 0x8025
+#endif
+
+#ifndef GLX_SGIS_shared_multisample
+#define GLX_MULTISAMPLE_SUB_RECT_WIDTH_SGIS 0x8026
+#define GLX_MULTISAMPLE_SUB_RECT_HEIGHT_SGIS 0x8027
+#endif
+
+#ifndef GLX_SUN_get_transparent_index
+#endif
+
+#ifndef GLX_3DFX_multisample
+#define GLX_SAMPLE_BUFFERS_3DFX 0x8050
+#define GLX_SAMPLES_3DFX 0x8051
+#endif
+
+#ifndef GLX_MESA_copy_sub_buffer
+#endif
+
+#ifndef GLX_MESA_pixmap_colormap
+#endif
+
+#ifndef GLX_MESA_release_buffers
+#endif
+
+#ifndef GLX_MESA_set_3dfx_mode
+#define GLX_3DFX_WINDOW_MODE_MESA 0x1
+#define GLX_3DFX_FULLSCREEN_MODE_MESA 0x2
+#endif
+
+#ifndef GLX_SGIX_visual_select_group
+#define GLX_VISUAL_SELECT_GROUP_SGIX 0x8028
+#endif
+
+#ifndef GLX_OML_swap_method
+#define GLX_SWAP_METHOD_OML 0x8060
+#define GLX_SWAP_EXCHANGE_OML 0x8061
+#define GLX_SWAP_COPY_OML 0x8062
+#define GLX_SWAP_UNDEFINED_OML 0x8063
+#endif
+
+#ifndef GLX_OML_sync_control
+#endif
+
+#ifndef GLX_NV_float_buffer
+#define GLX_FLOAT_COMPONENTS_NV 0x20B0
+#endif
+
+#ifndef GLX_SGIX_hyperpipe
+#define GLX_HYPERPIPE_PIPE_NAME_LENGTH_SGIX 80
+#define GLX_BAD_HYPERPIPE_CONFIG_SGIX 91
+#define GLX_BAD_HYPERPIPE_SGIX 92
+#define GLX_HYPERPIPE_DISPLAY_PIPE_SGIX 0x00000001
+#define GLX_HYPERPIPE_RENDER_PIPE_SGIX 0x00000002
+#define GLX_PIPE_RECT_SGIX 0x00000001
+#define GLX_PIPE_RECT_LIMITS_SGIX 0x00000002
+#define GLX_HYPERPIPE_STEREO_SGIX 0x00000003
+#define GLX_HYPERPIPE_PIXEL_AVERAGE_SGIX 0x00000004
+#define GLX_HYPERPIPE_ID_SGIX 0x8030
+#endif
+
+#ifndef GLX_MESA_agp_offset
+#endif
+
+#ifndef GLX_EXT_fbconfig_packed_float
+#define GLX_RGBA_UNSIGNED_FLOAT_TYPE_EXT 0x20B1
+#define GLX_RGBA_UNSIGNED_FLOAT_BIT_EXT 0x00000008
+#endif
+
+#ifndef GLX_EXT_framebuffer_sRGB
+#define GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT 0x20B2
+#endif
+
+#ifndef GLX_EXT_texture_from_pixmap
+#define GLX_TEXTURE_1D_BIT_EXT 0x00000001
+#define GLX_TEXTURE_2D_BIT_EXT 0x00000002
+#define GLX_TEXTURE_RECTANGLE_BIT_EXT 0x00000004
+#define GLX_BIND_TO_TEXTURE_RGB_EXT 0x20D0
+#define GLX_BIND_TO_TEXTURE_RGBA_EXT 0x20D1
+#define GLX_BIND_TO_MIPMAP_TEXTURE_EXT 0x20D2
+#define GLX_BIND_TO_TEXTURE_TARGETS_EXT 0x20D3
+#define GLX_Y_INVERTED_EXT 0x20D4
+#define GLX_TEXTURE_FORMAT_EXT 0x20D5
+#define GLX_TEXTURE_TARGET_EXT 0x20D6
+#define GLX_MIPMAP_TEXTURE_EXT 0x20D7
+#define GLX_TEXTURE_FORMAT_NONE_EXT 0x20D8
+#define GLX_TEXTURE_FORMAT_RGB_EXT 0x20D9
+#define GLX_TEXTURE_FORMAT_RGBA_EXT 0x20DA
+#define GLX_TEXTURE_1D_EXT 0x20DB
+#define GLX_TEXTURE_2D_EXT 0x20DC
+#define GLX_TEXTURE_RECTANGLE_EXT 0x20DD
+#define GLX_FRONT_LEFT_EXT 0x20DE
+#define GLX_FRONT_RIGHT_EXT 0x20DF
+#define GLX_BACK_LEFT_EXT 0x20E0
+#define GLX_BACK_RIGHT_EXT 0x20E1
+#define GLX_FRONT_EXT GLX_FRONT_LEFT_EXT
+#define GLX_BACK_EXT GLX_BACK_LEFT_EXT
+#define GLX_AUX0_EXT 0x20E2
+#define GLX_AUX1_EXT 0x20E3
+#define GLX_AUX2_EXT 0x20E4
+#define GLX_AUX3_EXT 0x20E5
+#define GLX_AUX4_EXT 0x20E6
+#define GLX_AUX5_EXT 0x20E7
+#define GLX_AUX6_EXT 0x20E8
+#define GLX_AUX7_EXT 0x20E9
+#define GLX_AUX8_EXT 0x20EA
+#define GLX_AUX9_EXT 0x20EB
+#endif
+
+#ifndef GLX_NV_present_video
+#define GLX_NUM_VIDEO_SLOTS_NV 0x20F0
+#endif
+
+#ifndef GLX_NV_video_out
+#define GLX_VIDEO_OUT_COLOR_NV 0x20C3
+#define GLX_VIDEO_OUT_ALPHA_NV 0x20C4
+#define GLX_VIDEO_OUT_DEPTH_NV 0x20C5
+#define GLX_VIDEO_OUT_COLOR_AND_ALPHA_NV 0x20C6
+#define GLX_VIDEO_OUT_COLOR_AND_DEPTH_NV 0x20C7
+#define GLX_VIDEO_OUT_FRAME_NV 0x20C8
+#define GLX_VIDEO_OUT_FIELD_1_NV 0x20C9
+#define GLX_VIDEO_OUT_FIELD_2_NV 0x20CA
+#define GLX_VIDEO_OUT_STACKED_FIELDS_1_2_NV 0x20CB
+#define GLX_VIDEO_OUT_STACKED_FIELDS_2_1_NV 0x20CC
+#endif
+
+#ifndef GLX_NV_swap_group
+#endif
+
+#ifndef GLX_NV_video_capture
+#define GLX_DEVICE_ID_NV 0x20CD
+#define GLX_UNIQUE_ID_NV 0x20CE
+#define GLX_NUM_VIDEO_CAPTURE_SLOTS_NV 0x20CF
+#endif
+
+#ifndef GLX_EXT_swap_control
+#define GLX_SWAP_INTERVAL_EXT 0x20F1
+#define GLX_MAX_SWAP_INTERVAL_EXT 0x20F2
+#endif
+
+#ifndef GLX_NV_copy_image
+#endif
+
+#ifndef GLX_INTEL_swap_event
+#define GLX_BUFFER_SWAP_COMPLETE_INTEL_MASK 0x04000000
+#define GLX_EXCHANGE_COMPLETE_INTEL 0x8180
+#define GLX_COPY_COMPLETE_INTEL 0x8181
+#define GLX_FLIP_COMPLETE_INTEL 0x8182
+#endif
+
+#ifndef GLX_NV_multisample_coverage
+#define GLX_COVERAGE_SAMPLES_NV 100001
+#define GLX_COLOR_SAMPLES_NV 0x20B3
+#endif
+
+#ifndef GLX_AMD_gpu_association
+#define GLX_GPU_VENDOR_AMD 0x1F00
+#define GLX_GPU_RENDERER_STRING_AMD 0x1F01
+#define GLX_GPU_OPENGL_VERSION_STRING_AMD 0x1F02
+#define GLX_GPU_FASTEST_TARGET_GPUS_AMD 0x21A2
+#define GLX_GPU_RAM_AMD 0x21A3
+#define GLX_GPU_CLOCK_AMD 0x21A4
+#define GLX_GPU_NUM_PIPES_AMD 0x21A5
+#define GLX_GPU_NUM_SIMD_AMD 0x21A6
+#define GLX_GPU_NUM_RB_AMD 0x21A7
+#define GLX_GPU_NUM_SPI_AMD 0x21A8
+#endif
+
+#ifndef GLX_EXT_create_context_es2_profile
+#define GLX_CONTEXT_ES2_PROFILE_BIT_EXT 0x00000004
+#endif
+
+
+/*************************************************************/
+
+#ifndef GLX_ARB_get_proc_address
+typedef void (*__GLXextFuncPtr)(void);
+#endif
+
+#ifndef GLX_SGIX_video_source
+typedef XID GLXVideoSourceSGIX;
+#endif
+
+#ifndef GLX_SGIX_fbconfig
+typedef XID GLXFBConfigIDSGIX;
+typedef struct __GLXFBConfigRec *GLXFBConfigSGIX;
+#endif
+
+#ifndef GLX_SGIX_pbuffer
+typedef XID GLXPbufferSGIX;
+typedef struct {
+ int type;
+ unsigned long serial; /* # of last request processed by server */
+ Bool send_event; /* true if this came for SendEvent request */
+ Display *display; /* display the event was read from */
+ GLXDrawable drawable; /* i.d. of Drawable */
+ int event_type; /* GLX_DAMAGED_SGIX or GLX_SAVED_SGIX */
+ int draw_type; /* GLX_WINDOW_SGIX or GLX_PBUFFER_SGIX */
+ unsigned int mask; /* mask indicating which buffers are affected*/
+ int x, y;
+ int width, height;
+ int count; /* if nonzero, at least this many more */
+} GLXBufferClobberEventSGIX;
+#endif
+
+#ifndef GLX_NV_video_output
+typedef unsigned int GLXVideoDeviceNV;
+#endif
+
+#ifndef GLX_NV_video_capture
+typedef XID GLXVideoCaptureDeviceNV;
+#endif
+
+#ifndef GLEXT_64_TYPES_DEFINED
+/* This code block is duplicated in glext.h, so must be protected */
+#define GLEXT_64_TYPES_DEFINED
+/* Define int32_t, int64_t, and uint64_t types for UST/MSC */
+/* (as used in the GLX_OML_sync_control extension). */
+#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
+#include <inttypes.h>
+#elif defined(__sun__) || defined(__digital__)
+#include <inttypes.h>
+#if defined(__STDC__)
+#if defined(__arch64__) || defined(_LP64)
+typedef long int int64_t;
+typedef unsigned long int uint64_t;
+#else
+typedef long long int int64_t;
+typedef unsigned long long int uint64_t;
+#endif /* __arch64__ */
+#endif /* __STDC__ */
+#elif defined( __VMS ) || defined(__sgi)
+#include <inttypes.h>
+#elif defined(__SCO__) || defined(__USLC__)
+#include <stdint.h>
+#elif defined(__UNIXOS2__) || defined(__SOL64__)
+typedef long int int32_t;
+typedef long long int int64_t;
+typedef unsigned long long int uint64_t;
+#elif defined(_WIN32) && defined(__GNUC__)
+#include <stdint.h>
+#elif defined(_WIN32)
+typedef __int32 int32_t;
+typedef __int64 int64_t;
+typedef unsigned __int64 uint64_t;
+#else
+#include <inttypes.h> /* Fallback option */
+#endif
+#endif
+
+#ifndef GLX_VERSION_1_3
+#define GLX_VERSION_1_3 1
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern GLXFBConfig * glXGetFBConfigs (Display *dpy, int screen, int *nelements);
+extern GLXFBConfig * glXChooseFBConfig (Display *dpy, int screen, const int *attrib_list, int *nelements);
+extern int glXGetFBConfigAttrib (Display *dpy, GLXFBConfig config, int attribute, int *value);
+extern XVisualInfo * glXGetVisualFromFBConfig (Display *dpy, GLXFBConfig config);
+extern GLXWindow glXCreateWindow (Display *dpy, GLXFBConfig config, Window win, const int *attrib_list);
+extern void glXDestroyWindow (Display *dpy, GLXWindow win);
+extern GLXPixmap glXCreatePixmap (Display *dpy, GLXFBConfig config, Pixmap pixmap, const int *attrib_list);
+extern void glXDestroyPixmap (Display *dpy, GLXPixmap pixmap);
+extern GLXPbuffer glXCreatePbuffer (Display *dpy, GLXFBConfig config, const int *attrib_list);
+extern void glXDestroyPbuffer (Display *dpy, GLXPbuffer pbuf);
+extern void glXQueryDrawable (Display *dpy, GLXDrawable draw, int attribute, unsigned int *value);
+extern GLXContext glXCreateNewContext (Display *dpy, GLXFBConfig config, int render_type, GLXContext share_list, Bool direct);
+extern Bool glXMakeContextCurrent (Display *dpy, GLXDrawable draw, GLXDrawable read, GLXContext ctx);
+extern GLXDrawable glXGetCurrentReadDrawable (void);
+extern Display * glXGetCurrentDisplay (void);
+extern int glXQueryContext (Display *dpy, GLXContext ctx, int attribute, int *value);
+extern void glXSelectEvent (Display *dpy, GLXDrawable draw, unsigned long event_mask);
+extern void glXGetSelectedEvent (Display *dpy, GLXDrawable draw, unsigned long *event_mask);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef GLXFBConfig * ( * PFNGLXGETFBCONFIGSPROC) (Display *dpy, int screen, int *nelements);
+typedef GLXFBConfig * ( * PFNGLXCHOOSEFBCONFIGPROC) (Display *dpy, int screen, const int *attrib_list, int *nelements);
+typedef int ( * PFNGLXGETFBCONFIGATTRIBPROC) (Display *dpy, GLXFBConfig config, int attribute, int *value);
+typedef XVisualInfo * ( * PFNGLXGETVISUALFROMFBCONFIGPROC) (Display *dpy, GLXFBConfig config);
+typedef GLXWindow ( * PFNGLXCREATEWINDOWPROC) (Display *dpy, GLXFBConfig config, Window win, const int *attrib_list);
+typedef void ( * PFNGLXDESTROYWINDOWPROC) (Display *dpy, GLXWindow win);
+typedef GLXPixmap ( * PFNGLXCREATEPIXMAPPROC) (Display *dpy, GLXFBConfig config, Pixmap pixmap, const int *attrib_list);
+typedef void ( * PFNGLXDESTROYPIXMAPPROC) (Display *dpy, GLXPixmap pixmap);
+typedef GLXPbuffer ( * PFNGLXCREATEPBUFFERPROC) (Display *dpy, GLXFBConfig config, const int *attrib_list);
+typedef void ( * PFNGLXDESTROYPBUFFERPROC) (Display *dpy, GLXPbuffer pbuf);
+typedef void ( * PFNGLXQUERYDRAWABLEPROC) (Display *dpy, GLXDrawable draw, int attribute, unsigned int *value);
+typedef GLXContext ( * PFNGLXCREATENEWCONTEXTPROC) (Display *dpy, GLXFBConfig config, int render_type, GLXContext share_list, Bool direct);
+typedef Bool ( * PFNGLXMAKECONTEXTCURRENTPROC) (Display *dpy, GLXDrawable draw, GLXDrawable read, GLXContext ctx);
+typedef GLXDrawable ( * PFNGLXGETCURRENTREADDRAWABLEPROC) (void);
+typedef Display * ( * PFNGLXGETCURRENTDISPLAYPROC) (void);
+typedef int ( * PFNGLXQUERYCONTEXTPROC) (Display *dpy, GLXContext ctx, int attribute, int *value);
+typedef void ( * PFNGLXSELECTEVENTPROC) (Display *dpy, GLXDrawable draw, unsigned long event_mask);
+typedef void ( * PFNGLXGETSELECTEDEVENTPROC) (Display *dpy, GLXDrawable draw, unsigned long *event_mask);
+#endif
+
+#ifndef GLX_VERSION_1_4
+#define GLX_VERSION_1_4 1
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern __GLXextFuncPtr glXGetProcAddress (const GLubyte *procName);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef __GLXextFuncPtr ( * PFNGLXGETPROCADDRESSPROC) (const GLubyte *procName);
+#endif
+
+#ifndef GLX_ARB_get_proc_address
+#define GLX_ARB_get_proc_address 1
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern __GLXextFuncPtr glXGetProcAddressARB (const GLubyte *procName);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef __GLXextFuncPtr ( * PFNGLXGETPROCADDRESSARBPROC) (const GLubyte *procName);
+#endif
+
+#ifndef GLX_ARB_multisample
+#define GLX_ARB_multisample 1
+#endif
+
+#ifndef GLX_ARB_fbconfig_float
+#define GLX_ARB_fbconfig_float 1
+#endif
+
+#ifndef GLX_ARB_framebuffer_sRGB
+#define GLX_ARB_framebuffer_sRGB 1
+#endif
+
+#ifndef GLX_ARB_create_context
+#define GLX_ARB_create_context 1
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern GLXContext glXCreateContextAttribsARB (Display *dpy, GLXFBConfig config, GLXContext share_context, Bool direct, const int *attrib_list);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef GLXContext ( * PFNGLXCREATECONTEXTATTRIBSARBPROC) (Display *dpy, GLXFBConfig config, GLXContext share_context, Bool direct, const int *attrib_list);
+#endif
+
+#ifndef GLX_ARB_create_context_profile
+#define GLX_ARB_create_context_profile 1
+#endif
+
+#ifndef GLX_ARB_create_context_robustness
+#define GLX_ARB_create_context_robustness 1
+#endif
+
+#ifndef GLX_SGIS_multisample
+#define GLX_SGIS_multisample 1
+#endif
+
+#ifndef GLX_EXT_visual_info
+#define GLX_EXT_visual_info 1
+#endif
+
+#ifndef GLX_SGI_swap_control
+#define GLX_SGI_swap_control 1
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern int glXSwapIntervalSGI (int interval);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef int ( * PFNGLXSWAPINTERVALSGIPROC) (int interval);
+#endif
+
+#ifndef GLX_SGI_video_sync
+#define GLX_SGI_video_sync 1
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern int glXGetVideoSyncSGI (unsigned int *count);
+extern int glXWaitVideoSyncSGI (int divisor, int remainder, unsigned int *count);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef int ( * PFNGLXGETVIDEOSYNCSGIPROC) (unsigned int *count);
+typedef int ( * PFNGLXWAITVIDEOSYNCSGIPROC) (int divisor, int remainder, unsigned int *count);
+#endif
+
+#ifndef GLX_SGI_make_current_read
+#define GLX_SGI_make_current_read 1
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern Bool glXMakeCurrentReadSGI (Display *dpy, GLXDrawable draw, GLXDrawable read, GLXContext ctx);
+extern GLXDrawable glXGetCurrentReadDrawableSGI (void);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef Bool ( * PFNGLXMAKECURRENTREADSGIPROC) (Display *dpy, GLXDrawable draw, GLXDrawable read, GLXContext ctx);
+typedef GLXDrawable ( * PFNGLXGETCURRENTREADDRAWABLESGIPROC) (void);
+#endif
+
+#ifndef GLX_SGIX_video_source
+#define GLX_SGIX_video_source 1
+#ifdef _VL_H
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern GLXVideoSourceSGIX glXCreateGLXVideoSourceSGIX (Display *display, int screen, VLServer server, VLPath path, int nodeClass, VLNode drainNode);
+extern void glXDestroyGLXVideoSourceSGIX (Display *dpy, GLXVideoSourceSGIX glxvideosource);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef GLXVideoSourceSGIX ( * PFNGLXCREATEGLXVIDEOSOURCESGIXPROC) (Display *display, int screen, VLServer server, VLPath path, int nodeClass, VLNode drainNode);
+typedef void ( * PFNGLXDESTROYGLXVIDEOSOURCESGIXPROC) (Display *dpy, GLXVideoSourceSGIX glxvideosource);
+#endif /* _VL_H */
+#endif
+
+#ifndef GLX_EXT_visual_rating
+#define GLX_EXT_visual_rating 1
+#endif
+
+#ifndef GLX_EXT_import_context
+#define GLX_EXT_import_context 1
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern Display * glXGetCurrentDisplayEXT (void);
+extern int glXQueryContextInfoEXT (Display *dpy, GLXContext context, int attribute, int *value);
+extern GLXContextID glXGetContextIDEXT (const GLXContext context);
+extern GLXContext glXImportContextEXT (Display *dpy, GLXContextID contextID);
+extern void glXFreeContextEXT (Display *dpy, GLXContext context);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef Display * ( * PFNGLXGETCURRENTDISPLAYEXTPROC) (void);
+typedef int ( * PFNGLXQUERYCONTEXTINFOEXTPROC) (Display *dpy, GLXContext context, int attribute, int *value);
+typedef GLXContextID ( * PFNGLXGETCONTEXTIDEXTPROC) (const GLXContext context);
+typedef GLXContext ( * PFNGLXIMPORTCONTEXTEXTPROC) (Display *dpy, GLXContextID contextID);
+typedef void ( * PFNGLXFREECONTEXTEXTPROC) (Display *dpy, GLXContext context);
+#endif
+
+#ifndef GLX_SGIX_fbconfig
+#define GLX_SGIX_fbconfig 1
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern int glXGetFBConfigAttribSGIX (Display *dpy, GLXFBConfigSGIX config, int attribute, int *value);
+extern GLXFBConfigSGIX * glXChooseFBConfigSGIX (Display *dpy, int screen, int *attrib_list, int *nelements);
+extern GLXPixmap glXCreateGLXPixmapWithConfigSGIX (Display *dpy, GLXFBConfigSGIX config, Pixmap pixmap);
+extern GLXContext glXCreateContextWithConfigSGIX (Display *dpy, GLXFBConfigSGIX config, int render_type, GLXContext share_list, Bool direct);
+extern XVisualInfo * glXGetVisualFromFBConfigSGIX (Display *dpy, GLXFBConfigSGIX config);
+extern GLXFBConfigSGIX glXGetFBConfigFromVisualSGIX (Display *dpy, XVisualInfo *vis);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef int ( * PFNGLXGETFBCONFIGATTRIBSGIXPROC) (Display *dpy, GLXFBConfigSGIX config, int attribute, int *value);
+typedef GLXFBConfigSGIX * ( * PFNGLXCHOOSEFBCONFIGSGIXPROC) (Display *dpy, int screen, int *attrib_list, int *nelements);
+typedef GLXPixmap ( * PFNGLXCREATEGLXPIXMAPWITHCONFIGSGIXPROC) (Display *dpy, GLXFBConfigSGIX config, Pixmap pixmap);
+typedef GLXContext ( * PFNGLXCREATECONTEXTWITHCONFIGSGIXPROC) (Display *dpy, GLXFBConfigSGIX config, int render_type, GLXContext share_list, Bool direct);
+typedef XVisualInfo * ( * PFNGLXGETVISUALFROMFBCONFIGSGIXPROC) (Display *dpy, GLXFBConfigSGIX config);
+typedef GLXFBConfigSGIX ( * PFNGLXGETFBCONFIGFROMVISUALSGIXPROC) (Display *dpy, XVisualInfo *vis);
+#endif
+
+#ifndef GLX_SGIX_pbuffer
+#define GLX_SGIX_pbuffer 1
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern GLXPbufferSGIX glXCreateGLXPbufferSGIX (Display *dpy, GLXFBConfigSGIX config, unsigned int width, unsigned int height, int *attrib_list);
+extern void glXDestroyGLXPbufferSGIX (Display *dpy, GLXPbufferSGIX pbuf);
+extern int glXQueryGLXPbufferSGIX (Display *dpy, GLXPbufferSGIX pbuf, int attribute, unsigned int *value);
+extern void glXSelectEventSGIX (Display *dpy, GLXDrawable drawable, unsigned long mask);
+extern void glXGetSelectedEventSGIX (Display *dpy, GLXDrawable drawable, unsigned long *mask);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef GLXPbufferSGIX ( * PFNGLXCREATEGLXPBUFFERSGIXPROC) (Display *dpy, GLXFBConfigSGIX config, unsigned int width, unsigned int height, int *attrib_list);
+typedef void ( * PFNGLXDESTROYGLXPBUFFERSGIXPROC) (Display *dpy, GLXPbufferSGIX pbuf);
+typedef int ( * PFNGLXQUERYGLXPBUFFERSGIXPROC) (Display *dpy, GLXPbufferSGIX pbuf, int attribute, unsigned int *value);
+typedef void ( * PFNGLXSELECTEVENTSGIXPROC) (Display *dpy, GLXDrawable drawable, unsigned long mask);
+typedef void ( * PFNGLXGETSELECTEDEVENTSGIXPROC) (Display *dpy, GLXDrawable drawable, unsigned long *mask);
+#endif
+
+#ifndef GLX_SGI_cushion
+#define GLX_SGI_cushion 1
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern void glXCushionSGI (Display *dpy, Window window, float cushion);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef void ( * PFNGLXCUSHIONSGIPROC) (Display *dpy, Window window, float cushion);
+#endif
+
+#ifndef GLX_SGIX_video_resize
+#define GLX_SGIX_video_resize 1
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern int glXBindChannelToWindowSGIX (Display *display, int screen, int channel, Window window);
+extern int glXChannelRectSGIX (Display *display, int screen, int channel, int x, int y, int w, int h);
+extern int glXQueryChannelRectSGIX (Display *display, int screen, int channel, int *dx, int *dy, int *dw, int *dh);
+extern int glXQueryChannelDeltasSGIX (Display *display, int screen, int channel, int *x, int *y, int *w, int *h);
+extern int glXChannelRectSyncSGIX (Display *display, int screen, int channel, GLenum synctype);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef int ( * PFNGLXBINDCHANNELTOWINDOWSGIXPROC) (Display *display, int screen, int channel, Window window);
+typedef int ( * PFNGLXCHANNELRECTSGIXPROC) (Display *display, int screen, int channel, int x, int y, int w, int h);
+typedef int ( * PFNGLXQUERYCHANNELRECTSGIXPROC) (Display *display, int screen, int channel, int *dx, int *dy, int *dw, int *dh);
+typedef int ( * PFNGLXQUERYCHANNELDELTASSGIXPROC) (Display *display, int screen, int channel, int *x, int *y, int *w, int *h);
+typedef int ( * PFNGLXCHANNELRECTSYNCSGIXPROC) (Display *display, int screen, int channel, GLenum synctype);
+#endif
+
+#ifndef GLX_SGIX_dmbuffer
+#define GLX_SGIX_dmbuffer 1
+#ifdef _DM_BUFFER_H_
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern Bool glXAssociateDMPbufferSGIX (Display *dpy, GLXPbufferSGIX pbuffer, DMparams *params, DMbuffer dmbuffer);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef Bool ( * PFNGLXASSOCIATEDMPBUFFERSGIXPROC) (Display *dpy, GLXPbufferSGIX pbuffer, DMparams *params, DMbuffer dmbuffer);
+#endif /* _DM_BUFFER_H_ */
+#endif
+
+#ifndef GLX_SGIX_swap_group
+#define GLX_SGIX_swap_group 1
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern void glXJoinSwapGroupSGIX (Display *dpy, GLXDrawable drawable, GLXDrawable member);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef void ( * PFNGLXJOINSWAPGROUPSGIXPROC) (Display *dpy, GLXDrawable drawable, GLXDrawable member);
+#endif
+
+#ifndef GLX_SGIX_swap_barrier
+#define GLX_SGIX_swap_barrier 1
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern void glXBindSwapBarrierSGIX (Display *dpy, GLXDrawable drawable, int barrier);
+extern Bool glXQueryMaxSwapBarriersSGIX (Display *dpy, int screen, int *max);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef void ( * PFNGLXBINDSWAPBARRIERSGIXPROC) (Display *dpy, GLXDrawable drawable, int barrier);
+typedef Bool ( * PFNGLXQUERYMAXSWAPBARRIERSSGIXPROC) (Display *dpy, int screen, int *max);
+#endif
+
+#ifndef GLX_SUN_get_transparent_index
+#define GLX_SUN_get_transparent_index 1
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern Status glXGetTransparentIndexSUN (Display *dpy, Window overlay, Window underlay, long *pTransparentIndex);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef Status ( * PFNGLXGETTRANSPARENTINDEXSUNPROC) (Display *dpy, Window overlay, Window underlay, long *pTransparentIndex);
+#endif
+
+#ifndef GLX_MESA_copy_sub_buffer
+#define GLX_MESA_copy_sub_buffer 1
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern void glXCopySubBufferMESA (Display *dpy, GLXDrawable drawable, int x, int y, int width, int height);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef void ( * PFNGLXCOPYSUBBUFFERMESAPROC) (Display *dpy, GLXDrawable drawable, int x, int y, int width, int height);
+#endif
+
+#ifndef GLX_MESA_pixmap_colormap
+#define GLX_MESA_pixmap_colormap 1
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern GLXPixmap glXCreateGLXPixmapMESA (Display *dpy, XVisualInfo *visual, Pixmap pixmap, Colormap cmap);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef GLXPixmap ( * PFNGLXCREATEGLXPIXMAPMESAPROC) (Display *dpy, XVisualInfo *visual, Pixmap pixmap, Colormap cmap);
+#endif
+
+#ifndef GLX_MESA_release_buffers
+#define GLX_MESA_release_buffers 1
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern Bool glXReleaseBuffersMESA (Display *dpy, GLXDrawable drawable);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef Bool ( * PFNGLXRELEASEBUFFERSMESAPROC) (Display *dpy, GLXDrawable drawable);
+#endif
+
+#ifndef GLX_MESA_set_3dfx_mode
+#define GLX_MESA_set_3dfx_mode 1
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern Bool glXSet3DfxModeMESA (int mode);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef Bool ( * PFNGLXSET3DFXMODEMESAPROC) (int mode);
+#endif
+
+#ifndef GLX_SGIX_visual_select_group
+#define GLX_SGIX_visual_select_group 1
+#endif
+
+#ifndef GLX_OML_swap_method
+#define GLX_OML_swap_method 1
+#endif
+
+#ifndef GLX_OML_sync_control
+#define GLX_OML_sync_control 1
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern Bool glXGetSyncValuesOML (Display *dpy, GLXDrawable drawable, int64_t *ust, int64_t *msc, int64_t *sbc);
+extern Bool glXGetMscRateOML (Display *dpy, GLXDrawable drawable, int32_t *numerator, int32_t *denominator);
+extern int64_t glXSwapBuffersMscOML (Display *dpy, GLXDrawable drawable, int64_t target_msc, int64_t divisor, int64_t remainder);
+extern Bool glXWaitForMscOML (Display *dpy, GLXDrawable drawable, int64_t target_msc, int64_t divisor, int64_t remainder, int64_t *ust, int64_t *msc, int64_t *sbc);
+extern Bool glXWaitForSbcOML (Display *dpy, GLXDrawable drawable, int64_t target_sbc, int64_t *ust, int64_t *msc, int64_t *sbc);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef Bool ( * PFNGLXGETSYNCVALUESOMLPROC) (Display *dpy, GLXDrawable drawable, int64_t *ust, int64_t *msc, int64_t *sbc);
+typedef Bool ( * PFNGLXGETMSCRATEOMLPROC) (Display *dpy, GLXDrawable drawable, int32_t *numerator, int32_t *denominator);
+typedef int64_t ( * PFNGLXSWAPBUFFERSMSCOMLPROC) (Display *dpy, GLXDrawable drawable, int64_t target_msc, int64_t divisor, int64_t remainder);
+typedef Bool ( * PFNGLXWAITFORMSCOMLPROC) (Display *dpy, GLXDrawable drawable, int64_t target_msc, int64_t divisor, int64_t remainder, int64_t *ust, int64_t *msc, int64_t *sbc);
+typedef Bool ( * PFNGLXWAITFORSBCOMLPROC) (Display *dpy, GLXDrawable drawable, int64_t target_sbc, int64_t *ust, int64_t *msc, int64_t *sbc);
+#endif
+
+#ifndef GLX_NV_float_buffer
+#define GLX_NV_float_buffer 1
+#endif
+
+#ifndef GLX_SGIX_hyperpipe
+#define GLX_SGIX_hyperpipe 1
+
+typedef struct {
+ char pipeName[GLX_HYPERPIPE_PIPE_NAME_LENGTH_SGIX];
+ int networkId;
+} GLXHyperpipeNetworkSGIX;
+
+typedef struct {
+ char pipeName[GLX_HYPERPIPE_PIPE_NAME_LENGTH_SGIX];
+ int channel;
+ unsigned int
+ participationType;
+ int timeSlice;
+} GLXHyperpipeConfigSGIX;
+
+typedef struct {
+ char pipeName[GLX_HYPERPIPE_PIPE_NAME_LENGTH_SGIX];
+ int srcXOrigin, srcYOrigin, srcWidth, srcHeight;
+ int destXOrigin, destYOrigin, destWidth, destHeight;
+} GLXPipeRect;
+
+typedef struct {
+ char pipeName[GLX_HYPERPIPE_PIPE_NAME_LENGTH_SGIX];
+ int XOrigin, YOrigin, maxHeight, maxWidth;
+} GLXPipeRectLimits;
+
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern GLXHyperpipeNetworkSGIX * glXQueryHyperpipeNetworkSGIX (Display *dpy, int *npipes);
+extern int glXHyperpipeConfigSGIX (Display *dpy, int networkId, int npipes, GLXHyperpipeConfigSGIX *cfg, int *hpId);
+extern GLXHyperpipeConfigSGIX * glXQueryHyperpipeConfigSGIX (Display *dpy, int hpId, int *npipes);
+extern int glXDestroyHyperpipeConfigSGIX (Display *dpy, int hpId);
+extern int glXBindHyperpipeSGIX (Display *dpy, int hpId);
+extern int glXQueryHyperpipeBestAttribSGIX (Display *dpy, int timeSlice, int attrib, int size, void *attribList, void *returnAttribList);
+extern int glXHyperpipeAttribSGIX (Display *dpy, int timeSlice, int attrib, int size, void *attribList);
+extern int glXQueryHyperpipeAttribSGIX (Display *dpy, int timeSlice, int attrib, int size, void *returnAttribList);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef GLXHyperpipeNetworkSGIX * ( * PFNGLXQUERYHYPERPIPENETWORKSGIXPROC) (Display *dpy, int *npipes);
+typedef int ( * PFNGLXHYPERPIPECONFIGSGIXPROC) (Display *dpy, int networkId, int npipes, GLXHyperpipeConfigSGIX *cfg, int *hpId);
+typedef GLXHyperpipeConfigSGIX * ( * PFNGLXQUERYHYPERPIPECONFIGSGIXPROC) (Display *dpy, int hpId, int *npipes);
+typedef int ( * PFNGLXDESTROYHYPERPIPECONFIGSGIXPROC) (Display *dpy, int hpId);
+typedef int ( * PFNGLXBINDHYPERPIPESGIXPROC) (Display *dpy, int hpId);
+typedef int ( * PFNGLXQUERYHYPERPIPEBESTATTRIBSGIXPROC) (Display *dpy, int timeSlice, int attrib, int size, void *attribList, void *returnAttribList);
+typedef int ( * PFNGLXHYPERPIPEATTRIBSGIXPROC) (Display *dpy, int timeSlice, int attrib, int size, void *attribList);
+typedef int ( * PFNGLXQUERYHYPERPIPEATTRIBSGIXPROC) (Display *dpy, int timeSlice, int attrib, int size, void *returnAttribList);
+#endif
+
+#ifndef GLX_MESA_agp_offset
+#define GLX_MESA_agp_offset 1
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern unsigned int glXGetAGPOffsetMESA (const void *pointer);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef unsigned int ( * PFNGLXGETAGPOFFSETMESAPROC) (const void *pointer);
+#endif
+
+#ifndef GLX_EXT_fbconfig_packed_float
+#define GLX_EXT_fbconfig_packed_float 1
+#endif
+
+#ifndef GLX_EXT_framebuffer_sRGB
+#define GLX_EXT_framebuffer_sRGB 1
+#endif
+
+#ifndef GLX_EXT_texture_from_pixmap
+#define GLX_EXT_texture_from_pixmap 1
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern void glXBindTexImageEXT (Display *dpy, GLXDrawable drawable, int buffer, const int *attrib_list);
+extern void glXReleaseTexImageEXT (Display *dpy, GLXDrawable drawable, int buffer);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef void ( * PFNGLXBINDTEXIMAGEEXTPROC) (Display *dpy, GLXDrawable drawable, int buffer, const int *attrib_list);
+typedef void ( * PFNGLXRELEASETEXIMAGEEXTPROC) (Display *dpy, GLXDrawable drawable, int buffer);
+#endif
+
+#ifndef GLX_NV_present_video
+#define GLX_NV_present_video 1
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern unsigned int * glXEnumerateVideoDevicesNV (Display *dpy, int screen, int *nelements);
+extern int glXBindVideoDeviceNV (Display *dpy, unsigned int video_slot, unsigned int video_device, const int *attrib_list);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef unsigned int * ( * PFNGLXENUMERATEVIDEODEVICESNVPROC) (Display *dpy, int screen, int *nelements);
+typedef int ( * PFNGLXBINDVIDEODEVICENVPROC) (Display *dpy, unsigned int video_slot, unsigned int video_device, const int *attrib_list);
+#endif
+
+#ifndef GLX_NV_video_output
+#define GLX_NV_video_output 1
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern int glXGetVideoDeviceNV (Display *dpy, int screen, int numVideoDevices, GLXVideoDeviceNV *pVideoDevice);
+extern int glXReleaseVideoDeviceNV (Display *dpy, int screen, GLXVideoDeviceNV VideoDevice);
+extern int glXBindVideoImageNV (Display *dpy, GLXVideoDeviceNV VideoDevice, GLXPbuffer pbuf, int iVideoBuffer);
+extern int glXReleaseVideoImageNV (Display *dpy, GLXPbuffer pbuf);
+extern int glXSendPbufferToVideoNV (Display *dpy, GLXPbuffer pbuf, int iBufferType, unsigned long *pulCounterPbuffer, GLboolean bBlock);
+extern int glXGetVideoInfoNV (Display *dpy, int screen, GLXVideoDeviceNV VideoDevice, unsigned long *pulCounterOutputPbuffer, unsigned long *pulCounterOutputVideo);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef int ( * PFNGLXGETVIDEODEVICENVPROC) (Display *dpy, int screen, int numVideoDevices, GLXVideoDeviceNV *pVideoDevice);
+typedef int ( * PFNGLXRELEASEVIDEODEVICENVPROC) (Display *dpy, int screen, GLXVideoDeviceNV VideoDevice);
+typedef int ( * PFNGLXBINDVIDEOIMAGENVPROC) (Display *dpy, GLXVideoDeviceNV VideoDevice, GLXPbuffer pbuf, int iVideoBuffer);
+typedef int ( * PFNGLXRELEASEVIDEOIMAGENVPROC) (Display *dpy, GLXPbuffer pbuf);
+typedef int ( * PFNGLXSENDPBUFFERTOVIDEONVPROC) (Display *dpy, GLXPbuffer pbuf, int iBufferType, unsigned long *pulCounterPbuffer, GLboolean bBlock);
+typedef int ( * PFNGLXGETVIDEOINFONVPROC) (Display *dpy, int screen, GLXVideoDeviceNV VideoDevice, unsigned long *pulCounterOutputPbuffer, unsigned long *pulCounterOutputVideo);
+#endif
+
+#ifndef GLX_NV_swap_group
+#define GLX_NV_swap_group 1
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern Bool glXJoinSwapGroupNV (Display *dpy, GLXDrawable drawable, GLuint group);
+extern Bool glXBindSwapBarrierNV (Display *dpy, GLuint group, GLuint barrier);
+extern Bool glXQuerySwapGroupNV (Display *dpy, GLXDrawable drawable, GLuint *group, GLuint *barrier);
+extern Bool glXQueryMaxSwapGroupsNV (Display *dpy, int screen, GLuint *maxGroups, GLuint *maxBarriers);
+extern Bool glXQueryFrameCountNV (Display *dpy, int screen, GLuint *count);
+extern Bool glXResetFrameCountNV (Display *dpy, int screen);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef Bool ( * PFNGLXJOINSWAPGROUPNVPROC) (Display *dpy, GLXDrawable drawable, GLuint group);
+typedef Bool ( * PFNGLXBINDSWAPBARRIERNVPROC) (Display *dpy, GLuint group, GLuint barrier);
+typedef Bool ( * PFNGLXQUERYSWAPGROUPNVPROC) (Display *dpy, GLXDrawable drawable, GLuint *group, GLuint *barrier);
+typedef Bool ( * PFNGLXQUERYMAXSWAPGROUPSNVPROC) (Display *dpy, int screen, GLuint *maxGroups, GLuint *maxBarriers);
+typedef Bool ( * PFNGLXQUERYFRAMECOUNTNVPROC) (Display *dpy, int screen, GLuint *count);
+typedef Bool ( * PFNGLXRESETFRAMECOUNTNVPROC) (Display *dpy, int screen);
+#endif
+
+#ifndef GLX_NV_video_capture
+#define GLX_NV_video_capture 1
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern int glXBindVideoCaptureDeviceNV (Display *dpy, unsigned int video_capture_slot, GLXVideoCaptureDeviceNV device);
+extern GLXVideoCaptureDeviceNV * glXEnumerateVideoCaptureDevicesNV (Display *dpy, int screen, int *nelements);
+extern void glXLockVideoCaptureDeviceNV (Display *dpy, GLXVideoCaptureDeviceNV device);
+extern int glXQueryVideoCaptureDeviceNV (Display *dpy, GLXVideoCaptureDeviceNV device, int attribute, int *value);
+extern void glXReleaseVideoCaptureDeviceNV (Display *dpy, GLXVideoCaptureDeviceNV device);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef int ( * PFNGLXBINDVIDEOCAPTUREDEVICENVPROC) (Display *dpy, unsigned int video_capture_slot, GLXVideoCaptureDeviceNV device);
+typedef GLXVideoCaptureDeviceNV * ( * PFNGLXENUMERATEVIDEOCAPTUREDEVICESNVPROC) (Display *dpy, int screen, int *nelements);
+typedef void ( * PFNGLXLOCKVIDEOCAPTUREDEVICENVPROC) (Display *dpy, GLXVideoCaptureDeviceNV device);
+typedef int ( * PFNGLXQUERYVIDEOCAPTUREDEVICENVPROC) (Display *dpy, GLXVideoCaptureDeviceNV device, int attribute, int *value);
+typedef void ( * PFNGLXRELEASEVIDEOCAPTUREDEVICENVPROC) (Display *dpy, GLXVideoCaptureDeviceNV device);
+#endif
+
+#ifndef GLX_EXT_swap_control
+#define GLX_EXT_swap_control 1
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern int glXSwapIntervalEXT (Display *dpy, GLXDrawable drawable, int interval);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef int ( * PFNGLXSWAPINTERVALEXTPROC) (Display *dpy, GLXDrawable drawable, int interval);
+#endif
+
+#ifndef GLX_NV_copy_image
+#define GLX_NV_copy_image 1
+#ifdef GLX_GLXEXT_PROTOTYPES
+extern void glXCopyImageSubDataNV (Display *dpy, GLXContext srcCtx, GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLXContext dstCtx, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth);
+#endif /* GLX_GLXEXT_PROTOTYPES */
+typedef void ( * PFNGLXCOPYIMAGESUBDATANVPROC) (Display *dpy, GLXContext srcCtx, GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLXContext dstCtx, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth);
+#endif
+
+#ifndef GLX_INTEL_swap_event
+#define GLX_INTEL_swap_event 1
+#endif
+
+#ifndef GLX_NV_multisample_coverage
+#define GLX_NV_multisample_coverage 1
+#endif
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/src/SFML/Window/glext/wglext.h b/src/SFML/Window/glext/wglext.h
new file mode 100644
index 0000000..e60c652
--- /dev/null
+++ b/src/SFML/Window/glext/wglext.h
@@ -0,0 +1,901 @@
+#ifndef __wglext_h_
+#define __wglext_h_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+** Copyright (c) 2007-2010 The Khronos Group Inc.
+**
+** Permission is hereby granted, free of charge, to any person obtaining a
+** copy of this software and/or associated documentation files (the
+** "Materials"), to deal in the Materials without restriction, including
+** without limitation the rights to use, copy, modify, merge, publish,
+** distribute, sublicense, and/or sell copies of the Materials, and to
+** permit persons to whom the Materials are furnished to do so, subject to
+** the following conditions:
+**
+** The above copyright notice and this permission notice shall be included
+** in all copies or substantial portions of the Materials.
+**
+** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
+*/
+
+/* Function declaration macros - to move into glplatform.h */
+
+#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__)
+#define WIN32_LEAN_AND_MEAN 1
+#include <windows.h>
+#endif
+
+#ifndef APIENTRY
+#define APIENTRY
+#endif
+#ifndef APIENTRYP
+#define APIENTRYP APIENTRY *
+#endif
+#ifndef GLAPI
+#define GLAPI extern
+#endif
+
+/*************************************************************/
+
+/* Header file version number */
+/* wglext.h last updated 2010/08/06 */
+/* Current version at http://www.opengl.org/registry/ */
+#define WGL_WGLEXT_VERSION 22
+
+#ifndef WGL_ARB_buffer_region
+#define WGL_FRONT_COLOR_BUFFER_BIT_ARB 0x00000001
+#define WGL_BACK_COLOR_BUFFER_BIT_ARB 0x00000002
+#define WGL_DEPTH_BUFFER_BIT_ARB 0x00000004
+#define WGL_STENCIL_BUFFER_BIT_ARB 0x00000008
+#endif
+
+#ifndef WGL_ARB_multisample
+#define WGL_SAMPLE_BUFFERS_ARB 0x2041
+#define WGL_SAMPLES_ARB 0x2042
+#endif
+
+#ifndef WGL_ARB_extensions_string
+#endif
+
+#ifndef WGL_ARB_pixel_format
+#define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
+#define WGL_DRAW_TO_WINDOW_ARB 0x2001
+#define WGL_DRAW_TO_BITMAP_ARB 0x2002
+#define WGL_ACCELERATION_ARB 0x2003
+#define WGL_NEED_PALETTE_ARB 0x2004
+#define WGL_NEED_SYSTEM_PALETTE_ARB 0x2005
+#define WGL_SWAP_LAYER_BUFFERS_ARB 0x2006
+#define WGL_SWAP_METHOD_ARB 0x2007
+#define WGL_NUMBER_OVERLAYS_ARB 0x2008
+#define WGL_NUMBER_UNDERLAYS_ARB 0x2009
+#define WGL_TRANSPARENT_ARB 0x200A
+#define WGL_TRANSPARENT_RED_VALUE_ARB 0x2037
+#define WGL_TRANSPARENT_GREEN_VALUE_ARB 0x2038
+#define WGL_TRANSPARENT_BLUE_VALUE_ARB 0x2039
+#define WGL_TRANSPARENT_ALPHA_VALUE_ARB 0x203A
+#define WGL_TRANSPARENT_INDEX_VALUE_ARB 0x203B
+#define WGL_SHARE_DEPTH_ARB 0x200C
+#define WGL_SHARE_STENCIL_ARB 0x200D
+#define WGL_SHARE_ACCUM_ARB 0x200E
+#define WGL_SUPPORT_GDI_ARB 0x200F
+#define WGL_SUPPORT_OPENGL_ARB 0x2010
+#define WGL_DOUBLE_BUFFER_ARB 0x2011
+#define WGL_STEREO_ARB 0x2012
+#define WGL_PIXEL_TYPE_ARB 0x2013
+#define WGL_COLOR_BITS_ARB 0x2014
+#define WGL_RED_BITS_ARB 0x2015
+#define WGL_RED_SHIFT_ARB 0x2016
+#define WGL_GREEN_BITS_ARB 0x2017
+#define WGL_GREEN_SHIFT_ARB 0x2018
+#define WGL_BLUE_BITS_ARB 0x2019
+#define WGL_BLUE_SHIFT_ARB 0x201A
+#define WGL_ALPHA_BITS_ARB 0x201B
+#define WGL_ALPHA_SHIFT_ARB 0x201C
+#define WGL_ACCUM_BITS_ARB 0x201D
+#define WGL_ACCUM_RED_BITS_ARB 0x201E
+#define WGL_ACCUM_GREEN_BITS_ARB 0x201F
+#define WGL_ACCUM_BLUE_BITS_ARB 0x2020
+#define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
+#define WGL_DEPTH_BITS_ARB 0x2022
+#define WGL_STENCIL_BITS_ARB 0x2023
+#define WGL_AUX_BUFFERS_ARB 0x2024
+#define WGL_NO_ACCELERATION_ARB 0x2025
+#define WGL_GENERIC_ACCELERATION_ARB 0x2026
+#define WGL_FULL_ACCELERATION_ARB 0x2027
+#define WGL_SWAP_EXCHANGE_ARB 0x2028
+#define WGL_SWAP_COPY_ARB 0x2029
+#define WGL_SWAP_UNDEFINED_ARB 0x202A
+#define WGL_TYPE_RGBA_ARB 0x202B
+#define WGL_TYPE_COLORINDEX_ARB 0x202C
+#endif
+
+#ifndef WGL_ARB_make_current_read
+#define ERROR_INVALID_PIXEL_TYPE_ARB 0x2043
+#define ERROR_INCOMPATIBLE_DEVICE_CONTEXTS_ARB 0x2054
+#endif
+
+#ifndef WGL_ARB_pbuffer
+#define WGL_DRAW_TO_PBUFFER_ARB 0x202D
+#define WGL_MAX_PBUFFER_PIXELS_ARB 0x202E
+#define WGL_MAX_PBUFFER_WIDTH_ARB 0x202F
+#define WGL_MAX_PBUFFER_HEIGHT_ARB 0x2030
+#define WGL_PBUFFER_LARGEST_ARB 0x2033
+#define WGL_PBUFFER_WIDTH_ARB 0x2034
+#define WGL_PBUFFER_HEIGHT_ARB 0x2035
+#define WGL_PBUFFER_LOST_ARB 0x2036
+#endif
+
+#ifndef WGL_ARB_render_texture
+#define WGL_BIND_TO_TEXTURE_RGB_ARB 0x2070
+#define WGL_BIND_TO_TEXTURE_RGBA_ARB 0x2071
+#define WGL_TEXTURE_FORMAT_ARB 0x2072
+#define WGL_TEXTURE_TARGET_ARB 0x2073
+#define WGL_MIPMAP_TEXTURE_ARB 0x2074
+#define WGL_TEXTURE_RGB_ARB 0x2075
+#define WGL_TEXTURE_RGBA_ARB 0x2076
+#define WGL_NO_TEXTURE_ARB 0x2077
+#define WGL_TEXTURE_CUBE_MAP_ARB 0x2078
+#define WGL_TEXTURE_1D_ARB 0x2079
+#define WGL_TEXTURE_2D_ARB 0x207A
+#define WGL_MIPMAP_LEVEL_ARB 0x207B
+#define WGL_CUBE_MAP_FACE_ARB 0x207C
+#define WGL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB 0x207D
+#define WGL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB 0x207E
+#define WGL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB 0x207F
+#define WGL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB 0x2080
+#define WGL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB 0x2081
+#define WGL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB 0x2082
+#define WGL_FRONT_LEFT_ARB 0x2083
+#define WGL_FRONT_RIGHT_ARB 0x2084
+#define WGL_BACK_LEFT_ARB 0x2085
+#define WGL_BACK_RIGHT_ARB 0x2086
+#define WGL_AUX0_ARB 0x2087
+#define WGL_AUX1_ARB 0x2088
+#define WGL_AUX2_ARB 0x2089
+#define WGL_AUX3_ARB 0x208A
+#define WGL_AUX4_ARB 0x208B
+#define WGL_AUX5_ARB 0x208C
+#define WGL_AUX6_ARB 0x208D
+#define WGL_AUX7_ARB 0x208E
+#define WGL_AUX8_ARB 0x208F
+#define WGL_AUX9_ARB 0x2090
+#endif
+
+#ifndef WGL_ARB_pixel_format_float
+#define WGL_TYPE_RGBA_FLOAT_ARB 0x21A0
+#endif
+
+#ifndef WGL_ARB_framebuffer_sRGB
+#define WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB 0x20A9
+#endif
+
+#ifndef WGL_ARB_create_context
+#define WGL_CONTEXT_DEBUG_BIT_ARB 0x00000001
+#define WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x00000002
+#define WGL_CONTEXT_MAJOR_VERSION_ARB 0x2091
+#define WGL_CONTEXT_MINOR_VERSION_ARB 0x2092
+#define WGL_CONTEXT_LAYER_PLANE_ARB 0x2093
+#define WGL_CONTEXT_FLAGS_ARB 0x2094
+#define ERROR_INVALID_VERSION_ARB 0x2095
+#endif
+
+#ifndef WGL_ARB_create_context_profile
+#define WGL_CONTEXT_PROFILE_MASK_ARB 0x9126
+#define WGL_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
+#define WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002
+#define ERROR_INVALID_PROFILE_ARB 0x2096
+#endif
+
+#ifndef WGL_ARB_create_context_robustness
+#define WGL_CONTEXT_ROBUST_ACCESS_BIT_ARB 0x00000004
+#define WGL_LOSE_CONTEXT_ON_RESET_ARB 0x8252
+#define WGL_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB 0x8256
+#define WGL_NO_RESET_NOTIFICATION_ARB 0x8261
+#endif
+
+#ifndef WGL_EXT_make_current_read
+#define ERROR_INVALID_PIXEL_TYPE_EXT 0x2043
+#endif
+
+#ifndef WGL_EXT_pixel_format
+#define WGL_NUMBER_PIXEL_FORMATS_EXT 0x2000
+#define WGL_DRAW_TO_WINDOW_EXT 0x2001
+#define WGL_DRAW_TO_BITMAP_EXT 0x2002
+#define WGL_ACCELERATION_EXT 0x2003
+#define WGL_NEED_PALETTE_EXT 0x2004
+#define WGL_NEED_SYSTEM_PALETTE_EXT 0x2005
+#define WGL_SWAP_LAYER_BUFFERS_EXT 0x2006
+#define WGL_SWAP_METHOD_EXT 0x2007
+#define WGL_NUMBER_OVERLAYS_EXT 0x2008
+#define WGL_NUMBER_UNDERLAYS_EXT 0x2009
+#define WGL_TRANSPARENT_EXT 0x200A
+#define WGL_TRANSPARENT_VALUE_EXT 0x200B
+#define WGL_SHARE_DEPTH_EXT 0x200C
+#define WGL_SHARE_STENCIL_EXT 0x200D
+#define WGL_SHARE_ACCUM_EXT 0x200E
+#define WGL_SUPPORT_GDI_EXT 0x200F
+#define WGL_SUPPORT_OPENGL_EXT 0x2010
+#define WGL_DOUBLE_BUFFER_EXT 0x2011
+#define WGL_STEREO_EXT 0x2012
+#define WGL_PIXEL_TYPE_EXT 0x2013
+#define WGL_COLOR_BITS_EXT 0x2014
+#define WGL_RED_BITS_EXT 0x2015
+#define WGL_RED_SHIFT_EXT 0x2016
+#define WGL_GREEN_BITS_EXT 0x2017
+#define WGL_GREEN_SHIFT_EXT 0x2018
+#define WGL_BLUE_BITS_EXT 0x2019
+#define WGL_BLUE_SHIFT_EXT 0x201A
+#define WGL_ALPHA_BITS_EXT 0x201B
+#define WGL_ALPHA_SHIFT_EXT 0x201C
+#define WGL_ACCUM_BITS_EXT 0x201D
+#define WGL_ACCUM_RED_BITS_EXT 0x201E
+#define WGL_ACCUM_GREEN_BITS_EXT 0x201F
+#define WGL_ACCUM_BLUE_BITS_EXT 0x2020
+#define WGL_ACCUM_ALPHA_BITS_EXT 0x2021
+#define WGL_DEPTH_BITS_EXT 0x2022
+#define WGL_STENCIL_BITS_EXT 0x2023
+#define WGL_AUX_BUFFERS_EXT 0x2024
+#define WGL_NO_ACCELERATION_EXT 0x2025
+#define WGL_GENERIC_ACCELERATION_EXT 0x2026
+#define WGL_FULL_ACCELERATION_EXT 0x2027
+#define WGL_SWAP_EXCHANGE_EXT 0x2028
+#define WGL_SWAP_COPY_EXT 0x2029
+#define WGL_SWAP_UNDEFINED_EXT 0x202A
+#define WGL_TYPE_RGBA_EXT 0x202B
+#define WGL_TYPE_COLORINDEX_EXT 0x202C
+#endif
+
+#ifndef WGL_EXT_pbuffer
+#define WGL_DRAW_TO_PBUFFER_EXT 0x202D
+#define WGL_MAX_PBUFFER_PIXELS_EXT 0x202E
+#define WGL_MAX_PBUFFER_WIDTH_EXT 0x202F
+#define WGL_MAX_PBUFFER_HEIGHT_EXT 0x2030
+#define WGL_OPTIMAL_PBUFFER_WIDTH_EXT 0x2031
+#define WGL_OPTIMAL_PBUFFER_HEIGHT_EXT 0x2032
+#define WGL_PBUFFER_LARGEST_EXT 0x2033
+#define WGL_PBUFFER_WIDTH_EXT 0x2034
+#define WGL_PBUFFER_HEIGHT_EXT 0x2035
+#endif
+
+#ifndef WGL_EXT_depth_float
+#define WGL_DEPTH_FLOAT_EXT 0x2040
+#endif
+
+#ifndef WGL_3DFX_multisample
+#define WGL_SAMPLE_BUFFERS_3DFX 0x2060
+#define WGL_SAMPLES_3DFX 0x2061
+#endif
+
+#ifndef WGL_EXT_multisample
+#define WGL_SAMPLE_BUFFERS_EXT 0x2041
+#define WGL_SAMPLES_EXT 0x2042
+#endif
+
+#ifndef WGL_I3D_digital_video_control
+#define WGL_DIGITAL_VIDEO_CURSOR_ALPHA_FRAMEBUFFER_I3D 0x2050
+#define WGL_DIGITAL_VIDEO_CURSOR_ALPHA_VALUE_I3D 0x2051
+#define WGL_DIGITAL_VIDEO_CURSOR_INCLUDED_I3D 0x2052
+#define WGL_DIGITAL_VIDEO_GAMMA_CORRECTED_I3D 0x2053
+#endif
+
+#ifndef WGL_I3D_gamma
+#define WGL_GAMMA_TABLE_SIZE_I3D 0x204E
+#define WGL_GAMMA_EXCLUDE_DESKTOP_I3D 0x204F
+#endif
+
+#ifndef WGL_I3D_genlock
+#define WGL_GENLOCK_SOURCE_MULTIVIEW_I3D 0x2044
+#define WGL_GENLOCK_SOURCE_EXTENAL_SYNC_I3D 0x2045
+#define WGL_GENLOCK_SOURCE_EXTENAL_FIELD_I3D 0x2046
+#define WGL_GENLOCK_SOURCE_EXTENAL_TTL_I3D 0x2047
+#define WGL_GENLOCK_SOURCE_DIGITAL_SYNC_I3D 0x2048
+#define WGL_GENLOCK_SOURCE_DIGITAL_FIELD_I3D 0x2049
+#define WGL_GENLOCK_SOURCE_EDGE_FALLING_I3D 0x204A
+#define WGL_GENLOCK_SOURCE_EDGE_RISING_I3D 0x204B
+#define WGL_GENLOCK_SOURCE_EDGE_BOTH_I3D 0x204C
+#endif
+
+#ifndef WGL_I3D_image_buffer
+#define WGL_IMAGE_BUFFER_MIN_ACCESS_I3D 0x00000001
+#define WGL_IMAGE_BUFFER_LOCK_I3D 0x00000002
+#endif
+
+#ifndef WGL_I3D_swap_frame_lock
+#endif
+
+#ifndef WGL_NV_render_depth_texture
+#define WGL_BIND_TO_TEXTURE_DEPTH_NV 0x20A3
+#define WGL_BIND_TO_TEXTURE_RECTANGLE_DEPTH_NV 0x20A4
+#define WGL_DEPTH_TEXTURE_FORMAT_NV 0x20A5
+#define WGL_TEXTURE_DEPTH_COMPONENT_NV 0x20A6
+#define WGL_DEPTH_COMPONENT_NV 0x20A7
+#endif
+
+#ifndef WGL_NV_render_texture_rectangle
+#define WGL_BIND_TO_TEXTURE_RECTANGLE_RGB_NV 0x20A0
+#define WGL_BIND_TO_TEXTURE_RECTANGLE_RGBA_NV 0x20A1
+#define WGL_TEXTURE_RECTANGLE_NV 0x20A2
+#endif
+
+#ifndef WGL_ATI_pixel_format_float
+#define WGL_TYPE_RGBA_FLOAT_ATI 0x21A0
+#endif
+
+#ifndef WGL_NV_float_buffer
+#define WGL_FLOAT_COMPONENTS_NV 0x20B0
+#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_R_NV 0x20B1
+#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RG_NV 0x20B2
+#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGB_NV 0x20B3
+#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGBA_NV 0x20B4
+#define WGL_TEXTURE_FLOAT_R_NV 0x20B5
+#define WGL_TEXTURE_FLOAT_RG_NV 0x20B6
+#define WGL_TEXTURE_FLOAT_RGB_NV 0x20B7
+#define WGL_TEXTURE_FLOAT_RGBA_NV 0x20B8
+#endif
+
+#ifndef WGL_3DL_stereo_control
+#define WGL_STEREO_EMITTER_ENABLE_3DL 0x2055
+#define WGL_STEREO_EMITTER_DISABLE_3DL 0x2056
+#define WGL_STEREO_POLARITY_NORMAL_3DL 0x2057
+#define WGL_STEREO_POLARITY_INVERT_3DL 0x2058
+#endif
+
+#ifndef WGL_EXT_pixel_format_packed_float
+#define WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT 0x20A8
+#endif
+
+#ifndef WGL_EXT_framebuffer_sRGB
+#define WGL_FRAMEBUFFER_SRGB_CAPABLE_EXT 0x20A9
+#endif
+
+#ifndef WGL_NV_present_video
+#define WGL_NUM_VIDEO_SLOTS_NV 0x20F0
+#endif
+
+#ifndef WGL_NV_video_out
+#define WGL_BIND_TO_VIDEO_RGB_NV 0x20C0
+#define WGL_BIND_TO_VIDEO_RGBA_NV 0x20C1
+#define WGL_BIND_TO_VIDEO_RGB_AND_DEPTH_NV 0x20C2
+#define WGL_VIDEO_OUT_COLOR_NV 0x20C3
+#define WGL_VIDEO_OUT_ALPHA_NV 0x20C4
+#define WGL_VIDEO_OUT_DEPTH_NV 0x20C5
+#define WGL_VIDEO_OUT_COLOR_AND_ALPHA_NV 0x20C6
+#define WGL_VIDEO_OUT_COLOR_AND_DEPTH_NV 0x20C7
+#define WGL_VIDEO_OUT_FRAME 0x20C8
+#define WGL_VIDEO_OUT_FIELD_1 0x20C9
+#define WGL_VIDEO_OUT_FIELD_2 0x20CA
+#define WGL_VIDEO_OUT_STACKED_FIELDS_1_2 0x20CB
+#define WGL_VIDEO_OUT_STACKED_FIELDS_2_1 0x20CC
+#endif
+
+#ifndef WGL_NV_swap_group
+#endif
+
+#ifndef WGL_NV_gpu_affinity
+#define WGL_ERROR_INCOMPATIBLE_AFFINITY_MASKS_NV 0x20D0
+#define WGL_ERROR_MISSING_AFFINITY_MASK_NV 0x20D1
+#endif
+
+#ifndef WGL_AMD_gpu_association
+#define WGL_GPU_VENDOR_AMD 0x1F00
+#define WGL_GPU_RENDERER_STRING_AMD 0x1F01
+#define WGL_GPU_OPENGL_VERSION_STRING_AMD 0x1F02
+#define WGL_GPU_FASTEST_TARGET_GPUS_AMD 0x21A2
+#define WGL_GPU_RAM_AMD 0x21A3
+#define WGL_GPU_CLOCK_AMD 0x21A4
+#define WGL_GPU_NUM_PIPES_AMD 0x21A5
+#define WGL_GPU_NUM_SIMD_AMD 0x21A6
+#define WGL_GPU_NUM_RB_AMD 0x21A7
+#define WGL_GPU_NUM_SPI_AMD 0x21A8
+#endif
+
+#ifndef WGL_NV_video_capture
+#define WGL_UNIQUE_ID_NV 0x20CE
+#define WGL_NUM_VIDEO_CAPTURE_SLOTS_NV 0x20CF
+#endif
+
+#ifndef WGL_NV_copy_image
+#endif
+
+#ifndef WGL_NV_multisample_coverage
+#define WGL_COVERAGE_SAMPLES_NV 0x2042
+#define WGL_COLOR_SAMPLES_NV 0x20B9
+#endif
+
+#ifndef WGL_EXT_create_context_es2_profile
+#define WGL_CONTEXT_ES2_PROFILE_BIT_EXT 0x00000004
+#endif
+
+
+/*************************************************************/
+
+#ifndef WGL_ARB_pbuffer
+DECLARE_HANDLE(HPBUFFERARB);
+#endif
+#ifndef WGL_EXT_pbuffer
+DECLARE_HANDLE(HPBUFFEREXT);
+#endif
+#ifndef WGL_NV_present_video
+DECLARE_HANDLE(HVIDEOOUTPUTDEVICENV);
+#endif
+#ifndef WGL_NV_video_output
+DECLARE_HANDLE(HPVIDEODEV);
+#endif
+#ifndef WGL_NV_gpu_affinity
+DECLARE_HANDLE(HPGPUNV);
+DECLARE_HANDLE(HGPUNV);
+
+typedef struct _GPU_DEVICE {
+ DWORD cb;
+ CHAR DeviceName[32];
+ CHAR DeviceString[128];
+ DWORD Flags;
+ RECT rcVirtualScreen;
+} GPU_DEVICE, *PGPU_DEVICE;
+#endif
+#ifndef WGL_NV_video_capture
+DECLARE_HANDLE(HVIDEOINPUTDEVICENV);
+#endif
+
+#ifndef WGL_ARB_buffer_region
+#define WGL_ARB_buffer_region 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern HANDLE WINAPI wglCreateBufferRegionARB (HDC hDC, int iLayerPlane, UINT uType);
+extern VOID WINAPI wglDeleteBufferRegionARB (HANDLE hRegion);
+extern BOOL WINAPI wglSaveBufferRegionARB (HANDLE hRegion, int x, int y, int width, int height);
+extern BOOL WINAPI wglRestoreBufferRegionARB (HANDLE hRegion, int x, int y, int width, int height, int xSrc, int ySrc);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef HANDLE (WINAPI * PFNWGLCREATEBUFFERREGIONARBPROC) (HDC hDC, int iLayerPlane, UINT uType);
+typedef VOID (WINAPI * PFNWGLDELETEBUFFERREGIONARBPROC) (HANDLE hRegion);
+typedef BOOL (WINAPI * PFNWGLSAVEBUFFERREGIONARBPROC) (HANDLE hRegion, int x, int y, int width, int height);
+typedef BOOL (WINAPI * PFNWGLRESTOREBUFFERREGIONARBPROC) (HANDLE hRegion, int x, int y, int width, int height, int xSrc, int ySrc);
+#endif
+
+#ifndef WGL_ARB_multisample
+#define WGL_ARB_multisample 1
+#endif
+
+#ifndef WGL_ARB_extensions_string
+#define WGL_ARB_extensions_string 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern const char * WINAPI wglGetExtensionsStringARB (HDC hdc);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef const char * (WINAPI * PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
+#endif
+
+#ifndef WGL_ARB_pixel_format
+#define WGL_ARB_pixel_format 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern BOOL WINAPI wglGetPixelFormatAttribivARB (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
+extern BOOL WINAPI wglGetPixelFormatAttribfvARB (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, FLOAT *pfValues);
+extern BOOL WINAPI wglChoosePixelFormatARB (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
+typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBFVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, FLOAT *pfValues);
+typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
+#endif
+
+#ifndef WGL_ARB_make_current_read
+#define WGL_ARB_make_current_read 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern BOOL WINAPI wglMakeContextCurrentARB (HDC hDrawDC, HDC hReadDC, HGLRC hglrc);
+extern HDC WINAPI wglGetCurrentReadDCARB (void);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef BOOL (WINAPI * PFNWGLMAKECONTEXTCURRENTARBPROC) (HDC hDrawDC, HDC hReadDC, HGLRC hglrc);
+typedef HDC (WINAPI * PFNWGLGETCURRENTREADDCARBPROC) (void);
+#endif
+
+#ifndef WGL_ARB_pbuffer
+#define WGL_ARB_pbuffer 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern HPBUFFERARB WINAPI wglCreatePbufferARB (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList);
+extern HDC WINAPI wglGetPbufferDCARB (HPBUFFERARB hPbuffer);
+extern int WINAPI wglReleasePbufferDCARB (HPBUFFERARB hPbuffer, HDC hDC);
+extern BOOL WINAPI wglDestroyPbufferARB (HPBUFFERARB hPbuffer);
+extern BOOL WINAPI wglQueryPbufferARB (HPBUFFERARB hPbuffer, int iAttribute, int *piValue);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef HPBUFFERARB (WINAPI * PFNWGLCREATEPBUFFERARBPROC) (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList);
+typedef HDC (WINAPI * PFNWGLGETPBUFFERDCARBPROC) (HPBUFFERARB hPbuffer);
+typedef int (WINAPI * PFNWGLRELEASEPBUFFERDCARBPROC) (HPBUFFERARB hPbuffer, HDC hDC);
+typedef BOOL (WINAPI * PFNWGLDESTROYPBUFFERARBPROC) (HPBUFFERARB hPbuffer);
+typedef BOOL (WINAPI * PFNWGLQUERYPBUFFERARBPROC) (HPBUFFERARB hPbuffer, int iAttribute, int *piValue);
+#endif
+
+#ifndef WGL_ARB_render_texture
+#define WGL_ARB_render_texture 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern BOOL WINAPI wglBindTexImageARB (HPBUFFERARB hPbuffer, int iBuffer);
+extern BOOL WINAPI wglReleaseTexImageARB (HPBUFFERARB hPbuffer, int iBuffer);
+extern BOOL WINAPI wglSetPbufferAttribARB (HPBUFFERARB hPbuffer, const int *piAttribList);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef BOOL (WINAPI * PFNWGLBINDTEXIMAGEARBPROC) (HPBUFFERARB hPbuffer, int iBuffer);
+typedef BOOL (WINAPI * PFNWGLRELEASETEXIMAGEARBPROC) (HPBUFFERARB hPbuffer, int iBuffer);
+typedef BOOL (WINAPI * PFNWGLSETPBUFFERATTRIBARBPROC) (HPBUFFERARB hPbuffer, const int *piAttribList);
+#endif
+
+#ifndef WGL_ARB_pixel_format_float
+#define WGL_ARB_pixel_format_float 1
+#endif
+
+#ifndef WGL_ARB_framebuffer_sRGB
+#define WGL_ARB_framebuffer_sRGB 1
+#endif
+
+#ifndef WGL_ARB_create_context
+#define WGL_ARB_create_context 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern HGLRC WINAPI wglCreateContextAttribsARB (HDC hDC, HGLRC hShareContext, const int *attribList);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef HGLRC (WINAPI * PFNWGLCREATECONTEXTATTRIBSARBPROC) (HDC hDC, HGLRC hShareContext, const int *attribList);
+#endif
+
+#ifndef WGL_ARB_create_context_profile
+#define WGL_ARB_create_context_profile 1
+#endif
+
+#ifndef WGL_ARB_create_context_robustness
+#define WGL_ARB_create_context_robustness 1
+#endif
+
+#ifndef WGL_EXT_display_color_table
+#define WGL_EXT_display_color_table 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern GLboolean WINAPI wglCreateDisplayColorTableEXT (GLushort id);
+extern GLboolean WINAPI wglLoadDisplayColorTableEXT (const GLushort *table, GLuint length);
+extern GLboolean WINAPI wglBindDisplayColorTableEXT (GLushort id);
+extern VOID WINAPI wglDestroyDisplayColorTableEXT (GLushort id);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef GLboolean (WINAPI * PFNWGLCREATEDISPLAYCOLORTABLEEXTPROC) (GLushort id);
+typedef GLboolean (WINAPI * PFNWGLLOADDISPLAYCOLORTABLEEXTPROC) (const GLushort *table, GLuint length);
+typedef GLboolean (WINAPI * PFNWGLBINDDISPLAYCOLORTABLEEXTPROC) (GLushort id);
+typedef VOID (WINAPI * PFNWGLDESTROYDISPLAYCOLORTABLEEXTPROC) (GLushort id);
+#endif
+
+#ifndef WGL_EXT_extensions_string
+#define WGL_EXT_extensions_string 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern const char * WINAPI wglGetExtensionsStringEXT (void);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef const char * (WINAPI * PFNWGLGETEXTENSIONSSTRINGEXTPROC) (void);
+#endif
+
+#ifndef WGL_EXT_make_current_read
+#define WGL_EXT_make_current_read 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern BOOL WINAPI wglMakeContextCurrentEXT (HDC hDrawDC, HDC hReadDC, HGLRC hglrc);
+extern HDC WINAPI wglGetCurrentReadDCEXT (void);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef BOOL (WINAPI * PFNWGLMAKECONTEXTCURRENTEXTPROC) (HDC hDrawDC, HDC hReadDC, HGLRC hglrc);
+typedef HDC (WINAPI * PFNWGLGETCURRENTREADDCEXTPROC) (void);
+#endif
+
+#ifndef WGL_EXT_pbuffer
+#define WGL_EXT_pbuffer 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern HPBUFFEREXT WINAPI wglCreatePbufferEXT (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList);
+extern HDC WINAPI wglGetPbufferDCEXT (HPBUFFEREXT hPbuffer);
+extern int WINAPI wglReleasePbufferDCEXT (HPBUFFEREXT hPbuffer, HDC hDC);
+extern BOOL WINAPI wglDestroyPbufferEXT (HPBUFFEREXT hPbuffer);
+extern BOOL WINAPI wglQueryPbufferEXT (HPBUFFEREXT hPbuffer, int iAttribute, int *piValue);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef HPBUFFEREXT (WINAPI * PFNWGLCREATEPBUFFEREXTPROC) (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList);
+typedef HDC (WINAPI * PFNWGLGETPBUFFERDCEXTPROC) (HPBUFFEREXT hPbuffer);
+typedef int (WINAPI * PFNWGLRELEASEPBUFFERDCEXTPROC) (HPBUFFEREXT hPbuffer, HDC hDC);
+typedef BOOL (WINAPI * PFNWGLDESTROYPBUFFEREXTPROC) (HPBUFFEREXT hPbuffer);
+typedef BOOL (WINAPI * PFNWGLQUERYPBUFFEREXTPROC) (HPBUFFEREXT hPbuffer, int iAttribute, int *piValue);
+#endif
+
+#ifndef WGL_EXT_pixel_format
+#define WGL_EXT_pixel_format 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern BOOL WINAPI wglGetPixelFormatAttribivEXT (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, int *piValues);
+extern BOOL WINAPI wglGetPixelFormatAttribfvEXT (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, FLOAT *pfValues);
+extern BOOL WINAPI wglChoosePixelFormatEXT (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVEXTPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, int *piValues);
+typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBFVEXTPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, FLOAT *pfValues);
+typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATEXTPROC) (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
+#endif
+
+#ifndef WGL_EXT_swap_control
+#define WGL_EXT_swap_control 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern BOOL WINAPI wglSwapIntervalEXT (int interval);
+extern int WINAPI wglGetSwapIntervalEXT (void);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
+typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
+#endif
+
+#ifndef WGL_EXT_depth_float
+#define WGL_EXT_depth_float 1
+#endif
+
+#ifndef WGL_NV_vertex_array_range
+#define WGL_NV_vertex_array_range 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern void* WINAPI wglAllocateMemoryNV (GLsizei size, GLfloat readfreq, GLfloat writefreq, GLfloat priority);
+extern void WINAPI wglFreeMemoryNV (void *pointer);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef void* (WINAPI * PFNWGLALLOCATEMEMORYNVPROC) (GLsizei size, GLfloat readfreq, GLfloat writefreq, GLfloat priority);
+typedef void (WINAPI * PFNWGLFREEMEMORYNVPROC) (void *pointer);
+#endif
+
+#ifndef WGL_3DFX_multisample
+#define WGL_3DFX_multisample 1
+#endif
+
+#ifndef WGL_EXT_multisample
+#define WGL_EXT_multisample 1
+#endif
+
+#ifndef WGL_OML_sync_control
+#define WGL_OML_sync_control 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern BOOL WINAPI wglGetSyncValuesOML (HDC hdc, INT64 *ust, INT64 *msc, INT64 *sbc);
+extern BOOL WINAPI wglGetMscRateOML (HDC hdc, INT32 *numerator, INT32 *denominator);
+extern INT64 WINAPI wglSwapBuffersMscOML (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder);
+extern INT64 WINAPI wglSwapLayerBuffersMscOML (HDC hdc, int fuPlanes, INT64 target_msc, INT64 divisor, INT64 remainder);
+extern BOOL WINAPI wglWaitForMscOML (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder, INT64 *ust, INT64 *msc, INT64 *sbc);
+extern BOOL WINAPI wglWaitForSbcOML (HDC hdc, INT64 target_sbc, INT64 *ust, INT64 *msc, INT64 *sbc);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef BOOL (WINAPI * PFNWGLGETSYNCVALUESOMLPROC) (HDC hdc, INT64 *ust, INT64 *msc, INT64 *sbc);
+typedef BOOL (WINAPI * PFNWGLGETMSCRATEOMLPROC) (HDC hdc, INT32 *numerator, INT32 *denominator);
+typedef INT64 (WINAPI * PFNWGLSWAPBUFFERSMSCOMLPROC) (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder);
+typedef INT64 (WINAPI * PFNWGLSWAPLAYERBUFFERSMSCOMLPROC) (HDC hdc, int fuPlanes, INT64 target_msc, INT64 divisor, INT64 remainder);
+typedef BOOL (WINAPI * PFNWGLWAITFORMSCOMLPROC) (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder, INT64 *ust, INT64 *msc, INT64 *sbc);
+typedef BOOL (WINAPI * PFNWGLWAITFORSBCOMLPROC) (HDC hdc, INT64 target_sbc, INT64 *ust, INT64 *msc, INT64 *sbc);
+#endif
+
+#ifndef WGL_I3D_digital_video_control
+#define WGL_I3D_digital_video_control 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern BOOL WINAPI wglGetDigitalVideoParametersI3D (HDC hDC, int iAttribute, int *piValue);
+extern BOOL WINAPI wglSetDigitalVideoParametersI3D (HDC hDC, int iAttribute, const int *piValue);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef BOOL (WINAPI * PFNWGLGETDIGITALVIDEOPARAMETERSI3DPROC) (HDC hDC, int iAttribute, int *piValue);
+typedef BOOL (WINAPI * PFNWGLSETDIGITALVIDEOPARAMETERSI3DPROC) (HDC hDC, int iAttribute, const int *piValue);
+#endif
+
+#ifndef WGL_I3D_gamma
+#define WGL_I3D_gamma 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern BOOL WINAPI wglGetGammaTableParametersI3D (HDC hDC, int iAttribute, int *piValue);
+extern BOOL WINAPI wglSetGammaTableParametersI3D (HDC hDC, int iAttribute, const int *piValue);
+extern BOOL WINAPI wglGetGammaTableI3D (HDC hDC, int iEntries, USHORT *puRed, USHORT *puGreen, USHORT *puBlue);
+extern BOOL WINAPI wglSetGammaTableI3D (HDC hDC, int iEntries, const USHORT *puRed, const USHORT *puGreen, const USHORT *puBlue);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef BOOL (WINAPI * PFNWGLGETGAMMATABLEPARAMETERSI3DPROC) (HDC hDC, int iAttribute, int *piValue);
+typedef BOOL (WINAPI * PFNWGLSETGAMMATABLEPARAMETERSI3DPROC) (HDC hDC, int iAttribute, const int *piValue);
+typedef BOOL (WINAPI * PFNWGLGETGAMMATABLEI3DPROC) (HDC hDC, int iEntries, USHORT *puRed, USHORT *puGreen, USHORT *puBlue);
+typedef BOOL (WINAPI * PFNWGLSETGAMMATABLEI3DPROC) (HDC hDC, int iEntries, const USHORT *puRed, const USHORT *puGreen, const USHORT *puBlue);
+#endif
+
+#ifndef WGL_I3D_genlock
+#define WGL_I3D_genlock 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern BOOL WINAPI wglEnableGenlockI3D (HDC hDC);
+extern BOOL WINAPI wglDisableGenlockI3D (HDC hDC);
+extern BOOL WINAPI wglIsEnabledGenlockI3D (HDC hDC, BOOL *pFlag);
+extern BOOL WINAPI wglGenlockSourceI3D (HDC hDC, UINT uSource);
+extern BOOL WINAPI wglGetGenlockSourceI3D (HDC hDC, UINT *uSource);
+extern BOOL WINAPI wglGenlockSourceEdgeI3D (HDC hDC, UINT uEdge);
+extern BOOL WINAPI wglGetGenlockSourceEdgeI3D (HDC hDC, UINT *uEdge);
+extern BOOL WINAPI wglGenlockSampleRateI3D (HDC hDC, UINT uRate);
+extern BOOL WINAPI wglGetGenlockSampleRateI3D (HDC hDC, UINT *uRate);
+extern BOOL WINAPI wglGenlockSourceDelayI3D (HDC hDC, UINT uDelay);
+extern BOOL WINAPI wglGetGenlockSourceDelayI3D (HDC hDC, UINT *uDelay);
+extern BOOL WINAPI wglQueryGenlockMaxSourceDelayI3D (HDC hDC, UINT *uMaxLineDelay, UINT *uMaxPixelDelay);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef BOOL (WINAPI * PFNWGLENABLEGENLOCKI3DPROC) (HDC hDC);
+typedef BOOL (WINAPI * PFNWGLDISABLEGENLOCKI3DPROC) (HDC hDC);
+typedef BOOL (WINAPI * PFNWGLISENABLEDGENLOCKI3DPROC) (HDC hDC, BOOL *pFlag);
+typedef BOOL (WINAPI * PFNWGLGENLOCKSOURCEI3DPROC) (HDC hDC, UINT uSource);
+typedef BOOL (WINAPI * PFNWGLGETGENLOCKSOURCEI3DPROC) (HDC hDC, UINT *uSource);
+typedef BOOL (WINAPI * PFNWGLGENLOCKSOURCEEDGEI3DPROC) (HDC hDC, UINT uEdge);
+typedef BOOL (WINAPI * PFNWGLGETGENLOCKSOURCEEDGEI3DPROC) (HDC hDC, UINT *uEdge);
+typedef BOOL (WINAPI * PFNWGLGENLOCKSAMPLERATEI3DPROC) (HDC hDC, UINT uRate);
+typedef BOOL (WINAPI * PFNWGLGETGENLOCKSAMPLERATEI3DPROC) (HDC hDC, UINT *uRate);
+typedef BOOL (WINAPI * PFNWGLGENLOCKSOURCEDELAYI3DPROC) (HDC hDC, UINT uDelay);
+typedef BOOL (WINAPI * PFNWGLGETGENLOCKSOURCEDELAYI3DPROC) (HDC hDC, UINT *uDelay);
+typedef BOOL (WINAPI * PFNWGLQUERYGENLOCKMAXSOURCEDELAYI3DPROC) (HDC hDC, UINT *uMaxLineDelay, UINT *uMaxPixelDelay);
+#endif
+
+#ifndef WGL_I3D_image_buffer
+#define WGL_I3D_image_buffer 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern LPVOID WINAPI wglCreateImageBufferI3D (HDC hDC, DWORD dwSize, UINT uFlags);
+extern BOOL WINAPI wglDestroyImageBufferI3D (HDC hDC, LPVOID pAddress);
+extern BOOL WINAPI wglAssociateImageBufferEventsI3D (HDC hDC, const HANDLE *pEvent, const LPVOID *pAddress, const DWORD *pSize, UINT count);
+extern BOOL WINAPI wglReleaseImageBufferEventsI3D (HDC hDC, const LPVOID *pAddress, UINT count);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef LPVOID (WINAPI * PFNWGLCREATEIMAGEBUFFERI3DPROC) (HDC hDC, DWORD dwSize, UINT uFlags);
+typedef BOOL (WINAPI * PFNWGLDESTROYIMAGEBUFFERI3DPROC) (HDC hDC, LPVOID pAddress);
+typedef BOOL (WINAPI * PFNWGLASSOCIATEIMAGEBUFFEREVENTSI3DPROC) (HDC hDC, const HANDLE *pEvent, const LPVOID *pAddress, const DWORD *pSize, UINT count);
+typedef BOOL (WINAPI * PFNWGLRELEASEIMAGEBUFFEREVENTSI3DPROC) (HDC hDC, const LPVOID *pAddress, UINT count);
+#endif
+
+#ifndef WGL_I3D_swap_frame_lock
+#define WGL_I3D_swap_frame_lock 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern BOOL WINAPI wglEnableFrameLockI3D (void);
+extern BOOL WINAPI wglDisableFrameLockI3D (void);
+extern BOOL WINAPI wglIsEnabledFrameLockI3D (BOOL *pFlag);
+extern BOOL WINAPI wglQueryFrameLockMasterI3D (BOOL *pFlag);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef BOOL (WINAPI * PFNWGLENABLEFRAMELOCKI3DPROC) (void);
+typedef BOOL (WINAPI * PFNWGLDISABLEFRAMELOCKI3DPROC) (void);
+typedef BOOL (WINAPI * PFNWGLISENABLEDFRAMELOCKI3DPROC) (BOOL *pFlag);
+typedef BOOL (WINAPI * PFNWGLQUERYFRAMELOCKMASTERI3DPROC) (BOOL *pFlag);
+#endif
+
+#ifndef WGL_I3D_swap_frame_usage
+#define WGL_I3D_swap_frame_usage 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern BOOL WINAPI wglGetFrameUsageI3D (float *pUsage);
+extern BOOL WINAPI wglBeginFrameTrackingI3D (void);
+extern BOOL WINAPI wglEndFrameTrackingI3D (void);
+extern BOOL WINAPI wglQueryFrameTrackingI3D (DWORD *pFrameCount, DWORD *pMissedFrames, float *pLastMissedUsage);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef BOOL (WINAPI * PFNWGLGETFRAMEUSAGEI3DPROC) (float *pUsage);
+typedef BOOL (WINAPI * PFNWGLBEGINFRAMETRACKINGI3DPROC) (void);
+typedef BOOL (WINAPI * PFNWGLENDFRAMETRACKINGI3DPROC) (void);
+typedef BOOL (WINAPI * PFNWGLQUERYFRAMETRACKINGI3DPROC) (DWORD *pFrameCount, DWORD *pMissedFrames, float *pLastMissedUsage);
+#endif
+
+#ifndef WGL_ATI_pixel_format_float
+#define WGL_ATI_pixel_format_float 1
+#endif
+
+#ifndef WGL_NV_float_buffer
+#define WGL_NV_float_buffer 1
+#endif
+
+#ifndef WGL_3DL_stereo_control
+#define WGL_3DL_stereo_control 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern BOOL WINAPI wglSetStereoEmitterState3DL (HDC hDC, UINT uState);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef BOOL (WINAPI * PFNWGLSETSTEREOEMITTERSTATE3DLPROC) (HDC hDC, UINT uState);
+#endif
+
+#ifndef WGL_EXT_pixel_format_packed_float
+#define WGL_EXT_pixel_format_packed_float 1
+#endif
+
+#ifndef WGL_EXT_framebuffer_sRGB
+#define WGL_EXT_framebuffer_sRGB 1
+#endif
+
+#ifndef WGL_NV_present_video
+#define WGL_NV_present_video 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern int WINAPI wglEnumerateVideoDevicesNV (HDC hDC, HVIDEOOUTPUTDEVICENV *phDeviceList);
+extern BOOL WINAPI wglBindVideoDeviceNV (HDC hDC, unsigned int uVideoSlot, HVIDEOOUTPUTDEVICENV hVideoDevice, const int *piAttribList);
+extern BOOL WINAPI wglQueryCurrentContextNV (int iAttribute, int *piValue);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef int (WINAPI * PFNWGLENUMERATEVIDEODEVICESNVPROC) (HDC hDC, HVIDEOOUTPUTDEVICENV *phDeviceList);
+typedef BOOL (WINAPI * PFNWGLBINDVIDEODEVICENVPROC) (HDC hDC, unsigned int uVideoSlot, HVIDEOOUTPUTDEVICENV hVideoDevice, const int *piAttribList);
+typedef BOOL (WINAPI * PFNWGLQUERYCURRENTCONTEXTNVPROC) (int iAttribute, int *piValue);
+#endif
+
+#ifndef WGL_NV_video_output
+#define WGL_NV_video_output 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern BOOL WINAPI wglGetVideoDeviceNV (HDC hDC, int numDevices, HPVIDEODEV *hVideoDevice);
+extern BOOL WINAPI wglReleaseVideoDeviceNV (HPVIDEODEV hVideoDevice);
+extern BOOL WINAPI wglBindVideoImageNV (HPVIDEODEV hVideoDevice, HPBUFFERARB hPbuffer, int iVideoBuffer);
+extern BOOL WINAPI wglReleaseVideoImageNV (HPBUFFERARB hPbuffer, int iVideoBuffer);
+extern BOOL WINAPI wglSendPbufferToVideoNV (HPBUFFERARB hPbuffer, int iBufferType, unsigned long *pulCounterPbuffer, BOOL bBlock);
+extern BOOL WINAPI wglGetVideoInfoNV (HPVIDEODEV hpVideoDevice, unsigned long *pulCounterOutputPbuffer, unsigned long *pulCounterOutputVideo);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef BOOL (WINAPI * PFNWGLGETVIDEODEVICENVPROC) (HDC hDC, int numDevices, HPVIDEODEV *hVideoDevice);
+typedef BOOL (WINAPI * PFNWGLRELEASEVIDEODEVICENVPROC) (HPVIDEODEV hVideoDevice);
+typedef BOOL (WINAPI * PFNWGLBINDVIDEOIMAGENVPROC) (HPVIDEODEV hVideoDevice, HPBUFFERARB hPbuffer, int iVideoBuffer);
+typedef BOOL (WINAPI * PFNWGLRELEASEVIDEOIMAGENVPROC) (HPBUFFERARB hPbuffer, int iVideoBuffer);
+typedef BOOL (WINAPI * PFNWGLSENDPBUFFERTOVIDEONVPROC) (HPBUFFERARB hPbuffer, int iBufferType, unsigned long *pulCounterPbuffer, BOOL bBlock);
+typedef BOOL (WINAPI * PFNWGLGETVIDEOINFONVPROC) (HPVIDEODEV hpVideoDevice, unsigned long *pulCounterOutputPbuffer, unsigned long *pulCounterOutputVideo);
+#endif
+
+#ifndef WGL_NV_swap_group
+#define WGL_NV_swap_group 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern BOOL WINAPI wglJoinSwapGroupNV (HDC hDC, GLuint group);
+extern BOOL WINAPI wglBindSwapBarrierNV (GLuint group, GLuint barrier);
+extern BOOL WINAPI wglQuerySwapGroupNV (HDC hDC, GLuint *group, GLuint *barrier);
+extern BOOL WINAPI wglQueryMaxSwapGroupsNV (HDC hDC, GLuint *maxGroups, GLuint *maxBarriers);
+extern BOOL WINAPI wglQueryFrameCountNV (HDC hDC, GLuint *count);
+extern BOOL WINAPI wglResetFrameCountNV (HDC hDC);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef BOOL (WINAPI * PFNWGLJOINSWAPGROUPNVPROC) (HDC hDC, GLuint group);
+typedef BOOL (WINAPI * PFNWGLBINDSWAPBARRIERNVPROC) (GLuint group, GLuint barrier);
+typedef BOOL (WINAPI * PFNWGLQUERYSWAPGROUPNVPROC) (HDC hDC, GLuint *group, GLuint *barrier);
+typedef BOOL (WINAPI * PFNWGLQUERYMAXSWAPGROUPSNVPROC) (HDC hDC, GLuint *maxGroups, GLuint *maxBarriers);
+typedef BOOL (WINAPI * PFNWGLQUERYFRAMECOUNTNVPROC) (HDC hDC, GLuint *count);
+typedef BOOL (WINAPI * PFNWGLRESETFRAMECOUNTNVPROC) (HDC hDC);
+#endif
+
+#ifndef WGL_NV_gpu_affinity
+#define WGL_NV_gpu_affinity 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern BOOL WINAPI wglEnumGpusNV (UINT iGpuIndex, HGPUNV *phGpu);
+extern BOOL WINAPI wglEnumGpuDevicesNV (HGPUNV hGpu, UINT iDeviceIndex, PGPU_DEVICE lpGpuDevice);
+extern HDC WINAPI wglCreateAffinityDCNV (const HGPUNV *phGpuList);
+extern BOOL WINAPI wglEnumGpusFromAffinityDCNV (HDC hAffinityDC, UINT iGpuIndex, HGPUNV *hGpu);
+extern BOOL WINAPI wglDeleteDCNV (HDC hdc);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef BOOL (WINAPI * PFNWGLENUMGPUSNVPROC) (UINT iGpuIndex, HGPUNV *phGpu);
+typedef BOOL (WINAPI * PFNWGLENUMGPUDEVICESNVPROC) (HGPUNV hGpu, UINT iDeviceIndex, PGPU_DEVICE lpGpuDevice);
+typedef HDC (WINAPI * PFNWGLCREATEAFFINITYDCNVPROC) (const HGPUNV *phGpuList);
+typedef BOOL (WINAPI * PFNWGLENUMGPUSFROMAFFINITYDCNVPROC) (HDC hAffinityDC, UINT iGpuIndex, HGPUNV *hGpu);
+typedef BOOL (WINAPI * PFNWGLDELETEDCNVPROC) (HDC hdc);
+#endif
+
+#ifndef WGL_AMD_gpu_association
+#define WGL_AMD_gpu_association 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern UINT WINAPI wglGetGPUIDsAMD (UINT maxCount, UINT *ids);
+extern INT WINAPI wglGetGPUInfoAMD (UINT id, int property, GLenum dataType, UINT size, void *data);
+extern UINT WINAPI wglGetContextGPUIDAMD (HGLRC hglrc);
+extern HGLRC WINAPI wglCreateAssociatedContextAMD (UINT id);
+extern HGLRC WINAPI wglCreateAssociatedContextAttribsAMD (UINT id, HGLRC hShareContext, const int *attribList);
+extern BOOL WINAPI wglDeleteAssociatedContextAMD (HGLRC hglrc);
+extern BOOL WINAPI wglMakeAssociatedContextCurrentAMD (HGLRC hglrc);
+extern HGLRC WINAPI wglGetCurrentAssociatedContextAMD (void);
+extern VOID WINAPI wglBlitContextFramebufferAMD (HGLRC dstCtx, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef UINT (WINAPI * PFNWGLGETGPUIDSAMDPROC) (UINT maxCount, UINT *ids);
+typedef INT (WINAPI * PFNWGLGETGPUINFOAMDPROC) (UINT id, int property, GLenum dataType, UINT size, void *data);
+typedef UINT (WINAPI * PFNWGLGETCONTEXTGPUIDAMDPROC) (HGLRC hglrc);
+typedef HGLRC (WINAPI * PFNWGLCREATEASSOCIATEDCONTEXTAMDPROC) (UINT id);
+typedef HGLRC (WINAPI * PFNWGLCREATEASSOCIATEDCONTEXTATTRIBSAMDPROC) (UINT id, HGLRC hShareContext, const int *attribList);
+typedef BOOL (WINAPI * PFNWGLDELETEASSOCIATEDCONTEXTAMDPROC) (HGLRC hglrc);
+typedef BOOL (WINAPI * PFNWGLMAKEASSOCIATEDCONTEXTCURRENTAMDPROC) (HGLRC hglrc);
+typedef HGLRC (WINAPI * PFNWGLGETCURRENTASSOCIATEDCONTEXTAMDPROC) (void);
+typedef VOID (WINAPI * PFNWGLBLITCONTEXTFRAMEBUFFERAMDPROC) (HGLRC dstCtx, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
+#endif
+
+#ifndef WGL_NV_video_capture
+#define WGL_NV_video_capture 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern BOOL WINAPI wglBindVideoCaptureDeviceNV (UINT uVideoSlot, HVIDEOINPUTDEVICENV hDevice);
+extern UINT WINAPI wglEnumerateVideoCaptureDevicesNV (HDC hDc, HVIDEOINPUTDEVICENV *phDeviceList);
+extern BOOL WINAPI wglLockVideoCaptureDeviceNV (HDC hDc, HVIDEOINPUTDEVICENV hDevice);
+extern BOOL WINAPI wglQueryVideoCaptureDeviceNV (HDC hDc, HVIDEOINPUTDEVICENV hDevice, int iAttribute, int *piValue);
+extern BOOL WINAPI wglReleaseVideoCaptureDeviceNV (HDC hDc, HVIDEOINPUTDEVICENV hDevice);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef BOOL (WINAPI * PFNWGLBINDVIDEOCAPTUREDEVICENVPROC) (UINT uVideoSlot, HVIDEOINPUTDEVICENV hDevice);
+typedef UINT (WINAPI * PFNWGLENUMERATEVIDEOCAPTUREDEVICESNVPROC) (HDC hDc, HVIDEOINPUTDEVICENV *phDeviceList);
+typedef BOOL (WINAPI * PFNWGLLOCKVIDEOCAPTUREDEVICENVPROC) (HDC hDc, HVIDEOINPUTDEVICENV hDevice);
+typedef BOOL (WINAPI * PFNWGLQUERYVIDEOCAPTUREDEVICENVPROC) (HDC hDc, HVIDEOINPUTDEVICENV hDevice, int iAttribute, int *piValue);
+typedef BOOL (WINAPI * PFNWGLRELEASEVIDEOCAPTUREDEVICENVPROC) (HDC hDc, HVIDEOINPUTDEVICENV hDevice);
+#endif
+
+#ifndef WGL_NV_copy_image
+#define WGL_NV_copy_image 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern BOOL WINAPI wglCopyImageSubDataNV (HGLRC hSrcRC, GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, HGLRC hDstRC, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef BOOL (WINAPI * PFNWGLCOPYIMAGESUBDATANVPROC) (HGLRC hSrcRC, GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, HGLRC hDstRC, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth);
+#endif
+
+#ifndef WGL_NV_multisample_coverage
+#define WGL_NV_multisample_coverage 1
+#endif
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif